text:
/*
 * <%= namespace %>' BaseModel
 *
 * BaseModel provides high level control of all model object in <%= namespace %>.
 * All <%= namespace %>' models should inherit from BaseModel rather than Backbone.Model.
 */

(function ($, _, Backbone) {

  "use strict";
  <% var namespace = _.camelize(appname).toLowerCase(); %>
  /*
   * Base class for all models within <%= namespace %> projects.
   *
   * BaseModel supports a set of socket events via ioBind happening on a
   * specific model. These events includes update and delete, and default event
   * handlers are provided named `serverChange` and `serverDelete`
   * respectively.
   *
   * `<%= namespace %>.socket` is used for socket communication used by ioBind.
   *
   * Besides all methods of Backbone's Model, BaseModel defines another method
   * named `patch` for you as a convenient way for saving in patch mode.
   *
   * When an object of this Model is never used, remember to call `dispose`.
   *
   * How to customization your own model.
   * - `urlRoot` must be specified when define your own model for a feature.
   * - override `serverChange` or `serverDelete` if necessary.
   */
  <%= namespace %>.models.BaseModel = Backbone.Model.extend({
    idAttribute: "_id",
    socket: <%= namespace %>.socket,
    urlRoot: undefined,
    noIoBind: false,

    url: function() {
      if (this.urlRoot === undefined || typeof this.urlRoot !== "string") {
        throw new TypeError("urlRoot is not well-defined.");
      }

      return "/" + this.urlRoot + "/" + this.id;
    },

    initialize: function (attributes, options) {

      if (!this.noIoBind) {
        this.ioBind('update', this.serverChange, this);
        this.ioBind('delete', this.serverDelete, this);
      }
    },

    /*
     * Event happened in the server-side when this object is changed.
     */
    serverChange: function (data) {
      this.set(data);
    },

    /*
     * Event happened in the server-side when this object is deleted.
     */
    serverDelete: function (data) {
      if (this.collection) {
        this.collection.remove(this);
      } else {
        this.trigger('remove', this);
      }
    },

    /*
     * Remove all event handlers bound via ioBind.
     */
    modelCleanup: function () {
      this.ioUnbindAll();
      return this;
    },

    /*
     * Support Backbone's patch option to save method.
     *
     * Method keeps the default behavior of Backbone.Model.save except that
     * options.patch is set to true.
     *
     * Return value is what is returned by Backbone.Model.save
     */
    patch: function(attributes, options) {
      var opts = options || {};
      opts.patch = true;
      return this.save(attributes, opts);
    },

    /*
     * Public interface called to release all resource reserved by this model,
     * including memory, any event listeners.
     *
     * By default, BaseModel removes all event listeners on this model and all
     * socket event listeners used by ioBind.
     */
    dispose: function() {
      this.off();
      if (!this.noIoBind) {
        this.ioUnbindAll();
      }
      return this;
    }

  });

  /*
   * Baes collection for all collections in <%= namespace %>.
   *
   * CollectionModel supports create event of an object of a Model via ioBind
   * happening on a specific model. Once an object of a model is created,
   * `serverCreate` is called by passing that object.
   *
   * `<%= namespace %>.socket` is used for socket communication used by ioBind.
   *
   * When an object of this Collection is never used, remember to call
   * `dispose`.
   *
   * How to customization your own model.
   * - `url` must be specified when define your own model for a feature.
   * - override `serverCreate` if necessary.
   */
  <%= namespace %>.models.BaseCollection = Backbone.Collection.extend({
    socket: <%= namespace %>.socket,
    noIoBind: false,

    initialize: function() {
      this.ioBind("create", this.serverCreate, this);
    },

    /*
     * Respond to event named activities:create from server-side.
     * By default, the newly created object is added to this collection.
     */
    serverCreate: function(data) {
      this.add(data);
    },

    /*
     * Remove all event listeners.
     *
     * By default, BaseCollection does following actions
     * - each element's event handlers is removed referencing BaseModel's
     *   dispose function.
     * - remove event listners registered on and for this collection.
     */
    dispose: function() {
      this.forEach(function(item) {
        item.dispose();
      });
      this.off();
      if (!this.noIoBind) {
        this.ioUnbind("create", this.serverCreate);
      }
      return this;
    }

  });

}(jQuery, _, Backbone));


text:
\documentclass[11pt,a4paper,oneside]{scrreprt}
\usepackage{style/coast}
\usepackage{style/graphvizzz}

% BEGIN Title Page
\title{COAST Application Framework}
\author{IFS - Institute for Software}
\begin{document}
\begin{titlepage}

\pagenumbering{alph}
\thispagestyle{empty}

\begin{center}
\begin{figure}[h]
 \centering
 \includegraphics[width=0.3\hsize]{logo/logo_ifs_english.png}
\end{figure}
\vspace{1,5cm}
{\Large \bfseries University of Applied Sciences Rapperswil\\}
\vspace{0,5cm}
{\Large \bfseries Institute for Software\\}
\vspace{2cm}
\sffamily
{\Huge \bfseries Technical Documentation}\\
\vspace{0.5cm}
{\Huge \bfseries COAST Webframework}\\
\vspace{1,5cm}
Peter Sommerlad, Marcel Huber, Dominik Wild, Michael Rueegg\\\url{ifs@hsr.ch}\\\vspace{1,0cm}
\begin{scriptsize}\url{https://sifs-coast1.hsr.ch/}\\\end{scriptsize}
\vspace{2,5cm}
\vspace{0,3cm}
\today
\end{center}
\end{titlepage}

\pagenumbering{roman}
\setcounter{tocdepth}{2}

% Table of contents
\tableofcontents
\newpage
\pagenumbering{arabic}
\pagestyle{scrheadings}

% BEGIN Include Chapters
\include{chapters/chap01}
%\include{chapters/chap02}
% END Include Chapters

%\setcounter{secnumdepth}{-1}
\appendix
%\chapter{First Appendix}
%\appendix
%\chapter{Appendix}
%\pagenumbering{Alph}

% List of Figures
\cleardoublepage
\addcontentsline{toc}{chapter}{\listfigurename}
\listoffigures

% Nomenclature
%\renewcommand{\nomname}{List of Symbols}
%\cleardoublepage%
\cleardoublepage
\addcontentsline{toc}{chapter}{\nomname}
\printnomenclature

% Bibliography
\nocite{*}
\bibliographystyle{alpha}
\cleardoublepage
\addcontentsline{toc}{chapter}{Bibliography}
\bibliography{manual}

\end{document}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using tc_dev.Core.Common.Utilities;
using tc_dev.Core.Identity;
using tc_dev.Core.Identity.Models;
using tc_dev.Core.Infrastructure.Identity.Utilities;

namespace tc_dev.Core.Infrastructure.Identity
{
    public class AppAuthenticationManager : IAppAuthenticationManager
    {
        private readonly IAuthenticationManager _authenticationManager;

        public AppAuthenticationManager(IAuthenticationManager authenticationManager) {
            authenticationManager.ThrowIfNull("authenticatonManager");

            _authenticationManager = authenticationManager;
        }

        public IEnumerable<AppAuthenticationDescription> GetExternalAuthenticationTypes() {
            var authenticationDescriptions = _authenticationManager.GetExternalAuthenticationTypes();
            var appAuthenticationDescriptions = authenticationDescriptions.Select(IdentityModelFactory.Create);

            return appAuthenticationDescriptions;
        }

        public AppExternalLoginInfo GetExternalLoginInfo() {
            var externalLoginInfo = _authenticationManager.GetExternalLoginInfo();
            var appExternalLoginInfos = IdentityModelFactory.Create(externalLoginInfo);

            return appExternalLoginInfos;
        }

        public async Task<AppExternalLoginInfo> GetExternalLoginInfoAsync() {
            var externalLoginInfo = await _authenticationManager.GetExternalLoginInfoAsync();
            var appExternalLoginInfos = IdentityModelFactory.Create(externalLoginInfo);

            return appExternalLoginInfos;
        }

        public void SignIn(params ClaimsIdentity[] identities) {
            identities.ThrowIfNull("identities");

            _authenticationManager.SignIn(identities);
        }

        public void SignOut(params string[] authenticationTypes) {
            authenticationTypes.ThrowIfNull("authenticationTypes");

            _authenticationManager.SignOut(authenticationTypes);
        }
    }
}


text:
require_relative '../../test_helper'

class TestFakerTvShowsTheExpanse < Test::Unit::TestCase
  def setup
    @tester = Faker::TvShows::TheExpanse
  end

  def test_character
    assert @tester.character.match(/\w+/)
  end

  def test_location
    assert @tester.location.match(/\w+/)
  end

  def test_quote
    assert @tester.quote.match(/\w+/)
  end

  def test_ship
    assert @tester.ship.match(/\w+/)
  end
end


text:
<?php

require_once __DIR__."/../src/StatusList.php";

class StatusListTest extends \PHPUnit_Framework_TestCase
{

	public function testIsFinal()
	{
		$statusList = new \LapayGroup\RussianPost\StatusList();

		$this->assertEquals(
			true,
			$statusList->isFinal(5,2)
		);
	}
}


text:
var bodyParser      = require('body-parser');
var cookieParser    = require('cookie-parser');
var express         = require('express');
var multer          = require('multer')
var session         = require('express-session');
var mongoose        = require('mongoose');
var passport        = require('passport');

var app = express();

var public_folder = __dirname + '/public';

var connectionUrl = 'mongodb://localhost/webdev'

app.use(express.static(public_folder));
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;

if (process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
    connectionUrl = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
            process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
            process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
            process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
            process.env.OPENSHIFT_APP_NAME;
    }

var session_secret = process.env.SESSION_SECRET || process.env.OPENSHIFT_APP_NAME;

var db = mongoose.connect(connectionUrl);

app.use(multer());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
    secret: session_secret,
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

app.get('/assignment', function(req, res){
   res.sendfile(public_folder + '/assignment/client/index.html');
});

app.get('/experiment', function(req, res){
    res.sendfile(public_folder + '/experiment/index.html');
});

app.get('/project', function(req, res){
    res.sendfile(public_folder + '/project/client/index.html');
});

var aUser = require("./public/assignment/server/models/user.model.js")(db, mongoose);
var cUser = require("./public/project/server/models/user.model.js")(db, mongoose);

require("./public/assignment/server/app.js")(app, db, mongoose, aUser, cUser, passport);
require("./public/project/server/app.js")(app, db, mongoose, aUser, cUser, passport);

app.listen(port, ipaddress);


text:
package com.beust.jcommander.converters;

import com.beust.jcommander.ParameterException;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Convert a string into a URI.
 *
 * @author samvv
 */
public class URLConverter extends BaseConverter<URL> {

	public URLConverter(String optionName) {
		super(optionName);
	}

	public URL convert(String value) {
		try {
			return new URL(value);
		} catch (MalformedURLException e) {
			throw new ParameterException(
					getErrorString(value, "a RFC 2396 and RFC 2732 compliant URL"));

		}
	}
}


text:
// Copyright 2008-2010 Victor Iacoban
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions and
// limitations under the License.
package org.zmlx.hg4idea.execution;

import com.intellij.ide.passwordSafe.PasswordSafe;
import com.intellij.ide.passwordSafe.PasswordSafeException;
import com.intellij.ide.passwordSafe.config.PasswordSafeSettings;
import com.intellij.ide.passwordSafe.impl.PasswordSafeImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.vcsUtil.AuthDialog;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zmlx.hg4idea.HgGlobalSettings;
import org.zmlx.hg4idea.HgVcs;
import org.zmlx.hg4idea.HgVcsMessages;

/**
 * Base class for any command interacting with a remote repository and which needs authentication.
 */
class HgCommandAuthenticator {

  private static final Logger LOG = Logger.getInstance(HgCommandAuthenticator.class.getName());

  private GetPasswordRunnable myGetPassword;
  private final Project myProject;
  private boolean myForceAuthorization;
  //todo replace silent mode and/or force authorization
  private boolean mySilentMode;

  public HgCommandAuthenticator(Project project, boolean forceAuthorization, boolean silent) {
    myProject = project;
    myForceAuthorization = forceAuthorization;
    mySilentMode = silent;
  }

  public void saveCredentials() {
    if (myGetPassword == null) return;

    // if checkbox is selected, save on disk. Otherwise in memory. Don't read password safe settings.

    final PasswordSafeImpl passwordSafe = (PasswordSafeImpl)PasswordSafe.getInstance();
    final String url = VirtualFileManager.extractPath(myGetPassword.getURL());
    final String key = keyForUrlAndLogin(url, myGetPassword.getUserName());
    try {
      if (myGetPassword.isRememberPassword()) {
        PasswordSafe.getInstance().storePassword(myProject, HgCommandAuthenticator.class, key, myGetPassword.getPassword());
      }
      else if (passwordSafe.getSettings().getProviderType() != PasswordSafeSettings.ProviderType.DO_NOT_STORE) {
        passwordSafe.getMemoryProvider().storePassword(myProject, HgCommandAuthenticator.class, key, myGetPassword.getPassword());
      }
      final HgVcs vcs = HgVcs.getInstance(myProject);
      if (vcs != null) {
        vcs.getGlobalSettings().addRememberedUrl(url, myGetPassword.getUserName());
      }
    }
    catch (PasswordSafeException e) {
      LOG.info("Couldn't store the password for key [" + key + "]", e);
    }
  }

  public boolean promptForAuthentication(Project project, String proposedLogin, String uri, String path, @Nullable ModalityState state) {
    GetPasswordRunnable runnable = new GetPasswordRunnable(project, proposedLogin, uri, path, myForceAuthorization, mySilentMode);
    ApplicationManager.getApplication().invokeAndWait(runnable, state == null ? ModalityState.defaultModalityState() : state);
    myGetPassword = runnable;
    return runnable.isOk();
  }

  public String getUserName() {
    return myGetPassword.getUserName();
  }

  public String getPassword() {
    return myGetPassword.getPassword();
  }

  private static class GetPasswordRunnable implements Runnable {
    private static final Logger LOG = Logger.getInstance(GetPasswordRunnable.class.getName());

    private String myUserName;
    private String myPassword;
    private Project myProject;
    private final String myProposedLogin;
    private boolean ok = false;
    @Nullable private String myURL;
    private boolean myRememberPassword;
    private boolean myForceAuthorization;
    private final boolean mySilent;

    public GetPasswordRunnable(Project project,
                               String proposedLogin,
                               String uri,
                               String path,
                               boolean forceAuthorization, boolean silent) {
      this.myProject = project;
      this.myProposedLogin = proposedLogin;
      this.myURL = uri + path;
      this.myForceAuthorization = forceAuthorization;
      mySilent = silent;
    }

    public void run() {

      // find if we've already been here
      final HgVcs vcs = HgVcs.getInstance(myProject);
      if (vcs == null) {
        return;
      }

      @NotNull final HgGlobalSettings hgGlobalSettings = vcs.getGlobalSettings();
      @Nullable String rememberedLoginsForUrl = null;
      if (!StringUtil.isEmptyOrSpaces(myURL)) {
        rememberedLoginsForUrl = hgGlobalSettings.getRememberedUserName(VirtualFileManager.extractPath(myURL));
      }

      String login = myProposedLogin;
      if (StringUtil.isEmptyOrSpaces(login)) {
        // find the last used login
        login = rememberedLoginsForUrl;
      }

      String password = null;
      if (!StringUtil.isEmptyOrSpaces(login) && myURL != null) {
        // if we've logged in with this login, search for password
        final String key = keyForUrlAndLogin(myURL, login);
        try {
          final PasswordSafeImpl passwordSafe = (PasswordSafeImpl)PasswordSafe.getInstance();
          if (mySilent) {
            password = passwordSafe.getMemoryProvider().getPassword(myProject, HgCommandAuthenticator.class, key);
          }
          else {
            password = passwordSafe.getPassword(myProject, HgCommandAuthenticator.class, key);
          }
        }
        catch (PasswordSafeException e) {
          LOG.info("Couldn't get password for key [" + key + "]", e);
        }
      }

      // don't show dialog if we don't have to (both fields are known) except force authorization required
      if (!myForceAuthorization && !StringUtil.isEmptyOrSpaces(
        password) && !StringUtil.isEmptyOrSpaces(login)) {
        myUserName = login;
        myPassword = password;
        ok = true;
        return;
      }

      if (mySilent) {
        ok = false;
        return;
      }

      final AuthDialog dialog = new AuthDialog(myProject, HgVcsMessages.message("hg4idea.dialog.login.password.required"),
                                               HgVcsMessages.message("hg4idea.dialog.login.description", myURL),
                                               login, password, true);
      if (dialog.showAndGet()) {
        myUserName = dialog.getUsername();
        myPassword = dialog.getPassword();
        myRememberPassword = dialog.isRememberPassword();
        ok = true;
      }
    }

    public String getUserName() {
      return myUserName;
    }

    public String getPassword() {
      return myPassword;
    }

    public boolean isOk() {
      return ok;
    }

    @Nullable
    public String getURL() {
      return myURL;
    }

    public boolean isRememberPassword() {
      return myRememberPassword;
    }
  }

  private static String keyForUrlAndLogin(String stringUrl, String login) {
    return login + ":" + stringUrl;
  }
}


text:
package com.example.androidgame1;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class MemoryPool<E> {

		private int capacity = 10000;

		//private LinkedList<Unit> freeList;

		private Class<E> cls;
		private E[] freeArray; // Total Memory
		private ArrayList<Object> pointers; // Free Memory

		//private int freeUnits;

		public MemoryPool(Class<E> cls, int capacity) {

			this.cls = cls;
			this.capacity = capacity;
			freeArray = (E[])Array.newInstance(cls, capacity);
			pointers = new ArrayList<Object>();
			pointers.ensureCapacity(capacity);

			for (int i = 0; i < capacity; i++) {
				try {
					freeArray[i] = cls.newInstance();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				pointers.add(freeArray[i]);
			}

		}

		public int getCapacity() { return capacity; }

		/**
		 * Puts unit into freeList.
		 * Unit ownership should transfer to memory pool
		 * @param unit
		 */
		public synchronized void recycleMemory(E unit) {

			//freeList.add(unit); // TODO: THIS CAUSES AN ALLOCATION
			//freeUnits += 1;
			pointers.add(unit);
		}

		/**
		 * Get a unit from free list.
		 * If pool is empty, allocate new unit
		 * @return
		 */
		public synchronized E fetchMemory() {
//			if (freeUnits < 1) {
//				return new Unit();
//			}
//			Unit ret = freeList.pop();
//			freeUnits -= 1;
//			return ret;
			if (pointers.size() < 1) {
				E obj;
				try {
					obj = cls.newInstance();
					return obj;
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			E unit = (E) pointers.remove(pointers.size() - 1);
			return unit;
		}

		/**
		 * Recycles an array list of the item of the memory pool type
		 * @param list
		 */
		public void recycleArrayList(ArrayList<E> list) {
			for (int i = list.size() - 1; i > -1; i--) {
				this.recycleMemory( list.get(i) );
				list.remove(i);
			}
		}
}


text:
var my_name = "Ovi";
my_name = my_name + "Calvo";
console.log(my_name);

// Favorite Food Program

var favFood = String(prompt("Hey pal, what's your favorite food?:", ""));
alert("Hey! That's my favorite too! I love " + favFood + ".");

// Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board

//Looping a Triangle

for (var triangle = "#"; triangle.length < 8; triangle += "#")
  console.log(triangle);

//FizzBuzz

for (var n = 1; n <=100; n++) {
	var output = "";
	if (n % 3 == 0)
		output += "Fizz";
	if (n % 5 == 0)
		output += "Buzz";
	console.log(output || n);
}
// Chess Board

var board = "";

for (var y = 0; y < 8; y++) {
   for (var x = 0; x < 8; x++) {
	if ((x + y) % 2 == 0)
		board += " ";
	else
		board += "#";
   }
   board += "\n";
 }

console.log(board)

// Functions

// Complete the `minimum` exercise.

var min = function(arg1, arg2) {
	if (arg1 < arg2)
		return arg1;
	else if (arg2 < arg1)
		return arg2;
	else
		return false;
}

// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.

var me = {
	name: "Ovi",
	age: 30,
	favFood1: "Saba Shioyaki",
	favFood2: "Spaghetti and Meatballs",
	favFood3: "Peking Duck",
	quirk: "I'm a huge Star Wars nerd."
}


text:
using System.Data.Entity;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Mvc;
using WhatNow.Data.Ef;

namespace WhatNow.Ui.Web.Api.Controllers
{
	[Route("api/[controller]")]
	public class ImagesController : Controller
	{
		private readonly WhatNowDataEntities _dbContext;

		public ImagesController(WhatNowDataEntities dbContext, IHostingEnvironment hostingEnvironment)
		{
			_dbContext = dbContext;
			HostingEnvironment = hostingEnvironment;
		}

		public IHostingEnvironment HostingEnvironment { get; set; }

		[HttpGet("{id}")]
		public async Task<IActionResult> Get(int id)
		{
			var file = await _dbContext
				.Files
				.FirstOrDefaultAsync(x => x.Id == id);

			if (file != null)
			{
				return File(file.Content, file.ContentType);
			}

			// return default image
			var path = Path.Combine(HostingEnvironment.WebRootPath, @"images\default_icon.png");
			var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
			return File(stream, "image/png");
		}
	}
}


text:
<?php

namespace OpenTracing\Wikia\Propagator;

use OpenTracing;
use OpenTracing\SplitBinaryCarrier;
use OpenTracing\Exception\EmptyCarrierException;
use OpenTracing\Exception\CorruptedCarrierException;
use OpenTracing\Exception\InvalidCarrierException;
use OpenTracing\Wikia\Span;

class SplitBinaryPropagator extends Propagator
{

    /**
     * Returns a Span instance with operation name $operationName
     * that's joined to the trace state embedded within $carrier, or null if
     * no such trace state could be found.
     *
     * Implementations may raise implementation-specific errors
     * if there are more fundamental problems with `carrier`.
     *
     * Upon success, the returned Span instance is already started.
     *
     * @throws EmptyCarrierException
     * @throws CorruptedCarrierException
     *
     * @param string $operationName
     * @param mixed $carrier
     * @return Span
     */
    public function joinTrace($operationName, &$carrier)
    {
        if (!$carrier instanceof SplitBinaryCarrier) {
            throw new EmptyCarrierException();
        }
        $state = $carrier->getState();
        $baggage = $carrier->getBaggage();

        if (is_null($state) && is_null($baggage)) {
            throw new EmptyCarrierException();
        }

        if (!is_string($state) || !is_string($baggage)) {
            throw new CorruptedCarrierException();
        }

        if (strlen($state) != 16) {
            throw new CorruptedCarrierException();
        }
        $traceId = substr($state, 0, 8);
        $spanId = substr($state, 8, 8);

        try {
            $baggage = $this->decodeArray($baggage);
        } catch (\InvalidArgumentException $e) {
            throw new CorruptedCarrierException();
        }

        return $this->tracer->createSpan($traceId, $spanId, $baggage);
    }

    /**
     * Takes $span and injects it into $carrier.
     *
     * The actual type of $carrier depends on the $format value passed to
     * Tracer.injector().
     *
     * Implementations may raise implementation-specific exception
     * if injection fails.
     *
     * @throws InvalidCarrierException
     *
     * @param OpenTracing\Span $span
     * @param $carrier
     * @return void
     */
    public function injectSpan(OpenTracing\Span $span, &$carrier)
    {
        $this->validateSpan($span);
        if (!$carrier instanceof SplitBinaryCarrier) {
            throw new InvalidCarrierException();
        }

        /** @var Span $span */
        $spanData = $span->getData();
        $state = $this->formatId($spanData->traceId) . $this->formatId($spanData->spanId);
        $baggage = $this->encodeArray($spanData->baggage);

        $carrier
            ->setState($state)
            ->setBaggage($baggage);
    }

    private function formatId($id)
    {
        if (!is_string($id) || strlen($id) != 8) {
            return str_repeat(chr(0), 8);
        }

        return $id;
    }

    private function encodeArray(array $data)
    {
        $s = [];
        $s[] = pack('N', count($data));
        foreach ($data as $k => $v) {
            $k = (string)$k;
            $v = (string)$v;
            $s[] = pack('N', strlen($k));
            $s[] = $k;
            $s[] = pack('N', strlen($v));
            $s[] = $v;
        }

        return implode('', $s);
    }

    private function decodeArray($bytes)
    {
        $len = strlen($bytes);
        $pos = 0;
        $count = $this->readInt32($bytes, $len, $pos);
        $data = [];
        for ($i = 0; $i < $count; $i++) {
            $k = $this->readString($bytes, $len, $pos);
            $v = $this->readString($bytes, $len, $pos);
            $data[$k] = $v;
        }

        if ($pos != $len) {
            throw new \InvalidArgumentException('Trailing bytes found when decoding array');
        }

        return $data;
    }

    private function readString($bytes, $len, &$pos)
    {
        $count = $this->readInt32($bytes, $len, $pos);

        return $this->readBytes($bytes, $len, $count, $pos);
    }

    private function readInt32($bytes, $len, &$pos)
    {
        return unpack('N', $this->readBytes($bytes, $len, 4, $pos));
    }

    private function readBytes($bytes, $len, $count, &$pos)
    {
        if ($pos + $count > $len) {
            throw new \InvalidArgumentException(sprintf('Could not read %d bytes from byte stream', $count));
        }

        $val = substr($bytes, $pos, $count);
        $pos += $count;

        return $val;
    }

}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip } from 'recharts';

import './VerticalBarChart.scss';
import constants from '../../config/constants';

const VerticalBarChart = ({ data }) => (
  <div className="VerticalBarChart">
    <ResponsiveContainer width="100%" height={155}>
      <BarChart
        layout="vertical"
        width={600}
        height={155}
        data={data}
        margin={{ top: 0, right: 40, bottom: 0, left: -40 }}
      >
        <XAxis type="number" hide />
        <YAxis dataKey="key" type="category" tick={<CustomizedAxisTick />} />
        <Tooltip />
        <Bar legendType="line" dataKey="value" barSize={15} label={{ fontSize: 20 }} fill={constants.chartColor.blue} />
      </BarChart>
    </ResponsiveContainer>
  </div>
);

VerticalBarChart.propTypes = {
  data: PropTypes.arrayOf(
    PropTypes.shape({
      key: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
      value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    }),
  ).isRequired,
};

const CustomizedAxisTick = ({ x, y, payload }) => (
  <g transform={`translate(${x},${y})`}>
    <text x="10" y="-10" dy="0" textAnchor="start" fill={constants.chartColor.tickColor}>
      {payload.value}
    </text>
  </g>
);

CustomizedAxisTick.propTypes = {
  x: PropTypes.number,
  y: PropTypes.number,
  payload: PropTypes.shape({
    value: PropTypes.isRequired,
  }),
};

CustomizedAxisTick.defaultProps = {
  x: 0,
  y: 0,
  payload: {
    value: '',
  },
};

export default VerticalBarChart;


text:
#ifndef ARGS_TRANSLATOR_BASIC_HPP
#define	ARGS_TRANSLATOR_BASIC_HPP

#include "../asi.h"
#include <memory>
#include <charov.hpp>
#include <type_traits>
#include <modloader/util/path.hpp>
#include <modloader/util/container.hpp>
#include <modloader/util/injector.hpp>

#include "xtranslator.hpp"
#include "hacks/RyosukeSetModule.hpp"
#include "hacks/Bass.hpp"

using namespace injector;
using namespace cwc;

/*
 *  path_translator_base
 *      Path translator for modules, the base.
 *      Virtual methods to communicate with the translator for each symbol
 */
struct path_translator_base
{
    typedef ThePlugin::ModuleInfo ModuleInfo;
    typedef std::vector<path_translator_base*> list_type;
    typedef path_translator_base* smart_ptr;

    // List of singletons
    static list_type& List()
    { static list_type a; return a; }

    // Tells whether singleton list initialization is done
    static bool& InitializationDone()
    { static bool bDone = false; return bDone; }

    // Helper function to clone a translator object
    template<class T> static smart_ptr DoClone(const T* self)
    {
        return smart_ptr(new T(*self));
    }

    // Checks if argument @type is a input path
    static bool IsInputPath(char type)
    {
        return type != AR_DUMMY;
    }

    // Pure abstract
    virtual smart_ptr clone()=0;                        // Clone this object.
    virtual const char* GetSymbol()=0;                  // Gets symbol the translator translates for
    virtual const char* GetLibName()=0;                 // Gets library name the translator translates for
    virtual const void* GetWrapper()=0;                 // Gets pointer to the replacement (translator) function

    virtual path_translator_base*& GetSingleton()=0;    // Each translator <symbol,lib> must have a singleton
                                                        // for safeness, so we have a safe spot to hide ourselfs when
                                                        // we fail to capture the stack frame to find the caller.

    // Type
    bool bIsSingleton;
    bool bGetModuleFileName;        // Must be set by child
    bool bIniOperations;            // ^
    bool bSetCurrentDirectory;      // ^
    bool bCreateFile;               // ^
    bool bFindFirstFile;            // ^
    bool bFindNextFile;             // ^
    bool bFindClose;                // ^
    bool bLoadLibrary;              // ^
    bool bDoBassHack;               // ^

    // Almost static vars (he), the value is always the same in all objects
    int npath;              // Num args that uses a path
    char argtype[32];       // eArgsType for [Ret + Args]

    // Object-dependent vars
    void* iat;              // Pointer to this func on IAT
    void* fun;              // Original function pointer

    //
    path_translator_base() : npath(0), fun(0), iat(0), bIsSingleton(false)
    { }

    // Patch address @addr at IAT to point into our wrapper
    void Patch(void* addr)
    {
        this->iat = addr;

        // Replace IAT pointers and get original function pointer into @fun
        this->fun = ReadMemory<void*>(raw_ptr(iat), true);
        WriteMemory<const void*>(raw_ptr(iat), this->GetWrapper(), true);

        // If the singleton has no function assigned to it yet, assign one
        // This will be our safe exit when we can't capture stack frames ;)
        auto& s = GetSingleton();
        if(s->fun == nullptr) s->fun = this->fun;
    }

    // Unpatches the IAT
    void Restore()
    {
        if(this->iat)
        {
            WriteMemory<void*>(raw_ptr(iat), this->fun, true);
            this->iat = 0;
        }
    }

    // Tries to make this object part of the singleton list
    // Must be called by the child's constructor!!!!
    void SetupSingleton()
    {
        if(InitializationDone() == false)
        {
            this->bIsSingleton = true;
            List().push_back(GetSingleton() = this);
        }
    }

    // Finishes the RegisterPathType function when there's no more arguments to register
    template<size_t N = 0>
    void RegisterPathType() {}

    // Goes registering and identifying the argument types (eArgsType) sent in the constructor
    template<size_t N = 0, class... ArgsType>
    void RegisterPathType(char t, ArgsType... ts)
    {
        if(InitializationDone() == false)   // Still initializing singletons?
        {
            if(IsInputPath(t))
                ++npath;                            // Increase num paths
            this->argtype[N] = t;                   // Register
            return RegisterPathType<N+1>(ts...);    // Next
        }
        else // Just copy stuff from the singleton
        {
            auto& s = GetSingleton();
            this->npath = s->npath;
            memcpy(this->argtype, s->argtype, sizeof(this->argtype));
        }
    }

    // Function that helps in the calling/translation process
    struct CallInfo
    {
        // Size of each element in the character pool
        static const size_t pool_elem_size = MAX_PATH * sizeof(wchar_t);

        bool bSetDir;                       // Call comming from gta_sa.exe:_chdir
        bool bAbsolutePath;                 // Is translating a path with absolute path?

        std::unique_ptr<char[]> path_pool;  // Character pool
        size_t path_pool_used;              // Size (not number of elements) used in the pool

        path_translator_base* base;         // Translator
        ModuleInfo* asi;                    // Pointer to Calling ASI module

        // Construct the information
        CallInfo() : asi(0), base(0), bSetDir(false)
        {}

        // Allocates a path in the pool. @size is the num characters the path will need.
        auto_pointer AllocPath(size_t size)
        {
            if(!path_pool)  // Lazy pool allocation ;)
            {
                // Allocate it
                path_pool.reset(new char[base->npath * pool_elem_size]);
                path_pool_used = 0;
            }

            // Get space on it
            void* p = &path_pool[path_pool_used];
            path_pool_used += size;
            return auto_pointer(p);
        }

        // Attaches @asi and translator from @symbol and @libname into this object
        bool SetupASI(ModuleInfo* asi, const char* symbol, const char* libname)
        {
            if(asi)
            {
                // Find translator in asi for symbol and library
                if(this->base = asi->FindTranslatorFrom(symbol, libname))
                {
                    // Yay, we did it!
                    this->asi = asi;
                    return true;
                }
            }

            // Hen, symbol or library not present in this asi
            return false;
        }

        // Finishes the TranslateForCall function when there's no more arguments to translate
        template<size_t N = 1>
        void TranslateForCall()
        { }

        // Translates argument @x at position @N
        template<size_t N = 1, class T, class... A>
        void TranslateForCall(T& x, A&&... a)
        {
            auto argtype = base->argtype[N];

            // Is it a input path?
            if(IsInputPath(argtype))
            {
                // Translate this path to be side by side with the asi path
                TranslatePath(x, argtype);
            }
            else
            {
                // Hack for ryosuke's plugins
                if(base->bGetModuleFileName && asi->hacks.bRyosukeModuleName)
                {
                    // If translating first argument for GetModuleFileName in a Ryosuke plugin
                    // override this argument with the plugin module instead of a (NULL) module.
                    if(N == 1) hacks::RyosukeSetModule(&x, asi->module);
                }
                // Hack for import hacked for bass.dll
                else if(base->bDoBassHack)
                {
                    // Don't continue if first param (BOOL mem) is TRUE, it isn't a path on the next param
                    if(N == 1 && hacks::BassIsMem(x))
                        return;
                }
            }

            // Translate the next parameter
            return TranslateForCall<N+1>(a...);
        }

        // Translate path for a unknown type, something is wrong if this thing gets called
        template<class T> void TranslatePath(T&&, char)
        {
            // ...He, no, what is this type?
            plugin_ptr->Error("std.asi: TranslatePath called with unknown type\n"
                         "Symbol: %s\nLibrary: %s",
                         base->GetSymbol(), base->GetLibName());
        }

        // Translate path for char type
        void TranslatePath(const char*& arg, char type)
        {
            return TranslatePathChar(arg, type);
        }

        // Translate path for wide char type
        void TranslatePath(const wchar_t*& arg, char type)
        {
            return TranslatePathChar(arg, type);
        }

        // Translate path for some character type (char or wchar) type
        template<class T>
        void TranslatePathChar(const T*& arg, char type)
        {
            // Call the path translator giving a functor that builds the output
            TranslatePath(arg, type, [](T* out, const char* prefix, const char* currdir, const T* suffix)
            {
                typedef typename std::decay<T>::type decayed_type;
                static const bool bIsWideChar = std::is_same<decayed_type, wchar_t>::value;

                // Character independent strings
				// This got broken badly for wchar_t overload with Visual Studio 2015!
				// swprintf %s will expect wchar_t* once again so we need to force char* by passing %hs
				// See here:
				// https://blogs.msdn.microsoft.com/vcblog/2014/06/18/c-runtime-crt-features-fixes-and-breaking-changes-in-visual-studio-14-ctp1/
                static const T a1[] = { '%', 'h', 's', '\0' };                   // "%hs"
                static const T a2[] = { '%', 'h', 's', '\\', '%', 'h', 's', '\0' };   // "%hs\\%hs"
                static const T a3[] = { '%', 'h', 's', '\\', '%', 'h', 's', '\\',     // "%hs\\%hs\\%hs" or "%hs\\%hs\\%ls"
                                        '%', bIsWideChar? 'l' : 'h', 's',
                                        '\0' };
                static const T a0[] = { '%', 'h', 's', '\\',                     // "%hs\\%hs" or "%hs\\%ls"
                                        '%', bIsWideChar? 'l' : 'h', 's',
                                        '\0' };

				#ifndef _MSC_VER
				#error Please check if printf formats in TranslatePathChar are compatible on this compiler!
				#endif

                // Build output string based on received prefixes / suffixes / whatever
                if(currdir)
                {
                    if(suffix)
                        sprintf(out, a3, prefix, currdir, suffix);  // "%hs\\%hs\\%hs" or "%hs\\%hs\\%ls"
                    else
                        sprintf(out, a2, prefix, currdir);          // "%hs\\%hs"
                }
                else
                {
                    if(suffix)
                        sprintf(out, a0, prefix, suffix);   // "%hs\\%hs" or "%hs\\%ls"
                    else
                        sprintf(out, a1, prefix);           // "%hs"
                }

                // Done
                return out;
            });
        }

        /*
         *  Translates path @arg for module @asi
         */
        template<class T, class F>
        void TranslatePath(const T*& arg, char type, F build_path)
        {
            if(true)
            {
                // Translate SetCurrentDirectory call only when coming from SetDir
                if(!base->bSetCurrentDirectory || this->bSetDir)
                {
                    this->bAbsolutePath = IsAbsolutePath(arg);

                    if(asi->bIsMainExecutable)
                    {
                        // If this is the module for the main game executable, calm down! It's special of course...
                        return TranslatePathForMainExecutable(arg, type, build_path);
                    }
                    else if(asi->bIsCleo)
                    {
                        // If this is CLEO.asi or any .cleo plugin module, translate path for a cs script
                        return TranslatePathForCleo(arg, type, build_path);
                    }
                    else if(asi->bIsASI || asi->bIsD3D9)
                    {
                        // If this is an ASI plugin module, translate path to be relative to it
                        return TranslatePathForASI(arg, type, build_path);
                    }
                    else
                    {
                        plugin_ptr->Error("std.asi error at TranslatePath<T,F>");
                    }
                }
            }
        }

        // The actual path translation goes on those functions, really specific
        template<class T, class F> void TranslatePathForMainExecutable(const T*&, char, F);
        template<class T, class F> void TranslatePathForCleo(const T*&, char, F);
        template<class T, class F> void TranslatePathForASI(const T*&, char, F);

        template<class T, class M, class F>
        bool CxBuildPath(T* p, const M& module, const char* currdir, const T*& arg, F build_path, bool bForce);

        template<class T>
        bool GetCurrentDir(const T*& arg, char type, const char*& currdir, char buffer[MAX_PATH]);

        // Gets the current working directory relative to the the game path
        // If working directory is not anywhere near the game path, return null
        static const char* GetCurrentDir(char* buffer, size_t max)
        {
            char *fullpath = buffer;
            const char* currdir = 0;

            // Get working directory...
            if(GetCurrentDirectoryA(max, fullpath))
            {
                // Do the hard work there...
                currdir = GetCurrentDir(fullpath, plugin_ptr->loader->gamepath, max);
            }

            return currdir;
        }

        // Gets the current working directory relative to the the game path
        // If working directory is not anywhere near the game path, return null
        // This is the manual version, where you send the current working directory (@fullpath) and game path (@gamepath)
        static const char* GetCurrentDir(const char* fullpath, const char* gamePath, size_t max)
        {
            const char* currdir = 0;

            // Iterate on the game path comparing it with the current working dir
            for(size_t i = 0; i < max; ++i)
            {
                if(gamePath[i] == 0)    // End of game path?
                {
                    // Then here starts the relative part
                    currdir = &fullpath[i];
                    break;
                }
                else if(gamePath[i] != fullpath[i]) // Piece of gamepath not equal to the working dir? wow
                {
                    // Let's calm down, if working directory ended and game path is ending, we're still 'equal'
                    if(fullpath[i] == 0 && gamePath[i] == '\\' && gamePath[i+1] == 0)
                    {
                        // Point current directory to "\0" part of fullpath
                        currdir = &fullpath[i];
                    }
                    break;
                }
            }

            return currdir;
        }

    };

};

/*
 *  path_translator_basic
 *      Now, this is the one that instantiates each Symbol X Library
 *      Must have child objects for each calling convenition!
 */
template<const char* Symbol, const char* LibName>
struct path_translator_basic : public path_translator_base
{
    // Store singleton for this Symbol X Library
    static path_translator_base*& StaticGetSingleton()
    { static path_translator_base* a; return a; }

    //
    virtual path_translator_base*& GetSingleton() { return StaticGetSingleton(); }
    virtual const char* GetSymbol()  { return Symbol; }
    virtual const char* GetLibName() { return LibName; }

    // Constructor, initialization
    path_translator_basic()
    {
        this->SetupSingleton();

        bDoBassHack = (LibName == aBass);

        if(LibName == aKernel32)
        {
            bGetModuleFileName = (Symbol == aGetModuleFileNameA) || (Symbol == aGetModuleFileNameW);
            bSetCurrentDirectory=(Symbol == aSetCurrentDirectoryA) || (Symbol == aSetCurrentDirectoryW);
            bCreateFile        = (Symbol == aCreateFileA) || (Symbol == aCreateFileW);
            bFindFirstFile     = (Symbol == aFindFirstFileA) || (Symbol == aFindFirstFileW);
            bFindNextFile      = (Symbol == aFindNextFileA) || (Symbol == aFindNextFileW);
            bFindClose         = (Symbol == aFindClose);
            bLoadLibrary	   = (Symbol == aLoadLibraryA) || (Symbol == aLoadLibraryW) || (Symbol == aLoadLibraryExA) || (Symbol == aLoadLibraryExW);
            bIniOperations     = false;
        }
    }

    // Let's extend CallInfo to work with out singleton, so we'll operate safe!
    struct CallInfo : public path_translator_base::CallInfo
    {
        // Gets information from pointer @pReturn inside a module
        bool FindInfo(void* pCaller)
        {
            static bool bAntiFlood = false; // Avoid flooding error message

            if(pCaller) // Succesfully got caller pointer?
            {
                if(Symbol == aSetCurrentDirectoryA)
                {
                    this->bSetDir = (pCaller == memory_pointer(0x836F3B).get());
                }

                // Identify the caller ASI from code segment pointer
                if(SetupASI(plugin_ptr->cast<ThePlugin>().FindModuleFromAddress(pCaller), Symbol, LibName))
                    return true;
                else
                    plugin_ptr->Error("std.asi: translator.SetupASI failed to identify caller ASI!");
            }
            else
            {
                // We don't have the caller pointer!!! WHAT TO DO?!?!?!?!
                // Let's calm down, and use our singleton instead ;)
                this->base = StaticGetSingleton();

                // Log about failure on this symbol/library only once
                if(!bAntiFlood)
                {
                    // Let's log about this situation we have here...
                    plugin_ptr->Log("Warning: std.asi failed to CaptureStackBackTrace for %s:%s! Trying singleton!",
                                   LibName, Symbol);
                    bAntiFlood = true;
                }
            }

            // We failed to find the asi module from the caller pointer...
            return false;
        }
    };

};

#endif


text:
// Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

using System;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace MyLivingRoom.Controls
{
    public class FontIconDefinition : IconDefinition
    {
        public FontFamily FontFamily { get; set; }
        public double FontSize { get; set; } = 20;
        public FontStyle FontStyle { get; set; } = FontStyle.Normal;
        public FontWeight FontWeight { get; set; } = FontWeights.Normal;
        public string Glyph { get; set; }

        public override UIElement CreateChildElement()
        {
            return new TextBlock
            {
                FontFamily = this.FontFamily,
                FontSize = this.FontSize,
                FontStyle = this.FontStyle,
                FontWeight = this.FontWeight,
                Text = this.Glyph,
                TextWrapping = TextWrapping.NoWrap,
                TextAlignment = TextAlignment.Center,
                IsTextSelectionEnabled = false,
                TextTrimming = TextTrimming.None,
                LineStackingStrategy = LineStackingStrategy.BlockLineHeight,
                MaxLines = 1,
            };
        }
    }
}


text:
<?php

namespace GpsLab\Component\Enum\Tests\Set;

use GpsLab\Component\Enum\Tests\Fixture\Set\ConstAccess;
use PHPUnit\Framework\TestCase;

class ConstAccessTest extends TestCase
{
    public function testChoices()
    {
        if (PHP_VERSION_ID < 70100) {
            $this->markTestSkipped('This test is for PHP-7.1 and upper only');
        }

        $choices = [
            ConstAccess::ACTION_GET => 'acme.demo.const_access.action_get',
            ConstAccess::ACTION_POST => 'acme.demo.const_access.action_post',
        ];
        $set = new ConstAccess([ConstAccess::ACTION_GET, ConstAccess::ACTION_POST]);

        $this->assertEquals($choices, $set->choices());
    }
}


text:
/* eslint-env mocha */

import should from 'should';

import config from '../test-config.js';
import { openDb, getDb, closeDb, importGtfs, getRoutes } from '../../index.js';

describe('getRoutes():', () => {
  before(async () => {
    await openDb(config);
    await importGtfs(config);
  });

  after(async () => {
    const db = getDb(config);
    await closeDb(db);
  });

  it('should return empty array if no routes for given agency exist', async () => {
    const routeId = 'fake-route-id';

    const results = await getRoutes({
      route_id: routeId,
    });
    should.exists(results);
    results.should.have.length(0);
  });

  it('should return expected routes', async () => {
    const results = await getRoutes({}, [], [['route_long_name', 'ASC']]);

    const expectedResults = [
      {
        route_id: 'Bu-16APR',
        agency_id: null,
        route_short_name: null,
        route_long_name: 'Baby Bullet',
        route_desc: null,
        route_type: 2,
        route_url: null,
        route_color: 'E31837',
        route_text_color: null,
        route_sort_order: null,
        continuous_pickup: null,
        continuous_drop_off: null,
        network_id: null,
      },
      {
        route_id: 'Li-16APR',
        agency_id: null,
        route_short_name: null,
        route_long_name: 'Limited',
        route_desc: null,
        route_type: 2,
        route_url: null,
        route_color: 'FEF0B5',
        route_text_color: null,
        route_sort_order: null,
        continuous_pickup: null,
        continuous_drop_off: null,
        network_id: null,
      },
      {
        route_id: 'Lo-16APR',
        agency_id: null,
        route_short_name: null,
        route_long_name: 'Local',
        route_desc: null,
        route_type: 2,
        route_url: null,
        route_color: 'FFFFFF',
        route_text_color: null,
        route_sort_order: null,
        continuous_pickup: null,
        continuous_drop_off: null,
        network_id: null,
      },
      {
        route_id: 'TaSj-16APR',
        agency_id: null,
        route_short_name: null,
        route_long_name: 'Tamien / San Jose Diridon Caltrain Shuttle',
        route_desc: null,
        route_type: 3,
        route_url: null,
        route_color: '41AD49',
        route_text_color: null,
        route_sort_order: null,
        continuous_pickup: null,
        continuous_drop_off: null,
        network_id: null,
      },
    ];

    should.exist(results);
    results.should.have.length(4);
    expectedResults.should.match(results);
  });

  it('should return expected routes for a specific stop_id', async () => {
    const results = await getRoutes(
      { stop_id: '70321' },
      [],
      [['route_long_name', 'ASC']]
    );

    const expectedResults = [
      {
        route_id: 'Li-16APR',
        agency_id: null,
        route_short_name: null,
        route_long_name: 'Limited',
        route_desc: null,
        route_type: 2,
        route_url: null,
        route_color: 'FEF0B5',
        route_text_color: null,
        route_sort_order: null,
        continuous_pickup: null,
        continuous_drop_off: null,
        network_id: null,
      },
    ];

    should.exist(results);
    results.should.have.length(1);
    expectedResults.should.match(results);
  });

  it('should return no routes for a invalid stop_id', async () => {
    const results = await getRoutes(
      { stop_id: 'not-valid' },
      [],
      [['route_long_name', 'ASC']]
    );

    const expectedResults = [];

    should.exist(results);
    results.should.have.length(0);
    expectedResults.should.match(results);
  });
});


text:
package io.digdag.core;

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import com.google.common.base.*;
import com.google.common.collect.*;
import com.google.inject.Guice;
import com.google.inject.Provider;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.google.inject.util.Modules;
import com.google.inject.multibindings.Multibinder;
import io.digdag.core.notification.NotificationModule;
import io.digdag.core.queue.QueueModule;
import io.digdag.core.config.YamlConfigLoader;
import io.digdag.core.database.DatabaseModule;
import io.digdag.core.workflow.WorkflowModule;
import io.digdag.core.workflow.WorkflowExecutorModule;
import io.digdag.core.schedule.ScheduleModule;
import io.digdag.core.schedule.ScheduleExecutorModule;
import io.digdag.core.config.ConfigModule;
import io.digdag.core.archive.ProjectArchiveLoader;
import io.digdag.core.agent.AgentModule;
import io.digdag.core.agent.LocalAgentModule;
import io.digdag.core.storage.StorageModule;
import io.digdag.core.log.LogModule;
import io.digdag.core.plugin.PluginSet;
import io.digdag.core.plugin.DynamicPluginModule;
import io.digdag.core.plugin.SystemPluginModule;
import org.embulk.guice.LifeCycleInjector;
import com.fasterxml.jackson.module.guice.ObjectMapperModule;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigElement;
import io.digdag.client.config.ConfigFactory;
import io.digdag.client.api.JacksonTimeModule;

public class DigdagEmbed
{
    public static class Bootstrap
    {
        private final List<Function<? super List<Module>, ? extends Iterable<? extends Module>>> moduleOverrides = new ArrayList<>();
        private ConfigElement systemConfig = ConfigElement.empty();
        private PluginSet systemPlugins = PluginSet.empty();
        private boolean withWorkflowExecutor = true;
        private boolean withScheduleExecutor = true;
        private boolean withLocalAgent = true;
        private boolean withExtensionLoader = true;

        public Bootstrap addModules(Module... additionalModules)
        {
            return addModules(Arrays.asList(additionalModules));
        }

        public Bootstrap addModules(Iterable<? extends Module> additionalModules)
        {
            final List<Module> copy = ImmutableList.copyOf(additionalModules);
            return overrideModules(modules -> Iterables.concat(modules, copy));
        }

        public Bootstrap overrideModules(Function<? super List<Module>, ? extends Iterable<? extends Module>> function)
        {
            moduleOverrides.add(function);
            return this;
        }

        public Bootstrap overrideModulesWith(Module... overridingModules)
        {
            return overrideModulesWith(Arrays.asList(overridingModules));
        }

        public Bootstrap overrideModulesWith(Iterable<? extends Module> overridingModules)
        {
            return overrideModules(modules -> ImmutableList.of(Modules.override(modules).with(overridingModules)));
        }

        public Bootstrap setSystemConfig(ConfigElement systemConfig)
        {
            this.systemConfig = systemConfig;
            return this;
        }

        public Bootstrap setSystemPlugins(PluginSet systemPlugins)
        {
            this.systemPlugins = systemPlugins;
            return this;
        }

        public Bootstrap withWorkflowExecutor(boolean v)
        {
            this.withWorkflowExecutor = v;
            return this;
        }

        public Bootstrap withScheduleExecutor(boolean v)
        {
            this.withScheduleExecutor = v;
            return this;
        }

        public Bootstrap withLocalAgent(boolean v)
        {
            this.withLocalAgent = v;
            return this;
        }

        public Bootstrap withExtensionLoader(boolean v)
        {
            this.withExtensionLoader = v;
            return this;
        }

        public DigdagEmbed initialize()
        {
            return build(true);
        }

        public DigdagEmbed initializeCloseable()
        {
            return build(false);
        }

        private DigdagEmbed build(boolean destroyOnShutdownHook)
        {
            final org.embulk.guice.Bootstrap bootstrap = new org.embulk.guice.Bootstrap()
                .requireExplicitBindings(true)
                .addModules(standardModules(systemConfig));
            moduleOverrides.stream().forEach(override -> bootstrap.overrideModules(override));

            LifeCycleInjector injector;
            if (destroyOnShutdownHook) {
                injector = bootstrap.initialize();
            }
            else {
                injector = bootstrap.initializeCloseable();
            }

            return new DigdagEmbed(injector);
        }

        private List<Module> standardModules(ConfigElement systemConfig)
        {
            ImmutableList.Builder<Module> builder = ImmutableList.builder();
            builder.addAll(Arrays.asList(
                    new ObjectMapperModule()
                        .registerModule(new GuavaModule())
                        .registerModule(new JacksonTimeModule()),
                    new DynamicPluginModule(),
                    new SystemPluginModule(systemPlugins),
                    new DatabaseModule(),
                    new AgentModule(),
                    new LogModule(),
                    new ScheduleModule(),
                    new ConfigModule(),
                    new WorkflowModule(),
                    new QueueModule(),
                    new NotificationModule(),
                    new StorageModule(),
                    (binder) -> {
                        binder.bind(ProjectArchiveLoader.class);
                        binder.bind(ConfigElement.class).toInstance(systemConfig);
                        binder.bind(Config.class).toProvider(SystemConfigProvider.class);
                        binder.bind(TempFileManager.class).toProvider(TempFileManagerProvider.class).in(Scopes.SINGLETON);
                    }
                ));
            if (withWorkflowExecutor) {
                builder.add(new WorkflowExecutorModule());
            }
            if (withScheduleExecutor) {
                builder.add(new ScheduleExecutorModule());
            }
            if (withLocalAgent) {
                builder.add(new LocalAgentModule());
            }
            if (withWorkflowExecutor) {
                builder.add((binder) -> {
                    binder.bind(LocalSite.class).in(Scopes.SINGLETON);
                });
            }
            if (withExtensionLoader) {
                builder.add(new ExtensionServiceLoaderModule());
            }
            return builder.build();
        }
    }

    public static class SystemConfigProvider
            implements Provider<Config>
    {
        private Config systemConfig;

        @Inject
        public SystemConfigProvider(ConfigElement ce, ConfigFactory cf)
        {
            this.systemConfig = ce.toConfig(cf);
        }

        @Override
        public Config get()
        {
            return systemConfig;
        }
    }

    public static class TempFileManagerProvider
            implements Provider<TempFileManager>
    {
        private final TempFileManager manager;

        @Inject
        public TempFileManagerProvider(Config systemConfig)
        {
            Path dir = systemConfig.getOptional("tmpdir", String.class)
                    .transform(s -> Paths.get(s))
                    .or(() -> {
                        try {
                            return Files.createTempDirectory("digdag-tempdir");
                        }
                        catch (IOException ex) {
                            throw Throwables.propagate(ex);
                        }
                    });
            this.manager = new TempFileManager(dir);
        }

        @Override
        public TempFileManager get()
        {
            return manager;
        }
    }

    private final LifeCycleInjector injector;

    DigdagEmbed(LifeCycleInjector injector)
    {
        this.injector = injector;
    }

    public Injector getInjector()
    {
        return injector;
    }

    public LocalSite getLocalSite()
    {
        return getInjector().getInstance(LocalSite.class);
    }

    public void destroy() throws Exception
    {
        injector.destroy();
    }
}


text:
@implementation SMilePGP

- (PGPKey*)importPGPKeyFromArmouredFile:(NSData*)fileContent {
    NSString* fileContentString = [[NSString alloc] initWithData:fileContent encoding:NSUTF8StringEncoding];
    BOOL isPrivate = [fileContentString containsString:@"-----BEGIN PGP PRIVATE KEY BLOCK-----"];
    NSData* packets = [PGPArmorHelper removeArmorFromKeyFileString:fileContentString];
    PGPPacketParser* parser = [[PGPPacketParser alloc] init];
    int nextpos = 0;
    do {
        nextpos = [parser extractPacketsFromBytes:packets atPostion:nextpos];
    } while (nextpos > 0);
    if (isPrivate) {
        PGPSecretKeyPacket* mainKeyPacket = [[parser getPacketsWithTag:5] objectAtIndex:0];
        int keyLen = [[[[mainKeyPacket pubKey] mpis] objectAtIndex:0] length]*8;
        NSMutableArray* userIDs = [[NSMutableArray alloc] init];
        for (int i = 0; i < [[parser getPacketsWithTag:13] count]; i++) {
            PGPUserIDPacket* userIDPacket = [[parser getPacketsWithTag:13] objectAtIndex:i];
            [userIDs addObject:[userIDPacket userID]];
        }
        NSData* keyID = [parser generateKeyID:[mainKeyPacket pubKey]];
        NSData* fingerprint = [parser generateFingerprint:[mainKeyPacket pubKey]];
        BOOL encrypted = (mainKeyPacket.s2k != 0);
        PGPKey* mainKey = [[PGPKey alloc] initWithKeyID:keyID andWithFingerPrint:fingerprint andWithUserIDs:userIDs andWithKeyLength:keyLen andWithKeyData:mainKeyPacket andIsPrivate:isPrivate andIsEncrypted:encrypted];
        for (int i = 0; i < [[parser getPacketsWithTag:7] count]; i++) {
            PGPSecretKeyPacket *subKeyPacket = [[parser getPacketsWithTag:7] objectAtIndex:i];
            NSData* subKeyID = [parser generateKeyID:[subKeyPacket pubKey]];
            NSData* subFingerprint = [parser generateFingerprint:[subKeyPacket pubKey]];
            PGPKey* subKey = [[PGPKey alloc] initWithKeyID:subKeyID andWithFingerPrint:subFingerprint andWithUserIDs:userIDs andWithKeyLength:keyLen andWithKeyData:subKeyPacket andIsPrivate:isPrivate andIsEncrypted:encrypted];
            [[mainKey subKeys] addObject:subKey];
        }
        return mainKey;
    } else {
        PGPPublicKeyPacket* mainKeyPacket = [[parser getPacketsWithTag:6] objectAtIndex:0];
        int keyLen = [[[mainKeyPacket mpis] objectAtIndex:0] length]*8;
        NSMutableArray* userIDs = [[NSMutableArray alloc] init];
        for (int i = 0; i < [[parser getPacketsWithTag:13] count]; i++) {
            PGPUserIDPacket* userIDPacket = [[parser getPacketsWithTag:13] objectAtIndex:i];
            [userIDs addObject:[userIDPacket userID]];
        }
        NSData* keyID = [parser generateKeyID:mainKeyPacket];
        NSData* fingerprint = [parser generateFingerprint:mainKeyPacket];
        PGPKey* mainKey = [[PGPKey alloc] initWithKeyID:keyID andWithFingerPrint:fingerprint andWithUserIDs:userIDs andWithKeyLength:keyLen andWithKeyData:mainKeyPacket andIsPrivate:isPrivate andIsEncrypted:false];
        for (int i = 0; i < [[parser getPacketsWithTag:14] count]; i++) {
            PGPPublicKeyPacket *subKeyPacket = [[parser getPacketsWithTag:14] objectAtIndex:i];
            NSData* subKeyID = [parser generateKeyID:subKeyPacket];
            NSData* subFingerprint = [parser generateFingerprint:subKeyPacket];
            PGPKey* subKey = [[PGPKey alloc] initWithKeyID:subKeyID andWithFingerPrint:subFingerprint andWithUserIDs:userIDs andWithKeyLength:keyLen andWithKeyData:subKeyPacket andIsPrivate:isPrivate andIsEncrypted:false];
            [[mainKey subKeys] addObject:subKey];
        }
        return mainKey;
    }
}

- (NSString*)getKeyIDFromArmoredPGPMessage:(NSData*)messageData {
    NSData* packets = [PGPArmorHelper removeArmorFromKeyFileString:[[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding]];
    PGPPacketParser* parser = [[PGPPacketParser alloc] init];
    int nextpos = 0;
    do {
        nextpos = [parser extractPacketsFromBytes:packets atPostion:nextpos];
    } while (nextpos > 0);
    if ([[parser getPacketsWithTag:1] count] == 0) {
        return NULL;
    }
    PGPPublicKeyEncryptedSessionKeyPacket* packet = [[parser getPacketsWithTag:1] objectAtIndex:0];
    NSData* keyID = [NSData dataWithBytes:(const void *)[packet pubKeyID] length:8];
    NSString* ret = [[keyID description] uppercaseString];
    return [ret substringWithRange:NSMakeRange(1, [ret length]-2)];
}

- (NSData*)decryptPGPMessageWithKey:(PGPKey*)secKey fromArmouredFile:(NSData*)fileContent {
    return [self decryptPGPMessageWithKey:secKey fromArmouredFile:fileContent WithPassphrase:NULL];
}

- (NSData*)decryptPGPMessageWithKey:(PGPKey*)secKey fromArmouredFile:(NSData*)fileContent WithPassphrase:(NSString*)passphrase {
    NSData* packets = [PGPArmorHelper removeArmorFromKeyFileString:[[NSString alloc] initWithData:fileContent encoding:NSUTF8StringEncoding]];
    PGPPacketParser* parser = [[PGPPacketParser alloc] init];
    int nextpos = 0;
    nextpos = [parser extractPacketsFromBytes:packets atPostion:nextpos];
    if (nextpos == -1) {
        return NULL;
    }
    if ([[parser getPacketsWithTag:1] count] > 0 || [[parser getPacketsWithTag:9] count] > 0 || [[parser getPacketsWithTag:18] count] > 0) {
        // Encrypted Message
        if ([[parser getPacketsWithTag:1] count] == 0) {
            return NULL; // not supported
        }
        PGPPublicKeyEncryptedSessionKeyPacket* encSessionKeyPacket = [[parser getPacketsWithTag:1] objectAtIndex:0];
        NSData* encSessionKey = [[encSessionKeyPacket mpis] objectAtIndex:0];

        NSData* keyID = [NSData dataWithBytes:(const void *)[encSessionKeyPacket pubKeyID] length:8];
        NSData* secretKey = NULL;
        if ([[secKey keyID] isEqualToData:keyID]) {
            if ([secKey encryted]) {
                secretKey = [secKey decryptKeyWithPassphrase:passphrase];
            } else {
                secretKey = [parser getPEMFromSecretKeyPacket:(PGPSecretKeyPacket*)[secKey keyData]];
            }
        } else {
            for (int i = 0; i < [[secKey subKeys] count]; i++) {
                PGPKey* subKey = [[secKey subKeys] objectAtIndex:i];
                if ([[subKey keyID] isEqualToData:keyID]) {
                    if ([secKey encryted]) {
                        secretKey = [subKey decryptKeyWithPassphrase:passphrase];
                    } else {
                        secretKey = [parser getPEMFromSecretKeyPacket:(PGPSecretKeyPacket*)[subKey keyData]];
                    }
                    break;
                }
            }
        }

        if (secretKey == NULL) {
            return NULL;
        }

        NSData* decryptedSessionKey = CTOpenSSLRSADecrypt(secretKey, encSessionKey);
        if (decryptedSessionKey == NULL) {
            return NULL;
        }

        NSData* sessionKey = [NSData dataWithBytes:decryptedSessionKey.bytes+1 length:decryptedSessionKey.length-3];
        // Check checksum
        int checksum = ((unsigned char*)[decryptedSessionKey bytes])[[decryptedSessionKey length]-2] << 8 | ((unsigned char*)[decryptedSessionKey bytes])[[decryptedSessionKey length]-1];
        int valueToCheck = 0;
        for (int i = 0; i < [sessionKey length]; i++) {
            valueToCheck += ((unsigned char*)[sessionKey bytes])[i];
        }
        valueToCheck %= 65536;
        if (checksum != valueToCheck) {
            return NULL;
        }

        nextpos = [parser extractPacketsFromBytes:packets atPostion:nextpos];
        if (nextpos == -1) {
            return NULL;
        }
        NSData* decryptedData;
        if ([[parser getPacketsWithTag:9] count] > 0) {
            PGPSymmetricallyEncryptedDataPacket* encData = [[parser getPacketsWithTag:9] objectAtIndex:0];
            int algorithm = ((unsigned char*)[decryptedSessionKey bytes])[0];
            switch (algorithm) {
                case 9:
                    if (!CTOpenSSLSymmetricDecryptAES256CFB(sessionKey, [encData encryptedData], &decryptedData)) {
                        return NULL;
                    }
                    break;
                default:
                    // all other values are not supported yet
                    return NULL;
                    break;
            }
        } else if ([[parser getPacketsWithTag:18] count] > 0) {
            PGPSymmetricEncryptedIntegrityProtectedDataPacket* encData = [[parser getPacketsWithTag:18] objectAtIndex:0];
            int algorithm = ((unsigned char*)[decryptedSessionKey bytes])[0];
            switch (algorithm) {
                case 9:
                    if (!CTOpenSSLSymmetricDecryptAES256CFB(sessionKey, [encData encryptedData], &decryptedData)) {
                        return NULL;
                    }
                    break;
                default:
                    // all other values are not supported yet
                    return NULL;
                    break;
            }
            decryptedData = [encData checkPacketFromDecryptedData:decryptedData];
            if (decryptedData == NULL) {
                return NULL;
            }
        } else {
            return NULL;
        }
        memset((void*)[decryptedSessionKey bytes], 0, [decryptedSessionKey length]);
        memset((void*)[sessionKey bytes], 0, [sessionKey length]);
        nextpos = 0;
        if ([parser extractPacketsFromBytes:decryptedData atPostion:nextpos] == -1) {
            return NULL;
        }
        if ([[parser getPacketsWithTag:8] count] > 0) {
            PGPCompressedDataPacket* compressedDataPacket = [[parser getPacketsWithTag:8] objectAtIndex:0];
            NSData* plainData;
            switch ([compressedDataPacket algorithm]) {
                case 1:
                    // not supported yet
                    return NULL;
                    break;
                case 2:
                    plainData = [[compressedDataPacket compressedData] dataByGZipDecompressingDataWithWindowSize:32 error:NULL];
                    if ([parser extractPacketsFromBytes:plainData atPostion:nextpos] == -1) {
                        return NULL;
                    }
                    return [[[parser getPacketsWithTag:11] objectAtIndex:0] literalData];
                    break;
                case 3:
                    // not supported yet
                    return NULL;
                    break;
                default:
                    return NULL;
                    break;
            }
        } else if ([[parser getPacketsWithTag:11] count] > 0) {
            return [[[parser getPacketsWithTag:11] objectAtIndex:0] literalData];
        } else {
            return NULL;
        }
    } else if ([[parser getPacketsWithTag:8] count] > 0) {
        // Compressed Message
        PGPCompressedDataPacket* compressedDataPacket = [[parser getPacketsWithTag:8] objectAtIndex:0];
        NSData* plainData;
        switch ([compressedDataPacket algorithm]) {
            case 1:
                // not supported yet
                return NULL;
                break;
            case 2:
                plainData = [[compressedDataPacket compressedData] dataByGZipDecompressingDataWithWindowSize:32 error:NULL];
                if ([parser extractPacketsFromBytes:plainData atPostion:nextpos] == -1) {
                    return NULL;
                }
                return [[[parser getPacketsWithTag:11] objectAtIndex:0] literalData];
                break;
            case 3:
                // not supported yet
                return NULL;
                break;
            default:
                return NULL;
                break;
        }
    } else if ([[parser getPacketsWithTag:11] count] > 0) {
        // Literal Message
        return [[[parser getPacketsWithTag:11] objectAtIndex:0] literalData];
    } else {
        // Signed Message
        return NULL; // Not supported yet
    }
}

- (NSData*)buildPGPMessageFromData:(NSData*)data WithKey:(PGPKey*)key {
    PGPMessageBuilder* builder = [[PGPMessageBuilder alloc] init];
    PGPKey* keyToEncrypt;
    if ([[key subKeys] count] > 0) {
        keyToEncrypt = [[key subKeys] objectAtIndex:0];
    } else {
        keyToEncrypt = key;
    }
    PGPPacketParser* parser = [[PGPPacketParser alloc] init];
    PGPPublicKeyPacket* pubKey;
    if (keyToEncrypt.isPrivate) {
        pubKey = [((PGPSecretKeyPacket*)[keyToEncrypt keyData]) pubKey];
    } else {
        pubKey = (PGPPublicKeyPacket*)[keyToEncrypt keyData];
    }
    NSData* keyData = [parser getPEMFromPublicKeyPacket:pubKey];
    NSData* messageData = [builder buildPGPEncryptedMessageFromData:data withPGPPublicKey:keyData andPubKeyID:(unsigned char*)[[keyToEncrypt keyID] bytes]];
    NSData* messageChecksum = [builder getChecksumForPGPMessageData:messageData];
    return [builder buildArmouredPGPMessageFromMessageData:messageData andChecksum:messageChecksum];
}

@end


text:
/*
 * Example for a simple IO extension
 *
 * This program enables a master to use the A/D converter and PORTD
 * from extern.
 */

#include <xpcc/architecture/platform.hpp>
#include <xpcc/driver/connectivity/sab/slave.hpp>

// ----------------------------------------------------------------------------
// wrapper class for the A/D converter
class AnalogDigital : public xpcc::sab::Callable
{
public:
	AnalogDigital()
	{
		// initialize the analog to digital converter
		xpcc::atmega::Adc::initialize(
				xpcc::atmega::Adc::REFERENCE_INTERNAL_AVCC, xpcc::atmega::Adc::PRESCALER_64);
	}

	void
	readChannel(xpcc::sab::Response& response, const uint8_t *channel)
	{
		uint16_t value = xpcc::atmega::Adc::readChannel(*channel);
		response.send(value);
	}
};

// ----------------------------------------------------------------------------
// wrapper for PORTD
class InOut : public xpcc::sab::Callable
{
public:
	void
	setDirection(xpcc::sab::Response& response, const uint8_t *direction)
	{
		DDRD = *direction;

		// send a response without any attached data
		response.send();
	}

	void
	readInput(xpcc::sab::Response& response)
	{
		uint8_t value = PIND;
		response.send(value);
	}

	void
	setOutput(xpcc::sab::Response& response, const uint8_t *output)
	{
		PORTD = *output;
		response.send();
	}
};

// ----------------------------------------------------------------------------
// create instances from the wrapper classes
AnalogDigital analogDigital;
InOut inOut;

// ----------------------------------------------------------------------------
// create a list of all possible actions
FLASH_STORAGE(xpcc::sab::Action actionList[]) =
{
	SAB__ACTION( 'A', analogDigital,	AnalogDigital::readChannel,	1 ),
	SAB__ACTION( 'D', inOut,			InOut::setDirection,		1 ),
	SAB__ACTION( 'I', inOut,			InOut::readInput,			0 ),
	SAB__ACTION( 'O', inOut,			InOut::setOutput,			1 ),
};

// wrap the type definition inside a typedef to make the code more readable
typedef xpcc::sab::Slave< xpcc::sab::Interface< xpcc::atmega::BufferedUart0 > > Slave;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	// initialize ABP interface, set baudrate etc.
	Slave slave(0x02,
			xpcc::accessor::asFlash(actionList),
			sizeof(actionList) / sizeof(xpcc::sab::Action));

	// enable interrupts
	sei();

	while (1)
	{
		// decode received messages etc.
		slave.update();
	}
}


text:
require 'spec_helper'
require 'timecop'

describe GamesController do
  before :each do
    @current_user = create(:user)
    @current_user.stub(:account).and_return(@current_user_account = double('UserAccount', :credits => 100, :use_credit! => true))
    @ability = Object.new
    @ability.extend(CanCan::Ability)
    @ability.can(:manage, :all)
    controller.stub(:current_ability).and_return(@ability)
    controller.stub(:current_user).and_return(@current_user)
    controller.stub(:send_stats)
  end

  describe 'GET index' do
    def do_get_index
      get :index
    end

    it 'assigns all completed games as @games' do
      game = create(:won_game)
      do_get_index
      assigns(:games).should eq([game])
    end

    it 'assigns current game as @current_game' do
      game = create(:game, :user => @current_user)
      do_get_index
      assigns(:current_game).should eq(game)
    end

    it 'renders successfully' do
      do_get_index
      response.should be_success
    end
  end

  describe 'GET show' do
    before :each do
      @game = create(:game)
    end

    def do_get_show
      get :show, {:id => @game.to_param}
    end

    it 'assigns the requested game as @game' do
      do_get_show
      assigns(:game).should eq(@game)
    end

    it 'renders successfully' do
      do_get_show
      response.should be_success
    end
  end

  describe 'GET show_clue' do
    before :each do
      @game = create(:game)
    end

    it 'assigns the requested game as @game' do
      get :show_clue, {:id => @game.to_param}
      assigns(:game).should eq(@game)
    end

    it 'renders successfully' do
      get :show_clue, {:id => @game.to_param}
      response.should be_success
    end

    it 'redirects home if no credits left' do
      @current_user_account.stub(:credits).and_return(0)
      get :show_clue, {:id => @game.to_param}
      response.should redirect_to(root_path)
      flash[:alert].should_not be_blank
    end
  end

  describe 'POST reveal_clue' do
    before :each do
      @game = create(:game, user: @current_user)
    end

    def do_post_reveal_clue
      post :reveal_clue, {:id => @game.to_param}
    end

    it 'must show clue' do
      @current_user_account.stub(:credits).and_return(1)
      expect {
        do_post_reveal_clue
      }.to change { @game.reload; @game.clue_revealed }
    end

    it 'wont show clue' do
      @current_user_account.stub(:credits).and_return(0)
      do_post_reveal_clue
      response.should redirect_to(root_path)
      flash[:alert].should_not be_blank
    end

    it 'assigns the requested game as @game' do
      do_post_reveal_clue
      assigns(:game).should eq(@game)
    end

    it 'redirect to show' do
      do_post_reveal_clue
      response.should redirect_to(action: 'show')
    end
  end

  describe 'GET play_letter' do
    before :each do
      @game = create(:game, choices: 'a', user: @current_user)
    end

    def do_get_play_letter
      get :play_letter, :id => @game.to_param, :letter => 'g'
    end

    it 'assigns the requested game as @game' do
      do_get_play_letter
      assigns(:game).should eq(@game)
      @game.reload
      @game.choices.should include('g')
    end

    it 'render the show template' do
      do_get_play_letter
      response.should redirect_to(@game)
    end

    it 'render adds a flash message if rank increases' do
      create(:user, daily_rating: 1)
      @game = create(:game, word: 'game', choices: 'ame', user: @current_user)
      expect {
        do_get_play_letter
      }.to change { @current_user.reload; @current_user.daily_rating }
      flash[:notice].should_not be_blank
    end

    it 'Should not get Bookworm Badge if a 10 letter word won and used a clue' do
      @game = create(:game, word: 'television', choices: 'telviso', user: @current_user)
      get :show_clue, {:id => @game.to_param}
      post :reveal_clue, {:id => @game.to_param}
      Timecop.freeze(Time.current + 31.seconds)
      get :play_letter, :id => @game.to_param, :letter => 'n'
      flash[:notice].should_not have_content 'Congratulations'
    end

    it 'First 10 letter word won with no clue receives Bookworm Badge' do
      @game = create(:game, word: 'television', choices: 'telviso', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 'n'
      flash[:notice].should have_content 'Congratulations'
    end

    it 'Should not get Bookworm Badge for <9 letter word won' do
      @game = create(:game, word: 'airport', choices: 'airpo', user: @current_user)
      Timecop.freeze(Time.current + 31.seconds)
      get :play_letter, :id => @game.to_param, :letter => 't'
      flash[:notice].should_not have_content 'Congratulations'
    end

    it 'Should not receive Bookworm Badge twice' do
      create(:badge, name: 'Bookworm', user: @current_user)
      @game = create(:game, word: 'television', choices: 'telviso', user: @current_user)
      Timecop.freeze(Time.current + 31.seconds)
      get :play_letter, :id => @game.to_param, :letter => 'n'
      flash[:notice].should_not have_content 'Congratulations'
    end

    it 'Should give Clueless Badge if 5 clues where used' do
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      @game = create(:game, word: 'duck', choices: 'duc', clue_revealed: true, user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 'k'
      flash[:notice].should have_content 'Congratulations'
    end

    it 'Should not give Clueless Badge twice' do
      create(:badge, name: 'Clueless', user: @current_user)
      @game = create(:game, word: 'duck', choices: 'duc', clue_revealed: true, user: @current_user)
      Timecop.freeze(Time.current + 31.seconds)
      get :play_letter, :id => @game.to_param, :letter => 'k'
      flash[:notice].should_not have_content 'Congratulations'
    end

    it 'Should not give Clueless Badge if 5 clues were not used in a row' do
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      create(:won_game, word: 'duck', user: @current_user)
      create(:won_game, word: 'duck', clue_revealed: true, user: @current_user)
      @game = create(:game, word: 'duck', choices: 'duc', clue_revealed: true, user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 'k'
      flash[:notice].should_not have_content 'Congratulations'
    end

    it 'Should give Brainey Badge if 10 words were played in a row without using clues' do
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      @game = create(:game, word: 'meaow', choices: 'meao', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 'w'
      flash[:notice].should have_content 'Congratulations'
    end

    it 'Should not give the Brainey Badge twice' do
      create(:badge, name: 'Brainey', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      @game = create(:game, word: 'meaow', choices: 'meao', user: @current_user)
      Timecop.freeze(Time.current + 31.seconds)
      get :play_letter, :id => @game.to_param, :letter => 'w'
      flash[:notice].should_not have_content 'Congratulations'
      Timecop.return
    end

    it 'Should not give Brainey Badge if 10 words were played but clue used' do
      create(:badge, name: 'Brainey', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      create(:won_game, word: 'meaow', user: @current_user)
      @game = create(:game, word: 'meaow', choices: 'meao', user: @current_user)
      Timecop.freeze(Time.current + 31.seconds)
      get :play_letter, :id => @game.to_param, :letter => 'w'
      flash[:notice].should_not have_content 'Congratulations'
      Timecop.return
    end

    it 'Should give both badges' do
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      flash[:notice].should have_content 'Quickster'
      flash[:notice].should have_content 'Brainey'
    end

    it 'Should give Quickster Badge if game was won under 30s' do
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      flash[:notice].should have_content 'Congratulations'
    end

    it 'Should not give Quickster Badge if game a clue was used' do
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :show_clue, {:id => @game.to_param}
      post :reveal_clue, {:id => @game.to_param}
      get :play_letter, :id => @game.to_param, :letter => 't'
      flash[:notice].should_not have_content 'Congratulations'
    end

    it 'Should not give Quickster Badge if game was won over 30s' do
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      Timecop.freeze(Time.current + 31.seconds)
      get :play_letter, :id => @game.to_param, :letter => 't'
      flash[:notice].should_not have_content 'Congratulations'
      Timecop.return
    end

    it 'Should not give the Quickster Badge twice' do
      create(:badge, name: 'Quickster', user: @current_user)
      @game = create(:game, word: 'cattle', choices: 'cale', user: @current_user)
      get :play_letter, :id => @game.to_param, :letter => 't'
      flash[:notice].should_not have_content 'Congratulations'
    end
  end

  describe 'GET new' do
    def do_get_new
      get :new
    end

    it 'assigns a new game as @game' do
      do_get_new
      assigns(:game).should be_a_new(Game)
    end

    it 'must be successful' do
      do_get_new
      response.should be_success
    end

    it 'redirects to purchase_transaction_path if no more credits' do
      @current_user_account.stub(:credits).and_return(0)
      do_get_new
      response.should redirect_to(root_path)
      flash[:alert].should_not be_blank
    end
  end

  describe 'GET play' do
    def do_get_play
      get :play
    end

    it 'assigns redirects to new game path' do
      do_get_play
      response.should redirect_to(new_game_path)
    end

    it 'assigns redirects to current game path' do
      game = create(:game, user: @current_user)
      do_get_play
      response.should redirect_to(game)
    end
  end

# update the return value of this method accordingly.
  def valid_attributes
    {}
  end

  describe 'POST create' do
    def do_create
      post :create,
           :game => valid_attributes
    end

    describe 'with valid params' do
      it 'creates a new Game' do
        expect {
          do_create
        }.to change(Game, :count).by(1)
      end

      it 'reduces the users credits' do
        @current_user_account.should_receive(:use_credit!)
        do_create
      end

      it 'assigns a newly created game as @game' do
        do_create
        assigns(:game).should be_a(Game)
        assigns(:game).user.should be == @current_user
        assigns(:game).should be_persisted
      end

      it 'redirects to the created game' do
        do_create
        response.should redirect_to(Game.last)
      end
    end

    describe 'with invalid params' do
      before :each do
        # Trigger the behavior that occurs when invalid params are submitted
        Game.any_instance.stub(:save).and_return(false)
      end

      it 'assigns a newly created but unsaved game as @game' do
        do_create
        assigns(:game).should be_a_new(Game)
      end

      it 'redirects to index' do
        do_create
        response.should redirect_to(Game)
      end

      it 'sets an alert message' do
        do_create
        flash[:alert].should_not be_blank
      end
    end
  end
end


text:
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

import optparse
import httplib

#
# Main.
#
def main():
  parser = optparse.OptionParser(usage="usage: %prog [options] component ")
  parser.add_option("-m", "--hosts", dest="hosts", help="Comma separated hosts list for WEB UI to check it availability")
  parser.add_option("-p", "--port", dest="port", help="Port of WEB UI to check it availability")
  parser.add_option("-s", "--https", dest="https", help="\"True\" if value of dfs.http.policy is \"HTTPS_ONLY\"")

  (options, args) = parser.parse_args()

  hosts = options.hosts.split(',')
  port = options.port
  https = options.https

  for host in hosts:
    try:
      conn = httplib.HTTPConnection(host, port) if not https.lower() == "true" else httplib.HTTPSConnection(host, port)
      # This can be modified to get a partial url part to be sent with request
      conn.request("GET", "/")
      httpCode = conn.getresponse().status
      conn.close()
    except Exception:
      httpCode = 404

    if httpCode != 200:
      print "Cannot access WEB UI on: http://" + host + ":" + port if not https.lower() == "true" else "Cannot access WEB UI on: https://" + host + ":" + port
      exit(1)

if __name__ == "__main__":
  main()