text:
#!/usr/bin/env node

var Rx = require('rx');

/* Have staggering intervals */
var source1 = Rx.Observable.interval(140)
    .map(function (i) { return 'First: ' + i; });

var source2 = Rx.Observable.interval(50)
    .map(function (i) { return 'Second: ' + i; });

// When source1 emits a value, combine it with the latest emission from source2.
//
// First が発火したときに、古い中で最新の Second を拾う
var source = source1.withLatestFrom(
    source2,
    function (s1, s2) { return s1 + ', ' + s2; }
).take(4);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x.toString());
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

// => Next: First: 0, Second: 1 =>  First: 140ms, Second: 100ms
// => Next: First: 1, Second: 4 =>  First: 280ms, Second: 250ms
// => Next: First: 2, Second: 7
// => Next: First: 3, Second: 10
// => Completed


text:
namespace blink {

CSSParser::CSSParser(const CSSParserContext& context)
    : m_bisonParser(context)
{
}

bool CSSParser::parseDeclaration(MutableStylePropertySet* propertySet, const String& declaration, CSSParserObserver* observer, StyleSheetContents* styleSheet)
{
    // FIXME: Add inspector observer support in the new CSS parser
    if (!observer && RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseDeclaration(propertySet, declaration, m_bisonParser.m_context);
    return m_bisonParser.parseDeclaration(propertySet, declaration, observer, styleSheet);
}

void CSSParser::parseSelector(const String& selector, CSSSelectorList& selectorList)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled()) {
        Vector<CSSParserToken> tokens;
        CSSTokenizer::tokenize(selector, tokens);
        CSSSelectorParser::parseSelector(tokens, m_bisonParser.m_context, starAtom, nullptr, selectorList);
        return;
    }
    m_bisonParser.parseSelector(selector, selectorList);
}

PassRefPtrWillBeRawPtr<StyleRuleBase> CSSParser::parseRule(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& rule)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseRule(rule, context, CSSParserImpl::AllowImportRules);
    return BisonCSSParser(context).parseRule(styleSheet, rule);
}

void CSSParser::parseSheet(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& text, const TextPosition& startPosition, CSSParserObserver* observer, bool logErrors)
{
    // FIXME: Add inspector observer support in the new CSS parser
    if (!observer && RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseStyleSheet(text, context, styleSheet);
    BisonCSSParser(context).parseSheet(styleSheet, text, startPosition, observer, logErrors);
}

bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, CSSParserMode parserMode, StyleSheetContents* styleSheet)
{
    if (string.isEmpty())
        return false;
    if (parseFastPath(declaration, propertyID, string, important, parserMode))
        return true;
    CSSParserContext context(parserMode, 0);
    if (styleSheet) {
        context = styleSheet->parserContext();
        context.setMode(parserMode);
    }
    return parseValue(declaration, propertyID, string, important, context);
}

bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, const CSSParserContext& context)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseValue(declaration, propertyID, string, important, context);
    return BisonCSSParser::parseValue(declaration, propertyID, string, important, context);
}

bool CSSParser::parseFastPath(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, CSSParserMode parserMode)
{
    RefPtrWillBeRawPtr<CSSValue> value = CSSParserFastPaths::maybeParseValue(propertyID, string, parserMode);
    if (!value)
        return false;
    declaration->addParsedProperty(CSSProperty(propertyID, value.release(), important));
    return true;
}

PassRefPtrWillBeRawPtr<CSSValue> CSSParser::parseSingleValue(CSSPropertyID propertyID, const String& string, const CSSParserContext& context)
{
    if (string.isEmpty())
        return nullptr;
    RefPtrWillBeRawPtr<MutableStylePropertySet> stylePropertySet = MutableStylePropertySet::create();
    bool success = parseFastPath(stylePropertySet.get(), propertyID, string, false, context.mode())
        || parseValue(stylePropertySet.get(), propertyID, string, false, context);
    ASSERT_UNUSED(success, success == stylePropertySet->hasProperty(propertyID));
    return stylePropertySet->getPropertyCSSValue(propertyID);
}

PassRefPtrWillBeRawPtr<ImmutableStylePropertySet> CSSParser::parseInlineStyleDeclaration(const String& styleString, Element* element)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseInlineStyleDeclaration(styleString, element);
    return BisonCSSParser::parseInlineStyleDeclaration(styleString, element);
}

PassOwnPtr<Vector<double> > CSSParser::parseKeyframeKeyList(const String& keyList)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled())
        return CSSParserImpl::parseKeyframeKeyList(keyList);
    return BisonCSSParser(strictCSSParserContext()).parseKeyframeKeyList(keyList);
}

PassRefPtrWillBeRawPtr<StyleRuleKeyframe> CSSParser::parseKeyframeRule(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& rule)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled()) {
        RefPtrWillBeRawPtr<StyleRuleBase> keyframe = CSSParserImpl::parseRule(rule, context, CSSParserImpl::KeyframeRules);
        return toStyleRuleKeyframe(keyframe.get());
    }
    return BisonCSSParser(context).parseKeyframeRule(styleSheet, rule);
}

bool CSSParser::parseSupportsCondition(const String& condition)
{
    if (RuntimeEnabledFeatures::newCSSParserEnabled()) {
        Vector<CSSParserToken> tokens;
        CSSTokenizer::tokenize(condition, tokens);
        CSSParserImpl parser(strictCSSParserContext(), "");
        return CSSSupportsParser::supportsCondition(tokens, parser) == CSSSupportsParser::Supported;
    }
    return BisonCSSParser(CSSParserContext(HTMLStandardMode, 0)).parseSupportsCondition(condition);
}

bool CSSParser::parseColor(RGBA32& color, const String& string, bool strict)
{
    if (string.isEmpty())
        return false;

    // First try creating a color specified by name, rgba(), rgb() or "#" syntax.
    if (CSSPropertyParser::fastParseColor(color, string, strict))
        return true;

    // In case the fast-path parser didn't understand the color, try the full parser.
    RefPtrWillBeRawPtr<MutableStylePropertySet> stylePropertySet = MutableStylePropertySet::create();
    // FIXME: The old CSS parser is only working in strict mode ignoring the strict parameter.
    // It needs to be investigated why.
    if (!parseValue(stylePropertySet.get(), CSSPropertyColor, string, false, strictCSSParserContext()))
        return false;

    RefPtrWillBeRawPtr<CSSValue> value = stylePropertySet->getPropertyCSSValue(CSSPropertyColor);
    if (!value || !value->isPrimitiveValue())
        return false;

    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
    if (!primitiveValue->isRGBColor())
        return false;

    color = primitiveValue->getRGBA32Value();
    return true;
}

StyleColor CSSParser::colorFromRGBColorString(const String& string)
{
    // FIXME: Rework css parser so it is more SVG aware.
    RGBA32 color;
    if (parseColor(color, string.stripWhiteSpace()))
        return StyleColor(color);
    // FIXME: This branch catches the string currentColor, but we should error if we have an illegal color value.
    return StyleColor::currentColor();
}

bool CSSParser::parseSystemColor(RGBA32& color, const String& colorString)
{
    CSSParserString cssColor;
    cssColor.init(colorString);
    CSSValueID id = cssValueKeywordID(cssColor);
    if (!CSSPropertyParser::isSystemColor(id))
        return false;

    Color parsedColor = LayoutTheme::theme().systemColor(id);
    color = parsedColor.rgb();
    return true;
}

} // namespace blink

redpajama_set_name: RedPajamaGithub


text:
#include <Python.h>

typedef struct kinfo_proc kinfo_proc;

static char *psutil_get_cmd_args(long pid, size_t *argsize);
int psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount);
int psutil_kinfo_proc(const pid_t pid, struct kinfo_proc *proc);
int psutil_pid_exists(long pid);

//
PyObject* psutil_cpu_count_phys(PyObject* self, PyObject* args);
PyObject* psutil_disk_io_counters(PyObject* self, PyObject* args);
PyObject* psutil_get_cmdline(long pid);
PyObject* psutil_per_cpu_times(PyObject* self, PyObject* args);
PyObject* psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args);
PyObject* psutil_proc_cpu_affinity_set(PyObject* self, PyObject* args);
PyObject* psutil_proc_cwd(PyObject* self, PyObject* args);
PyObject* psutil_proc_exe(PyObject* self, PyObject* args);
PyObject* psutil_proc_memory_maps(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_fds(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_threads(PyObject* self, PyObject* args);
PyObject* psutil_proc_threads(PyObject* self, PyObject* args);
PyObject* psutil_swap_mem(PyObject* self, PyObject* args);
PyObject* psutil_virtual_mem(PyObject* self, PyObject* args);


text:
function copy(...args) {
  return Object.assign({}, ...args)
}

function keys(source) {
  return Object.keys(source)
}

function values(source) {
  let values = []
  keys(source).forEach(key => values.push(source[key]))
  return values
}

function iterator() {
  let _keys, _values
  if (this instanceof Bag) {
    _keys = this.keys, _values = this.values
  } else {
    _keys = keys(this), _values = values(this)
  }
  this[Symbol.iterator] = () => {
    return loop(_keys, _values)
  }
  return this
}

function loop(keys, values) {
  const length = keys.length
  let position = 0

  return {
    next: () => {
      return position < length ? {
        value: [keys[position], values[position++]],
        done: false
      } : {done: true}
    }
  }
}

/**
 * An alternative for Map to handle key-value data
 */
export default class Bag {
  /**
   * @param {?{}} [data={}] Initial object data
   */
  constructor(data = {}) {
    this.replace(data)
    iterator.apply(this)
  }

  /**
   * Return size (total items)
   * @returns {number}
   */
  size() {
    return this.length
  }

  /**
   * Return total items
   * @returns {number}
   */
  get length() {
    return this.keys.length
  }

  /**
   * Return all keys in Bag
   * @returns {Array}
   */
  get keys() {
    return keys(this._data)
  }

  /**
   * Return all values in Bag
   * @returns {Array}
   */
  get values() {
    return values(this._data)
  }

  /**
   * Replace the current data with new one
   * @param {?{}} [data={}] Data to replace
   */
  replace(data = {}) {
    this._data = copy(data)
  }

  /**
   * Determine whether or not a key exists in Bag
   * @param {!string} key
   * @returns {boolean}
   */
  has(key) {
    return !(typeof this._data[key] === "undefined")
  }

  /**
   * Get value of a pre-defined key
   * @param {!string} key
   * @param {?*} [def=null] Default value to return if key does not exist
   * @returns {*}
   */
  get(key, def = null) {
    return this.has(key) ? this._data[key] : def
  }

  /**
   * Set a key-value pair
   * @param {!string} key
   * @param {!*} value
   */
  set(key, value) {
    this._data[key] = value
  }

  /**
   * Remove a value by key
   * @param {!string} key
   */
  delete(key) {
    delete this._data[key]
  }

  /**
   * Return a cloned version of Bag data
   * @returns {{}}
   */
  all() {
    return copy(this._data)
  }

  /**
   * Get key-value pairs only for proposed keys
   * @param {!Array} keys An array of keys to get their's values
   * @returns {{}}
   */
  only(keys) {
    let items = {}
    keys.forEach(key => items[key] = this._data[key])
    return items
  }

  /**
   * Clear all data
   */
  clear() {
    this._data = {}
  }

  /**
   * Combine all key-value pairs into string with a proposed delimiter
   * @param {?Array} [keys=null] (Optional) only render key-value pairs which has key in this pre-defined keys
   * @param {?string} [delimiter="&"] Conjunction of string to connect key-value pairs
   * @returns {string}
   */
  toString(keys = null, delimiter = "&") {
    let data = [], string = ""

    if (Array.isArray(keys)) {
      data = this.only(keys)
    } else {
      data = copy(this._data)
    }

    Object.keys(data).forEach((key) => {
      string += (string === "" ? "" : delimiter) + `${key}=${data[key]}`
    })
    return string
  }

  /**
   * Loop through data with a callback
   * @param {function} callback A callback function to handle item,
   *                            it would receive 2 parameters (key, value) as the input
   * @param {?Object} target An object to become "this argument" (receiver) of the callback
   */
  forEach(callback, target) {
    this.keys.forEach((key) => {
      if (typeof target === "undefined") {
        callback(key, this._data[key])
      } else {
        callback.apply(target, [key, this._data[key]])
      }
    })
  }

  /**
   * Return an iterator to be looped through data of Bag
   * @param {?Array} keys (Optional) Only allow to loop pre-defined keys
   * @returns {function} Iterator function to be used as for..of
   */
  entries(keys) {
    return iterator.apply(typeof keys === "undefined" ? this : this.only(keys))
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Pdelvo.Minecraft.Proxy.Library
{
    /// <summary>
    ///   Provide functionality to work with custom attributes. This is needed because the extension methods in the framework are not implemented in mono.
    /// </summary>
    public static class AttributeExtensions
    {
        /// <summary>
        ///   Get a collection of attributes of a given type in a given assembly
        /// </summary>
        /// <typeparam name="T"> The type of the attribute </typeparam>
        /// <param name="assembly"> The assembly </param>
        /// <param name="inherit"> True if this method should also return derived types, otherwise false </param>
        /// <returns> A collection of attributes </returns>
        public static IEnumerable<T> GetAttributes<T>(this Assembly assembly, bool inherit = true) where T : Attribute
        {
            object[] attributes = assembly.GetCustomAttributes(typeof (T), inherit);

            return attributes.Select(m => (T) m);
        }
    }
}


text:
package com.springcloud.myapp.employee.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Version;

@Entity
public class Position {

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((description == null) ? 0 : description.hashCode());
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    result = prime * result + ((version == null) ? 0 : version.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Position other = (Position) obj;
    if (description == null) {
      if (other.description != null)
        return false;
    } else if (!description.equals(other.description))
      return false;
    if (id == null) {
      if (other.id != null)
        return false;
    } else if (!id.equals(other.id))
      return false;
    if (version == null) {
      if (other.version != null)
        return false;
    } else if (!version.equals(other.version))
      return false;
    return true;
  }

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @Version
  private Integer version;

  private String description;

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public Integer getVersion() {
    return version;
  }

  public void setVersion(Integer version) {
    this.version = version;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }
}


text:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Threading;
using Microsoft.ApplicationServer.Http.Dispatcher;

namespace WebApiHaack
{
    public class AuthOperationHandler : HttpOperationHandler<HttpRequestMessage, HttpRequestMessage>
    {
        readonly RequireAuthorizationAttribute _authorizeAttribute;

        public AuthOperationHandler(RequireAuthorizationAttribute authorizeAttribute)
            : base("response")
        {
            _authorizeAttribute = authorizeAttribute;
        }

        protected override HttpRequestMessage OnHandle(HttpRequestMessage input)
        {
            IPrincipal user = Thread.CurrentPrincipal;
            if (!user.Identity.IsAuthenticated)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            if (_authorizeAttribute.Roles == null)
            {
                return input;
            }

            var roles = _authorizeAttribute.Roles.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            if (roles.Any(user.IsInRole))
            {
                return input;
            }

            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
    }
}


text:
var mergeTrees         = require('broccoli-merge-trees');
var writeFile          = require('broccoli-file-creator');

var filterInitializers = require('../broccoli/filter-initializers');
var FastBootConfig     = require('../models/fastboot-config');
var fastbootAppModule  = require('../utilities/fastboot-app-module');

var CONFIG = {
  APP: { autoboot: false }
};

module.exports = {
  ////////////////////////////////
  // EMBER ADDON HOOKS
  //

  /**
   * Augments the applications configuration settings. The object returned from
   * this hook is merged with the application's configuration object.
   * Application's configuration always take precedence.
   */
  config: function() {
    return CONFIG;
  },

  /**
   * After the entire Broccoli tree has been built for the `dist` directory,
   * adds the `fastboot-config.json` file to the root.
   */
  postprocessTree: function(type, tree) {
    if (type === 'all') {
      var configTree = this.treeForFastBootConfig();
      tree = mergeTrees([tree, configTree]);
    }

    return tree;
  },

  /**
   * Filters out initializers and instance initializers that should only run in
   * browser mode.
   */
  treeForApp: function(tree) {
    return filterInitializers(tree, 'browser');
  },

  /**
   * Inserts placeholders into index.html that are used by the FastBoot server
   * to insert the rendered content into the right spot. Also injects a module
   * for FastBoot application boot.
   */
  contentFor: function(type, config) {
    if (type === 'body') {
      return "<!-- EMBER_CLI_FASTBOOT_BODY -->";
    }

    if (type === 'head') {
      return "<!-- EMBER_CLI_FASTBOOT_TITLE -->";
    }

    if (type === 'app-boot') {
      return fastbootAppModule(config.modulePrefix);
    }
  },

  ///////////////////////////////
  // METHODS
  //

  treeForFastBootConfig: function() {
    var config = new FastBootConfig(this.project);
    return writeFile('fastboot-config.json', config.toJSONString());
  }

};


text:
angular.module('loseYourWayServer.services', ['ngResource'])

.factory('Routes', ['$resource', function($resource){
    return $resource('/routes/:id', null, {
        'update': { method:'PUT' }
    });
}])
.factory('RouteResults', ['$resource', function($resource){
    return $resource('/routeresults/:id', null, {
        'update': { method:'PUT' }
    });
}]);


text:
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Compute.Automation
{
    [Cmdlet(VerbsCommon.Set, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DiskUpdateDiskEncryptionKey", SupportsShouldProcess = true)]
    [OutputType(typeof(PSDiskUpdate))]
    public partial class SetAzureRmDiskUpdateDiskEncryptionKeyCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
    {
        [Parameter(
            Mandatory = true,
            Position = 0,
            ValueFromPipeline = true,
            ValueFromPipelineByPropertyName = true)]
        public PSDiskUpdate DiskUpdate { get; set; }

        [Parameter(
            Mandatory = false,
            Position = 1,
            ValueFromPipelineByPropertyName = true)]
        public string SecretUrl { get; set; }

        [Parameter(
            Mandatory = false,
            Position = 2,
            ValueFromPipelineByPropertyName = true)]
        public string SourceVaultId { get; set; }

        protected override void ProcessRecord()
        {
            if (ShouldProcess("DiskUpdate", "Set"))
            {
                Run();
            }
        }

        private void Run()
        {
            if (this.MyInvocation.BoundParameters.ContainsKey("SecretUrl"))
            {
                // EncryptionSettings
                if (this.DiskUpdate.EncryptionSettings == null)
                {
                    this.DiskUpdate.EncryptionSettings = new EncryptionSettings();
                }
                // DiskEncryptionKey
                if (this.DiskUpdate.EncryptionSettings.DiskEncryptionKey == null)
                {
                    this.DiskUpdate.EncryptionSettings.DiskEncryptionKey = new KeyVaultAndSecretReference();
                }
                this.DiskUpdate.EncryptionSettings.DiskEncryptionKey.SecretUrl = this.SecretUrl;
            }

            if (this.MyInvocation.BoundParameters.ContainsKey("SourceVaultId"))
            {
                // EncryptionSettings
                if (this.DiskUpdate.EncryptionSettings == null)
                {
                    this.DiskUpdate.EncryptionSettings = new EncryptionSettings();
                }
                // DiskEncryptionKey
                if (this.DiskUpdate.EncryptionSettings.DiskEncryptionKey == null)
                {
                    this.DiskUpdate.EncryptionSettings.DiskEncryptionKey = new KeyVaultAndSecretReference();
                }
                // SourceVault
                if (this.DiskUpdate.EncryptionSettings.DiskEncryptionKey.SourceVault == null)
                {
                    this.DiskUpdate.EncryptionSettings.DiskEncryptionKey.SourceVault = new SourceVault();
                }
                this.DiskUpdate.EncryptionSettings.DiskEncryptionKey.SourceVault.Id = this.SourceVaultId;
            }

            WriteObject(this.DiskUpdate);
        }
    }
}


text:
// ============================================
// The header file define the missile module
// Fall 2016 Gatech ECE2035
//=============================================

/** @file missile_public.h */

#ifndef MISSILE_PUBLIC_H
#define MISSILE_PUBLIC_H

#include <stdint.h>
#include "doubly_linked_list.h"

/**
 * @enum    MISSILE_STATUS
 * @brief   An enum that describes the state of a missile.
 */

typedef enum {

    MISSILE_EXPLODED    = 0,
    MISSILE_ACTIVE      = 1

} MISSILE_STATUS;

/**
 * @struct  MISSILE
 * @brief   The structure to store the information of a missile
 */
typedef struct {

    int x;                   ///< The x-coordinate of missile current position
    int y;                   ///< The y-coordinate of missile current position

    double source_x;           ///< The x-coordinate of the missile's origin
    double target_x;           ///< The x-coordinate of the missile's target

    int tick;                  ///< The missile's internal tick

    MISSILE_STATUS status;   ///< The missile status, see MISSILE_STATUS

} MISSILE;

/**
 * missile_init
 *
 * @description         Call missile_init() only once at the begining of your code
 */

void missile_init(void);

/**
 * missile_generator
 *
 * @description         This function draw the missiles onto the screen
 *                      Call missile_generator() repeatedly in your game-loop. ex: main()
 */

void missile_generator(void);

/**
 * get_missile_list
 *
 * @description         This function will return a linked-list of all active MISSILE structures.
 *                      This can be used to modify the active missiles. Marking missiles with status
 *                      MISSILE_EXPLODED will cue their erasure from the screen and removal from the
 *                      list at the next missile_generator() call.
 *
 * @return              A linked list (DLinkedList *) with all the missiles.
 */

DLinkedList* get_missile_list();

/**
 * set_missile_speed
 *
 * @description     Set the speed of missiles, Speed has range of 1-8 with 1 being fastest and 8 being slowest
 * @param   speed   The speed of the missiles.
 */

void set_missile_speed(int speed);

/**
 * set_missile_interval
 *
 * @description         Set the interval that the missiles fire, interval has range of 1-100 with 1 being fired in
 *                      very quick succession and 100 being fired very slowly after one another.
 * @param   interval    An integer describing how frequently the missiles should be generated.
 */

void set_missile_interval(int interval);

/**
 * getMissilesThisLevel
 *
 * @brief   Return the number of missiles that have been drawn this level.
 * @return  The number of missiles.
 */

uint32_t getMissilesThisLevel();

/**
 * setContinueToDrawMissiles
 *
 * @brief                       Set a boolean determining whether missiles should be drawn.
 * @param   shouldDrawMissiles  A boolean determining whether missiles should be drawn.
 */

void setContinueToDrawMissiles(bool shouldDrawMissiles);

#endif //MISSILE_PUBLIC_H


text:
#ifndef NTRP_EVAL_CODEGENERATOR_H
#error Do not include this file. This is used internaly by CodeGenerator.h
#endif

/**
 * @file CodeGenerator-Impl.h Implementation of eval::CodeGenerator
 */

#include "eval/util/InstructionPrinter.h"
#include "util/log.h"

#include <boost/log/attributes/named_scope.hpp>

//#include <algebra/BigInteger.h>
//#include <algebra/BigIntegerUtils.h>

namespace eval {
/*
template <typename F, int T> class Operation;
enum {SUM, PRODUCT};

template <typename F>
class Operation<F, SUM> {
public:
  static F identity() { return 0; }
  static bool isIdentity(const F& val) { return F.isZero(); }
  static typename eval::Instruction<F>::Type getLongInstruction(bool isPositive) {
    return isPositive?eval::Instruction<F>::Type::ADD
                     :eval::Instruction<F>::Type::SUB;
  }
  static typename eval::Instruction<F>::Type getAccumulateConstantInstruction() {
    return eval::Instruction<F>::Type::ADDC;
  }
  static void accumulate(F& sum, bool isPositive, F& val) {
    sum += isPositive?val:-val;
  }
};

template <typename F, typename Op, typename T>
class Processor {
public:
void operator()(CodeGenerator<F>& cg, T v, int& resultLocation_, F& resultValue_) {
  int nTerms = v.getNumberOfNodes();
  BOOST_SCOPED_LOG_CTX(LTRC_) << "Generating code for Sum " << nTerms << " terms...";
  int sumLocation = -1; // undefined, location where this sum will be stored
  int firstTermLocation = -1; // Location of first sum term
  F sumValue = Op::identity();  // Accumulation of constants
  eval::Instruction<F>::Type instrType;

  for (int i = 0; i < nTerms; ++i) {
    v.getNode(i).accept(cg); // generate code for this term
    // If result was a constant, just accumulate
    if (resultLocation_ < 0) {
      Op::accumulate(sumValue, v.isPos(i), this->resultValue_)
      continue;
    }
    // Establish sum location
    if (sumLocation < 0) { // If sum location is not set
      if (firstTermLocation >= 0) {
        if (cg.alloc.isTemporaryLocation(firstTermLocation)) {
          sumLocation = firstTermLocation;
        } else {
          sumLocation = this->alloc.reserveLocation();
          std::stringstream oss; oss << "_t" << sumLocation;
          annPtr_->setDataName(sumLocation, oss.str());

          instrType = Op::getLongInstruction(v.isPos(i));
          codePtr_->push_back(eval::Instruction<F>(
            instrType, firstTermLocation, this->resultLocation_, sumLocation));
          LDBG_ << codePtr_->back();
          continue;
        }
      } else {
        firstTermLocation = this->resultLocation_;
        continue;
      }
    }
    // It is not a constant and sum location is set
    if (i < nTerms-1) { // If this is not the last term
      instrType = Op::getSortInstruction(v.isPos(i));
      codePtr_->push_back(eval::Instruction<F>(
        instrType, this->resultLocation_, 0, sumLocation));
    } else {
      instrType = Op::getLongInstruction(v.isPos(i));
      codePtr_->push_back(eval::Instruction<F>(
        instrType, sumLocation, this->resultLocation_, sumLocation));
    }
    LDBG_ << codePtr_->back();
    // Release previous result location if it is temporary as it is no longer needed
    if (this->alloc.isTemporaryLocation(this->resultLocation_)) {
      this->alloc.releaseLocation(this->resultLocation_);
    }
  }
  // Once we passed though all sum terms, we have 3 cases
  //  1. only contant(s) have been encountered (sumlocation < 0 && firstTermLocation < 0)
  //     - nothing todo just propogate the constant
  //  2. there was only one non-constant with possibly a accumulated constant
  //     (sumlocation < 0 && firstTermLocation >=0)
  //     - add constant if exist otherwise propogate
  //  3. there was at least few terms in the sum (sumlocation >= 0)
  //     - return sumLocation (after adding in a constant)

  if (sumLocation < 0) {
    if (firstTermLocation < 0) { // case 1
      this->resultValue_ = sumValue;  // Only set resultValue as constant
      this->resultLocation_ = -1;
    } else { // case 2
      if (!Op::isIdentity(sumValue)) {
        if (this->alloc.isTemporaryLocation(firstTermLocation)) {
          sumLocation = firstTermLocation;
        } else {
          sumLocation = this->alloc.reserveLocation();
          std::stringstream oss; oss << "_t" << sumLocation;
          annPtr_->setDataName(sumLocation, oss.str());
        }
        codePtr_->push_back(eval::Instruction<F>(
          Op::getAccumulateConstantInstruction(), firstTermLocation, sumValue, sumLocation));
        LDBG_ << codePtr_->back();
      } else {
        sumLocation = firstTermLocation;
      }
      this->resultLocation_ = sumLocation;
    }
  } else { // case 3, nothing to do except perhaps add in accumulated constant if any
    if (!sumValue.isZero()) {
      codePtr_->push_back(eval::Instruction<F>(
        Op::getAccumulateConstantInstruction(), sumLocation, sumValue, sumLocation));
      LDBG_ << codePtr_->back();
    }
    resultLocation_ = sumLocation;
  }
}
};

template <typename F>
void CodeGenerator<F>::process(const context::Sum& v) {
  eval::Processor<typename F, Operation<F, SUM>, const context::Sum&> process;
  process(*this, v, this->resultLocation_, this->resultValue_);
}

template <typename F>
void CodeGenerator<F>::process(const context::Product& v) {
  eval::Processor<F, Operation<F, PRODUCT>, const context::Product&> process;
  process(*this, v, this->resultLocation_, this->resultValue_);
}
*/

template <typename F>
void CodeGenerator<F>::process(const context::Sum& v) {
  int nTerms = v.getNumberOfNodes();
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Sum " << nTerms << " terms...";
  int sumLocation = -1; // undefined, location where this sum will be stored
  int firstTermLocation = -1; // Location of first sum term
  F sumValue(0);  // Accumulation of constants
  eval::InstructionEnum instrType;

  for (int i = 0; i < nTerms; ++i) {
    v.getNode(i).accept(*this); // generate code for this term
    // If result was a constant, just accumulate
    if (resultLocation_ < 0) {
      sumValue += v.isPos(i)?this->resultValue_:-this->resultValue_;
      continue;
    }
    // Establish sum location
    if (sumLocation < 0) { // If sum location is not set
      if (firstTermLocation >= 0) {
        if (this->alloc.isTemporaryLocation(firstTermLocation)) {
          sumLocation = firstTermLocation;
        } else {
          sumLocation = this->alloc.reserveLocation();
          std::stringstream oss; oss << "_t" << sumLocation;
          annPtr_->setDataName(sumLocation, oss.str());
          instrType = v.isPos(i)?eval::InstructionEnum::ADD
                                :eval::InstructionEnum::SUB;
          codePtr_->push_back(eval::Instruction<F>(
            instrType, firstTermLocation, this->resultLocation_, sumLocation));
          LDBG_ << codePtr_->back();
          continue;
        }
      } else {
        firstTermLocation = this->resultLocation_;
        continue;
      }
    }
    // It is not a constant and sum location is set
    if (i < nTerms-1) { // If this is not the last term
      instrType = v.isPos(i)?eval::InstructionEnum::ADDTO
                            :eval::InstructionEnum::SUBFROM;
      codePtr_->push_back(eval::Instruction<F>(
        instrType, this->resultLocation_, 0, sumLocation));
    } else {
      instrType = v.isPos(i)?eval::InstructionEnum::ADD
                            :eval::InstructionEnum::SUB;
      codePtr_->push_back(eval::Instruction<F>(
        instrType, sumLocation, this->resultLocation_, sumLocation));
    }
    LDBG_ << codePtr_->back();
    // Release previous result location if it is temporary as it is no longer needed
    if (this->alloc.isTemporaryLocation(this->resultLocation_)) {
      this->alloc.releaseLocation(this->resultLocation_);
    }
  }
  // Once we passed though all sum terms, we have 3 cases
  //  1. only contant(s) have been encountered (sumlocation < 0 && firstTermLocation < 0)
  //     - nothing todo just propogate the constant
  //  2. there was only one non-constant with possibly a accumulated constant
  //     (sumlocation < 0 && firstTermLocation >=0)
  //     - add constant if exist otherwise propogate
  //  3. there was at least few terms in the sum (sumlocation >= 0)
  //     - return sumLocation (after adding in a constant)

  if (sumLocation < 0) {
    if (firstTermLocation < 0) { // case 1
      this->resultValue_ = sumValue;  // Only set resultValue as constant
      this->resultLocation_ = -1;
    } else { // case 2
      if (!sumValue.template is<0>()) {
        if (this->alloc.isTemporaryLocation(firstTermLocation)) {
          sumLocation = firstTermLocation;
        } else {
          sumLocation = this->alloc.reserveLocation();
          std::stringstream oss; oss << "_t" << sumLocation;
          annPtr_->setDataName(sumLocation, oss.str());
        }
        codePtr_->push_back(eval::Instruction<F>(
          eval::InstructionEnum::ADDC, firstTermLocation, sumValue, sumLocation));
        LDBG_ << codePtr_->back();
      } else {
        sumLocation = firstTermLocation;
      }
      this->resultLocation_ = sumLocation;
    }
  } else { // case 3, nothing to do except perhaps add in accumulated constant if any
    if (!sumValue.template is<0>()) {
      codePtr_->push_back(eval::Instruction<F>(
        eval::InstructionEnum::ADDC, sumLocation, sumValue, sumLocation));
      LDBG_ << codePtr_->back();
    }
    resultLocation_ = sumLocation;
  }
}

template <typename F>
void CodeGenerator<F>::process(const context::Product& v) {
  int nTerms = v.getNumberOfNodes();
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Product " << nTerms << " terms...";
  int sumLocation = -1; // undefined, location where this sum will be stored
  int firstTermLocation = -1; // Location of first sum term
  F sumValue(1);  // Accumulation of constants
  eval::InstructionEnum instrType;

  for (int i = 0; i < nTerms; ++i) {
    v.getNode(i).accept(*this); // generate code for this term
    // If result was a constant, just accumulate
    if (resultLocation_ < 0) {
      sumValue *= v.isPos(i)?this->resultValue_:this->resultValue_.getInverse();
      continue;
    }
    // Establish sum location
    if (sumLocation < 0) { // If sum location is not set
      if (firstTermLocation >= 0) {
        if (this->alloc.isTemporaryLocation(firstTermLocation)) {
          sumLocation = firstTermLocation;
        } else {
          sumLocation = this->alloc.reserveLocation();
          std::stringstream oss; oss << "_t" << sumLocation;
          annPtr_->setDataName(sumLocation, oss.str());
          instrType = v.isPos(i)?eval::InstructionEnum::MUL
                                :eval::InstructionEnum::DIV;
          codePtr_->push_back(eval::Instruction<F>(
            instrType, firstTermLocation, this->resultLocation_, sumLocation));
          LDBG_ << codePtr_->back();
          continue;
        }
      } else {
        firstTermLocation = this->resultLocation_;
        continue;
      }
    }
    // It is not a constant and sum location is set
    if (i < nTerms-1) { // If this is not the last term
      instrType = v.isPos(i)?eval::InstructionEnum::MULBY
                            :eval::InstructionEnum::DIVBY;
      codePtr_->push_back(eval::Instruction<F>(
        instrType, this->resultLocation_, 0, sumLocation));
    } else {
      instrType = v.isPos(i)?eval::InstructionEnum::MUL
                            :eval::InstructionEnum::DIV;
      codePtr_->push_back(eval::Instruction<F>(
        instrType, sumLocation, this->resultLocation_, sumLocation));
    }
    LDBG_ << codePtr_->back();
    // Release previous result location if it is temporary as it is no longer needed
    if (this->alloc.isTemporaryLocation(this->resultLocation_)) {
      this->alloc.releaseLocation(this->resultLocation_);
    }
  }
  // Once we passed though all sum terms, we have 3 cases
  //  1. only contant(s) have been encountered (sumlocation < 0 && firstTermLocation < 0)
  //     - nothing todo just propogate the constant
  //  2. there was only one non-constant with possibly a accumulated constant
  //     (sumlocation < 0 && firstTermLocation >=0)
  //     - add constant if exist otherwise propogate
  //  3. there was at least few terms in the sum (sumlocation >= 0)
  //     - return sumLocation (after adding in a constant)

  if (sumLocation < 0) {
    if (firstTermLocation < 0) { // case 1
      this->resultValue_ = sumValue;  // Only set resultValue as constant
      this->resultLocation_ = -1;
    } else { // case 2
      if (!sumValue.template is<1>()) {
        if (this->alloc.isTemporaryLocation(firstTermLocation)) {
          sumLocation = firstTermLocation;
        } else {
          sumLocation = this->alloc.reserveLocation();
          std::stringstream oss; oss << "_t" << sumLocation;
          annPtr_->setDataName(sumLocation, oss.str());
        }
        codePtr_->push_back(eval::Instruction<F>(
          eval::InstructionEnum::MULC, firstTermLocation, sumValue, sumLocation));
        LDBG_ << codePtr_->back();
      } else {
        sumLocation = firstTermLocation;
      }
      this->resultLocation_ = sumLocation;
    }
  } else { // case 3, nothing to do except perhaps add in accumulated constant if any
    if (!sumValue.template is<1>()) {
      codePtr_->push_back(eval::Instruction<F>(
        eval::InstructionEnum::MULC, sumLocation, sumValue, sumLocation));
      LDBG_ << codePtr_->back();
    }
    resultLocation_ = sumLocation;
  }
}

/*

template <typename F>
void CodeGenerator<F>::process(const context::Sum& v) {
  // TODO: need to be refactored
  int nTerms = v.getNumberOfNodes();
  BOOST_SCOPED_LOG_CTX(LTRC_) << "Generating code for Sum " << nTerms << " terms...";

  int sumLocation = -1; // undefined, location where this sum will be stored
  int firstTermLocation = -1; // Location of first sum term
  F sumValue = 0;  // Accumulation of constants
  for (int i = 0; i < nTerms; ++i) {
    v.getNode(i).accept(*this); // generate code for this term
    if (resultLocation_ < 0) { // If result was a constant
      if (v.isPos(i)) {
        sumValue += resultValue_;
      } else {
        sumValue -= resultValue_;
      }
    } else { // Result is not a constant
      if (sumLocation >= 0) { // If sum location already determined
        if (i < nTerms-1) { // If this is not the last term
          if (v.isPos(i)) {
            LDBG_ << "ADDTO   " << sumLocation << ", "  << this->resultLocation_;
            codePtr_->push_back(eval::Instruction<F>(
              eval::Instruction<F>::Type::ADDTO, this->resultLocation_, 0, sumLocation));
          } else {
            LDBG_ << "SUBFROM " << sumLocation << ", "  << this->resultLocation_;
            codePtr_->push_back(eval::Instruction<F>(
              eval::Instruction<F>::Type::SUBFROM, this->resultLocation_, 0, sumLocation));
          }
        } else { // This is last term of the sum
          if (v.isPos(i)) {
            LDBG_ << "ADD   " << sumLocation << ", "  << sumLocation << ", " << resultLocation_;
            codePtr_->push_back(eval::Instruction<F>(
              eval::Instruction<F>::Type::ADD, this->resultLocation_, sumLocation, sumLocation));
          } else {
            LDBG_ << "SUB   " << sumLocation << ", "  << sumLocation << ", " << resultLocation_;
            codePtr_->push_back(eval::Instruction<F>(
              eval::Instruction<F>::Type::SUB, sumLocation, this->resultLocation_, sumLocation));
          }
        }
        if (this->alloc.isTemporaryLocation(this->resultLocation_)) {
          this->alloc.releaseLocation(this->resultLocation_);
        }
      } else { // very first non constant term
        if (firstTermLocation >= 0) {
          if (this->alloc.isTemporaryLocation(firstTermLocation)) {
            sumLocation = firstTermLocation;
            if (i < nTerms-1) { // If this is not the last term
              if (v.isPos(i)) {
                LDBG_ << "ADDTO  " << sumLocation << ", "  << this->resultLocation_;
                codePtr_->push_back(eval::Instruction<F>(
                  eval::Instruction<F>::Type::ADDTO, this->resultLocation_, 0, sumLocation));
              } else {
                LDBG_ << "SUBFROM " << sumLocation << ", "  << this->resultLocation_;
                codePtr_->push_back(eval::Instruction<F>(
                  eval::Instruction<F>::Type::SUBFROM, this->resultLocation_, 0, sumLocation));
              }
            } else {
              if (v.isPos(i)) {
                LDBG_ << "ADD   " << sumLocation << ", "  << sumLocation << ", " << resultLocation_;
                codePtr_->push_back(eval::Instruction<F>(
                  eval::Instruction<F>::Type::ADD, this->resultLocation_, sumLocation, sumLocation));
              } else {
                LDBG_ << "SUB   " << sumLocation << ", "  << sumLocation << ", " << resultLocation_;
                codePtr_->push_back(eval::Instruction<F>(
                  eval::Instruction<F>::Type::SUB, sumLocation, this->resultLocation_, sumLocation));
              }
            }
          } else {
            sumLocation = this->alloc.reserveLocation();
            std::stringstream oss; oss << "_t" << sumLocation;
            annPtr_->setDataName(sumLocation, oss.str());
            if (v.isPos(i)) {
              LDBG_ << "ADD  " << sumLocation << ", "  << firstTermLocation << ", " << this->resultLocation_;
              codePtr_->push_back(eval::Instruction<F>(
                eval::Instruction<F>::Type::ADD, this->resultLocation_, firstTermLocation, sumLocation));
            } else {
              LDBG_ << "SUB   " << sumLocation << ", "  << sumLocation << ", " << resultLocation_;
              codePtr_->push_back(eval::Instruction<F>(
                eval::Instruction<F>::Type::SUB, sumLocation, this->resultLocation_, sumLocation));
            }
          }
          if (this->alloc.isTemporaryLocation(this->resultLocation_)) {
            this->alloc.releaseLocation(this->resultLocation_);
          }
        } else {
          firstTermLocation = this->resultLocation_;
        }
      }
    }
  }
  if (sumLocation >= 0) { // and there was non-constant term
      if (!sumValue.isZero()) {
        LDBG_ << "ADDC  " << sumLocation << ", " << sumLocation << ", F(" << sumValue << ")";
        codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::ADDC, sumLocation, sumValue, sumLocation));
      }
  }  else {
    if (firstTermLocation >= 0) {  // But there was non-const term
      if (!sumValue.isZero()) {
          if (this->alloc.isTemporaryLocation(firstTermLocation)) {
            sumLocation = firstTermLocation;
            LDBG_ << "ADDC  " << sumLocation << ", " << sumLocation << ", F(" << sumValue << ")";
            codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::ADDC, sumLocation, sumValue, sumLocation));
          } else {
            sumLocation = this->alloc.reserveLocation();
            std::stringstream oss; oss << "_t" << sumLocation;
            annPtr_->setDataName(sumLocation, oss.str());

            LDBG_ << "ADDC  " << sumLocation << ", "  << firstTermLocation << ", F(" << sumValue << ")";
            codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::ADDC, firstTermLocation, sumValue, sumLocation));
          }
      } else {
        sumLocation = firstTermLocation;
      }
    }
  }
  resultLocation_ = sumLocation;
  if (resultLocation_ > 0) { // New temporary location was used
  } else {
    resultValue_ = sumValue;
  }
}
*/

template <typename F>
void CodeGenerator<F>::process(const context::Assignment& v) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Assignment to '"
    << v.getId() << "' (" << cntxPtr_->getIdIndex(v.getId()) << ")";

  v.getValue().accept(*this);  // Process right hand side first.

  // Get last instruction produced by rhs.
  if (!codePtr_ || (codePtr_->size() == 0)) {
    const char* err = "Unexpected null or empty code array while generating code for assignment";
    LERR_ << err;
    throw std::runtime_error(err);
  }
  // Get index of a variable to assign to.
  int idxDest = this->cntxPtr_->getIdIndex(v.getId());
  if (resultLocation_ < 0) {  // Result is just a constant.
    codePtr_->push_back(eval::Instruction<F>(
        eval::InstructionEnum::SET, 0, resultValue_,idxDest));
  } else if (!this->alloc.isTemporaryLocation(resultLocation_)) {
      //resultLocation_ != currDataSize_-1) {
    codePtr_->push_back(eval::Instruction<F>(
        eval::InstructionEnum::COPY, resultLocation_, 0, idxDest));
  } else { // Temporary location, modify last instruction
    eval::Instruction<F>& last = codePtr_->back();
    // Change destination of last instruction to it.
    last.setDestination(idxDest);
    // Anotate destination location with a name.
    annPtr_->setDataName(idxDest, v.getId());
  }
}

template <typename F>
void CodeGenerator<F>::process(const context::Determinant& v) {
  const context::Matrix& mtx = v.getMatrix();

  int nRows = mtx.getNRows();
  int nCols = mtx.getNCols();

  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Determinant of matrix "
    << mtx.getName() << " " << nRows << "x" << nCols;
  //int size2 = math::intlog(nRows);

  // Reserve memmory locations for this matrix
  int matrixStart = this->alloc.reserveLocation(
      nRows * nCols /* 1 << (size2 << 1) */, false /* non-temporary */);

  //std::vector<std::pair<int,int> > zeroes;
  //int prevZeroLocation = -1;
  codePtr_->push_back(eval::Instruction<F>(
    eval::InstructionEnum::SETM, nRows*nCols, F(0), matrixStart));

  LDBG_ << this->codePtr_->back();

  for (int i = 0; i < nRows; i++) {
    for (int j = 0; j < nCols; j++) {
      //int loc = matrixStart+(i<<size2)|j;
      int loc = matrixStart+i*nRows+j;

      const context::Value& val = mtx.getEntry(i,j);

      // Get string representation of matrix entry assignment
      std::ostringstream ss;
      ss << "(" << i << "," << j << ") = ";
      context::Printer strPrinter(ss);
      val.accept(strPrinter);
      int startInstr = this->codePtr_->size();

      // Compile right side of matrix entry assignment
      val.accept(*this);

      // Set matrix entry

      if (resultLocation_ < 0) {
        if (!this->resultValue_.template is<0>()) {
          this->annPtr_->addAnnotation(startInstr, ss.str());
          codePtr_->push_back(eval::Instruction<F>(
            eval::InstructionEnum::SET, 1, this->resultValue_, loc));
          LDBG_ << this->codePtr_->back();
        }
      } else {
        this->annPtr_->addAnnotation(startInstr, ss.str());
        if (!this->alloc.isTemporaryLocation(resultLocation_)) {
          //resultLocation_ != currDataSize_-1) {
          codePtr_->push_back(eval::Instruction<F>(
             eval::InstructionEnum::COPY, resultLocation_, 0, loc));
          LDBG_ << this->codePtr_->back();
        } else {
          // No need to issue instruction, just change last destination.
          this->setLastDestination(loc);
        }
      }
      // Annotate matrix entry memory location
      std::stringstream oss;
      oss << mtx.getName() << "(" << i << "," << j << ")";
      annPtr_->setDataName(loc, oss.str());
    }
  }
  // Save result of the determinant into temporary location
  int loc = this->alloc.reserveLocation();
  codePtr_->push_back(eval::Instruction<F>(
      eval::InstructionEnum::DET, matrixStart, nRows, loc));
  LDBG_ << this->codePtr_->back();
  resultLocation_ = loc;
  // Anotate memory location
  std::stringstream oss; oss << "_t" << resultLocation_;
  annPtr_->setDataName(resultLocation_, oss.str());
}

template <typename F>
void CodeGenerator<F>::process(const context::Function& f) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Function: " << f.getName().toString();
  switch (f.getName().getId()) {
    case context::FunctionEnum::DET: {
    } break;
    default:
      LERR_ << "Unimplemented function";
  }
}

template <typename F>
void CodeGenerator<F>::process(const context::Id& v) {
  int varIndex = cntxPtr_->getIdIndex(v.getName());
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Id '"
      << v.getName() << "' (" << varIndex << ")";

  this->resultLocation_ = this->cntxPtr_->getIdIndex(v.getName());
}

template <typename F>
void CodeGenerator<F>::process(const context::Integer& v) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Integer '"
      << v.getInt() << "'";

  // Convert integer represented as string into Field value this way unlimited
  // size integers are supported and only limited by field size.
  const std::string& val = v.getInt();

  this->resultValue_.template setTo<0>();
  const F radix(10);
  for (size_t i = 0; i < val.size(); ++i) {
    this->resultValue_ *= radix;
    this->resultValue_ += F(val[i] - '0');
  }
  this->resultLocation_ = -1;
}

template <typename F>
void CodeGenerator<F>::process(const context::Matrix& /* v */) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Matrix...";
  throw std::logic_error("Cant generate code for Matrix");
}

/*
template <typename F>
void CodeGenerator<F>::process(const context::Product& v) {
  int nTerms = v.getNumberOfNodes();
  BOOST_SCOPED_LOG_CTX(LTRC_) << "Generating code for Product of " << nTerms << " terms...";

  int productLocation = -1; // undefined
  int firstTermLocation = -1; // undefined
  F productValue = 1; // occumulation of constants
  for (int i = 0; i < nTerms; ++i) {
    v.getNode(i).accept(*this); // generate code for this term
    if (resultLocation_ < 0) { // If result was a constant
      LDBG_ << "Got constant, accumulating";
      if (v.isPos(i)) {
        LDBG_ << productValue << " * " << resultValue_;
        productValue *= resultValue_;
      } else {
        LDBG_ << productValue << " / " << resultValue_;
        productValue /= resultValue_;
      }
    } else { // Result is not a constant
      if (productLocation >= 0) { // If we have a place to accumulate product
         if (i < nTerms-1) { // If not last term
           LDBG_ << "MULBY  " << productLocation << ", " << resultLocation_;
           codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::MULBY, resultLocation_, 0,  productLocation));
         } else {
           LDBG_ << "MUL  " << productLocation << ", " << productLocation << ", " << resultLocation_;
           codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::MUL, resultLocation_, productLocation,  productLocation));
         }
      } else { // No product location has not been established yet
        if (firstTermLocation >= 0) { // See if there was already a non constant term
          if (this->alloc.isTemporaryLocation(firstTermLocation)) {
            productLocation = firstTermLocation;
            LDBG_ << "MULTO  " << productLocation << ", "  << this->resultLocation_;
            codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::MULBY, this->resultLocation_, 0, productLocation));
          } else {
            productLocation = this->alloc.reserveLocation();
            std::stringstream oss; oss << "_t" << productLocation;
            annPtr_->setDataName(productLocation, oss.str());

            LDBG_ << "MUL  " << productLocation << ", "  << firstTermLocation << ", " << this->resultLocation_;
            codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::MUL, this->resultLocation_, firstTermLocation, productLocation));
          }
        } else { // This is first non-const term
          firstTermLocation = this->resultLocation_;
        }
      }
    }
  }
  if (productLocation >= 0) { // There was product accumulation location established
     if (!productValue.isOne()) {
       LDBG_ << "MULC  " << productLocation << ", " << productLocation << ", F(" << productValue << ")";
       codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::MULC, productLocation, productValue, productLocation));
     }
  } else {
    if (firstTermLocation >= 0) {  // But there was non-const term
      if (!productValue.isOne()) {
          if (this->alloc.isTemporaryLocation(firstTermLocation)) {
            productLocation = firstTermLocation;
            LDBG_ << "MULC  " << productLocation << ", " << productLocation << ", F(" << productValue << ")";
            codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::MULC, productLocation, productValue, productLocation));
          } else {
            productLocation = this->alloc.reserveLocation();
            std::stringstream oss; oss << "_t" << productLocation;
            annPtr_->setDataName(productLocation, oss.str());

            LDBG_ << "MULC  " << productLocation << ", "  << firstTermLocation << ", F(" << productValue << ")";
            codePtr_->push_back(eval::Instruction<F>(eval::Instruction<F>::Type::MULC, firstTermLocation, productValue, productLocation));
          }
      } else {
        productLocation = firstTermLocation;
      }
    }
  }
  resultLocation_ = productLocation;
  if (resultLocation_ > 0) { // New temporary location was used
  } else {
    resultValue_ = productValue;
  }
}
*/

template <typename F>
void CodeGenerator<F>::process(const context::NamedValue&) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for NamedValue...";
  throw std::logic_error("Cant generate code for NamedValue");
}

template <typename F>
void CodeGenerator<F>::process(const context::Negation& v) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Negation...";
  v.getValue().accept(*this);
  if (this->resultLocation_ < 0) {
    this->resultLocation_ = -1;
    this->resultValue_.negate();
  } else {
    int loc = this->alloc.reserveLocation();
    std::stringstream oss; oss << "_t" << loc;
    annPtr_->setDataName(loc, oss.str());

    this->codePtr_->push_back(eval::Instruction<F>(
      eval::InstructionEnum::NEG, this->resultLocation_, 0, loc));
    LDBG_ << this->codePtr_->back();
    this->resultLocation_ = loc;
  }
}

template <typename F>
void CodeGenerator<F>::process(const context::Power& v) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Power...";
  v.getLeftValue().accept(*this);
  long exponent = v.getExponent();
  if (this->resultLocation_ < 0) {
    this->resultLocation_ = -1;
    F val = this->resultValue_;
    for (int i = 0; i < exponent; i++) { this->resultValue_ *= val; }
  } else {
    int loc = this->alloc.reserveLocation();
    std::stringstream oss; oss << "_t" << loc;
    annPtr_->setDataName(loc, oss.str());

    codePtr_->push_back(eval::Instruction<F>(
      eval::InstructionEnum::POW, resultLocation_, exponent, loc));
    LDBG_ << this->codePtr_->back();
    this->resultLocation_ = loc;
  }
}

template <typename F>
void CodeGenerator<F>::process(const context::RealNumber&) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for RealNumber...";
  throw std::logic_error("Cant generate code for Real Number");
}

template <typename F>
void CodeGenerator<F>::process(const context::String&) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for String...";
  throw std::logic_error("Cant generate code for String");
}

template <typename F>
void CodeGenerator<F>::process(const context::Table&) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for Table...";
  LERR_ << "Cant generate code for table";
  throw std::logic_error("Cant generate code for table");
}

template <typename F>
void CodeGenerator<F>::process(const context::ValueList& /* v */) {
  BOOST_LOG_FUNCTION();
  LTRC_ << "Generating code for ValueList...";
  LERR_ << "Cant generate code for Value list";
  throw std::logic_error("Cant generate code for Value list");
}

}  // namespace eval


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using rocketsoftware.MVSP; //add MVS .NET Library

namespace D3_ASP_NET
{

    public partial class CustList : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                // retrieve search arguments from previous customer search form

                string custName = (string)(Session["CustName"]);
                string custAddress = (string)(Session["CustAddr"]);
                string custPhone = (string)(Session["CustPhone"]);
                string custTerrNo = (string)(Session["CustTerr"]);

                var am = (char)254;
                var vm = (char)253;

                // assign connection values and create variables to use
                string hostName = "den-vm-dg02"; // replace with your host or leverage a config file or similar approach
                int hostPort = 9000;
                string userName = "DM";
                string userPassword = "";
                Boolean x = false;
                string subroutine = "";
                int args = 0;
                String Account = "acme";

                Pick D3 = new rocketsoftware.MVSP.Pick(); // make an instance of the D3 class
                Functions func = new Functions(); // make an instance of the Functions Class
                x = D3.Connect(hostName, hostPort, userName, userPassword); // connect to D3 and check status
                if (x)
                {
                    bool acctstat = D3.Logto(Account, ""); //Move to the correct account
                    //if (acctstat)
                    // {
                    //Prepare to call the subroutine that gets the customer lists
                    subroutine = "cust_lookup.sub";
                    args = 5;
                    Pick.mvSubroutine mysub = new Pick.mvSubroutine(subroutine, args, D3);

                    mysub.SetArgs(0, custName); // set the required arguments into the array for the arguments of the subroutine
                    mysub.SetArgs(1, custAddress);
                    mysub.SetArgs(2, custPhone);
                    mysub.SetArgs(3, custTerrNo);
                    mysub.SetArgs(4, "");

                    mysub.MvCall();
                    string custResults = mysub.GetArgs(4); // gets the return values from the subroutine

                    int amCount = func.Count(custResults, am); // counts the number of items we have
                    if (amCount != 0)
                    {
                        int vmCount = func.Dcount(custResults, vm);
                        int itemCount = vmCount / amCount; //determine how many items we retreived

                        DataTable dt = new DataTable(); //map results into a dataTable that can be then bound to the dataGrid
                        // Create the Headers for the DataTable
                        dt.Columns.Add("Account#", typeof(string));
                        dt.Columns.Add("Name", typeof(string));
                        dt.Columns.Add("Address", typeof(string));
                        dt.Columns.Add("City", typeof(string));
                        dt.Columns.Add("State", typeof(string));
                        dt.Columns.Add("Zip", typeof(string));
                        dt.Columns.Add("Phone", typeof(string));

                        for (int v = 0; v < itemCount + 1; v++) // need to add 1 to the amCount to allow for the loop going enough times for all items
                        {

                            dt.Rows.Add();

                            dt.Rows[dt.Rows.Count - 1]["Account#"] = func.Extract(custResults, 1, v + 1);
                            dt.Rows[dt.Rows.Count - 1]["Name"] = func.Extract(custResults, 2, v + 1);
                            dt.Rows[dt.Rows.Count - 1]["Address"] = func.Extract(custResults, 3, v + 1);
                            dt.Rows[dt.Rows.Count - 1]["City"] = func.Extract(custResults, 4, v + 1);
                            dt.Rows[dt.Rows.Count - 1]["State"] = func.Extract(custResults, 5, v + 1);
                            dt.Rows[dt.Rows.Count - 1]["Zip"] = func.Extract(custResults, 6, v + 1);
                            dt.Rows[dt.Rows.Count - 1]["Phone"] = func.Extract(custResults, 7, v + 1);

                        }

                        Grid_CustList.DataSource = dt;
                        Grid_CustList.DataBind();
                        Session["dt_table"] = dt;

                    }
                    else { lbl_STATUS.Text = custResults; btn_NewSearch.Visible = false; } // show error and hide controls

                    D3.CloseConnection(); //close out the connection to D3

                }

            }

        }

        //************************************************************************************************************************************************************************

        private void DataGridView1_CellContentClick(object sender, EventArgs e)
        {

            string InvoiceNo = Grid_CustList.SelectedValue.ToString();
        }

        protected void Get_CustomerSearch(object sender, EventArgs e)
        {
            Response.Redirect("~/CustomerSearch.aspx");
        }

        protected void Insert_Item_Click(object sender, EventArgs e)
        {
            string CUSTID = ((TextBox)Grid_CustList.FooterRow.FindControl("txtAcct")).Text;
            TextBox tx = (TextBox)Grid_CustList.FooterRow.FindControl("txtAcct");
            if (string.IsNullOrEmpty(tx.Text))
            {
                return;
            }

            string NAME = ((TextBox)Grid_CustList.FooterRow.FindControl("txtName")).Text;
            string ADDR = ((TextBox)Grid_CustList.FooterRow.FindControl("txtAddr")).Text;
            string CITY = ((TextBox)Grid_CustList.FooterRow.FindControl("txtCity")).Text;
            string STATE = ((TextBox)Grid_CustList.FooterRow.FindControl("txtState")).Text;
            string ZIP = ((TextBox)Grid_CustList.FooterRow.FindControl("txtZip")).Text;
            string PHONE = ((TextBox)Grid_CustList.FooterRow.FindControl("txtPhone")).Text;

            // ***************************** prepare and write data to D3 via Basic Subroutine Call *******************************

            // assign connection values and create variables to use
            string hostName = "den-vm-dg02"; // replace with your host or leverage a config file or similar approach
            int hostPort = 9000;
            string userName = "DM";
            string userPassword = "";
            Boolean x = false;
            string subroutine = "WriteCustItem.sub";
            int args = 8; // 7 inputs and a retured status code
            String Account = "acme";

            Pick D3 = new rocketsoftware.MVSP.Pick(); // make an instance of the D3 class
            Functions func = new Functions(); // make an instance of the Functions Class
            x = D3.Connect(hostName, hostPort, userName, userPassword); // connect to D3 and check status
            if (x)
            {
                bool acctstat = D3.Logto(Account, ""); //Move to the correct account
                //if (acctstat)..... would normally add error handling logic here

                //Prepare to call the subroutine that gets the customer lists

                Pick.mvSubroutine mysub = new Pick.mvSubroutine(subroutine, args, D3);

                mysub.SetArgs(0, CUSTID); // set the required arguments into the array for the arguments of the subroutine
                mysub.SetArgs(1, NAME);
                mysub.SetArgs(2, ADDR);
                mysub.SetArgs(3, CITY);
                mysub.SetArgs(4, STATE);
                mysub.SetArgs(5, ZIP);
                mysub.SetArgs(6, PHONE);
                mysub.SetArgs(7, "");
                mysub.MvCall();

                string STATUS = mysub.GetArgs(7); // gets the return values from the subroutine

                //  Perform Error checking based on status returned

                // Retrieve the datatable from Session and add the row so we can dbind it back to the gridtable
                DataTable dt = (DataTable)(Session["dt_Table"]);

                dt.Rows.Add(); // add row to datatable so we can insert the new data
                dt.Rows[dt.Rows.Count - 1]["Account#"] = CUSTID;
                dt.Rows[dt.Rows.Count - 1]["Name"] = NAME;
                dt.Rows[dt.Rows.Count - 1]["Address"] = ADDR;
                dt.Rows[dt.Rows.Count - 1]["City"] = CITY;
                dt.Rows[dt.Rows.Count - 1]["State"] = STATE;
                dt.Rows[dt.Rows.Count - 1]["Zip"] = ZIP;
                dt.Rows[dt.Rows.Count - 1]["Phone"] = PHONE;

                Grid_CustList.DataSource = dt;
                Grid_CustList.DataBind();
                Session["dt_table"] = dt;
                D3.CloseConnection(); //close out the connection to D3
            }
        }

        public Label custResults { get; set; }

        protected void Grid_CustList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteItem")
            {
                // Retrieve the row index stored in the
                // CommandArgument property.
                int row_index = int.Parse(e.CommandArgument.ToString());

                string CUSTID = ((HyperLink)Grid_CustList.Rows[row_index].Cells[0].FindControl("HyperLink1")).Text;

                // assign connection values and create variables to use
                string hostName = "den-vm-dg02"; // replace with your host or leverage a config file or similar approach
                int hostPort = 9000;
                string userName = "DM";
                string userPassword = "";
                Boolean x = false;
                string subroutine = "";
                int args = 0;
                String Account = "acme";

                Pick D3 = new rocketsoftware.MVSP.Pick(); // make an instance of the D3 class
                Functions func = new Functions(); // make an instance of the Functions Class
                x = D3.Connect(hostName, hostPort, userName, userPassword); // connect to D3 and check status
                if (x)
                {
                    bool acctstat = D3.Logto(Account, ""); //Move to the correct account
                    if (acctstat)
                    {

                        subroutine = "delete_cust_item.sub";
                        args = 2;
                        Pick.mvSubroutine mysub = new Pick.mvSubroutine(subroutine, args, D3);
                        mysub.SetArgs(0, CUSTID);
                        mysub.MvCall();
                        string Status = mysub.GetArgs(1); // gets the return values from the subroutine
                        // do proper error handling on return status

                        Grid_CustList.DataBind();

                        D3.CloseConnection(); //close out the connection to D3

                        Response.Redirect(Request.RawUrl);

                    }
                }

            }

        }
    }
}


text:
import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appStopPropagation]'
})
export class StopPropagationDirective {
  @HostListener('click', ['$event']) onClick(event: MouseEvent): void {
    event.stopPropagation();
  }
}


text:
#include <aws/ec2/model/ExportEnvironment.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace EC2
  {
    namespace Model
    {
      namespace ExportEnvironmentMapper
      {

        static const int citrix_HASH = HashingUtils::HashString("citrix");
        static const int vmware_HASH = HashingUtils::HashString("vmware");
        static const int microsoft_HASH = HashingUtils::HashString("microsoft");

        ExportEnvironment GetExportEnvironmentForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == citrix_HASH)
          {
            return ExportEnvironment::citrix;
          }
          else if (hashCode == vmware_HASH)
          {
            return ExportEnvironment::vmware;
          }
          else if (hashCode == microsoft_HASH)
          {
            return ExportEnvironment::microsoft;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ExportEnvironment>(hashCode);
          }

          return ExportEnvironment::NOT_SET;
        }

        Aws::String GetNameForExportEnvironment(ExportEnvironment enumValue)
        {
          switch(enumValue)
          {
          case ExportEnvironment::citrix:
            return "citrix";
          case ExportEnvironment::vmware:
            return "vmware";
          case ExportEnvironment::microsoft:
            return "microsoft";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace ExportEnvironmentMapper
    } // namespace Model
  } // namespace EC2
} // namespace Aws


text:
package org.apache.camel.component.aws.firehose;

import java.util.Map;
import java.util.Set;

import com.amazonaws.services.kinesisfirehose.AmazonKinesisFirehose;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.DefaultComponent;

@Component("aws-kinesis-firehose")
public class KinesisFirehoseComponent extends DefaultComponent {

    @Metadata
    private KinesisFirehoseConfiguration configuration = new KinesisFirehoseConfiguration();

    public KinesisFirehoseComponent() {
        this(null);
    }

    public KinesisFirehoseComponent(CamelContext context) {
        super(context);

        registerExtension(new KinesisFirehoseComponentVerifierExtension());
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        KinesisFirehoseConfiguration configuration = this.configuration != null ? this.configuration.copy() : new KinesisFirehoseConfiguration();
        configuration.setStreamName(remaining);
        KinesisFirehoseEndpoint endpoint = new KinesisFirehoseEndpoint(uri, configuration, this);
        setProperties(endpoint, parameters);
        checkAndSetRegistryClient(configuration);
        if (configuration.getAmazonKinesisFirehoseClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) {
            throw new IllegalArgumentException("AmazonKinesisFirehoseClient or accessKey and secretKey must be specified");
        }
        return endpoint;
    }

    public KinesisFirehoseConfiguration getConfiguration() {
        return configuration;
    }

    /**
     * The component configuration
     */
    public void setConfiguration(KinesisFirehoseConfiguration configuration) {
        this.configuration = configuration;
    }

    private void checkAndSetRegistryClient(KinesisFirehoseConfiguration configuration) {
        Set<AmazonKinesisFirehose> clients = getCamelContext().getRegistry().findByType(AmazonKinesisFirehose.class);
        if (clients.size() == 1) {
            configuration.setAmazonKinesisFirehoseClient(clients.stream().findFirst().get());
        }
    }
}


text:
name: Bug report
about: Report a problem to help us improve
---

<!--

Thanks for taking an interest in Scrapy!

If you have a question that starts with "How to...", please see the Scrapy Community page: https://scrapy.org/community/.
The GitHub issue tracker's purpose is to deal with bug reports and feature requests for the project itself.

Keep in mind that by filing an issue, you are expected to comply with Scrapy's Code of Conduct, including treating everyone with respect: https://github.com/scrapy/scrapy/blob/master/CODE_OF_CONDUCT.md

The following is a suggested template to structure your issue, you can find more guidelines at https://doc.scrapy.org/en/latest/contributing.html#reporting-bugs

-->

### Description

[Description of the issue]

### Steps to Reproduce

1. [First Step]
2. [Second Step]
3. [and so on...]

**Expected behavior:** [What you expect to happen]

**Actual behavior:** [What actually happens]

**Reproduces how often:** [What percentage of the time does it reproduce?]

### Versions

Please paste here the output of executing `scrapy version --verbose` in the command line.

### Additional context

Any additional information, configuration, data or output from commands that might be necessary to reproduce or understand the issue. Please try not to include screenshots of code or the command line, paste the contents as text instead. You can use [GitHub Flavored Markdown](https://help.github.com/en/articles/creating-and-highlighting-code-blocks) to make the text look better.


text:
package com.lordmau5.ffs.client;

import com.lordmau5.ffs.tile.TileEntityTankFrame;
import com.lordmau5.ffs.util.ExtendedBlock;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;

/**
 * Created by Dustin on 02.07.2015.
 */
public class FrameBlockAccessWrapper extends IBlockAccessHandler {

    public FrameBlockAccessWrapper(IBlockAccess iBlockAccess) {
        super(iBlockAccess);
    }

    @Override
    public Block getBlock(int x, int y, int z) {
        Block block = super.getBlock(x, y, z);
        TileEntity tile = getTileEntity(x, y, z);
        if(tile instanceof TileEntityTankFrame) {
            TileEntityTankFrame frame = (TileEntityTankFrame) tile;
            if(frame.getBlock() == null)
                return block;

            Block fac = frame.getBlock().getBlock();
            if(fac != null) {
                block = fac;
            }
        }
        return block;
    }

    @Override
    @SideOnly(Side.CLIENT)
    public int getLightBrightnessForSkyBlocks(int var1, int var2, int var3, int var4) {
        return ba.getLightBrightnessForSkyBlocks(var1, var2, var3, var4);
    }

    @Override
    public int getBlockMetadata(int x, int y, int z) {
        TileEntity tile = getTileEntity(x, y, z);
        if(tile instanceof TileEntityTankFrame) {
            TileEntityTankFrame frame = (TileEntityTankFrame) tile;
            ExtendedBlock exBlock = frame.getBlock();
            if(exBlock.getBlock() != null) {
                return exBlock.getMetadata();
            }
        }
        return super.getBlockMetadata(x, y, z);
    }

}


text:
exports.start = spheroStart;
exports.startAndDoWhenReady = spheroStartAndDoWhenReady;
exports.roll = spheroRoll;
exports.setColor = spheroSetColor;
exports.turn = spheroTurn;
exports.isReady = isReady;

var Cylon = require('cylon');

var ROBOT_NAME = 'Purple with joy';

var spheroReady = false;

Cylon.robot({
  connection: {
      name: 'sphero',
      adaptor: 'sphero',
      port: '/dev/cu.Sphero-OYR-AMP-SPP'
   //   port: '/dev/cu.Sphero-RYR-AMP-SPP'
   //   port: '/dev/cu.Sphero-RRP-AMP-SPP'
  },
  device: { name: 'Sphero-OYR', driver: 'sphero' },
//  device: { name: 'Sphero-RYR', driver: 'sphero' },
//  device: { name: 'Sphero-RRP', driver: 'sphero' },

  name: ROBOT_NAME,

  myAngle : 0,
  myColor : 'yellow',
  mySpeed : 150,
  rolling : false,

  work: function(my) {
    console.log('Setting up collision detection.');
//    my.sphero.detectCollisions();
    my.sphero.configureCollisionDetection(0x01, 0x30, 0x30, 0x50, 0x50, 0x50)
    my.sphero.on('collision', function() {
      console.log("Ouch, collision!")
      my.sphero.setColor('purple');
      my.sphero.stop();
      my.markCollision();
    });

    var black = true;
    every((0.5).second(), function(){
 //     if (!my.amIRolling()) {
        var color = my.readMyColor();
        if (black) {
          my.sphero.setColor('black');
        } else {
          my.sphero.setColor(color);
        }
        black = !black
  //    }
    });
  },

  readMyColor : function() {
    return this.myColor;
  },

  amIRolling : function() {
    return this.rolling;
  },

  startedRolling : function() {
    this.rolling = true;
  },

  stoppedRolling: function() {
    this.rolling = false;
  },

  setColor: function(color, callback) {
    console.log("Sphero changing to color " + color);
    this.myColor = color;
    callback(null, {'message': "Sphero changed to color " + color});
  },

  turn: function(direction, callback) {
    if (direction == "left") {
      this.myAngle += 270;
    } else if (direction == "right") {
      this.myAngle += 90;
    } else {
      var message = "Sphero can't turn in direction " + direction
        + ". It only understands left and right.";
      console.error(message);
      callback(message, null);
      return;
    }

    if (this.myAngle >= 360) this.myAngle -= 360;
    console.log("Sphero turning " + direction + ", will roll at " + this.myAngle + " degrees");
    this.sphero.roll(0, this.myAngle, 0);
    callback(null, {'message': "Sphero turned " + direction});
  },

  roll: function(units, direction, callback) {
    if (direction != "forward" && direction != "backward") {
      var errorMessage = "Sphero can't roll in direction " + direction
        + ". It only understands forward and backward.";
      console.error(errorMessage);
      callback(errorMessage, null);
      return;
    }
    var rollAngle = direction == "forward" ? this.myAngle : (this.myAngle + 180);
    if (rollAngle >= 360) rollAngle -= 360;
    console.log("Sphero rolling at speed " + this.mySpeed
        + " for " + units + " seconds"
        + " in a " + rollAngle + " degree angle ");
    this.startedRolling();
    this.sphero.roll(0, rollAngle, 1);
    after((0.5).seconds(), function() {
      this.sphero.roll(this.mySpeed, rollAngle, 2);
      after((units).seconds(), function() {
        console.log("Sphero stopping after " + units + " seconds");
        this.stop(rollAngle);
        var justHitSomething = this.hitSomething;
        this.clearCollision();
        message = "Sphero rolled " + units + " units " + direction;
        if (justHitSomething) message = message + " but hit something on the way";
        callback(null, {
          'message': message,
          'collision': justHitSomething,
        });
      }.bind(this));
    }.bind(this));
  },

  stop: function(rollAngle) {
    if (rollAngle == null) rollAngle = this.myAngle;
    this.sphero.roll(0, rollAngle, 0);
    this.stoppedRolling();
  },

  hitSomething: false,
  markCollision: function() {
    this.hitSomething = true;
  },
  clearCollision: function() {
    this.hitSomething = false;
  },
});

function spheroStart() {
  Cylon.robots[ROBOT_NAME].on('ready', function() {
    spheroReady = true;
  });
  Cylon.start();
}

function spheroStartAndDoWhenReady(callback) {
  spheroStart();
  callbackWhenReady = function() {
    if (spheroReady) {
      callback();
    } else {
      console.log("SpheroDriver not ready, waiting a sec...");
      setTimeout(function() {callbackWhenReady.call()}, 1000);
    }
  }
  callbackWhenReady();
}

function spheroRoll(units, direction, callback) {
  console.log('Requested roll ' + units + " units " + direction);
  enqueue(Cylon.robots[ROBOT_NAME].roll, [units, direction, callback]);
}

function spheroSetColor(color, callback) {
  console.log('Requested set color to ' + color);
  enqueue(Cylon.robots[ROBOT_NAME].setColor, [color, callback]);
}

function spheroTurn(direction, callback) {
  console.log('Requested turn ' + direction);
  enqueue(Cylon.robots[ROBOT_NAME].turn, [direction, callback]);
}

function restart() {
  Cylon.halt(function() {
    Cylon.start();
  });
}

function isReady() {
  return spheroReady;
}

var commandQueue = [];
var busy = false;
var pause_ms = 300;

function enqueue(handler, params) {
  commandQueue.push({
    'handler': handler,
    'params': params
  });
}

function processQueue() {
  if (!busy) {
    busy = true;
    var nextCommand = commandQueue.shift();
    if (nextCommand != null) {
      setTimeout(function() {
        var originalCallback = nextCommand.params.pop();
        var queuedCallback = function(err, data) {
          originalCallback(err, data);
          busy = false;
        };
        nextCommand.params.push(queuedCallback);
        nextCommand.handler.apply(Cylon.robots[ROBOT_NAME], nextCommand.params);
      }, pause_ms);
    } else {
      busy = false;
    }
  }
}

setInterval(processQueue, 500);


text:
'use strict'

const getEventData = require('./modules/get-event-data')
const shuffle = require('knuth-shuffle').knuthShuffle

let CUSTOM_API_URL
let CUSTOM_PROFILE_URL

function chooseAWinner (winnersAmount, confirmedMembersList) {
  return new Promise((resolve, reject) => {
    if (!confirmedMembersList.length) {
      return reject(new Error('No qualified attendees available.'))
    }

    if (winnersAmount > confirmedMembersList.length) {
      return reject(new Error(`The amount of winners (${winnersAmount}) is greater than the amount of confirmed members (${confirmedMembersList.length}).`))
    }

    const winners = shuffle(confirmedMembersList.slice(0))

    return resolve(winners.slice(0, winnersAmount))
  })
}

function excludeHosts (membersList) {
  return new Promise((resolve, reject) => {
    if (Array.isArray(membersList)) {
      const membersListWithoutHosts = membersList.filter(m => !m.member.event_context.host)

      return resolve(membersListWithoutHosts)
    }

    if (membersList.errors && membersList.errors.length) {
      const firstError = membersList.errors.shift()

      if (firstError.message) {
        return reject(new Error(firstError.message))
      }
    }

    return reject(new Error('Unknown error encountered with the Meetup API.'))
  })
}

function excludeNonConfirmedMembers (membersListWithoutHosts) {
  return new Promise((resolve, reject) => {
    const confirmedMembersList = membersListWithoutHosts.reduce(
      (membersList, user) => {
        if (user.response === 'yes') {
          let photoURL

          if (user.member.photo) {
            photoURL = user.member.photo.highres_link || user.member.photo.photo_link
          }

          membersList.push({
            name: user.member.name,
            photoURL,
            profileURL: CUSTOM_PROFILE_URL ||
              `http://www.meetup.com/${user.group.urlname}/members/${user.member.id}`
          })
        }

        return membersList
      },
      []
    )

    resolve(confirmedMembersList)
  })
}

function run (meetupName, eventId, winnersAmount) {
  const API_URL = CUSTOM_API_URL ||
    `https://api.meetup.com/${meetupName}/events/${eventId}/rsvps?only=group.urlname,member,response`

  return getEventData(API_URL, meetupName, eventId)
    .then(excludeHosts)
    .then(excludeNonConfirmedMembers)
    .then(chooseAWinner.bind(null, winnersAmount))
}

function setCustomApiUrl (customApiUrl) {
  CUSTOM_API_URL = customApiUrl
}

function setCustomProfileUrl (customProfileUrl) {
  CUSTOM_PROFILE_URL = customProfileUrl
}

module.exports = {
  run,
  setCustomApiUrl,
  setCustomProfileUrl
}


text:
using ESISharp.Enumerations;
using ESISharp.Web;

namespace ESISharp.ESIPath
{
    /// Public Market paths
    public class Market
    {
        protected ESIEve EasyObject;

        internal Market(ESIEve EasyEve)
        {
            EasyObject = EasyEve;
        }

        /// List Market Prices
        /// <returns>EsiRequest</returns>
        public EsiRequest GetPrices()
        {
            var Path = "/markets/prices/";
            return new EsiRequest(EasyObject, Path, EsiWebMethod.Get);
        }

        /// Get historic market statistics in a Region for the specified Type ID
        /// <param name="RegionID">(Int32) Region ID</param>
        /// <param name="TypeID">(Int32) Type ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetRegionMarketHistory(int RegionID, int TypeID)
        {
            var Path = $"/markets/{RegionID.ToString()}/history/";
            var Data = new
            {
                type_id = TypeID
            };
            return new EsiRequest(EasyObject, Path, EsiWebMethod.Get, Data);
        }

        /// Get orders in a Region (First Page)
        /// <param name="RegionID">(Int32) Region ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetRegionOrders(int RegionID)
        {
            return GetRegionOrders(RegionID, null, MarketOrderType.All.Value, 1);
        }

        /// Get orders in a Region (First Page)
        /// <param name="RegionID">(Int32) Region ID</param>
        /// <param name="TypeID">(Int32) Type ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetRegionOrders(int RegionID, int TypeID)
        {
            return GetRegionOrders(RegionID, TypeID, MarketOrderType.All.Value, 1);
        }

        /// Get orders in a Region (First Page)
        /// <param name="RegionID">(Int32) Region ID</param>
        /// <param name="TypeID">(Int32) Type ID</param>
        /// <param name="OrderType">(MarketOrderType) Market Order Type</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetRegionOrders(int RegionID, int? TypeID, MarketOrderType OrderType)
        {
            return GetRegionOrders(RegionID, TypeID, OrderType.Value, 1);
        }

        /// Get orders in a Region (First Page)
        /// <param name="RegionID">(Int32) Region ID</param>
        /// <param name="TypeID">(Int32) Type ID</param>
        /// <param name="OrderType">(String) Market Order Type</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetRegionOrders(int RegionID, int? TypeID, string OrderType)
        {
            return GetRegionOrders(RegionID, TypeID, OrderType, 1);
        }

        /// Get orders in a Region (First Page)
        /// <param name="RegionID">(Int32) Region ID</param>
        /// <param name="TypeID">(Int32) Type ID</param>
        /// <param name="OrderType">(MarketOrderType) Market Order Type</param>
        /// <param name="Page">(Int32) Page number</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetRegionOrders(int RegionID, int? TypeID, MarketOrderType OrderType, int Page)
        {
            return GetRegionOrders(RegionID, TypeID, OrderType.Value, Page);
        }

        /// Get orders in a Region (First Page)
        /// <param name="RegionID">(Int32) Region ID</param>
        /// <param name="TypeID">(Int32) Type ID</param>
        /// <param name="OrderType">(String) Market Order Type</param>
        /// <param name="Page">(Int32) Page number</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetRegionOrders(int RegionID, int? TypeID, string OrderType, int Page)
        {
            var Path = $"/markets/{RegionID.ToString()}/orders/";
            var Data = new
            {
                type_id = TypeID,
                order_type = OrderType,
                page = Page
            };
            return new EsiRequest(EasyObject, Path, EsiWebMethod.Get, Data);
        }

        /// Get Market Groups
        /// <returns>EsiRequest</returns>
        public EsiRequest GetMarketGroups()
        {
            var Path = "/markets/groups/";
            return new EsiRequest(EasyObject, Path, EsiWebMethod.Get);
        }

        /// Get Market Group Information
        /// <param name="GroupID">(Int32) Market Group ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetMarketGroupInfo(int GroupID)
        {
            return GetMarketGroupInfo(GroupID, Language.English);
        }

        /// Get Market Group Information
        /// <param name="GroupID">(Int32) Market Group ID</param>
        /// <param name="Language">(Language) Language</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetMarketGroupInfo(int GroupID, Language Language)
        {
            var Path = $"/markets/groups/{GroupID.ToString()}/";
            var Data = new
            {
                language = Language.Value
            };
            return new EsiRequest(EasyObject, Path, EsiWebMethod.Get, Data);
        }

        ///
        /// Get type IDs with active orders in a Region (First Page)
        ///
        /// <param name="RegionID">(Int32 Region ID)</param>
        /// <returns></returns>
        public EsiRequest GetMarketTypes(int RegionID)
        {
            return GetMarketTypes(RegionID, 1);
        }

        ///
        /// Get type IDs with active orders in a Region
        ///
        /// <param name="RegionID">(Int32 Region ID)</param>
        /// <param name="Page">(Int32) Page number</param>
        /// <returns></returns>
        public EsiRequest GetMarketTypes(int RegionID, int Page)
        {
            var Path = $"/markets/{RegionID.ToString()}/types/";
            var Data = new
            {
                page = Page
            };
            return new EsiRequest(EasyObject, Path, EsiWebMethod.Get, Data);
        }
    }

    /// Public and Authenticated Market paths
    public class AuthMarket : Market
    {
        internal AuthMarket(ESIEve EasyEve) : base(EasyEve)
        {
            EasyObject = EasyEve;
        }

        /// Get Market Orders posted in a Structure (First Page)
        /// <remarks>Requires SSO Authentication, using "structure_markets" scope</remarks>
        /// <param name="StructureID">(Int64) Structure ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetStructureOrders(long StructureID)
        {
            return GetStructureOrders(StructureID, 1);
        }

        /// Get Market Orders posted in a Structure (Specified Page)
        /// <remarks>Requires SSO Authentication, using "structure_markets" scope</remarks>
        /// <param name="StructureID">(Int64) Structure ID</param>
        /// <param name="Page">(Int32) Page number</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetStructureOrders(long StructureID, int Page)
        {
            var Path = $"/markets/structures/{StructureID.ToString()}/";
            var Data = new { page = Page };
            return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet, Data);
        }
    }
}


text:
FactoryGirl.define do
  factory :meal do
    details "Apple"
    calories 200
    created_at { Time.current }
    user
  end

end