text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using EnsureThat.Annotations;
using EnsureThat.Internals;
using JetBrains.Annotations;

using NotNullAttribute = System.Diagnostics.CodeAnalysis.NotNullAttribute;

namespace EnsureThat.Enforcers
{
    [SuppressMessage("Performance", "CA1822:Mark members as static")]
    public sealed class TypeArg
    {
        private static class Types
        {
            internal static readonly Type IntType = typeof(int);

            internal static readonly Type ShortType = typeof(short);

            internal static readonly Type DecimalType = typeof(decimal);

            internal static readonly Type DoubleType = typeof(double);

            internal static readonly Type FloatType = typeof(float);

            internal static readonly Type BoolType = typeof(bool);

            internal static readonly Type DateTimeType = typeof(DateTime);

            internal static readonly Type StringType = typeof(string);
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsInt([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.IntType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsInt([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.IntType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsShort([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.ShortType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsShort([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.ShortType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsDecimal([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.DecimalType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsDecimal([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.DecimalType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsDouble([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.DoubleType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsDouble([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.DoubleType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsFloat([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.FloatType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsFloat([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.FloatType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsBool([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.BoolType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsBool([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.BoolType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsDateTime([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.DateTimeType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsDateTime([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.DateTimeType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsString([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.StringType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public object IsString([ValidatedNotNull, NotNull]object param, [InvokerParameterName] string paramName = null)
            => IsOfType(param, Types.StringType, paramName);

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public T IsOfType<T>([ValidatedNotNull, NotNull]T param, Type expectedType, [InvokerParameterName] string paramName = null) where T : class
        {
            Ensure.Any.IsNotNull(param, paramName);

            IsOfType(param.GetType(), expectedType, paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsOfType([ValidatedNotNull, NotNull]Type param, Type expectedType, [InvokerParameterName] string paramName = null)
        {
            Ensure.Any.IsNotNull(param, paramName);
            Ensure.Any.IsNotNull(expectedType, nameof(expectedType));

            if (param != expectedType)
                throw Ensure.ExceptionFactory.ArgumentException(
                    string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsOfType_Failed, expectedType.FullName, param.FullName),
                    paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public T IsNotOfType<T>([ValidatedNotNull, NotNull]T param, Type nonExpectedType, [InvokerParameterName] string paramName = null) where T : class
        {
            Ensure.Any.IsNotNull(param, paramName);

            IsNotOfType(param.GetType(), nonExpectedType, paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsNotOfType([ValidatedNotNull, NotNull]Type param, Type nonExpectedType, [InvokerParameterName] string paramName = null)
        {
            Ensure.Any.IsNotNull(param, paramName);
            Ensure.Any.IsNotNull(nonExpectedType, nameof(nonExpectedType));

            if (param == nonExpectedType)
                throw Ensure.ExceptionFactory.ArgumentException(
                    string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsNotOfType_Failed, nonExpectedType.FullName),
                    paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public T IsAssignableToType<T>([ValidatedNotNull, NotNull]T param, Type expectedType, [InvokerParameterName] string paramName = null) where T : class
        {
            Ensure.Any.IsNotNull(param, paramName);

            IsAssignableToType(param.GetType(), expectedType, paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsAssignableToType([ValidatedNotNull, NotNull]Type param, Type expectedType, [InvokerParameterName] string paramName = null)
        {
            Ensure.Any.IsNotNull(param, paramName);
            Ensure.Any.IsNotNull(expectedType, nameof(expectedType));

            if (!expectedType.IsAssignableFrom(param))
                throw Ensure.ExceptionFactory.ArgumentException(
                    string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsAssignableToType_Failed, expectedType.FullName, param.FullName),
                    paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public T IsNotAssignableToType<T>([ValidatedNotNull, NotNull]T param, Type nonExpectedType, [InvokerParameterName] string paramName = null) where T : class
        {
            Ensure.Any.IsNotNull(param, paramName);

            IsNotAssignableToType(param.GetType(), nonExpectedType, paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsNotAssignableToType([ValidatedNotNull, NotNull]Type param, Type nonExpectedType, [InvokerParameterName] string paramName = null)
        {
            Ensure.Any.IsNotNull(param, paramName);
            Ensure.Any.IsNotNull(nonExpectedType, nameof(nonExpectedType));

            if (nonExpectedType.IsAssignableFrom(param))
                throw Ensure.ExceptionFactory.ArgumentException(
                    string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsNotAssignableToType_Failed, nonExpectedType.FullName),
                    paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public T IsClass<T>([ValidatedNotNull, NotNull]T param, [InvokerParameterName] string paramName = null)
        {
            if (param == null)
                throw Ensure.ExceptionFactory.ArgumentNullException(
                    ExceptionMessages.Types_IsClass_Failed_Null,
                    paramName);

            IsClass(param.GetType(), paramName);

            return param;
        }

        [return: NotNull]
        [ContractAnnotation("param:null => halt")]
        public Type IsClass([ValidatedNotNull, NotNull]Type param, [InvokerParameterName] string paramName = null)
        {
            if (param == null)
                throw Ensure.ExceptionFactory.ArgumentNullException(
                    ExceptionMessages.Types_IsClass_Failed_Null,
                    paramName);

            if (!param.GetTypeInfo().IsClass)
                throw Ensure.ExceptionFactory.ArgumentException(
                    string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Types_IsClass_Failed, param.FullName),
                    paramName);

            return param;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
SubscriptionService subscriptionService = paymillContext.getSubscriptionService();
subscriptionService.pause( "sub_dea86e5c65b2087202e3" );


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

namespace Passenger.Core.Domain
{
    public class Driver
    {
        private ISet<Route> _routes = new HashSet<Route>();
        private ISet<DailyRoute> _dailyRoutes = new HashSet<DailyRoute>();

        public Guid UserId { get; protected set; }
        public string Name { get; protected set; }
        public Vehicle Vehicle { get; protected set; }
        public DateTime UpdatedAt { get; private set; }
        public IEnumerable<Route> Routes
        {
            get { return _routes; }
            set { _routes = new HashSet<Route>(value); }
        }
        public IEnumerable<DailyRoute> DailyRoutes
        {
            get { return _dailyRoutes; }
            set { _dailyRoutes = new HashSet<DailyRoute>(value); }
        }

        protected Driver()
        {
        }

        public Driver (User user)
        {
            UserId = user.Id;
            Name = user.Username;
        }

        public void SetVehicle(Vehicle vehicle)
        {
            Vehicle = vehicle;
            UpdatedAt = DateTime.UtcNow;
        }

        public void AddRoute(string name, Node start, Node end, double length)
        {
            var route = Routes.SingleOrDefault(x => x.Name == name);
            if(route != null)
            {
                throw new Exception($"Route with name: '{name}' already exists for driver: {Name}.");
            }
            _routes.Add(Route.Create(name, start, end, length));
            UpdatedAt = DateTime.UtcNow;
        }

        public void DeleteRoute(string name)
        {
            var route = Routes.SingleOrDefault(x => x.Name == name);
            if(route == null)
            {
                throw new Exception($"Route named: '{name}' for driver: '{Name}' was not found.");
            }
            _routes.Remove(route);
            UpdatedAt = DateTime.UtcNow;
        }
    }
}


text:
<!DOCTYPE HTML>
<html>
<head>
	<title>phaser.js - a new beginning</title>
	<?php
		require('js.php');
	?>
</head>
<body>

<script type="text/javascript">

var MegaGame = {};

MegaGame.MainMenu = function (game) {
	//	A reference to the local game will always be passed to your state when created
	//	You should store it somewhere handy for use in your functions, like this ...
	this.game = game;
};

MegaGame.MainMenu.prototype = {

	preload: function () {

		console.log('MainMenu.preload');
		this.game.load.image('bladerunner', 'assets/pics/acryl_bladerunner.png');

	},

	create: function () {

		console.log('MainMenu.create');
		document.body.appendChild(this.game.cache.getImage('bladerunner'));

	}

};

(function () {

	//	Finally in this example we pass in a custom State object which will be created upon boot
	var game = new Phaser.Game(800, 600, Phaser.RENDERER_AUTO, '', MegaGame.MainMenu);

})();

</script>

</body>
</html>


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef _SAM4L_ADCIFE_INSTANCE_
#define _SAM4L_ADCIFE_INSTANCE_

/* ========== Register definition for ADCIFE peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_ADCIFE_CR              (0x40038000U) /**< \brief (ADCIFE) Control Register */
#define REG_ADCIFE_CFG             (0x40038004U) /**< \brief (ADCIFE) Configuration Register */
#define REG_ADCIFE_SR              (0x40038008U) /**< \brief (ADCIFE) Status Register */
#define REG_ADCIFE_SCR             (0x4003800CU) /**< \brief (ADCIFE) Status Clear Register */
#define REG_ADCIFE_RTS             (0x40038010U) /**< \brief (ADCIFE) Resistive Touch Screen Register */
#define REG_ADCIFE_SEQCFG          (0x40038014U) /**< \brief (ADCIFE) Sequencer Configuration Register */
#define REG_ADCIFE_CDMA            (0x40038018U) /**< \brief (ADCIFE) Configuration Direct Memory Access Register */
#define REG_ADCIFE_TIM             (0x4003801CU) /**< \brief (ADCIFE) Timing Configuration Register */
#define REG_ADCIFE_ITIMER          (0x40038020U) /**< \brief (ADCIFE) Internal Timer Register */
#define REG_ADCIFE_WCFG            (0x40038024U) /**< \brief (ADCIFE) Window Monitor Configuration Register */
#define REG_ADCIFE_WTH             (0x40038028U) /**< \brief (ADCIFE) Window Monitor Threshold Configuration Register */
#define REG_ADCIFE_LCV             (0x4003802CU) /**< \brief (ADCIFE) Sequencer Last Converted Value Register */
#define REG_ADCIFE_IER             (0x40038030U) /**< \brief (ADCIFE) Interrupt Enable Register */
#define REG_ADCIFE_IDR             (0x40038034U) /**< \brief (ADCIFE) Interrupt Disable Register */
#define REG_ADCIFE_IMR             (0x40038038U) /**< \brief (ADCIFE) Interrupt Mask Register */
#define REG_ADCIFE_CALIB           (0x4003803CU) /**< \brief (ADCIFE) Calibration Register */
#define REG_ADCIFE_VERSION         (0x40038040U) /**< \brief (ADCIFE) Version Register */
#define REG_ADCIFE_PARAMETER       (0x40038044U) /**< \brief (ADCIFE) Parameter Register */
#else
#define REG_ADCIFE_CR              (*(WoReg  *)0x40038000U) /**< \brief (ADCIFE) Control Register */
#define REG_ADCIFE_CFG             (*(RwReg  *)0x40038004U) /**< \brief (ADCIFE) Configuration Register */
#define REG_ADCIFE_SR              (*(RoReg  *)0x40038008U) /**< \brief (ADCIFE) Status Register */
#define REG_ADCIFE_SCR             (*(WoReg  *)0x4003800CU) /**< \brief (ADCIFE) Status Clear Register */
#define REG_ADCIFE_RTS             (*(RwReg  *)0x40038010U) /**< \brief (ADCIFE) Resistive Touch Screen Register */
#define REG_ADCIFE_SEQCFG          (*(RwReg  *)0x40038014U) /**< \brief (ADCIFE) Sequencer Configuration Register */
#define REG_ADCIFE_CDMA            (*(WoReg  *)0x40038018U) /**< \brief (ADCIFE) Configuration Direct Memory Access Register */
#define REG_ADCIFE_TIM             (*(RwReg  *)0x4003801CU) /**< \brief (ADCIFE) Timing Configuration Register */
#define REG_ADCIFE_ITIMER          (*(RwReg  *)0x40038020U) /**< \brief (ADCIFE) Internal Timer Register */
#define REG_ADCIFE_WCFG            (*(RwReg  *)0x40038024U) /**< \brief (ADCIFE) Window Monitor Configuration Register */
#define REG_ADCIFE_WTH             (*(RwReg  *)0x40038028U) /**< \brief (ADCIFE) Window Monitor Threshold Configuration Register */
#define REG_ADCIFE_LCV             (*(RoReg  *)0x4003802CU) /**< \brief (ADCIFE) Sequencer Last Converted Value Register */
#define REG_ADCIFE_IER             (*(WoReg  *)0x40038030U) /**< \brief (ADCIFE) Interrupt Enable Register */
#define REG_ADCIFE_IDR             (*(WoReg  *)0x40038034U) /**< \brief (ADCIFE) Interrupt Disable Register */
#define REG_ADCIFE_IMR             (*(RoReg  *)0x40038038U) /**< \brief (ADCIFE) Interrupt Mask Register */
#define REG_ADCIFE_CALIB           (*(RwReg  *)0x4003803CU) /**< \brief (ADCIFE) Calibration Register */
#define REG_ADCIFE_VERSION         (*(RoReg  *)0x40038040U) /**< \brief (ADCIFE) Version Register */
#define REG_ADCIFE_PARAMETER       (*(RoReg  *)0x40038044U) /**< \brief (ADCIFE) Parameter Register */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */

/* ========== Instance parameters for ADCIFE peripheral ========== */
#define ADCIFE_CHANNELS             16
#define ADCIFE_CHANNEL_MSB          15
#define ADCIFE_EXT_TRIGGERS_MSB     0
#define ADCIFE_GCLK_NUM             10
#define ADCIFE_PDCA_ID_RX           11
#define ADCIFE_PDCA_ID_TX           29
#define ADCIFE_REG_RX               LCV
#define ADCIFE_REG_TX               CDMA

#endif /* _SAM4L_ADCIFE_INSTANCE_ */


text:
layout: post-no-feature
title: Smash Hit
category: articles
tags: [iOS, twitch, shmup]
linky: http://smashhitgame.com/
img: smashhit.jpeg
---

{% if page.linky %}
![{{ page.title }}](/images/{{page.img}})
{% else %}
![{{ page.title }}](/images/{{page.img}})
{% endif %}

* Cool modern Tron-ish vibes for the presentation. Blippy and bloopy music that fits the visuals well.
* Very cunning system: your ammunition is also your health. When your ammo is empty, it's game over. When you hit an obstacle, you loose a big chunk of ammunition.
* Great at keeping the challenges fresh: new twists and takes on the tap-tap shooting mechanic.

[{{ page.title }}]({{page.linky}})


text:
namespace GafferCortex
{

template<typename T>
class GAFFERCORTEX_API TypedParameterHandler : public ParameterHandler
{

	public :

		IE_CORE_DECLAREMEMBERPTR( TypedParameterHandler<T> );

		using ParameterType = IECore::TypedParameter<T>;
		using PlugType = typename Gaffer::PlugType<T>::Type;

		TypedParameterHandler( typename ParameterType::Ptr parameter );
		~TypedParameterHandler() override;

		IECore::Parameter *parameter() override;
		const IECore::Parameter *parameter() const override;
		void restore( Gaffer::GraphComponent *plugParent ) override;
		Gaffer::Plug *setupPlug( Gaffer::GraphComponent *plugParent, Gaffer::Plug::Direction direction=Gaffer::Plug::In, unsigned flags = Gaffer::Plug::Default | Gaffer::Plug::Dynamic ) override;
		Gaffer::Plug *plug() override;
		const Gaffer::Plug *plug() const override;
		void setParameterValue() override;
		void setPlugValue() override;

	private :

		typename PlugType::Ptr createPlug( Gaffer::Plug::Direction direction ) const;
		// variant for StringPlugs
		typename PlugType::Ptr createPlug( Gaffer::Plug::Direction direction, IECore::StringAlgo::Substitutions substitutions ) const;

		typename ParameterType::Ptr m_parameter;
		typename PlugType::Ptr m_plug;

		static ParameterHandlerDescription<TypedParameterHandler<T>, ParameterType> g_description;

};

} // namespace GafferCortex

#endif // GAFFERCORTEX_TYPEDPARAMETERHANDLER_H


text:
<?php
class awpm_plugin_list extends WP_List_Table
{

    function __construct(){
        parent::__construct(array(
                            'singular'  => __('Plugins','awpm'),
                            'plural'    => __('plugin','awpm'),
                            'ajax'      => false
                            ));

    }
    function column_default($item, $column_name){
        switch($column_name){
            case 'status':
                if($item['file']!=AWPM_PLUGIN_FILE){
                    $activation_link='
';
                    $activation_link.='Activate';
                    $activation_link.="  " . '';
                    $activation_link.='
';
                    $deactivation_link='
';
                    $deactivation_link.='Deactivate';
                    $deactivation_link.="  " . '';
                    $deactivation_link.='
';
                    return ((is_plugin_active($item['file'])==TRUE)?$deactivation_link:$activation_link);
                }else{
                    return sprintf(__('You Can Not Perform any Action For this Plugin From Here.Go to Plugins Page','awpm'),admin_url('network/plugins.php'));
                }
                break;
            case 'plugin_name':
                return $item['Name'];
                break;
            case 'description':
                return $item['Description'];
                break;
            }
    }

    function get_columns(){
        $columns = array(
                        'plugin_name'=>__('Plugin','awpm'),
                        'description'=>__('Description','awpm'),
                        'status'=>__('Status','awpm'),
                        );
        return $columns;
    }

    function prepare_items($config){
            $columns  = $this->get_columns();
            $hidden = array();
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = array($columns, $hidden,$sortable);
            $this->items = $config['data'];
    }

    function column_cb($item) {
        return sprintf('<input type="checkbox" name="%1$s[]" value="%2$s" />','activity',$item->activity_id);
    }
}


text:
require 'spec_helper'

describe Nacre::API::Order do
  let(:connection) { double("connection") }

  before do
    Nacre::API::Order.stub(:connection).and_return(connection)
  end

  context "when instantiated with no data" do
    let(:model) {
      Nacre::API::Order.new
    }

    it 'should create an instance' do
      model.should be_a(Nacre::API::Order)
    end
  end

  context "when instantiated with valid data" do
    let(:valid_params) {}

    let(:model) {
      Nacre::API::Order.new(valid_params)
    }

    describe "initialization" do
      it 'should create an instance' do
        model.should be_a(Nacre::API::Order)
      end

      it 'should have a list of fields' do
        model.class.fields.should == [
          :id, :parent_order_id, :order_type_code,
          :reference, :acknowledged, :order_status,
          :stock_status_code, :allocation_status_code,
          :placed_on, :created_on, :created_by_id,
          :price_list_id, :price_mode_code, :delivery,
          :invoices, :currency, :total_value,
          :assignment, :parties, :order_rows
        ]
      end

      pending 'should contain the correct model data' do
        model.id.should == 1
        model.order_type_code.should == ''
      end
    end

    describe "find" do
      before do
        response = double("response")
        response.stub(:body).and_return(response_json)
        connection.stub(:get).
          and_return(response)
        connection.should_receive(:get).
          with("/order-service/order/123456")
      end

      context "when an empty list comes back" do
        let(:response_json) { { "response" => [] }.to_json }

        it 'should return nil' do
          Nacre::API::Order.find(123456).should be_nil
        end
      end

      context "when one valid value comes back" do
        let(:results) { [] }
        let(:response_json) { IO.read("spec/fixtures/json/order.json") }

        it 'should return a valid Order' do
          order = Nacre::API::Order.find(123456)
          order.should be_a(Nacre::API::Order)
          order.id.should == 123456
          order.reference.should == 'order#001'
          order.currency.accounting_currency_code.should == 'GBP'
        end
      end
    end

    describe "all" do
      context "when an empty list comes back" do
        it 'should return an empty array' do
          Nacre::API::OrderSearch.any_instance.should_receive(:results).and_return(Nacre::API::OrderSearchResults.new)
          all_orders = Nacre::API::Order.all
          all_orders.should be_a(Array)
          all_orders.should be_empty
        end
      end

      context "when a list with actual values comes back" do
        let(:response_json) { IO.read("spec/fixtures/json/order.json") }

        it 'should return an array of Orders' do
          search_results = Nacre::API::OrderSearchResults.new_from_json(
              IO.read("spec/fixtures/json/order_search_result.json")
          )
          Nacre::API::OrderSearch.any_instance.should_receive(:results).and_return(search_results)

          response = double("response")
          response.stub(:body).and_return(response_json)
          connection.should_receive(:get).
            with("/order-service/order/123456,123457,123458").
            and_return(response)

          orders = Nacre::API::Order.all
          orders.should be_a(Array)
          orders.length.should == 1

          order = orders.first
          order.should be_a(Nacre::API::Order)
          order.id.should == 123456
          order.reference.should == 'order#001'
          order.currency.accounting_currency_code.should == 'GBP'
        end
      end
    end

    describe "save"

    describe "delete"
  end
end


text:
'''
    rauth.test_service_oauth1
    -------------------------

    Test suite for rauth.service.OAuth1Service.
'''

from base import RauthTestCase
from test_service import HttpMixin, RequestMixin, ServiceMixin

from rauth.compat import parse_qsl, quote, is_basestring, iteritems
from rauth.service import OAuth1Service
from rauth.session import OAUTH1_DEFAULT_TIMEOUT, OAuth1Session
from rauth.utils import CaseInsensitiveDict, ENTITY_METHODS, FORM_URLENCODED

from copy import deepcopy
from hashlib import sha1

from mock import patch

import rauth

import requests

import json
import pickle

class OAuth1ServiceTestCase(RauthTestCase, RequestMixin, ServiceMixin,
                            HttpMixin):
    consumer_key = '000'
    consumer_secret = '111'

    access_token = '123'
    access_token_secret = '456'

    def setUp(self):
        RauthTestCase.setUp(self)

        self.request_token_url = 'http://example.com/request'
        self.access_token_url = 'http://example.com/access'
        self.authorize_url = 'http://example.com/authorize'
        self.base_url = 'http://example.com/api/'

        self.service = OAuth1Service(self.consumer_key,
                                     self.consumer_secret,
                                     name='service',
                                     request_token_url=self.request_token_url,
                                     access_token_url=self.access_token_url,
                                     authorize_url=self.authorize_url,
                                     base_url=self.base_url)

        self.session = self.service.get_session(('123', '456'))

        # patches
        self.session.request = self.fake_request
        self.service.get_session = self.fake_get_session

    def fake_get_auth_header(self, oauth_params, realm=None):
        auth_header = 'OAuth realm="{realm}"'.format(realm=realm)
        params = ''
        for k, v in iteritems(oauth_params):
            params += ',{key}="{value}"'.format(key=k, value=quote(str(v)))
        auth_header += params
        return auth_header

    @patch.object(rauth.session.HmacSha1Signature, 'sign')
    @patch.object(rauth.session, 'time')
    @patch.object(rauth.session, 'random')
    @patch.object(requests.Session, 'request')
    def fake_request(self,
                     method,
                     url,
                     mock_request,
                     mock_random,
                     mock_time,
                     mock_sig,
                     header_auth=False,
                     realm='',
                     **kwargs):
        fake_random = 1
        fake_time = 1
        fake_sig = 'foo'
        fake_sig_meth = 'HMAC-SHA1'
        fake_nonce = sha1(str(fake_random).encode('ascii')).hexdigest()

        mock_request.return_value = self.response
        mock_random.return_value = fake_random
        mock_time.return_value = fake_time
        mock_sig.return_value = fake_sig

        method = method
        url = self.session._set_url(url)

        service = OAuth1Service(self.consumer_key,
                                self.consumer_secret,
                                name='service',
                                request_token_url=self.request_token_url,
                                access_token_url=self.access_token_url,
                                authorize_url=self.authorize_url,
                                base_url=self.base_url)

        session = service.get_session((self.access_token,
                                       self.access_token_secret))

        r = session.request(method,
                            url,
                            header_auth=header_auth,
                            realm=realm,
                            **deepcopy(kwargs))

        kwargs.setdefault('headers', {})
        kwargs['headers'] = CaseInsensitiveDict(kwargs['headers'])

        entity_method = method.upper() in ENTITY_METHODS
        if entity_method:
            kwargs['headers'].setdefault('Content-Type', FORM_URLENCODED)

        form_urlencoded = \
            kwargs['headers'].get('Content-Type') == FORM_URLENCODED

        if is_basestring(kwargs.get('params')):
            kwargs['params'] = dict(parse_qsl(kwargs['params']))

        if is_basestring(kwargs.get('data')) and form_urlencoded:
            kwargs['data'] = dict(parse_qsl(kwargs['data']))

        oauth_params = {'oauth_consumer_key': session.consumer_key,
                        'oauth_nonce': fake_nonce,
                        'oauth_signature_method': fake_sig_meth,
                        'oauth_timestamp': fake_time,
                        'oauth_token': self.access_token,
                        'oauth_version': session.VERSION,
                        'oauth_signature': fake_sig}

        if header_auth:
            auth = mock_request.call_args[1]['auth']
            auth_header = self.fake_get_auth_header(oauth_params, realm=realm)
            self.assertEqual(auth(requests.Request()).headers['Authorization'],
                             auth_header)
            kwargs['auth'] = auth
        elif entity_method:
            kwargs['data'] = kwargs.get('data') or {}

            if form_urlencoded:
                kwargs['data'].update(oauth_params)
            else:
                kwargs.setdefault('params', {})
                kwargs['params'].update(oauth_params)
        else:
            kwargs.setdefault('params', {})
            kwargs['params'].update(**oauth_params)

        mock_request.assert_called_with(method,
                                        url,
                                        timeout=OAUTH1_DEFAULT_TIMEOUT,
                                        **kwargs)
        return r

    def fake_get_session(self, token=None, signature=None):
        return self.session

    def test_get_session(self):
        s = self.service.get_session()
        self.assertIsInstance(s, OAuth1Session)

    def test_get_raw_request_token(self):
        resp = 'oauth_token=foo&oauth_token_secret=bar'
        self.response.content = resp
        r = self.service.get_raw_request_token()
        self.assertEqual(r.content, resp)

    def test_get_raw_request_token_missing_request_token_url(self):
        self.service.request_token_url = None
        resp = 'oauth_token=foo&oauth_token_secret=bar'
        self.response.content = resp
        with self.assertRaises(TypeError) as e:
            self.service.get_raw_request_token()
        self.assertEqual(str(e.exception),
                         'request_token_url must not be None')

    def test_get_request_token(self):
        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'
        request_token, request_token_secret = self.service.get_request_token()
        self.assertEqual(request_token, 'foo')
        self.assertEqual(request_token_secret, 'bar')

    def test_get_request_token_with_json_decoder(self):
        self.response.content = json.dumps({'oauth_token': 'foo',
                                            'oauth_token_secret': 'bar'})
        request_token, request_token_secret = \
            self.service.get_request_token(decoder=json.loads)
        self.assertEqual(request_token, 'foo')
        self.assertEqual(request_token_secret, 'bar')

    def test_get_authorize_url(self):
        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'
        request_token, request_token_secret = self.service.get_request_token()

        url = self.service.get_authorize_url(request_token)
        expected_fmt = 'http://example.com/authorize?oauth_token={0}'
        self.assertEqual(url, expected_fmt.format(request_token))

    def test_get_authorize_url_with_url_encoded_characters(self):
        token = 'uDV8XWNLSJjzMUSVfbG1gYHWMjY%3D'
        token_secret = 'e%2Bt9QCndiw1%2BtJbhy5UYVMAPTPo%3D'
        response_fmt = 'oauth_token={0}&oauth_token_secret={1}'
        self.response.content = response_fmt.format(token, token_secret)
        request_token, request_token_secret = self.service.get_request_token()

        url = self.service.get_authorize_url(request_token)
        expected_fmt = 'http://example.com/authorize?oauth_token={0}'
        self.assertEqual(url, expected_fmt.format(token))

    def test_get_raw_access_token(self):
        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'
        request_token, request_token_secret = self.service.get_request_token()

        resp = 'oauth_token=foo&oauth_token_secret=bar'
        self.response.content = resp
        r = self.service.get_raw_access_token(request_token,
                                              request_token_secret)
        self.assertEqual(r.content, resp)

    def test_get_raw_access_token_missing_access_token_url(self):
        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'
        request_token, request_token_secret = self.service.get_request_token()

        self.service.access_token_url = None
        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'

        with self.assertRaises(TypeError) as e:
            self.service.get_raw_access_token(request_token,
                                              request_token_secret)
        self.assertEqual(str(e.exception),
                         'access_token_url must not be None')

    def test_get_access_token(self):
        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'
        request_token, request_token_secret = self.service.get_request_token()

        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'
        access_token, access_token_secret = \
            self.service.get_access_token(request_token,
                                          request_token_secret)
        self.assertEqual(access_token, 'foo')
        self.assertEqual(access_token_secret, 'bar')

    def test_get_access_token_with_json_decoder(self):
        self.response.content = 'oauth_token=foo&oauth_token_secret=bar'
        request_token, request_token_secret = self.service.get_request_token()

        self.response.content = json.dumps({'oauth_token': 'foo',
                                            'oauth_token_secret': 'bar'})
        access_token, access_token_secret = \
            self.service.get_access_token(request_token,
                                          request_token_secret,
                                          decoder=json.loads)
        self.assertEqual(access_token, 'foo')
        self.assertEqual(access_token_secret, 'bar')

    def test_request_with_optional_params_oauth_callback(self):
        params = {'oauth_callback': 'http://example.com/callback'}
        r = self.session.request('GET', 'http://example.com/', params=params)
        self.assert_ok(r)

    def test_request_with_optional_params_oauth_verifier(self):
        params = {'oauth_verifier': 'foo'}
        r = self.session.request('GET', 'http://example.com/', params=params)
        self.assert_ok(r)

    def test_request_with_optional_params_oauth_version(self):
        params = {'oauth_verifier': 'foo'}
        r = self.session.request('GET', 'http://example.com/', params=params)
        self.assert_ok(r)

    def test_request_with_optional_params_as_string(self):
        params = 'oauth_callback=http://example.com/callback'
        r = self.session.request('GET', 'http://example.com/', params=params)
        self.assert_ok(r)

    def test_request_with_optional_data_as_string(self):
        data = 'oauth_callback=http://example.com/callback'
        r = self.session.request('POST', 'http://example.com/', data=data)
        self.assert_ok(r)

    def test_request_with_optional_params_with_data(self):
        data = {'oauth_callback': 'http://example.com/callback'}
        r = self.session.request('POST', 'http://example.com/', data=data)
        self.assert_ok(r)

    def test_request_with_header_auth(self):
        r = self.session.request('GET',
                                 'http://example.com/',
                                 header_auth=True)
        self.assert_ok(r)

    def test_request_with_header_auth_with_realm(self):
        r = self.session.request('GET',
                                 'http://example.com/',
                                 header_auth=True,
                                 realm='http://example.com/foo/')
        self.assert_ok(r)

    def test_get_auth_session(self):
        resp = 'oauth_token=foo&oauth_token_secret=bar'
        self.response.content = resp
        s = self.service.get_auth_session('foo', 'bar')
        self.assertIsInstance(s, OAuth1Session)

    def test_get_auth_session_with_request_token_response(self):
        resp = 'oauth_token=foo&oauth_token_secret=bar'
        self.response.content = resp
        self.service.request_token_response = 'ok'
        s = self.service.get_auth_session('foo', 'bar')
        self.assertEqual(s.request_token_response, 'ok')

    def test_pickle_session(self):
        session = pickle.loads(pickle.dumps(self.session))

        # Add the fake request back to the session
        session.request = self.fake_request
        r = session.request('GET', 'http://example.com/', header_auth=True)
        self.assert_ok(r)


text:
goobly ~= rocksdb + raft.

see the 'docs' folder for a more detailed design

# how to contribute?
* use clang-format on all your cpp code. This is what I use in emacs:
```
(global-set-key (kbd "<C-M-tab>") 'clang-format-buffer)
```
* submit PR's for any change / brainstorm ideas
* file issues

# how to get up and running quickly?
* build the transitive dependencies:

```
# assuming bash
# tested on ubuntu 14.04 x86_64 only
$ cd meta && source source_ansible_bash && ansible-playbook -K playbook/dev_all.yml
```

* That's it, just build & run the unit tests:

```
# add -j<cpus> to both make & ctest for parallelism
#
$ mkdir build && cd build && cmake .. && make && ctest -V
```

Yours truly,
[@gallegoxx](https://twitter.com/gallegoxx)


text:
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { UserLogin } from 'models';
import { NgForm } from '@angular/forms';

import { AuthenticationService } from '../../services/index';

@Component({
    selector: 'login',
    templateUrl: 'login.html'
})
export class LoginComponent  {
    @ViewChild(NgForm)
    ngForm: NgForm;

    model = new UserLogin();
    constructor(
            private authService: AuthenticationService,
            private router : Router
    ) { }

    login() {
        if (this.ngForm.form.invalid) {
            document.getElementById("badLogin").hidden = false;
            return;
        }else{
            document.getElementById("badLogin").hidden = true;
            this.authService.authenticate(this.model)
            .then((onfulfilled) => {
            this.router.navigate(['/'], "channel");
            }, (rejected) => {
                document.getElementById("badLogin").hidden = false;
            });
        }
    }
}


text:
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
 * jHue row selector plugin
 *
 */
;
(function ($, window, document, undefined) {

  var pluginName = "jHueRowSelector",
    defaults = {};

  function Plugin(element, options) {
    this.element = element;
    this.options = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  Plugin.prototype.setOptions = function (options) {
    this.options = $.extend({}, defaults, options);
  };

  Plugin.prototype.init = function () {
    var _this = this;
    $(_this.element).closest("tr").click(function (e) {
      if ($(e.target).data("row-selector-exclude") || $(e.target).closest("td").hasClass("row-selector-exclude")) {
        return;
      }
      if (!$(e.target).is("a")) {
        var href = $.trim($(_this.element).attr("href"));
        if (href != "" && href != "#" && href.indexOf("void(0)") == -1) {
          if (IS_HUE_4) {
            huePubSub.publish('open.link', $(_this.element).attr("href"));
          }
          else {
            location.href = $(_this.element).attr("href");
          }
        }
        else {
          $(_this.element).click();
        }
      }
    }).css("cursor", "pointer");
  };

  $.fn[pluginName] = function (options) {
    return this.each(function () {
      if (!$.data(this, 'plugin_' + pluginName)) {
        $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
      }
      else {
        $.data(this, 'plugin_' + pluginName).setOptions(options);
      }
    });
  }

})(jQuery, window, document);


text:
minifier
========

A simple tool for minifying CSS/JS without a big setup.

Feature highlights
------------------

- It minifies JS and CSS
- It reworks URLs in CSS from the original location to the output location.
- It automatically resolves `@import` statements in CSS.

How to install
--------------

There are two ways to install it:

1. `npm install [-g] minifier`
2. Cloning directly from [github](https://github.com/fizker/minifier).

Installing through `npm` will create a binary (`minify`) in the usual
locations. Cloning and installing from `github` will not, but the `index.js`
file can be executed either directly or via `node index.js`; this is the file
that the binary links to anyway.

How to run from a command-line
------------------------------

Running it is simple:

	minify [--output path/to/put/file] path/to/file

If the output parameter is not set, it will place a file next to the original,
with the suffix `.min`.

For example, `minifier script.js` will output `script.min.js`, whereas
`minifier --output out.js script.js` will output `out.js`.

A folder can also be targeted. When that is done, it will minify all css and js
file in that folder.

In that case, `--output` does not make much sense, as all files will be minified
to the same. If the name still requires a specific pattern such as a timestamp,
`--template` is the option for you. Note that files named after a template will
be left in the same folder as the original file.

There are various options available:

- `{{filename}}` is the original filename.
- `{{ext}}` is the extension.
- `{{sha}}` is a sha-digest of the unminified file contents.
- `{{md5}}` is a md5-digest of the unminified file contents.

For example, `{{filename}}-{{md5}}.min.{{ext}}` will make `abc.js` into something
like `abc-f90731d65c61af25b149658a120d26cf.min.js`.

To avoid the minification of previously minified files, there is a `--clean`
option, which will delete all files that match the output pattern.

This also means that any real files that match the pattern will be removed as
well, so please be careful.

Running from a node-script
--------------------------

It is also possible to run the minifier from within another node script:

	var minifier = require('minifier')
	var input = '/some/path'

	minifier.on('error', function(err) {
		// handle any potential error
	})
	minifier.minify(input, options)

As with the command-line variant, the input should be a path to either a
javascript file, a css file or a folder.

The options-dictionary takes the same parameters as the command-line variant:

- output: A path-string that tells where to put the output.
- template: A string template for how to build the outputted filenames.
- clean: A bool for whether other files with names similar to the template
  should be deleted before minifying the contents of a folder.
- cleanOnly: A bool for whether to run with `clean` option and then exiting
  before minifying any files.

There are one important additional option: `uglify`. This will be passed on to
uglify, so that the minification can be controlled. See the
[uglify documentation](https://github.com/mishoo/UglifyJS2#the-simple-way)
for more details (the `uglify.minify(path, opts)` function is used internally).

-----

The method for building the output name from the template is exposed for
convenience:

	var minifier = require('minifier')
	var file = 'abc.js'
	var template = '{{filename}}.{{md5}}.{{ext}}'
	var content = null; // or the content, if md5 or sha1 should be calculated
	var result = minifier.generateOutputName(file, { template: template, content: content })

If the input-path includes any folders, they will also be added to the output.

If `content` is eschewed, the `md5` and `sha` digests cannot be calculated.

But there is an option for turning them into either `RegExp` or `glob` compatible
syntax: Simply add `glob: true` or `regex: true` to the options array:

	var result = minifier.generateOutputName(file, { template: template, glob: true })

`glob` will return a string for passing to a `glob` function, whereas `regex`
will return a `RegExp` instance for manual comparison.

Concatenating multiple javascript files
---------------------------------------

It is possible to concatenate multiple javascript files into a single, minified file.

Simply pass multiple in via the CLI interface, or pass an array to the API.

They will have the same order as the input-parameter.

Running the tests
-----------------

After installing from [github](https://github.com/fizker/minifier), simply run
`npm test`.

There is a script called `prepareManualTests.js`, which will run the script
against the css-files inside `test/manual/css/` and provides a real-world
example of the CSS minification tools.

The manual tests can be seen by opening `test/manual/index.html` in a browser
after executing `prepareManualTests.js`.

Credits
-------

In no particular order:

- [duckduckgo](http://duckduckgo.com) for the image used by the manual tests.
- [sqwish](https://github.com/ded/sqwish) for minifying CSS files.
- [uglify-js](https://github.com/mishoo/UglifyJS2) for minifying JS files.
- [commander](https://github.com/visionmedia/commander.js) for command-line
  interaction.
- [mocha](https://github.com/visionmedia/mocha) and [chai](http://chaijs.com)
  for testing home-brewed logic.
- [glob](https://github.com/isaacs/node-glob) for trawling through the
  file-system when targetting a folder.
- [hogan.js](http://twitter.github.com/hogan.js/) for parsing the template
  string.


text:
var alasql = require('../../alasql');

alasql.from.csv = function (filename, opts) {
	var fs = require('fs');
	//	console.log(__dirname+'/'+filename);
	var txt = fs.readFileSync(filename).toString();
	var aaa = txt.split(/\r?\n/);
	var h = aaa.shift().split(',');
	//	console.log(h);
	return {rows: aaa, headers: h};
};

alasql(
	"select country_name into #city from csv('country.csv',@{headers:true}) where continent_code = 'AF'",
	[],
	function (res) {
		console.log(res[0]);
		console.log(alasql.temp.city);
	}
);


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0" metadata-complete="true">

    <distributable />
</web-app>


text:
typedef NS_ENUM(NSUInteger, AWFVenueType) {
	AWFVenueTypeUnknown = 0,
	AWFVenueTypeGas,
	AWFVenueTypeLodging,
	AWFVenueTypeFood,
	AWFVenueTypeMedical,
	AWFVenueTypeEmergencyRoom
};

@interface AWFVenue : AWFGeographicObject

@property (nonatomic, strong) NSString *code;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *category;
@property (nonatomic, strong) NSString *source;

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *address;
@property (nonatomic, strong) NSString *phone;
@property (nonatomic, strong) NSString *website;

@property (nonatomic, strong) NSString *adPath;
@property (nonatomic, strong) NSString *iconPath;
@property (nonatomic, strong) NSString *markerPath;

@property (nonatomic, readonly) BOOL isFoursquareVenue;

+ (NSString *)filterStringForVenueType:(enum AWFVenueType)venueType;

@end


text:
package org.apache.sysml.runtime.instructions.spark;

import java.util.ArrayList;
import java.util.Iterator;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.apache.spark.api.java.function.PairFunction;

import scala.Tuple2;

import org.apache.sysml.parser.Expression.DataType;
import org.apache.sysml.parser.Expression.ValueType;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.caching.MatrixObject.UpdateType;
import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;
import org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext;
import org.apache.sysml.runtime.functionobjects.DiagIndex;
import org.apache.sysml.runtime.functionobjects.RevIndex;
import org.apache.sysml.runtime.functionobjects.SortIndex;
import org.apache.sysml.runtime.functionobjects.SwapIndex;
import org.apache.sysml.runtime.instructions.InstructionUtils;
import org.apache.sysml.runtime.instructions.cp.CPOperand;
import org.apache.sysml.runtime.instructions.spark.functions.FilterDiagBlocksFunction;
import org.apache.sysml.runtime.instructions.spark.functions.IsBlockInList;
import org.apache.sysml.runtime.instructions.spark.functions.IsBlockInRange;
import org.apache.sysml.runtime.instructions.spark.utils.RDDAggregateUtils;
import org.apache.sysml.runtime.instructions.spark.utils.RDDSortUtils;
import org.apache.sysml.runtime.instructions.spark.utils.SparkUtils;
import org.apache.sysml.runtime.instructions.spark.functions.ReorgMapFunction;
import org.apache.sysml.runtime.matrix.MatrixCharacteristics;
import org.apache.sysml.runtime.matrix.data.LibMatrixReorg;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
import org.apache.sysml.runtime.matrix.data.MatrixIndexes;
import org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue;
import org.apache.sysml.runtime.matrix.operators.Operator;
import org.apache.sysml.runtime.matrix.operators.ReorgOperator;
import org.apache.sysml.runtime.util.DataConverter;
import org.apache.sysml.runtime.util.IndexRange;
import org.apache.sysml.runtime.util.UtilFunctions;

public class ReorgSPInstruction extends UnarySPInstruction {
	// sort-specific attributes (to enable variable attributes)
	private CPOperand _col = null;
	private CPOperand _desc = null;
	private CPOperand _ixret = null;
	private boolean _bSortIndInMem = false;

	private ReorgSPInstruction(Operator op, CPOperand in, CPOperand out, String opcode, String istr) {
		super(SPType.Reorg, op, in, out, opcode, istr);
	}

	private ReorgSPInstruction(Operator op, CPOperand in, CPOperand col, CPOperand desc, CPOperand ixret, CPOperand out,
			String opcode, boolean bSortIndInMem, String istr) {
		this(op, in, out, opcode, istr);
		_col = col;
		_desc = desc;
		_ixret = ixret;
		_bSortIndInMem = bSortIndInMem;
	}

	public static ReorgSPInstruction parseInstruction ( String str )
		throws DMLRuntimeException
	{
		CPOperand in = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
		CPOperand out = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
		String opcode = InstructionUtils.getOpCode(str);

		if ( opcode.equalsIgnoreCase("r'") ) {
			parseUnaryInstruction(str, in, out); //max 2 operands
			return new ReorgSPInstruction(new ReorgOperator(SwapIndex.getSwapIndexFnObject()), in, out, opcode, str);
		}
		else if ( opcode.equalsIgnoreCase("rev") ) {
			parseUnaryInstruction(str, in, out); //max 2 operands
			return new ReorgSPInstruction(new ReorgOperator(RevIndex.getRevIndexFnObject()), in, out, opcode, str);
		}
		else if ( opcode.equalsIgnoreCase("rdiag") ) {
			parseUnaryInstruction(str, in, out); //max 2 operands
			return new ReorgSPInstruction(new ReorgOperator(DiagIndex.getDiagIndexFnObject()), in, out, opcode, str);
		}
		else if ( opcode.equalsIgnoreCase("rsort") ) {
			String[] parts = InstructionUtils.getInstructionPartsWithValueType(str);
			InstructionUtils.checkNumFields(parts, 5, 6);
			in.split(parts[1]);
			out.split(parts[5]);
			CPOperand col = new CPOperand(parts[2]);
			CPOperand desc = new CPOperand(parts[3]);
			CPOperand ixret = new CPOperand(parts[4]);
			boolean bSortIndInMem = false;

			if(parts.length > 5)
				bSortIndInMem = Boolean.parseBoolean(parts[6]);

			return new ReorgSPInstruction(new ReorgOperator(new SortIndex(1,false,false)),
				in, col, desc, ixret, out, opcode, bSortIndInMem, str);
		}
		else {
			throw new DMLRuntimeException("Unknown opcode while parsing a ReorgInstruction: " + str);
		}
	}

	@Override
	public void processInstruction(ExecutionContext ec)
			throws DMLRuntimeException
	{
		SparkExecutionContext sec = (SparkExecutionContext)ec;
		String opcode = getOpcode();

		//get input rdd handle
		JavaPairRDD<MatrixIndexes,MatrixBlock> in1 = sec.getBinaryBlockRDDHandleForVariable( input1.getName() );
		JavaPairRDD<MatrixIndexes,MatrixBlock> out = null;
		MatrixCharacteristics mcIn = sec.getMatrixCharacteristics(input1.getName());

		if( opcode.equalsIgnoreCase("r'") ) //TRANSPOSE
		{
			//execute transpose reorg operation
			out = in1.mapToPair(new ReorgMapFunction(opcode));
		}
		else if( opcode.equalsIgnoreCase("rev") ) //REVERSE
		{
			//execute reverse reorg operation
			out = in1.flatMapToPair(new RDDRevFunction(mcIn));
			if( mcIn.getRows() % mcIn.getRowsPerBlock() != 0 )
				out = RDDAggregateUtils.mergeByKey(out, false);
		}
		else if ( opcode.equalsIgnoreCase("rdiag") ) // DIAG
		{
			if(mcIn.getCols() == 1) { // diagV2M
				out = in1.flatMapToPair(new RDDDiagV2MFunction(mcIn));
			}
			else { // diagM2V
				//execute diagM2V operation
				out = in1.filter(new FilterDiagBlocksFunction())
					     .mapToPair(new ReorgMapFunction(opcode));
			}
		}
		else if ( opcode.equalsIgnoreCase("rsort") ) //ORDER
		{
			// Sort by column 'col' in ascending/descending order and return either index/value

			//get parameters
			long[] cols = _col.getDataType().isMatrix() ? DataConverter.convertToLongVector(ec.getMatrixInput(_col.getName())) :
				new long[]{ec.getScalarInput(_col.getName(), _col.getValueType(), _col.isLiteral()).getLongValue()};
			boolean desc = ec.getScalarInput(_desc.getName(), _desc.getValueType(), _desc.isLiteral()).getBooleanValue();
			boolean ixret = ec.getScalarInput(_ixret.getName(), _ixret.getValueType(), _ixret.isLiteral()).getBooleanValue();
			boolean singleCol = (mcIn.getCols() == 1);
			out = in1;

			if( cols.length > mcIn.getColsPerBlock() )
				LOG.warn("Unsupported sort with number of order-by columns large than blocksize: "+cols.length);

			if( singleCol || cols.length==1 ) {
				// extract column (if necessary) and sort
				if( !singleCol )
					out = out.filter(new IsBlockInRange(1, mcIn.getRows(), cols[0], cols[0], mcIn))
						.mapValues(new ExtractColumn((int)UtilFunctions.computeCellInBlock(cols[0], mcIn.getColsPerBlock())));

				//actual index/data sort operation
				if( ixret ) //sort indexes
					out = RDDSortUtils.sortIndexesByVal(out, !desc, mcIn.getRows(), mcIn.getRowsPerBlock());
				else if( singleCol && !desc) //sort single-column matrix
					out = RDDSortUtils.sortByVal(out, mcIn.getRows(), mcIn.getRowsPerBlock());
				else if( !_bSortIndInMem ) //sort multi-column matrix w/ rewrite
					out = RDDSortUtils.sortDataByVal(out, in1, !desc, mcIn.getRows(), mcIn.getCols(), mcIn.getRowsPerBlock(), mcIn.getColsPerBlock());
				else //sort multi-column matrix
					out = RDDSortUtils.sortDataByValMemSort(out, in1, !desc, mcIn.getRows(), mcIn.getCols(), mcIn.getRowsPerBlock(), mcIn.getColsPerBlock(), sec, (ReorgOperator) _optr);
			}
			else { //general case: multi-column sort
				// extract columns (if necessary)
				if( cols.length < mcIn.getCols() )
					out = out.filter(new IsBlockInList(cols, mcIn))
						.mapToPair(new ExtractColumns(cols, mcIn));

				// append extracted columns (if necessary)
				if( mcIn.getCols() > mcIn.getColsPerBlock() )
					out = RDDAggregateUtils.mergeByKey(out);

				//actual index/data sort operation
				if( ixret ) //sort indexes
					out = RDDSortUtils.sortIndexesByVals(out, !desc, mcIn.getRows(), (long)cols.length, mcIn.getRowsPerBlock());
				else if( cols.length==mcIn.getCols() && !desc) //sort single-column matrix
					out = RDDSortUtils.sortByVals(out, mcIn.getRows(), cols.length, mcIn.getRowsPerBlock());
				else //sort multi-column matrix
					out = RDDSortUtils.sortDataByVals(out, in1, !desc, mcIn.getRows(), mcIn.getCols(),
						cols.length, mcIn.getRowsPerBlock(), mcIn.getColsPerBlock());
			}
		}
		else {
			throw new DMLRuntimeException("Error: Incorrect opcode in ReorgSPInstruction:" + opcode);
		}

		//store output rdd handle
		if( opcode.equalsIgnoreCase("rsort") && _col.getDataType().isMatrix() )
			sec.releaseMatrixInput(_col.getName());
		updateReorgMatrixCharacteristics(sec);
		sec.setRDDHandleForVariable(output.getName(), out);
		sec.addLineageRDD(output.getName(), input1.getName());
	}

	private void updateReorgMatrixCharacteristics(SparkExecutionContext sec)
		throws DMLRuntimeException
	{
		MatrixCharacteristics mc1 = sec.getMatrixCharacteristics(input1.getName());
		MatrixCharacteristics mcOut = sec.getMatrixCharacteristics(output.getName());

		//infer initially unknown dimensions from inputs
		if( !mcOut.dimsKnown() )
		{
			if( !mc1.dimsKnown() )
				throw new DMLRuntimeException("Unable to compute output matrix characteristics from input.");

			if ( getOpcode().equalsIgnoreCase("r'") )
				mcOut.set(mc1.getCols(), mc1.getRows(), mc1.getColsPerBlock(), mc1.getRowsPerBlock());
			else if ( getOpcode().equalsIgnoreCase("rdiag") )
				mcOut.set(mc1.getRows(), (mc1.getCols()>1)?1:mc1.getRows(), mc1.getRowsPerBlock(), mc1.getColsPerBlock());
			else if ( getOpcode().equalsIgnoreCase("rsort") ) {
				boolean ixret = sec.getScalarInput(_ixret.getName(), _ixret.getValueType(), _ixret.isLiteral()).getBooleanValue();
				mcOut.set(mc1.getRows(), ixret?1:mc1.getCols(), mc1.getRowsPerBlock(), mc1.getColsPerBlock());
			}
		}

		//infer initially unknown nnz from input
		if( !mcOut.nnzKnown() && mc1.nnzKnown() ){
			boolean sortIx = getOpcode().equalsIgnoreCase("rsort") && sec.getScalarInput(_ixret.getName(), _ixret.getValueType(), _ixret.isLiteral()).getBooleanValue();
			if( sortIx )
				mcOut.setNonZeros(mc1.getRows());
			else //default (r', rdiag, rsort data)
				mcOut.setNonZeros(mc1.getNonZeros());
		}
	}

	private static class RDDDiagV2MFunction implements PairFlatMapFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock>
	{
		private static final long serialVersionUID = 31065772250744103L;

		private ReorgOperator _reorgOp = null;
		private MatrixCharacteristics _mcIn = null;

		public RDDDiagV2MFunction(MatrixCharacteristics mcIn)
			throws DMLRuntimeException
		{
			_reorgOp = new ReorgOperator(DiagIndex.getDiagIndexFnObject());
			_mcIn = mcIn;
		}

		@Override
		public Iterator<Tuple2<MatrixIndexes, MatrixBlock>> call( Tuple2<MatrixIndexes, MatrixBlock> arg0 )
			throws Exception
		{
			ArrayList<Tuple2<MatrixIndexes, MatrixBlock>> ret = new ArrayList<>();

			MatrixIndexes ixIn = arg0._1();
			MatrixBlock blkIn = arg0._2();

			//compute output indexes and reorg data
			long rix = ixIn.getRowIndex();
			MatrixIndexes ixOut = new MatrixIndexes(rix, rix);
			MatrixBlock blkOut = (MatrixBlock) blkIn.reorgOperations(_reorgOp, new MatrixBlock(), -1, -1, -1);
			ret.add(new Tuple2<>(ixOut,blkOut));

			// insert newly created empty blocks for entire row
			int numBlocks = (int) Math.ceil((double)_mcIn.getRows()/_mcIn.getRowsPerBlock());
			for(int i = 1; i <= numBlocks; i++) {
				if(i != ixOut.getColumnIndex()) {
					int lrlen = UtilFunctions.computeBlockSize(_mcIn.getRows(), rix, _mcIn.getRowsPerBlock());
					int lclen = UtilFunctions.computeBlockSize(_mcIn.getRows(), i, _mcIn.getRowsPerBlock());
					MatrixBlock emptyBlk = new MatrixBlock(lrlen, lclen, true);
					ret.add(new Tuple2<>(new MatrixIndexes(rix, i), emptyBlk));
				}
			}

			return ret.iterator();
		}
	}

	private static class RDDRevFunction implements PairFlatMapFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock>
	{
		private static final long serialVersionUID = 1183373828539843938L;

		private MatrixCharacteristics _mcIn = null;

		public RDDRevFunction(MatrixCharacteristics mcIn)
			throws DMLRuntimeException
		{
			_mcIn = mcIn;
		}

		@Override
		public Iterator<Tuple2<MatrixIndexes, MatrixBlock>> call( Tuple2<MatrixIndexes, MatrixBlock> arg0 )
			throws Exception
		{
			//construct input
			IndexedMatrixValue in = SparkUtils.toIndexedMatrixBlock(arg0);

			//execute reverse operation
			ArrayList<IndexedMatrixValue> out = new ArrayList<>();
			LibMatrixReorg.rev(in, _mcIn.getRows(), _mcIn.getRowsPerBlock(), out);

			//construct output
			return SparkUtils.fromIndexedMatrixBlock(out).iterator();
		}
	}

	private static class ExtractColumn implements Function<MatrixBlock, MatrixBlock>
	{
		private static final long serialVersionUID = -1472164797288449559L;

		private int _col;

		public ExtractColumn(int col) {
			_col = col;
		}

		@Override
		public MatrixBlock call(MatrixBlock arg0)
			throws Exception
		{
			return arg0.slice(0, arg0.getNumRows()-1, _col, _col, new MatrixBlock());
		}
	}

	private static class ExtractColumns implements PairFunction<Tuple2<MatrixIndexes, MatrixBlock>,MatrixIndexes,MatrixBlock>
	{
		private static final long serialVersionUID = 2902729186431711506L;

		private final long[] _cols;
		private final int _brlen, _bclen;

		public ExtractColumns(long[] cols, MatrixCharacteristics mc) {
			_cols = cols;
			_brlen = mc.getRowsPerBlock();
			_bclen = mc.getColsPerBlock();
		}

		public Tuple2<MatrixIndexes, MatrixBlock> call(Tuple2<MatrixIndexes, MatrixBlock> arg0)
			throws Exception
		{
			MatrixIndexes ix = arg0._1();
			MatrixBlock in = arg0._2();
			MatrixBlock out = new MatrixBlock(in.getNumRows(), _cols.length, true);
			for(int i=0; i<_cols.length; i++)
				if( UtilFunctions.isInBlockRange(ix, _brlen, _bclen, new IndexRange(1, Long.MAX_VALUE, _cols[i], _cols[i])) ) {
					int index = UtilFunctions.computeCellInBlock(_cols[i], _bclen);
					out.leftIndexingOperations(in.slice(0, in.getNumRows()-1, index, index, new MatrixBlock()),
						0, in.getNumRows()-1, i, i, out, UpdateType.INPLACE);
				}
			return new Tuple2<>(new MatrixIndexes(ix.getRowIndex(), 1), out);
		}
	}
}


text:
Before do
  if ENV['DRIVER']
    Capybara.current_driver = ENV['DRIVER'].to_sym
  end
end


text:
var env = require('node-env-file')
// Load any undefined ENV variables from a specified file
env(__dirname + '/.env')

require('babel-core/register')
require('babel-polyfill')
require('./server')


text:
package org.home.whatsfordinner.common;

import org.home.whatsfordinner.domain.BaseEntity;

import static org.home.whatsfordinner.utils.Constants.FIXED_DATE_TIME_MILLIS_CREATION_DATE;
import static org.home.whatsfordinner.utils.Constants.FIXED_DATE_TIME_MILLIS_LAST_MODIFIED_DATE;
import static org.junit.Assert.assertEquals;

/**
 * Class used to test the persistence methods of a class.
 */
public class PersistenceJUnitTest {

    /**
     * Test the pre persist of the BaseEntity class.
     * Note: When calling this method make sure you have set the current millis fixed.
     * DateTimeUtils.setCurrentMillisFixed(FIXED_DATE_TIME_MILLIS_CREATION_DATE)
     *
     * @param entity
     */
    public static void testPrePersist(final BaseEntity entity) {
        assertEquals("The creation date of the entity is incorrect", FIXED_DATE_TIME_MILLIS_CREATION_DATE, entity.getCreationDate().getMillis());
        assertEquals("The last modified date of the entity is incorrect", FIXED_DATE_TIME_MILLIS_CREATION_DATE, entity.getLastModifiedDate().getMillis());
    }

    /**
     * Test the pre update of the BaseEntity class.
     * Note: When calling this method make sure you have set the current millis fixed.
     * DateTimeUtils.setCurrentMillisFixed(FIXED_DATE_TIME_MILLIS_LAST_MODIFIED_DATE)
     *
     * @param entity
     */
    public static void testPreUpdate(final BaseEntity entity) {
        assertEquals("The creation date of the entity should not be altered in the preUpdate", FIXED_DATE_TIME_MILLIS_CREATION_DATE, entity.getCreationDate().getMillis());
        assertEquals("The last modified date of the updated dish is incorrect", FIXED_DATE_TIME_MILLIS_LAST_MODIFIED_DATE, entity.getLastModifiedDate().getMillis());
    }
}


text:
namespace Yap
{
	class LogUserImpl : public ILogUser
	{
	public:
		~LogUserImpl();

		bool Init(const wchar_t * default_log, const wchar_t * default_module);
		virtual void SetLog(ILog * log) override;

		void Trace(const wchar_t * info, const wchar_t * module = nullptr, const wchar_t * log_name = nullptr);
		void Debug(const wchar_t * info, const wchar_t * module = nullptr, const wchar_t * log_name = nullptr);
		void Info (const wchar_t * info, const wchar_t * module = nullptr, const wchar_t * log_name = nullptr);
		void Warn (const wchar_t * info, const wchar_t * module = nullptr, const wchar_t * log_name = nullptr);
		void Error(const wchar_t * info, const wchar_t * module = nullptr, const wchar_t * log_name = nullptr);
		void Fatal(const wchar_t * info, const wchar_t * module = nullptr, const wchar_t * log_name = nullptr);

		static LogUserImpl& GetInstance();
	protected:
		LogUserImpl();

		static std::shared_ptr<LogUserImpl> s_instance;

		ILog * _log;
		std::wstring _module;
		std::wstring _log_name;
		bool _flush;
	};
}

#endif // LOGUSERIMPL_H_


text:
Magacin

           Šifra
           Naziv
           Adresa
           Mesto

         {{article.sifraMagacina}}
        {{article.nazivMagacina}}
        {{article.adresaMagacina}}
        {{article.mesto.nazivMesta}}

      <button class="btn btn-default" ng-click="add()">Dodaj</button>
       <button class="btn btn-default" ng-click="delete()">Obriši</button>
        <button class="btn btn-default" ng-click="update()">Izmeni</button>


text:
<?php

include_once('Config.class.php');

class StopTimesDao {

    public function __construct() {
        require('rb.php');
        R::setup(TECConfig::$DB, TECConfig::$DB_USER, TECConfig::$DB_PASSWORD);
    }

    /*
     *  Timezone set to Europe/Brussels
     */
    var $timezone = "Europe/Brussels";

    private $GET_DEPARTURES_BY_NAME_QUERY = "SELECT DISTINCT route.route_short_name, trip.trip_headsign, trip.direction_id, times.departure_time
                                    FROM tecgtfs_stop_times times
                                    JOIN tecgtfs_trips trip
                                        ON trip.trip_id = times.trip_id
                                    JOIN tecgtfs_routes route
                                        ON route.route_id = trip.route_id
                                    JOIN tecgtfs_calendar_dates calendar
                                        ON calendar.service_id = trip.service_id
                                    INNER JOIN tecgtfs_stops stop
                                        ON stop.stop_name = :stationName
                                    WHERE times.stop_id = stop.stop_id
                                    AND times.departure_time >= TIME(STR_TO_DATE(CONCAT(:hour, ':', :minute), '%k:%i'))
                                    AND calendar.date = STR_TO_DATE(CONCAT(:year, '-', :month, '-', :day), '%Y-%m-%d')
                                    AND (SELECT count(time.stop_id)
                                        FROM  tecgtfs_stop_times time
                                        WHERE time.trip_id = trip.trip_id
                                        AND time.arrival_time > times.departure_time) > 0
                                    ORDER BY times.departure_time
                                    LIMIT :offset, :rowcount;";

    private $GET_DEPARTURES_BY_ID_QUERY = "SELECT DISTINCT route.route_short_name, trip.trip_headsign, trip.direction_id, times.departure_time
                                    FROM tecgtfs_stop_times times
                                    JOIN tecgtfs_trips trip
                                        ON trip.trip_id = times.trip_id
                                    JOIN tecgtfs_routes route
                                        ON route.route_id = trip.route_id
                                    JOIN tecgtfs_calendar_dates calendar
                                        ON calendar.service_id = trip.service_id
                                    WHERE times.stop_id = :stationId
                                    AND times.departure_time >= TIME(STR_TO_DATE(CONCAT(:hour, ':', :minute), '%k:%i'))
                                    AND calendar.date = STR_TO_DATE(CONCAT(:year, '-', :month, '-', :day), '%Y-%m-%d')
                                    AND (SELECT count(time.stop_id)
                                        FROM  tecgtfs_stop_times time
                                        WHERE time.trip_id = trip.trip_id
                                        AND time.arrival_time > times.departure_time) > 0
                                    ORDER BY times.departure_time
                                    LIMIT :offset, :rowcount;";

    private $GET_ARRIVALS_BY_NAME_QUERY = "SELECT DISTINCT route.route_short_name, trip.trip_headsign, trip.direction_id, times.arrival_time
                                    FROM tecgtfs_stop_times times
                                    JOIN tecgtfs_trips trip
                                        ON trip.trip_id = times.trip_id
                                    JOIN tecgtfs_routes route
                                        ON route.route_id = trip.route_id
                                    JOIN tecgtfs_calendar_dates calendar
                                        ON calendar.service_id = trip.service_id
                                    INNER JOIN tecgtfs_stops stop
                                        ON stop.stop_name = :stationName
                                    WHERE times.stop_id = stop.stop_id
                                    AND times.arrival_time >= TIME(STR_TO_DATE(CONCAT(:hour, ':', :minute), '%k:%i'))
                                    AND calendar.date = STR_TO_DATE(CONCAT(:year, '-', :month, '-', :day), '%Y-%m-%d')
                                    AND (SELECT count(time.stop_id)
                                        FROM  tecgtfs_stop_times time
                                        WHERE time.trip_id = trip.trip_id
                                        AND time.arrival_time > times.departure_time) > 0
                                    ORDER BY times.arrival_time
                                    LIMIT :offset, :rowcount;";

    private $GET_ARRIVALS_BY_ID_QUERY = "SELECT DISTINCT route.route_short_name, trip.trip_headsign, trip.direction_id, times.arrival_time
                                    FROM tecgtfs_stop_times times
                                    JOIN tecgtfs_trips trip
                                        ON trip.trip_id = times.trip_id
                                    JOIN tecgtfs_routes route
                                        ON route.route_id = trip.route_id
                                    JOIN tecgtfs_calendar_dates calendar
                                        ON calendar.service_id = trip.service_id
                                    WHERE times.stop_id = :stationId
                                    AND times.arrival_time >= TIME(STR_TO_DATE(CONCAT(:hour, ':', :minute), '%k:%i'))
                                    AND calendar.date = STR_TO_DATE(CONCAT(:year, '-', :month, '-', :day), '%Y-%m-%d')
                                    AND (SELECT count(time.stop_id)
                                        FROM  tecgtfs_stop_times time
                                        WHERE time.trip_id = trip.trip_id
                                        AND time.arrival_time > times.departure_time) > 0
                                    ORDER BY times.arrival_time
                                    LIMIT :offset, :rowcount;";

    /**
     *
     * @param int $stationName The Name of a station (Required)
     * @param int $year The Year (Required)
     * @param int $month The Month (Required)
     * @param int $day The Day (Required)
     * @param int $hour The Hour (Required)
     * @param int $minute The Minute (Required)
     * @return array A List of Departures for a given station, date and starting from a given time
     */
    public function getDeparturesByName($stationName, $year, $month, $day, $hour, $minute, $offset=0, $rowcount=1024) {
        date_default_timezone_set($this->timezone);

        $arguments = array(":stationName" => urldecode($stationName), ":year" => urldecode($year), ":month" => urldecode($month), ":day" => urldecode($day), ":hour" => urldecode($hour), ":minute" => urldecode($minute), ":offset" => intval(urldecode($offset)), ":rowcount" => intval(urldecode($rowcount)));
        $query = $this->GET_DEPARTURES_BY_NAME_QUERY;

        $result = R::getAll($query, $arguments);
        return $this->parseStopTimes($result, $year, $month, $day);
    }

    /**
     *
     * @param int $stationId The ID of a station (Required)
     * @param int $year The Year (Required)
     * @param int $month The Month (Required)
     * @param int $day The Day (Required)
     * @param int $hour The Hour (Required)
     * @param int $minute The Minute (Required)
     * @return array A List of Departures for a given station, date and starting from a given time
     */
    public function getDeparturesByID($stationId, $year, $month, $day, $hour, $minute, $offset=0, $rowcount=1024) {
        date_default_timezone_set($this->timezone);

        $arguments = array(":stationId" => urldecode($stationId), ":year" => urldecode($year), ":month" => urldecode($month), ":day" => urldecode($day), ":hour" => urldecode($hour), ":minute" => urldecode($minute), ":offset" => intval(urldecode($offset)), ":rowcount" => intval(urldecode($rowcount)));
        $query = $this->GET_DEPARTURES_BY_ID_QUERY;

        $result = R::getAll($query, $arguments);
        return $this->parseStopTimes($result, $year, $month, $day);
    }

    /**
     *
     * @param int $stationName The Name of a station (Required)
     * @param int $year The Year (Required)
     * @param int $month The Month (Required)
     * @param int $day The Day (Required)
     * @param int $hour The Hour (Required)
     * @param int $minute The Minute (Required)
     * @return array A List of Arrivals for a given station, date and starting from a given time
     */
    public function getArrivalsByName($stationName, $year, $month, $day, $hour, $minute, $offset=0, $rowcount=1024) {
        date_default_timezone_set($this->timezone);

        $arguments = array(":stationName" => urldecode($stationName), ":year" => urldecode($year), ":month" => urldecode($month), ":day" => urldecode($day), ":hour" => urldecode($hour), ":minute" => urldecode($minute), ":offset" => intval(urldecode($offset)), ":rowcount" => intval(urldecode($rowcount)));
        $query = $this->GET_ARRIVALS_BY_NAME_QUERY;

        $result = R::getAll($query, $arguments);
        return $this->parseStopTimes($result, $year, $month, $day);
    }

    /**
     *
     * @param int $stationId The ID of a station (Required)
     * @param int $year The Year (Required)
     * @param int $month The Month (Required)
     * @param int $day The Day (Required)
     * @param int $hour The Hour (Required)
     * @param int $minute The Minute (Required)
     * @return array A List of Arrivals for a given station, date and starting from a given time
     */
    public function getArrivalsById($stationId, $year, $month, $day, $hour, $minute, $offset=0, $rowcount=1024) {
        date_default_timezone_set($this->timezone);

        $arguments = array(":stationId" => urldecode($stationId), ":year" => urldecode($year), ":month" => urldecode($month), ":day" => urldecode($day), ":hour" => urldecode($hour), ":minute" => urldecode($minute), ":offset" => intval(urldecode($offset)), ":rowcount" => intval(urldecode($rowcount)));
        $query = $this->GET_ARRIVALS_BY_ID_QUERY;

        $result = R::getAll($query, $arguments);
        return $this->parseStopTimes($result, $year, $month, $day);
    }

    /**
     * Parses the data that comes out of the queries and creates nice objects that could be returned to the user.
     */
    private function parseStopTimes($result, $year, $month, $day) {
        $stoptimes = array();
        foreach($result as &$row){
            $stoptime = array();

            $stoptime["short_name"] = $row["route_short_name"];
            //$stoptime["type"] = $row["route_type"];
            $stoptime["long_name"] = $row["trip_headsign"];
            //$stoptime["color"] = $row["route_color"];
            //$stoptime["text_color"] = $row["route_text_color"];
            $stoptime["direction"] = $row["direction_id"];

            if(isset($row["departure_time"])) {
                $timeString =  $row["departure_time"];
            } else {
                $timeString =  $row["arrival_time"];
            }

            $split = explode(':', $timeString);
            $hour = $split[0];
            $minute = $split[1];

            $date = mktime($hour, $minute, 0, $month, $day, $year);
            $stoptime["iso8601"] = date("c", $date);
            $stoptime["time"] = date("U", $date);

            $stoptimes[] = $stoptime;
        }

        return $stoptimes;
    }
}


text:
import logger from '@wdio/logger'
import Runner from '@wdio/runner'

const log = logger('wdio-lambda-runner')

module.exports.run = (event, context, callback) => {
    log.info('Start Lambda function...')
    const runner = new Runner()

    /**
     * run test
     */
    runner.run(event).catch((e) => {
        log.error(`Failed launching test session: ${e.stack}`)
        callback(e)
        context.fail(e)
    })

    runner.on('exit', (failures) => {
        log.info('call the callback', failures)
        callback(null, { failures })
    })
}


text:
<?xml version="1.0" encoding="utf-8"?>
<metadata>
	<view title="Contact">
		<message><![CDATA[Choose a contact layout.]]></message>
	</view>
</metadata>


text:
Load a mo file, retuan a lua function or table.
A sample and description(in chinese): http://zengrong.net/post/1986.htm

@see http://lua-users.org/lists/lua-l/2010-04/msg00005.html
Modifier zrong(zengrong.net)
Creation 2013-11-29

usage:

    local mo_data=assert(require("utils.Gettext").loadMOFromFile("main.mo"))
    print(mo_data["hello"])
   -- 你好
    print(mo_data["world"])
   -- nil

then you'll get a kind of gettext function:

    local gettext=assert(require("utils.Gettext").gettextFromFile("main.mo"))
    print(gettext("hello"))
   -- 你好
    print(gettext("world"))
    -- world

with a slight modification this will be ready-to-use for the xgettext tool:

    _ = assert(require("utils.Gettext").gettextFromFile("main.mo"))
    print(_("hello"))
    print(_("world"))
]]

-- Original description
-----------------------------------------------------------
-- load an mo file and return a lua table
-- @param mo_file name of the file to load
-- @return table on success
-- @return nil,string on failure
-- @copyright J.J?rgen von Bargen
-- @licence I provide this as public domain
-- @see http://www.gnu.org/software/hello/manual/gettext/MO-Files.html
-----------------------------------------------------------

local Gettext = {}

function Gettext._getFileData(mo_file)
	--- use lua io, cannot use in Android
	--[[
    local fd,err=io.open(mo_file,"rb")
    if not fd then return nil,err end
    local mo_data=fd:read("*all")
    fd:close()
	--]]

	--- use quick-cocos2d-x cc.FileUtils, cross-platform
	local mo_data = cc.HelperFunc:getFileData(mo_file)
	return mo_data
end

function Gettext.loadMOFromFile(mo_file)
	return Gettext.parseData(Gettext._getFileData(mo_file))
end

function Gettext.gettextFromFile(mo_file)
	return Gettext.gettext(Gettext._getFileData(mo_file))
end

function Gettext.gettext(mo_data)
	local __hash = Gettext.parseData(mo_data)
    return function(text)
        return __hash[text] or text
    end
end

function Gettext.parseData(mo_data)
    --------------------------------
    -- precache some functions
    --------------------------------
    local byte=string.byte
    local sub=string.sub

    --------------------------------
    -- check format
    --------------------------------
    local peek_long --localize
    local magic=sub(mo_data,1,4)
    -- intel magic 0xde120495
    if magic=="\222\018\004\149" then
        peek_long=function(offs)
            local a,b,c,d=byte(mo_data,offs+1,offs+4)
            return ((d*256+c)*256+b)*256+a
        end
    -- motorola magic = 0x950412de
    elseif magic=="\149\004\018\222" then
        peek_long=function(offs)
            local a,b,c,d=byte(mo_data,offs+1,offs+4)
            return ((a*256+b)*256+c)*256+d
        end
    else
        return nil,"no valid mo-file"
    end

    --------------------------------
    -- version
    --------------------------------
    local V=peek_long(4)
    if V~=0 then
        return nul,"unsupported version"
    end

    ------------------------------
    -- get number of offsets of table
    ------------------------------
    local N,O,T=peek_long(8),peek_long(12),peek_long(16)
    ------------------------------
    -- traverse and get strings
    ------------------------------
    local hash={}
    for nstr=1,N do
        local ol,oo=peek_long(O),peek_long(O+4) O=O+8
        local tl,to=peek_long(T),peek_long(T+4) T=T+8
        hash[sub(mo_data,oo+1,oo+ol)]=sub(mo_data,to+1,to+tl)
    end
    return hash    -- return table
end

return Gettext