text:
 1. Clone repo
 2. ```cd``` to repo dir.
 3. Add platform support
    * Android: ```cordova platform add android```
    * iOS: ```cordova platform add ios```
 4. Add [ble-central plugin](https://github.com/don/cordova-plugin-ble-central): ```cordova plugin add com.megster.cordova.ble```
 5. Run:
    * Android: ```cordova run android --device```
    * iOS: ```cordova run ios --device```

### Arduino

 1. Setup [ir_bridge.ino](https://github.com/sandeepmistry/arduino-BLEPeripheral/blob/master/examples/ir_bridge/ir_bridge.ino) example sketch from [arduino-BLEPeripheral](https://github.com/sandeepmistry/arduino-BLEPeripheral)

## Usage

### Regular mode

 1. Press black button to send programmed button IR signal.

__Note__: Unprogrammed buttons are disabled (grayed out).

### Program mode

 1. Press "Program" button, buttons turn blue.
 2. Press button you wish to program, selected button remains blue (others disabled).
 3. Point regular IR remote at IR receiver attached to Arduino, press button the remote.
 4. Value for button saved in app.
 5. App switches to regular mode.


text:
          <button class="link-button" id="moreInfoButton"
                  i18n-content="more_info"></button>

        <select id="channelSelect">
          <option value="stable-channel" i18n-content="stable"></option>
          <option value="beta-channel" i18n-content="beta"></option>
          <option value="dev-channel" i18n-content="dev"></option>
        </select>

WebKit

        <button disabled id="checkNow" i18n-content="check_now"></button>

redpajama_set_name: RedPajamaGithub


text:
namespace palo {

class Expr;
struct ExprValue;
class TupleRow;

class MathFunctions {
public:
    static void init();

    static palo_udf::DoubleVal pi(palo_udf::FunctionContext* ctx);
    static palo_udf::DoubleVal e(palo_udf::FunctionContext* ctx);

    static palo_udf::DoubleVal abs(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::FloatVal sign(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& v);

    static palo_udf::DoubleVal sin(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal asin(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal cos(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal acos(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal tan(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal atan(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);

    static palo_udf::BigIntVal ceil(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::BigIntVal floor(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::BigIntVal round(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& v);
    static palo_udf::DoubleVal round_up_to(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& v,
        const palo_udf::IntVal& scale);
    static palo_udf::DoubleVal truncate(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& v,
        const palo_udf::IntVal& scale);

    static palo_udf::DoubleVal ln(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal log(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& base,
        const palo_udf::DoubleVal& v);
    static palo_udf::DoubleVal log2(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& v);
    static palo_udf::DoubleVal log10(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal exp(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);

    static palo_udf::DoubleVal radians(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& v);
    static palo_udf::DoubleVal degrees(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& v);

    static palo_udf::DoubleVal sqrt(palo_udf::FunctionContext*, const palo_udf::DoubleVal&);
    static palo_udf::DoubleVal pow(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& base,
        const palo_udf::DoubleVal& exp);

    /// Used for both Rand() and RandSeed()
    static void rand_prepare(
        palo_udf::FunctionContext*, palo_udf::FunctionContext::FunctionStateScope);
    static palo_udf::DoubleVal rand(palo_udf::FunctionContext*);
    static palo_udf::DoubleVal rand_seed(
        palo_udf::FunctionContext*, const palo_udf::BigIntVal& seed);

    static palo_udf::StringVal bin(
        palo_udf::FunctionContext* ctx, const palo_udf::BigIntVal& v);
    static palo_udf::StringVal hex_int(
        palo_udf::FunctionContext* ctx, const palo_udf::BigIntVal& v);
    static palo_udf::StringVal hex_string(
        palo_udf::FunctionContext* ctx, const palo_udf::StringVal& s);
    static palo_udf::StringVal unhex(
        palo_udf::FunctionContext* ctx, const palo_udf::StringVal& s);

    static palo_udf::StringVal conv_int(
        palo_udf::FunctionContext* ctx, const palo_udf::BigIntVal& num,
        const palo_udf::TinyIntVal& src_base, const palo_udf::TinyIntVal& dest_base);
    static palo_udf::StringVal conv_string(
        palo_udf::FunctionContext* ctx, const palo_udf::StringVal& num_str,
        const palo_udf::TinyIntVal& src_base, const palo_udf::TinyIntVal& dest_base);

    static palo_udf::BigIntVal pmod_bigint(
        palo_udf::FunctionContext* ctx, const palo_udf::BigIntVal& a,
        const palo_udf::BigIntVal& b);
    static palo_udf::DoubleVal pmod_double(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& a,
        const palo_udf::DoubleVal& b);
    static palo_udf::FloatVal fmod_float(
        palo_udf::FunctionContext*, const palo_udf::FloatVal&,
        const palo_udf::FloatVal&);
    static palo_udf::DoubleVal fmod_double(
        palo_udf::FunctionContext*, const palo_udf::DoubleVal&,
        const palo_udf::DoubleVal&);

    static palo_udf::BigIntVal positive_bigint(
        palo_udf::FunctionContext* ctx, const palo_udf::BigIntVal& val);
    static palo_udf::DoubleVal positive_double(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& val);
    static palo_udf::DecimalVal positive_decimal(
        palo_udf::FunctionContext* ctx, const palo_udf::DecimalVal& val);
    static palo_udf::BigIntVal negative_bigint(
        palo_udf::FunctionContext* ctx, const palo_udf::BigIntVal& val);
    static palo_udf::DoubleVal negative_double(
        palo_udf::FunctionContext* ctx, const palo_udf::DoubleVal& val);
    static palo_udf::DecimalVal negative_decimal(
        palo_udf::FunctionContext* ctx, const palo_udf::DecimalVal& val);

    static palo_udf::TinyIntVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::TinyIntVal* args);
    static palo_udf::TinyIntVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::TinyIntVal* args);
    static palo_udf::SmallIntVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::SmallIntVal* val);
    static palo_udf::SmallIntVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::SmallIntVal* val);
    static palo_udf::IntVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::IntVal* val);
    static palo_udf::IntVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::IntVal* val);
    static palo_udf::BigIntVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::BigIntVal* val);
    static palo_udf::BigIntVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::BigIntVal* val);
    static palo_udf::LargeIntVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::LargeIntVal* val);
    static palo_udf::LargeIntVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::LargeIntVal* val);
    static palo_udf::FloatVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::FloatVal* val);
    static palo_udf::FloatVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::FloatVal* val);
    static palo_udf::DoubleVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::DoubleVal* val);
    static palo_udf::DoubleVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::DoubleVal* val);
    static palo_udf::StringVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::StringVal* val);
    static palo_udf::StringVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::StringVal* val);
    static palo_udf::DateTimeVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::DateTimeVal* val);
    static palo_udf::DateTimeVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::DateTimeVal* val);
    static palo_udf::DecimalVal least(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::DecimalVal* val);
    static palo_udf::DecimalVal greatest(
        palo_udf::FunctionContext* ctx, int num_args, const palo_udf::DecimalVal* val);

private:
    static const int32_t MIN_BASE = 2;
    static const int32_t MAX_BASE = 36;
    static const char* _s_alphanumeric_chars;

    // Converts src_num in decimal to dest_base,
    // and fills expr_val.string_val with the result.
    static palo_udf::StringVal decimal_to_base(
        palo_udf::FunctionContext* ctx, int64_t src_num, int8_t dest_base);

    // Converts src_num representing a number in src_base but encoded in decimal
    // into its actual decimal number.
    // For example, if src_num is 21 and src_base is 5,
    // then this function sets *result to 2*5^1 + 1*5^0 = 11.
    // Returns false if overflow occurred, true upon success.
    static bool decimal_in_base_to_decimal(int64_t src_num, int8_t src_base, int64_t* result);

    // Helper function used in Conv to implement behavior consistent
    // with MySQL and Hive in case of numeric overflow during Conv.
    // Inspects parse_res, and in case of overflow sets num to MAXINT64 if dest_base
    // is positive, otherwise to -1.
    // Returns true if no parse_res == PARSE_SUCCESS || parse_res == PARSE_OVERFLOW.
    // Returns false otherwise, indicating some other error condition.
    static bool handle_parse_result(
            int8_t dest_base,
            int64_t* num,
            StringParser::ParseResult parse_res);

};

}

#endif


text:
package com.smartapps.smartkids.smartkids.Modele;

import com.smartapps.smartkids.smartkids.Controlleur.AttaqueEnum;
import com.smartapps.smartkids.smartkids.Controlleur.MainEnum;

/**
 * Created by Esteban Puello on 10/08/2017.
 */

public class Jeueur extends JeueurA {

    public Jeueur() {
    }

    @Override
    public AttaqueEnum attaque(JeueurA j) {
        return null;
    }

    @Override
    public AttaqueEnum attaque(JeueurA j, AttaqueEnum ae) {

        return null;
    }
}


text:
/*
 * BindingContext.java
 * Created: 19-Apr-2004
 * By: Rick Cameron
 */

package org.openquark.samples.bam;

import org.openquark.gems.client.CollectorGem;

/**
 * Interface BindingContext
 *
 * This interface allows the retrieval of CollectorGems to be used for binding
 * the inputs of gems whilst building a gem graph
 *
 */
public interface BindingContext {

    /**
     * Method getCollector
     *
     * @param id
     * @return Returns the CollectorGem for the given message property
     */
    CollectorGem getCollector (Object id);

}


text:
class Spinach::Features::User < Spinach::FeatureSteps
  include SharedAuthentication
  include SharedPaths
  include SharedUser
  include SharedProject

  step 'I should see user "John Doe" page' do
    expect(title).to match(/^\s*John Doe/)
  end
end


text:
@interface TBNBeerXMLEquipmentParser : TBNBeerXMLParser

@end


text:
/*
 * lightem - light 'em up! a library to control RGB LED's
 */

#ifndef LIGHTEM_H_
#define LIGHTEM_H_

#include <stdint.h>

#ifdef __cplusplus
class lightem {
public:

  static const size_t sz_frame = 7;

  lightem();
  ~lightem();

  uint32_t color(uint8_t r, uint8_t g, uint8_t b);

  void setColor(uint32_t color);
  inline void setColor(uint8_t r, uint8_t g, uint8_t b) { setColor(color(r,g,b)); }
  void setAddr(int led);

  int isPixelValue(void);
  int isValid(void);

  uint8_t* getAddr(size_t* psz);
  int getAddr(void);
  uint32_t getColor(void);

  /**
   * This method will copy the first 7 octets from f to the internal buffer
   *
   * \param f   pointer to a min 7 octet wide buffer
   *
   * \return 0  The frame is considered as invalid
   * \return 1  The frame is valid
   */
  int setFrame(const void* f);
  /**
   * This method will return a copy of the current frame.
   *
   * You have to free the pointer returned by yourself.
   */
  void* getFrame(size_t *psz);

private:

  uint8_t frame[7];

  uint8_t _csum(uint8_t* p);
  void createCsum(void);

};
extern "C" {
#endif /* __cplusplus */

  /**
   * This method creates a frame and returns a copy of it.
   *
   * You have to free the pointer returned by yourself.
   */
  void* lightem_c (int addr, uint8_t r, uint8_t g, uint8_t b, size_t *psz);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* LIGHTEM_H_ */


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fieldiana, Bot. 21: 98 (1989)

#### Original name
Hiatulopsis aureoflava Singer, 1989

### Remarks
null


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe "Howkast::Processor::Videos" do
  before :all do
    @config ||= YAML.load File.read(File.expand_path(File.dirname(__FILE__) + '/../../../.howkast'))
    Howkast::configure @config
    @howcast = Howkast::API.new
  end

  it "should raise an error if given a non-valid video ID" do
    lambda{ @howcast.video :id => '9999999999999999999999999' }.should \
    raise_error Howkast::Error::RequestError
  end

  it "should return a Video object given a valid video ID" do
    video = @howcast.video :id => 6570
    video.should be_an_instance_of Howkast::Model::Video
  end

  it "should return an array of Video objects" do
    categories = @howcast.categories.map{ |category| category.permalink.split('/').last }
    categories = categories[0 .. 9]
    categories << nil
    categories.each do |category|
      %w{ most_viewed most_recent top_rated }.each do |sort|
        %w{ all howcast_studios }.each do |filter|
          opts = { :sort => sort, :filter => filter }
          opts[:category] = category unless category.nil?
          list = @howcast.videos opts
          list.should be_an_instance_of Array
          list.each do |entry|
            entry.should be_an_instance_of Howkast::Model::Video
          end
        end
      end
    end
  end
end


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

using Google.Api.Gax;
using System;
using System.Threading;

namespace Google.Cloud.Diagnostics.AspNetCore
{
    /// Scope for the <see cref="GoogleLogger"/>.
    internal class GoogleLoggerScope : IDisposable
    {
        private static AsyncLocal<GoogleLoggerScope> _current = new AsyncLocal<GoogleLoggerScope>();

        ///
        /// The current scope, can be null.
        ///
        public static GoogleLoggerScope Current
        {
            get
            {
                return _current.Value;
            }
            set
            {
                _current.Value = value;
            }
        }

        /// The state associated with the this scope.
        public object State { get; }

        /// The parent scope, can be null.
        public GoogleLoggerScope Parent { get; }

        public GoogleLoggerScope(object state)
        {
            State = GaxPreconditions.CheckNotNull(state, nameof(state));
            Parent = Current;
            Current = this;
        }

        /// Disposes of the current scope.
        public void Dispose() => Current = Current?.Parent;

        ///
        /// Gets the scope (and parents') as a string. It is in the format:
        /// "grandparent => parent => child => " where the scope
        /// value is "child", its parent is "parent" and its grandparent is "grandparent".
        ///
        public override string ToString() => $"{Parent}{State} => ";
    }
}


text:
<?php

namespace NilPortugues\Tests\SchemaOrg\Classes;

use NilPortugues\SchemaOrg\Classes\PhysicalActivityCategory;
use NilPortugues\SchemaOrg\Mapping;

/**
 * Classes PhysicalActivityCategoryTest
 * @package NilPortugues\Tests\SchemaOrg\Classes
 */
class PhysicalActivityCategoryTest extends \PHPUnit_Framework_TestCase
{
    public function testSchemaUrlReturnsExpectedUrl()
    {
        $this->assertEquals(PhysicalActivityCategory::schemaUrl(), "http://schema.org/PhysicalActivityCategory");
    }

    public function testAdditionalTypeWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::additionalType());
    }

    public function testAlternateNameWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::alternateName());
    }

    public function testCodeWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::code());
    }

    public function testDescriptionWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::description());
    }

    public function testGuidelineWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::guideline());
    }

    public function testImageWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::image());
    }

    public function testMainEntityOfPageWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::mainEntityOfPage());
    }

    public function testMedicineSystemWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::medicineSystem());
    }

    public function testNameWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::name());
    }

    public function testPotentialActionWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::potentialAction());
    }

    public function testRecognizingAuthorityWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::recognizingAuthority());
    }

    public function testRelevantSpecialtyWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::relevantSpecialty());
    }

    public function testSameAsWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::sameAs());
    }

    public function testStudyWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::study());
    }

    public function testSupersededByWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::supersededBy());
    }

    public function testUrlWillReturnMappingObject()
    {
        $this->assertInstanceOf(Mapping::class, PhysicalActivityCategory::url());
    }
}


text:
var find = require('findit');
var finder = find(process.cwd());
var ncu = require('npm-check-updates');
var currentdirectory = process.cwd();
var npmsToInstall = [];
finder.on('file', function (file, stat) {
  if (file.indexOf('package.json') > -1) {
    console.log('Examining package: ' + file);
    npmsToInstall.push(file);
  }
});
finder.on('directory', function (dir, stat, stop) {
  if (dir.indexOf('bower_components') > -1) {
    console.log('Ingnoring ' + dir);
    stop();
  }
  if (dir.indexOf('node_modules') > -1) {
    console.log('Ingnoring ' + dir);
    stop();
  }
  if (dir.indexOf('.git') > -1) {
    console.log('Ingnoring ' + dir);
    stop();
  }
  currentdirectory = dir;
});
finder.on('end', function () {
  console.log('====== upgrading ======');
  installnpm(0, npmsToInstall);  //console.dir(bowersToInstall);
});
var result = '';
var installnpm = function (index, array) {
  var file = array[index];
  console.log('======== installing =======');
  console.log(file);
  ncu.run({
    packageFile: file,
    packageManager: 'npm',
    upgrade: true,
    upgradeall: true,
    jsonUpgraded: false
  }).then(function (upgraded) {
    console.log('dependencies to upgrade:', upgraded);
    index++;
    if (index < array.length) {
      installnpm(index, array);
    }
  });
};


text:
@implementation LibraryFoldersController

+ (NSMutableArray *)libraryFolders {
  static NSMutableArray *arr = nil;
  if (arr == nil) {
    arr = [NSMutableArray arrayWithArray:[DefaultsManager objectForKey:kDefaultsKeyLibraryFolders]];
  }
  return arr;
}

+ (void)save {
  [DefaultsManager setObject:[self libraryFolders] forKey:kDefaultsKeyLibraryFolders];
}

@end


text:
package com.company;

import java.util.Scanner;

public class ReverseCharacters {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        char[] input = new char[3];

        for (int i = 0; i < input.length; i++) {
            input[i] = scanner.next().charAt(0);
        }

        for (int i = input.length - 1; i >= 0 ; i--) {
            System.out.print(input[i]);
        }
    }
}


text:
function [Time_units,rho_vec,nn,total_prop_op]=HEOM_plus_light...
            (Htot,QQ,rho_0,cc_com,cc_acom,vv,Kap1,Kap2,viblvls,...
            E_t, omega,mu, wave_vec_trunc , use_RWA,...
            numpoints,tendps,saveuptotier,use_reduced_mat,save_file_name)

%In this version cc and vv and cell arrays
%All terms in inverse cm, conversion to sensible units achieved by
%E = hc / lamba => 6.62606957 *10^{-33} 299792458 *10 * "E in code" gives
%
%% Inputs
 % Htot is the total N site + ground state system and
 % whatever vibrations are treated quantum mechanically.
 % QQ is the extra convergence parameter made up of all the terms of the
 % form int_0^t d tau exp(-v (t-tau)) * ( c_1 V^X(tau) + c_2 V^O(tau) )
 %  which are evaluated via exp(-v (t-tau)) ~ delta(t-tau)/v, as v->inf
 % and are thus just markovian terms.
 % cc_com = coefficients with exp(-vv*t) prefact contributing to V^x
 % cc_acom = coefficients with exp(-vv*t) prefact contributing to V^o
 % i.e. the anti commutator part
 % each of these is paired with a frequency vv
 % N is the total number of states
 N = length(Htot);
% E_t time dependent electric field envelope, SYMBOLIC in t, e.g. exp(-(t-1)^2/10)
% omega is the frequency
% mu dipole coupling operator, in general this is a tensor quantity
% wave_vec_trunc: how many additional density matricies with factors of
% exp(1i*j*dot(k,r)) in front to include.  this sets the maximum j.  Note
% this is related to the order of time dep pert theory considered, chosing
% wave_vec_trunc = n is equiv to 2nth order TDPT
% use_RWA: logical, whether rotating wave approx used
V_int = -(mu{1}*E_t(1) + mu{2}*E_t(2) + mu{3}*E_t(3));
%V_int_p = -(mu{1}*E_t(1) + mu{2}*E_t(2) + mu{3}*E_t(3))*exp(1i*omega*t);
%V_int_m = -(mu{1}*E_t(1) + mu{2}*E_t(2) + mu{3}*E_t(3))*exp(-1i*omega*t);
%interaction terms in the hamiltonian split into fwd and backward waves

 if saveuptotier > Kap2
     warning('ordered to save up to a tier above the truncation threshold, will reduce')
     saveuptotier = Kap2
 end
 %Kappa = size(cc1,2); now delt with before the function
% Kappa e.g.= 1; %truncation parameter satisfying Kappa >>omega_0 beta hbar/2pi
 %beyond this e^(-v_(k>kappa) t)*v_k ~delta(t) is made
 % Kap1 e.g. = 4*omega_0 (frequency of significant transition), this
 % truncation parameter is used instead of / as well as Kap2, this
 % truncates the heirarchy based on cc dot vv via the approximation
 % exp(-cc.vv*t) ~ delta(t)/(cc.vv)
% Kap2 e.g.= 4; %second truncation parameter, there are Kappa + 1 explicitly
 %treated exponentials, this number is the maximum order the sum of the
 %number of powers can take, e.g. n_1 + n_2 +... + n_Kappa <= Kap2
 % numpoints is the number of time points to save of the solved equation
 % for all the auxilary density matricies
 % tendps e.g.= 2 is the end time in pico seconds
% rho_0 is some initial condition
% saveonlyrho00 is a flag which makes the solver save only rho00
if ~exist('saveuptotier','var')
    saveuptotier =0;
end
if ~exist('use_reduced_mat','var')
    use_reduced_mat =false;
end
if ~exist('save_file_name','var')
   save_file_name  = 'saved_data.mat';
end
 %use_reduced_mat =1; %include only linearly independent elements of rho
 %i.e. for 2 X 2 rho: rho_vec_red rho_11, rho_21, p_22
 %tested to work ONLY for drude

    light_speed = 299792458; %units m s^{-1}, NOT cm
    length_unit = 100; % units m, this is 1/[1(cm)^{-1}]
% to run the code not as a function just uncomment and use each module
% Energy in Joules,  extra factor of 10 is because thats speed in cm/s
convfact = 2*pi * light_speed *length_unit  *10^(-12); %2 pi * "c" in cm/s * 1ps
tend =convfact*tendps; %end time in units you get by putting everything in wavenumbers
totpoles = sum(cellfun(@length,cc_com));
tic

%% Construct Ltot, the total Louville for self coupling density matricies

% For N X N A and B we have the following
% reshape(A * B, N^2,1) = kron(eye(N),A)*reshape(B, N^2,1)
% reshape(B * A, N^2,1) = kron(A.',eye(N))*reshape(B, N^2,1)
% Hence H rho - rho H can be expressed with a flattened rho as L *rho

 LL = -1i*(kron(eye(length(Htot)),Htot)-kron(Htot.',eye(length(Htot))));
 L2 = -1i*(kron(eye(length(Htot)),V_int)-kron(V_int.',eye(length(Htot))));
 %symbolic liouvillian for the interaction, these couple to terms with
 %different spatial phase factors

% QQ as input should be the constants in the correction
if size(QQ) == size(LL) %assume matrix given that is Q
    Q = QQ; clear QQ
else
if size(QQ,1) == 1 %assume same for every site
    QQ = repmat(QQ,N*viblvls,1);
end
 Q = LL*0;
%
% %if include_truncation_correction
for j = 1:N

    Qj = zeros(N);
    Qj(j,j) = 1;  Qj = kron(Qj,eye(viblvls));eyeQ = eye(length(Qj));

      %note Qj^2 = Qj so I don't need to worry about this

    Q = Q + QQ(j,1).*(kron(Qj.',eyeQ) + kron(eyeQ,Qj) - 2*kron(Qj.',Qj));
    Q = Q  + QQ(j,2) .*(kron(Qj.',eyeQ) - kron(eyeQ,Qj));

    %reshape(A * B * A, N^2,1) = kron(A.',A)*reshape(B, N^2,1)
    %[Q_i,[Q_i,rho_n]] = (1 X Q_i*Q_i + Q_i^T*Q_i^T X 1 - 2 Q_i^T X Q_i ) rho_vec
    % with rho_vec the flattened (vector) version of rho_n (matrix)

    % .*(kron(Vj.',eyeQ) + kron(eyeQ,Vj));
end
% %end
end
Ltot = (LL-Q);
%in principle Q can also include high frequency decaying components from
% poles in J(omega)

%% Construct labels for auxilliary density matrix

if isempty(Kap1)
    Kap1 = inf; %no truncation based on Kap1
end

if Kap2>0  %else trivial

numwithn = zeros(1,Kap2+1); %size(cc2,2) is number of poles in J(omega)
tot_poles = sum(cellfun(@length,cc_com));
for kk = 0:Kap2
numwithn(kk+1) = nchoosek(tot_poles-1+kk,kk);
%number of density operators with each order, equal to size of
%irreducible nth power rep of sym group U(N*(Kappa+size(cc2,2)))
end

if length(Kap1)>1 %this is an overloading to allow you to just pass nn
    %straight to the function if it has already been calculated before
   nn = Kap1; totfreq = horzcat(vv{:}).';
else

nn = zeros(sum(numwithn),tot_poles); %if Kap1 <inf then less elements may be present
totfreq = horzcat(vv{:}).';
count1=0; tmp3 = 0;
for k =2:Kap2+1

        count2 = count1 + size(tmp3,1);

        tmp3 = zeros(length(count1+1:count2)*size(nn,2),size(nn,2));
       for j = count1+1:count2
        tmp = repmat(nn(j,:),size(nn,2),1); %select element from tier below
        tmp2 = tmp+eye(size(nn,2)); %add one to every position
        tmp3(1+(j-(count1+1))*size(nn,2):(j-count1)*size(nn,2) ,:) = tmp2;
       end
       %remove any elements of tmp3 which fail to satisfy the high
       %frequency cut off condition
       lg = true(size(tmp3,1),1);
       if isfinite(Kap1)
            for j =1:length(count1+1:count2)*size(nn,2)
                lg(j) = tmp3(j,:)*real(totfreq) < Kap1;
            end
       end
       tmp3 = tmp3(lg,:);
       %now remove duplicate entries
       jj=1;
       while jj < size(tmp3,1)-1
           lg = any(tmp3(jj+1:end,:)  ~= repmat(tmp3(jj,:),size(tmp3,1)-jj,1),2);
           tmp3 = tmp3([true(jj,1);lg],:);
           jj=jj+1;
       end
       count1 = count2;
       nn(count1+1:count1 + size(tmp3,1),:) = tmp3;
end
end

%would be good to include a complicated truncation condition such that
%weakly coupled modes could be taken only to lower orders

%clean any nn values which are all zero besides the first
nn = nn([true;any(nn(2:end,:)~=0,2)],:);
tierofnn = sum(nn,2);
for k  =2:Kap2+1
    numwithn(k) = sum(tierofnn == (k-1)); %set actual number included
end
else
   nn=0; numwithn=1; %trivial case, DON'T ENTER Kap1 as nn and also Kap2 =0;
end

toc
tic
%% Set initial condition as lioville space
rho_vec = zeros(size(nn,1)*numel(rho_0),1);
%initial condition
rho_vec(1:numel(rho_0)) = reshape(rho_0,numel(rho_0),1);

% Can reshape to zeros(size(rho_heir,1)*numel(rho),1);
%Column vector of ever possible element of every order of density matrix.
% Ordered as you would get if you called the density matrix by one number
% e.g. if rho is an N X N matrix, rho(n) is the [n-1,mod(N)]+1th row and
%the floor((n-1)/N)+1 th column.

%% Calculate the coupling from the heirarchy

%general up and down coupling terms
coup_com = zeros(size(nn,1));  %coefficient will be the sqrt of number it couples to (upward)
%coup_p1_save= zeros(size(nn,1),size(nn,1),N);  %takes up too much memory

coup_com_save{N}= sparse(coup_com);

%must also have the term that accounts for the fact that down coupling
%terms are different except for the matsubara terms
%coup_m1 = coup_com ;
coup_m1_acom = coup_com ;  %anti commutator part
coup_acom_save= coup_com_save;

rng_j =0; %full_rng = 1:totpoles;

for j = 1:N
    if ~isempty(cc_com{j}) %no bath at this mode for some reason
    rng_j = rng_j(end)+1:length(cc_com{j})+rng_j(end);
    rng_rest = [1:rng_j(1)-1 , rng_j(end)+1:totpoles];
    cc = cc_com{j};  ccI = cc_acom{j};
for k =1:sum(numwithn(1:end-1))

    currenttier = tierofnn(k);
    tierabove = currenttier+1;

    tierpickr = abs(tierofnn-tierabove)<eps(10);

    nnsec = nn(k,rng_j); %section of interest
    nnsec2 = nn(k,rng_rest); %rest
    %which obviously must still match, but must be element of j section
    %changed

    temp0 = repmat(nnsec,numwithn(tierabove+1),1);
    %make same size as nn in tier above in dimension 1
    temp02 = repmat(nnsec2,numwithn(tierabove+1),1);

    temp = temp0 - nn(tierpickr,rng_j);
    %take away elements in the tier above

    temp4 = temp02 - nn(tierpickr,rng_rest);

    temp2 = sum(temp~=0,2) ==1; %only one element +/- 1 diff

    temp3 = sum(temp,2) < -1/2 & sum(temp,2) > -3/2; %ones with a -1 net
    temp4 = all(temp4==0,2); %match rest of the terms

    comb_lg = temp2 & temp3 & temp4; %full condition required
    tierpickr(tierpickr) = comb_lg ;
    %use to put elements in the right row position in coupling matrix,
    %comb_lg is displaced by the number of tiers below

    if any(comb_lg)

    [~,temp44] = find(temp(comb_lg,:)); %find row position, i.e. which coefficient
    temp7 = sqrt(sqrt(abs(cc(temp44)).^2+abs(ccI(temp44)).^2));
    coup_com(k,tierpickr)=temp7.*sqrt(1+nnsec(temp44));

    %elements with minus are in the positions which are the transpose of this
    %due to the rescaling the coefficients should be the same up and down
    %for the matsubara terms and the commutator part of the drude terms
    %now second down coupling operator

    coup_com(tierpickr,k) = cc(temp44).*sqrt(1+nnsec(temp44))./temp7;%...
       % ./ sqrt(sqrt(abs(cc(j,temp44)).^2+abs(ccI(j,temp44)).^2));
     %  if any(cc_acom{j}(temp44))
    coup_m1_acom(tierpickr,k) = ccI(temp44).*sqrt(1+nnsec(temp44))./temp7;%...
      %  ./ sqrt(sqrt(abs(cc(j,temp44)).^2+abs(ccI(j,temp44)).^2));
     %  end
    end

end
    %Note I am scaling things w.r.t. (abs(a)^2+abs(b)^2)^(1/4)
    %for a term with operator a V^O + b V^X

    end

coup_com_save{j} = sparse(coup_com); coup_com = 0*coup_com;
coup_acom_save{j}= sparse(coup_m1_acom); coup_m1_acom=coup_com;

end
%down coupling from real frequency and residue modes is just  coup_p1.'

% calculate the sum_{j=1}^N sum_{k=0}^Kappa n_{jk} v_{ik}
if size(nn,1)==1
  const_factor = 0;
else
    %reshape(vv.',numel(vv),1)
    %([vv(1,:).';vv(2,:).';vv(3,:).';vv(4,:).'])

const_factor = nn*totfreq;%([vv(1,:).';vv(2,:).']);
non_hermit = abs(imag(const_factor))>eps(max(imag(const_factor)));
%const_factor = const_factor -imag(sum(const_factor))/length(const_factor);
end

%%  Calculate the Uber operator that propogates the entire thing
total_prop_op = sparse(length(rho_vec),length(rho_vec));
   %plus_term = total_prop_op;  minus_term = total_prop_op;

        for j = 1:N

    Qjsec = zeros(N);  Qjsec(j,j) = 1;
    Qjsec = kron(Qjsec,eye(viblvls));
    eyeQ = eye(length(Qjsec));
    Qj = -1i*sparse(kron(eyeQ,Qjsec) - kron(Qjsec.',eyeQ)); %commtator
    %keep factor of -1i from -1i tilde(V)^X term
    Uj=  sparse(kron(eyeQ,Qjsec) + kron(Qjsec.',eyeQ)); %anti commutator

    total_prop_op = total_prop_op + kron(sparse(coup_com_save{j}),Qj);
    total_prop_op = total_prop_op + kron(sparse(coup_acom_save{j}),Uj);
        end

    szmat = length(rho_vec)/numel(Htot);
    spmat = sparse(1:szmat,1:szmat,ones(szmat,1)); %identity
    total_prop_op = total_prop_op + kron(spmat,sparse(Ltot));

    prop_light = kron(spmat,sparse(L2));

    temp = kron(const_factor,ones(numel(Htot),1));
    %identical constant factor
    total_prop_op = total_prop_op - sparse(1:length(temp),1:length(temp),temp);

%% Propogate in time and solve system
topass{1} = total_prop_op;
topass{2} = prop_p;  topass{3} = prop_light; topass{4} = omega;
if  use_reduced_mat
    topass{5} = length(Htot);   topass{6} = size(nn,1);
rhs_dif_eq2(1,topass); %pass parameters to function
else
rhs_dif_eq(1,topass); %pass parameters to function
end
toc

clearvars -except tend basis_proj convfact rho_vec nn use_reduced_mat wave_vec_trunc...
            rho_0 numpoints saveuptotier save_file_name non_hermit numwithn

%no point keeping two copies really, save memory etc

tic
options = odeset('OutputFcn',@outputfun);
%call with number of points,
%in general one can call the output function with
% outputfun([numpoints,timetosave1,...timetosaveN],rho_vec,'file.mat')
% to get it to save N different sections numpoints long to a file, useful
% for long intergrations that may have to be killed.
%options.refine = 1; %less output
if length(numpoints)>1
   save(save_file_name,'convfact') %needed to convert time to ps
end

if  use_reduced_mat
    warning('havent got this to work with brownian modes yet...')
       temp = reshape(tril(true(size(rho_0))) , 1 , numel(rho_0));
       temp2 = repmat(temp,1,size(nn,1));

       rho_vec = rho_vec(temp2);  %reduced rho_vec

    outputfun(numpoints,rho_vec(1:sum(numwithn(1:saveuptotier+1))*sum(temp)...
        ),save_file_name);  %save only denmat, only works with no nonhermitian

    %[Time_units,rho_vec] = ode45(@rhs_dif_eq2,[0,tend],rho_vec,options);
    rho_vec = [rho_vec; repmat(rho_vec*0,2*wave_vec_trunc,1)];
       %add extra tiers on the bottom relating to terms with spatial
       %dependence, note none of these are saved
    ode45(@rhs_dif_eq2,[0,tend],rho_vec,options);

    [Time_units,rho_vec] =outputfun(numpoints,rho_vec,'get_data'); %also cleans
else

       outputfun(numpoints,rho_vec(1:(sum(numwithn(1:(saveuptotier+1)))...
           *numel(rho_0))),save_file_name);

       rho_vec = [rho_vec; repmat(rho_vec*0,2*wave_vec_trunc,1)];
       %add extra tiers on the bottom relating to terms with spatial
       %dependence, note none of these are saved

    %[Time_units,rho_vec] = ode45(@rhs_dif_eq,[0,tend],rho_vec,options);
    ode45(@rhs_dif_eq,[0,tend],rho_vec,options);
    %[~,~] = ode23(@rhs_dif_eq,[0,tend],rho_vec,options);
    [Time_units,rho_vec] =outputfun(numpoints,rho_vec,'get_data');
end

    non_redundant_points = [true;Time_units(2:end)~=0];
    Time_units = Time_units(non_redundant_points)/convfact;
    rho_vec = rho_vec(non_redundant_points,:);
toc
%end
nntot = nn;
save(save_file_name,'nntot','-append')
clear nntot
nn = nn(1:sum(numwithn(1:(saveuptotier+1))),:);
if length(numpoints)>1
   save(save_file_name,'nn','-append')
end
%trim off nn that isn't part of the saved component

if nargout ==4
total_prop_op = rhs_dif_eq2([],[]);
end
end
%%
function drho = rhs_dif_eq(t,rho_vc) %Couples to same numwithn value

persistent total_prop p_light omega num_wvc rng rngex coup_plus coup_minus

        if isempty(tt) %pass empty t to get persistent vars back
            drho = total_prop;
                        clear total_prop p_plus p_minus
            return
        end
        if iscell(rho_vc)

            total_prop = rho_vc{1}; %propogation matrix
            p_light = rho_vc{2};
            omega = rho_vc{3};
            num_wvc = rho_vc{4};

            %this just speeds up what sections couple etc
            rng = 1:length(total_prop);  rngex(1) = 0;
            coup_plus = false(2*num_wvc+1);
            for j = (1:2:2*num_wvc-1)
                coup_plus(j,j+1) = true;
            end
                coup_minus = coup_plus';
            %arranged like 0,1,-1,2,-2 ....
            for k =2:(2*num_wvc+1)
                rngex(k) = rngex(k-1) + length(total_prop);
            end

            drho =[];

            return
        end
        %outtest = [t,max(max(abs(rho_vc)))]

        drho = zeros(rngex(end) + rng(end),1);
        pp_plus = p_light.*exp(1i*omega*t);
        pp_minus = p_light.*exp(-1i*omega*t);
        for k = 1:num_wvc
            rng1 = rng+rngex(k);
            drho(rng1) = drho(rng1) + full(total_prop*rho_vc(rng1));
            drho(rng1) = drho(rng1) + full(...
                pp_plus*rho_vc(rng + rngex(coup_plus(k,:))) ) ;
            drho(rng1) = drho(rng1) + full(...
                pp_minus*rho_vc(rng + rngex(coup_minus(k,:))) ) ;
        end
end
function drho = rhs_dif_eq2(t,rho_vc_red)

%rho_vc_red is the reduced vector (length = numstates * (N^2+N)/2 )
%from taking only the independent vectors of each density matrix

persistent total_prop_1  total_prop_2 pickr

        if isempty(t) %pass empty t to get persistent vars back
            drho{1} = total_prop_1;
            drho{2} = total_prop_2;
                        clear total_prop_1 total_prop_2  pickr
            return
        end
        if iscell(rho_vc_red)

            total_prop = rho_vc_red{1}; %propogation matrix
            N = rho_vc_red{2}; %size of Htot
            NN = rho_vc_red{3}; %total number of density matricies
            temp = reshape(tril(true(N)) , 1,N^2);
            temp2 = repmat(temp,1,NN);  %picks out L.I. elements in lower d
            total_prop_1 = total_prop(temp2,temp2);
            %total_1 doesn't include anything that multiples the conjugates
            total_prop_2 = total_prop(temp2,~temp2);
            %element that multiples the conjugate terms

 % must construct matrix that maps the off diagonal positions to
 % the order they need to appear in the matrix multiplication,
 % the flattening does not preserve this order... must map to the order in
 % which the non LI elements (upper half) appear to the order in which the
 % elements on the lower diagonal (on which they depend) will appear.

            count1 =1;  count2 = 0;
            test = zeros(N);
     for k = 1:(N-1)
     count2 = count2 + N-k;
     test(1+k:N,k) =count1:count2;
     count1= count2+1;
     end
%     for k = 2:N
%     count2 = count2 + k-1;
%     test(1:k-1,k) =count1:count2;
%     count1= count2+1;
%     end
    test2 = reshape(test',1,N^2);
    [~,order] = sort(test2(test2~=0));

            pickr = reshape(tril(true(N),-1) , 1,N^2);
            pickr = pickr(temp);
            %pic elements of rho_vec_red which are on diagonal
            pickr = repmat(pickr,1,NN);
            %prop 2 multiplies, i.e. off diag element
            drho =[];

                neworder = zeros(sum(pickr),1);
                neworder(1:count2) = order;
    for k = 2:NN
        neworder(1+((k-1)*count2):(k*count2))  = ...
            neworder(1+((k-2)*count2):((k-1)*count2)) + max(order);
    end
    total_prop_2 = total_prop_2(:,neworder);

            return
        end
        drho = full(total_prop_1*rho_vc_red);

        drho = drho + full(total_prop_2*conj(rho_vc_red(pickr)));

end

%to get rho_vec from rho_vec red
%             temp = reshape(tril(true(N)) , 1,N^2);
%            temp2 = repmat(temp,1,size(nn,1));
%       rho_vec(temp2) = rho_vec_red;
% extra density matrix as normal and then just add the conjugate of matrix
% minus the leading diagonal

function [status,othervar] = outputfun(t,rho_v,flag)
persistent filetosave whentosave cnt numpoints saved_timee saved_rho Tpoints lastpoint %wtfmatlab
        %This function controls the output from the ODE solver to stop it
        %saving so much fucking data!

status= 0;
if ~isempty(t) && strcmp(flag,'')
    %size(saved_rho,2)
   % size(rho_v)
    tt = t(end);
    rr = rho_v(1:size(saved_rho,2),end);
end
        if strcmp(flag,'') %empty flag = standard call during time-ev

            oldlastpoint = lastpoint;
            while tt>=Tpoints(lastpoint+1) %if time is past the spacing interval save it

                lastpoint = lastpoint+1;
                %if so many intervals are picked and the solver takes big
                %steps the saved things will have lots of zeros, I can't be
                %arsed to feed back into the options with refine for shit I
                %will never need.
            end

            if  oldlastpoint~=lastpoint

                saved_timee(lastpoint + 1) = tt;
                saved_rho(lastpoint + 1,:) = rr;
            end

        elseif strcmp(flag,'init')
         % wtfmatlab = 1:10

            if isempty(whentosave)
            Tpoints = [linspace(t(1),t(2),numpoints),inf];
            else
                %function will save to disk as it goes, dumping all
                %previous data
             Tpoints = [linspace(t(1),whentosave(1),numpoints),inf];
             cnt = 1;

            end
            saved_timee(1) = t(1);
            saved_rho(1,:) = rho_v(1:size(saved_rho,2));

            lastpoint=1;
            return
            %when time is larger than this save the value to the var
        elseif strcmp(flag,'get_data')

            status = saved_timee;
            othervar = saved_rho;
               %clearvars -except status othervar
               return
        elseif ~strcmp(flag,'done') && ~isempty(flag)
         %   most initial step of all, pass savefilename as flag

            if length(t) == 1 %past a single number t equal to the
                %number of points you wish to save
            numpoints = t;
            saved_timee = zeros(numpoints,1);
            %size(saved_timee)
            saved_rho = zeros(numpoints,length(rho_v));
            whentosave = [];

            else %past a vector t indicating how many points after which
                %to save the output to disk under a filename given by flag
                numpoints = t(1);
                saved_timee = zeros(numpoints,1);
                saved_rho = zeros(numpoints,length(rho_v));
                filetosave = flag;
                whentosave = t(2:end);

            end
            return

        elseif strcmp(flag,'done') %finish integration
                    clearvars -except saved_rho saved_time
                      status = 1;
        return
        end

    if ~isempty(whentosave)
%out  = flag
        if tt >= whentosave(1)

            if cnt==1

            non_redundant_points = [true;saved_timee(2:lastpoint)~=0];  %#ok<NASGU>
            else
            non_redundant_points = saved_timee~=0;     %#ok<NASGU>
            end
eval([strcat('saved_time',num2str(cnt)) '= saved_timee(non_redundant_points);']);
eval([strcat('saved_rho',num2str(cnt))  '= saved_rho(non_redundant_points,:);']);

            saved_timee = 0*saved_timee;
            saved_rho   = 0*saved_rho;

            save(filetosave,strcat('saved_time',num2str(cnt)),...
                strcat('saved_rho',num2str(cnt)),'-append') ;
            %toc
            if length(whentosave)>1  %shouldn't not be the case
            Tpoints =  [linspace(whentosave(1),whentosave(2),length(saved_timee)),inf];
            whentosave = whentosave(2:end); %get rid of first value
            else
            Tpoints =  [whentosave(1),inf];    %no more gets saved
                status = 1; %stop the integration
            end
            lastpoint = 1;  cnt = cnt+1;
        end
    end
end


text:
<?php
	require 'require/db.php';

	$sqlQuery = "SELECT * FROM model";

	require 'require\_populationHeader.php';

	while($row = mysqli_fetch_array($result))
	{
		addToJson($i, "ModelID", $row);
		addToJson($i, "URL", $row);
		addToJson($i, "Name", $row);
		addToJson($i, "Type", $row);
		addToJson($i, "MethodID", $row);

		$i++;
	}

	echo json_encode($jsonData);
?>


text:
var mongoose = require('mongoose');

var PassengerRoutesSchema = new mongoose.Schema({
  start: [Number],
  end: [Number],
  startLabel: String,
  endLabel: String,
  days: [{
    type: Boolean,
    default: [false, false, false, false, false, false, false]
  }],
  fromHour: {min: 0, max: 24, type: Number},
  fromMinutes: {min: 0, max: 60, type: Number},
  toHour: {min: 0, max: 24, type: Number},
  toMinutes: {min: 0, max: 60, type: Number},
  name: String,
  driverRoutesIAmInterestedIn: [{ type: mongoose.Schema.Types.ObjectId, ref: 'driverRoutes' }],
  confirmedDriverRoute: {type: mongoose.Schema.Types.ObjectId, ref: 'driverRoutes'},
  passengerInformation: { type: mongoose.Schema.Types.ObjectId, ref: 'users' }
});

module.exports = mongoose.model('passengerRoutes', PassengerRoutesSchema);


text:
namespace Goon.Events
{
    /// <summary>
    /// Base event type which is needed to be implemented in all events that can be dispatched to methods using EventDispatcher.
    ///
    /// @author DisTurBinG
    /// </summary>
    public interface Event
    {

    }
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

$string['clientid'] = 'Client ID';
$string['clientsecret'] = 'Client secret';
$string['existingfolder'] = 'Existing folder to put file(s) into';
$string['folderclash'] = 'The folder you asked to create already exists!';
$string['foldercreatefailed'] = 'Failed to create your target folder on Box';
$string['folderlistfailed'] = 'Failed to retrieve a folder listing from Box';
$string['missinghttps'] = 'HTTPS required';
$string['missinghttps_help'] = 'Box will only work with an HTTPS enabled website.';
$string['missingoauthkeys'] = 'Missing client ID and secret';
$string['missingoauthkeys_help'] = 'There is no client ID or secret configured for this plugin. You can get one of these from Box development page.';
$string['newfolder'] = 'New folder to put file(s) into';
$string['noauthtoken'] = 'Could not retrieve an authentication token for use in this session';
$string['notarget'] = 'You must specify either an existing folder or a new folder to upload into';
$string['noticket'] = 'Could not retrieve a ticket from Box to begin the authentication session';
$string['password'] = 'Your Box password (will not be stored)';
$string['pluginname'] = 'Box';
$string['sendfailed'] = 'Failed to send content to Box: {$a}';
$string['setupinfo'] = 'Setup instructions';
$string['setupinfodetails'] = 'To obtain a client ID and secret, log in to Box and visit the servicesurl}">Box developers page. Follow \'Create new application\' and create a new application for your Moodle site. The client ID and secret are displayed in the \'OAuth2 parameters\' section of the application edit form. Optionally, you can also provide other information about your Moodle site.';
$string['sharedfolder'] = 'Shared';
$string['sharefile'] = 'Share this file?';
$string['sharefolder'] = 'Share this new folder?';
$string['targetfolder'] = 'Target folder';
$string['tobecreated'] = 'To be created';
$string['username'] = 'Your Box username (will not be stored)';
$string['warninghttps'] = 'Box requires your website to be using HTTPS in order for the portfolio to work.';


text:
package com.gilt.thehand.rules.typed

import com.gilt.thehand.rules.conversions.ConvertsToString
import com.gilt.thehand.rules.comparison.Eq
import com.gilt.thehand.rules.SingleValueRuleParser

/**
 * A typed implementation of the Eq trait, specific to String.
 */
case class StringEq(value: String) extends Eq with ConvertsToString

/**
 * Use this to differentiate Eq[String] from other versions of Eq.
 */
object StringEqParser extends SingleValueRuleParser[StringEq] {
  def ruleConstructor(value: String) = StringEq(value)
  def toValue(value: String) = value
}


text:
import itertools
import unittest
from copy import deepcopy
from datetime import date, time
from typing import Dict

import mock
from botocore.credentials import Credentials
from freezegun import freeze_time
from parameterized import parameterized

from airflow import AirflowException
from airflow.models import DAG, TaskInstance
from airflow.providers.google.cloud.hooks.cloud_storage_transfer_service import (
    ACCESS_KEY_ID, AWS_ACCESS_KEY, AWS_S3_DATA_SOURCE, BUCKET_NAME, FILTER_JOB_NAMES, GCS_DATA_SINK,
    GCS_DATA_SOURCE, HTTP_DATA_SOURCE, LIST_URL, NAME, SCHEDULE, SCHEDULE_END_DATE, SCHEDULE_START_DATE,
    SECRET_ACCESS_KEY, START_TIME_OF_DAY, STATUS, TRANSFER_SPEC,
)
from airflow.providers.google.cloud.operators.cloud_storage_transfer_service import (
    CloudDataTransferServiceCancelOperationOperator, CloudDataTransferServiceCreateJobOperator,
    CloudDataTransferServiceDeleteJobOperator, CloudDataTransferServiceGCSToGCSOperator,
    CloudDataTransferServiceGetOperationOperator, CloudDataTransferServiceListOperationsOperator,
    CloudDataTransferServicePauseOperationOperator, CloudDataTransferServiceResumeOperationOperator,
    CloudDataTransferServiceS3ToGCSOperator, CloudDataTransferServiceUpdateJobOperator,
    TransferJobPreprocessor, TransferJobValidator,
)
from airflow.utils import timezone

try:
    import boto3
except ImportError:  # pragma: no cover
    boto3 = None

GCP_PROJECT_ID = 'project-id'
TASK_ID = 'task-id'

JOB_NAME = "job-name"
OPERATION_NAME = "operation-name"
AWS_BUCKET_NAME = "aws-bucket-name"
GCS_BUCKET_NAME = "gcp-bucket-name"
DESCRIPTION = "description"

DEFAULT_DATE = timezone.datetime(2017, 1, 1)

TEST_FILTER = {FILTER_JOB_NAMES: [JOB_NAME]}

TEST_AWS_ACCESS_KEY_ID = "test-key-1"
TEST_AWS_ACCESS_SECRET = "test-secret-1"
TEST_AWS_ACCESS_KEY = {ACCESS_KEY_ID: TEST_AWS_ACCESS_KEY_ID, SECRET_ACCESS_KEY: TEST_AWS_ACCESS_SECRET}

NATIVE_DATE = date(2018, 10, 15)
DICT_DATE = {'day': 15, 'month': 10, 'year': 2018}
NATIVE_TIME = time(hour=11, minute=42, second=43)
DICT_TIME = {'hours': 11, 'minutes': 42, 'seconds': 43}
SCHEDULE_NATIVE = {
    SCHEDULE_START_DATE: NATIVE_DATE,
    SCHEDULE_END_DATE: NATIVE_DATE,
    START_TIME_OF_DAY: NATIVE_TIME,
}

SCHEDULE_DICT = {
    SCHEDULE_START_DATE: {'day': 15, 'month': 10, 'year': 2018},
    SCHEDULE_END_DATE: {'day': 15, 'month': 10, 'year': 2018},
    START_TIME_OF_DAY: {'hours': 11, 'minutes': 42, 'seconds': 43},
}

SOURCE_AWS = {AWS_S3_DATA_SOURCE: {BUCKET_NAME: AWS_BUCKET_NAME}}
SOURCE_GCS = {GCS_DATA_SOURCE: {BUCKET_NAME: GCS_BUCKET_NAME}}
SOURCE_HTTP = {HTTP_DATA_SOURCE: {LIST_URL: "http://example.com"}}

VALID_TRANSFER_JOB_BASE = {
    NAME: JOB_NAME,
    DESCRIPTION: DESCRIPTION,
    STATUS: 'ENABLED',
    SCHEDULE: SCHEDULE_DICT,
    TRANSFER_SPEC: {GCS_DATA_SINK: {BUCKET_NAME: GCS_BUCKET_NAME}},
}  # type: Dict
VALID_TRANSFER_JOB_GCS = deepcopy(VALID_TRANSFER_JOB_BASE)
VALID_TRANSFER_JOB_GCS[TRANSFER_SPEC].update(deepcopy(SOURCE_GCS))
VALID_TRANSFER_JOB_AWS = deepcopy(VALID_TRANSFER_JOB_BASE)
VALID_TRANSFER_JOB_AWS[TRANSFER_SPEC].update(deepcopy(SOURCE_AWS))

VALID_TRANSFER_JOB_GCS = {
    NAME: JOB_NAME,
    DESCRIPTION: DESCRIPTION,
    STATUS: 'ENABLED',
    SCHEDULE: SCHEDULE_NATIVE,
    TRANSFER_SPEC: {
        GCS_DATA_SOURCE: {BUCKET_NAME: GCS_BUCKET_NAME},
        GCS_DATA_SINK: {BUCKET_NAME: GCS_BUCKET_NAME},
    },
}

VALID_TRANSFER_JOB_RAW = {
    DESCRIPTION: DESCRIPTION,
    STATUS: 'ENABLED',
    SCHEDULE: SCHEDULE_DICT,
    TRANSFER_SPEC: {GCS_DATA_SINK: {BUCKET_NAME: GCS_BUCKET_NAME}},
}  # type: Dict

VALID_TRANSFER_JOB_GCS_RAW = deepcopy(VALID_TRANSFER_JOB_RAW)
VALID_TRANSFER_JOB_GCS_RAW[TRANSFER_SPEC].update(SOURCE_GCS)
VALID_TRANSFER_JOB_AWS_RAW = deepcopy(VALID_TRANSFER_JOB_RAW)
VALID_TRANSFER_JOB_AWS_RAW[TRANSFER_SPEC].update(deepcopy(SOURCE_AWS))
VALID_TRANSFER_JOB_AWS_RAW[TRANSFER_SPEC][AWS_S3_DATA_SOURCE][AWS_ACCESS_KEY] = TEST_AWS_ACCESS_KEY

VALID_OPERATION = {NAME: "operation-name"}

class TestTransferJobPreprocessor(unittest.TestCase):
    def test_should_do_nothing_on_empty(self):
        body = {}
        TransferJobPreprocessor(body=body).process_body()
        self.assertEqual(body, {})

    @unittest.skipIf(boto3 is None, "Skipping test because boto3 is not available")
    @mock.patch('airflow.providers.google.cloud.operators.cloud_storage_transfer_service.AwsBaseHook')
    def test_should_inject_aws_credentials(self, mock_hook):
        mock_hook.return_value.get_credentials.return_value = Credentials(
            TEST_AWS_ACCESS_KEY_ID, TEST_AWS_ACCESS_SECRET, None
        )

        body = {TRANSFER_SPEC: deepcopy(SOURCE_AWS)}
        body = TransferJobPreprocessor(body=body).process_body()
        self.assertEqual(body[TRANSFER_SPEC][AWS_S3_DATA_SOURCE][AWS_ACCESS_KEY], TEST_AWS_ACCESS_KEY)

    @parameterized.expand([(SCHEDULE_START_DATE,), (SCHEDULE_END_DATE,)])
    def test_should_format_date_from_python_to_dict(self, field_attr):
        body = {SCHEDULE: {field_attr: NATIVE_DATE}}
        TransferJobPreprocessor(body=body).process_body()
        self.assertEqual(body[SCHEDULE][field_attr], DICT_DATE)

    def test_should_format_time_from_python_to_dict(self):
        body = {SCHEDULE: {START_TIME_OF_DAY: NATIVE_TIME}}
        TransferJobPreprocessor(body=body).process_body()
        self.assertEqual(body[SCHEDULE][START_TIME_OF_DAY], DICT_TIME)

    @parameterized.expand([(SCHEDULE_START_DATE,), (SCHEDULE_END_DATE,)])
    def test_should_not_change_date_for_dict(self, field_attr):
        body = {SCHEDULE: {field_attr: DICT_DATE}}
        TransferJobPreprocessor(body=body).process_body()
        self.assertEqual(body[SCHEDULE][field_attr], DICT_DATE)

    def test_should_not_change_time_for_dict(self):
        body = {SCHEDULE: {START_TIME_OF_DAY: DICT_TIME}}
        TransferJobPreprocessor(body=body).process_body()
        self.assertEqual(body[SCHEDULE][START_TIME_OF_DAY], DICT_TIME)

    @freeze_time("2018-10-15")
    def test_should_set_default_schedule(self):
        body = {}
        TransferJobPreprocessor(body=body, default_schedule=True).process_body()
        self.assertEqual(body, {
            SCHEDULE: {
                SCHEDULE_END_DATE: {'day': 15, 'month': 10, 'year': 2018},
                SCHEDULE_START_DATE: {'day': 15, 'month': 10, 'year': 2018}
            }
        })

class TestTransferJobValidator(unittest.TestCase):
    def test_should_raise_exception_when_encounters_aws_credentials(self):
        body = {"transferSpec": {"awsS3DataSource": {"awsAccessKey": TEST_AWS_ACCESS_KEY}}}
        with self.assertRaises(AirflowException) as cm:
            TransferJobValidator(body=body).validate_body()
        err = cm.exception
        self.assertIn(
            "AWS credentials detected inside the body parameter (awsAccessKey). This is not allowed, please "
            "use Airflow connections to store credentials.",
            str(err),
        )

    def test_should_raise_exception_when_body_empty(self):
        body = None
        with self.assertRaises(AirflowException) as cm:
            TransferJobValidator(body=body).validate_body()
        err = cm.exception
        self.assertIn("The required parameter 'body' is empty or None", str(err))

    @parameterized.expand(
        [
            (dict(itertools.chain(SOURCE_AWS.items(), SOURCE_GCS.items(), SOURCE_HTTP.items())),),
            (dict(itertools.chain(SOURCE_AWS.items(), SOURCE_GCS.items())),),
            (dict(itertools.chain(SOURCE_AWS.items(), SOURCE_HTTP.items())),),
            (dict(itertools.chain(SOURCE_GCS.items(), SOURCE_HTTP.items())),),
        ]
    )
    def test_verify_data_source(self, transfer_spec):
        body = {TRANSFER_SPEC: transfer_spec}

        with self.assertRaises(AirflowException) as cm:
            TransferJobValidator(body=body).validate_body()
        err = cm.exception
        self.assertIn(
            "More than one data source detected. Please choose exactly one data source from: "
            "gcsDataSource, awsS3DataSource and httpDataSource.",
            str(err),
        )

    @parameterized.expand([(VALID_TRANSFER_JOB_GCS,), (VALID_TRANSFER_JOB_AWS,)])
    def test_verify_success(self, body):
        try:
            TransferJobValidator(body=body).validate_body()
            validated = True
        except AirflowException:
            validated = False

        self.assertTrue(validated)

class TestGcpStorageTransferJobCreateOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_job_create_gcs(self, mock_hook):
        mock_hook.return_value.create_transfer_job.return_value = VALID_TRANSFER_JOB_GCS_RAW
        body = deepcopy(VALID_TRANSFER_JOB_GCS)
        del body['name']
        op = CloudDataTransferServiceCreateJobOperator(body=body, task_id=TASK_ID)
        result = op.execute(None)

        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')

        mock_hook.return_value.create_transfer_job.assert_called_once_with(body=VALID_TRANSFER_JOB_GCS_RAW)

        self.assertEqual(result, VALID_TRANSFER_JOB_GCS_RAW)

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    @mock.patch('airflow.providers.google.cloud.operators.cloud_storage_transfer_service.AwsBaseHook')
    def test_job_create_aws(self, aws_hook, mock_hook):
        mock_hook.return_value.create_transfer_job.return_value = VALID_TRANSFER_JOB_AWS_RAW
        aws_hook.return_value.get_credentials.return_value = Credentials(
            TEST_AWS_ACCESS_KEY_ID, TEST_AWS_ACCESS_SECRET, None
        )
        body = deepcopy(VALID_TRANSFER_JOB_AWS)
        del body['name']
        op = CloudDataTransferServiceCreateJobOperator(body=body, task_id=TASK_ID)

        result = op.execute(None)

        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')

        mock_hook.return_value.create_transfer_job.assert_called_once_with(body=VALID_TRANSFER_JOB_AWS_RAW)

        self.assertEqual(result, VALID_TRANSFER_JOB_AWS_RAW)

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    @mock.patch('airflow.providers.google.cloud.operators.cloud_storage_transfer_service.AwsBaseHook')
    def test_job_create_multiple(self, aws_hook, gcp_hook):
        aws_hook.return_value.get_credentials.return_value = Credentials(
            TEST_AWS_ACCESS_KEY_ID, TEST_AWS_ACCESS_SECRET, None
        )
        gcp_hook.return_value.create_transfer_job.return_value = VALID_TRANSFER_JOB_AWS_RAW
        body = deepcopy(VALID_TRANSFER_JOB_AWS)

        op = CloudDataTransferServiceCreateJobOperator(body=body, task_id=TASK_ID)
        result = op.execute(None)
        self.assertEqual(result, VALID_TRANSFER_JOB_AWS_RAW)

        op = CloudDataTransferServiceCreateJobOperator(body=body, task_id=TASK_ID)
        result = op.execute(None)
        self.assertEqual(result, VALID_TRANSFER_JOB_AWS_RAW)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_templates(self, _):
        dag_id = 'test_dag_id'
        # pylint: disable=attribute-defined-outside-init
        self.dag = DAG(dag_id, default_args={'start_date': DEFAULT_DATE})
        op = CloudDataTransferServiceCreateJobOperator(
            body={"description": "{{ dag.dag_id }}"},
            gcp_conn_id='{{ dag.dag_id }}',
            aws_conn_id='{{ dag.dag_id }}',
            task_id='task-id',
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'body')[DESCRIPTION])
        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))
        self.assertEqual(dag_id, getattr(op, 'aws_conn_id'))

class TestGcpStorageTransferJobUpdateOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_job_update(self, mock_hook):
        mock_hook.return_value.update_transfer_job.return_value = VALID_TRANSFER_JOB_GCS
        body = {'transferJob': {'description': 'example-name'}, 'updateTransferJobFieldMask': DESCRIPTION}

        op = CloudDataTransferServiceUpdateJobOperator(job_name=JOB_NAME, body=body, task_id=TASK_ID)
        result = op.execute(None)

        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')
        mock_hook.return_value.update_transfer_job.assert_called_once_with(job_name=JOB_NAME, body=body)
        self.assertEqual(result, VALID_TRANSFER_JOB_GCS)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceUpdateJobOperator(
            job_name='{{ dag.dag_id }}',
            body={'transferJob': {"name": "{{ dag.dag_id }}"}},
            task_id='task-id',
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'body')['transferJob']['name'])
        self.assertEqual(dag_id, getattr(op, 'job_name'))

class TestGcpStorageTransferJobDeleteOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_job_delete(self, mock_hook):
        op = CloudDataTransferServiceDeleteJobOperator(
            job_name=JOB_NAME, project_id=GCP_PROJECT_ID, task_id='task-id'
        )
        op.execute(None)
        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')
        mock_hook.return_value.delete_transfer_job.assert_called_once_with(
            job_name=JOB_NAME, project_id=GCP_PROJECT_ID
        )

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_job_delete_with_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceDeleteJobOperator(
            job_name='{{ dag.dag_id }}',
            gcp_conn_id='{{ dag.dag_id }}',
            api_version='{{ dag.dag_id }}',
            task_id=TASK_ID,
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'job_name'))
        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))
        self.assertEqual(dag_id, getattr(op, 'api_version'))

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_job_delete_should_throw_ex_when_name_none(self, mock_hook):
        with self.assertRaises(AirflowException) as cm:
            op = CloudDataTransferServiceDeleteJobOperator(job_name="", task_id='task-id')
            op.execute(None)
        err = cm.exception
        self.assertIn("The required parameter 'job_name' is empty or None", str(err))
        mock_hook.assert_not_called()

class TestGpcStorageTransferOperationsGetOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_get(self, mock_hook):
        mock_hook.return_value.get_transfer_operation.return_value = VALID_OPERATION
        op = CloudDataTransferServiceGetOperationOperator(operation_name=OPERATION_NAME, task_id=TASK_ID)
        result = op.execute(None)
        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')
        mock_hook.return_value.get_transfer_operation.assert_called_once_with(operation_name=OPERATION_NAME)
        self.assertEqual(result, VALID_OPERATION)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_get_with_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceGetOperationOperator(
            operation_name='{{ dag.dag_id }}', task_id='task-id', dag=self.dag
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'operation_name'))

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_get_should_throw_ex_when_operation_name_none(self, mock_hook):
        with self.assertRaises(AirflowException) as cm:
            op = CloudDataTransferServiceGetOperationOperator(operation_name="", task_id=TASK_ID)
            op.execute(None)
        err = cm.exception
        self.assertIn("The required parameter 'operation_name' is empty or None", str(err))
        mock_hook.assert_not_called()

class TestGcpStorageTransferOperationListOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_list(self, mock_hook):
        mock_hook.return_value.list_transfer_operations.return_value = [VALID_TRANSFER_JOB_GCS]
        op = CloudDataTransferServiceListOperationsOperator(request_filter=TEST_FILTER, task_id=TASK_ID)
        result = op.execute(None)
        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')
        mock_hook.return_value.list_transfer_operations.assert_called_once_with(request_filter=TEST_FILTER)
        self.assertEqual(result, [VALID_TRANSFER_JOB_GCS])

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceListOperationsOperator(
            request_filter={"job_names": ['{{ dag.dag_id }}']},
            gcp_conn_id='{{ dag.dag_id }}',
            task_id='task-id',
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()

        # pylint: disable=unsubscriptable-object
        self.assertEqual(dag_id, getattr(op, 'filter')['job_names'][0])
        # pylint: enable=unsubscriptable-object

        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))

class TestGcpStorageTransferOperationsPauseOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_pause(self, mock_hook):
        op = CloudDataTransferServicePauseOperationOperator(operation_name=OPERATION_NAME, task_id='task-id')
        op.execute(None)
        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')
        mock_hook.return_value.pause_transfer_operation.assert_called_once_with(operation_name=OPERATION_NAME)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_pause_with_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServicePauseOperationOperator(
            operation_name='{{ dag.dag_id }}',
            gcp_conn_id='{{ dag.dag_id }}',
            api_version='{{ dag.dag_id }}',
            task_id=TASK_ID,
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'operation_name'))
        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))
        self.assertEqual(dag_id, getattr(op, 'api_version'))

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_pause_should_throw_ex_when_name_none(self, mock_hook):
        with self.assertRaises(AirflowException) as cm:
            op = CloudDataTransferServicePauseOperationOperator(operation_name="", task_id='task-id')
            op.execute(None)
        err = cm.exception
        self.assertIn("The required parameter 'operation_name' is empty or None", str(err))
        mock_hook.assert_not_called()

class TestGcpStorageTransferOperationsResumeOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_resume(self, mock_hook):
        op = CloudDataTransferServiceResumeOperationOperator(operation_name=OPERATION_NAME, task_id=TASK_ID)
        result = op.execute(None)  # pylint: disable=assignment-from-no-return
        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')
        mock_hook.return_value.resume_transfer_operation.assert_called_once_with(
            operation_name=OPERATION_NAME
        )
        self.assertIsNone(result)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_resume_with_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceResumeOperationOperator(
            operation_name='{{ dag.dag_id }}',
            gcp_conn_id='{{ dag.dag_id }}',
            api_version='{{ dag.dag_id }}',
            task_id=TASK_ID,
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'operation_name'))
        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))
        self.assertEqual(dag_id, getattr(op, 'api_version'))

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_resume_should_throw_ex_when_name_none(self, mock_hook):
        with self.assertRaises(AirflowException) as cm:
            op = CloudDataTransferServiceResumeOperationOperator(operation_name="", task_id=TASK_ID)
            op.execute(None)
        err = cm.exception
        self.assertIn("The required parameter 'operation_name' is empty or None", str(err))
        mock_hook.assert_not_called()

class TestGcpStorageTransferOperationsCancelOperator(unittest.TestCase):
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_cancel(self, mock_hook):
        op = CloudDataTransferServiceCancelOperationOperator(operation_name=OPERATION_NAME, task_id=TASK_ID)
        result = op.execute(None)  # pylint: disable=assignment-from-no-return
        mock_hook.assert_called_once_with(api_version='v1', gcp_conn_id='google_cloud_default')
        mock_hook.return_value.cancel_transfer_operation.assert_called_once_with(
            operation_name=OPERATION_NAME
        )
        self.assertIsNone(result)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_cancel_with_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceCancelOperationOperator(
            operation_name='{{ dag.dag_id }}',
            gcp_conn_id='{{ dag.dag_id }}',
            api_version='{{ dag.dag_id }}',
            task_id=TASK_ID,
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'operation_name'))
        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))
        self.assertEqual(dag_id, getattr(op, 'api_version'))

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_operation_cancel_should_throw_ex_when_name_none(self, mock_hook):
        with self.assertRaises(AirflowException) as cm:
            op = CloudDataTransferServiceCancelOperationOperator(operation_name="", task_id=TASK_ID)
            op.execute(None)
        err = cm.exception
        self.assertIn("The required parameter 'operation_name' is empty or None", str(err))
        mock_hook.assert_not_called()

class TestS3ToGoogleCloudStorageTransferOperator(unittest.TestCase):
    def test_constructor(self):
        operator = CloudDataTransferServiceS3ToGCSOperator(
            task_id=TASK_ID,
            s3_bucket=AWS_BUCKET_NAME,
            gcs_bucket=GCS_BUCKET_NAME,
            project_id=GCP_PROJECT_ID,
            description=DESCRIPTION,
            schedule=SCHEDULE_DICT,
        )

        self.assertEqual(operator.task_id, TASK_ID)
        self.assertEqual(operator.s3_bucket, AWS_BUCKET_NAME)
        self.assertEqual(operator.gcs_bucket, GCS_BUCKET_NAME)
        self.assertEqual(operator.project_id, GCP_PROJECT_ID)
        self.assertEqual(operator.description, DESCRIPTION)
        self.assertEqual(operator.schedule, SCHEDULE_DICT)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceS3ToGCSOperator(
            s3_bucket='{{ dag.dag_id }}',
            gcs_bucket='{{ dag.dag_id }}',
            description='{{ dag.dag_id }}',
            object_conditions={'exclude_prefixes': ['{{ dag.dag_id }}']},
            gcp_conn_id='{{ dag.dag_id }}',
            task_id=TASK_ID,
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 's3_bucket'))
        self.assertEqual(dag_id, getattr(op, 'gcs_bucket'))
        self.assertEqual(dag_id, getattr(op, 'description'))

        # pylint: disable=unsubscriptable-object
        self.assertEqual(dag_id, getattr(op, 'object_conditions')['exclude_prefixes'][0])
        # pylint: enable=unsubscriptable-object

        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    @mock.patch('airflow.providers.google.cloud.operators.cloud_storage_transfer_service.AwsBaseHook')
    def test_execute(self, mock_aws_hook, mock_transfer_hook):
        mock_aws_hook.return_value.get_credentials.return_value = Credentials(
            TEST_AWS_ACCESS_KEY_ID, TEST_AWS_ACCESS_SECRET, None
        )

        operator = CloudDataTransferServiceS3ToGCSOperator(
            task_id=TASK_ID,
            s3_bucket=AWS_BUCKET_NAME,
            gcs_bucket=GCS_BUCKET_NAME,
            description=DESCRIPTION,
            schedule=SCHEDULE_DICT,
        )

        operator.execute(None)

        mock_transfer_hook.return_value.create_transfer_job.assert_called_once_with(
            body=VALID_TRANSFER_JOB_AWS_RAW
        )

        self.assertTrue(mock_transfer_hook.return_value.wait_for_transfer_job.called)

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    @mock.patch('airflow.providers.google.cloud.operators.cloud_storage_transfer_service.AwsBaseHook')
    def test_execute_skip_wait(self, mock_aws_hook, mock_transfer_hook):
        mock_aws_hook.return_value.get_credentials.return_value = Credentials(
            TEST_AWS_ACCESS_KEY_ID, TEST_AWS_ACCESS_SECRET, None
        )

        operator = CloudDataTransferServiceS3ToGCSOperator(
            task_id=TASK_ID,
            s3_bucket=AWS_BUCKET_NAME,
            gcs_bucket=GCS_BUCKET_NAME,
            description=DESCRIPTION,
            schedule=SCHEDULE_DICT,
            wait=False,
        )

        operator.execute(None)

        mock_transfer_hook.return_value.create_transfer_job.assert_called_once_with(
            body=VALID_TRANSFER_JOB_AWS_RAW
        )

        self.assertFalse(mock_transfer_hook.return_value.wait_for_transfer_job.called)

class TestGoogleCloudStorageToGoogleCloudStorageTransferOperator(unittest.TestCase):
    def test_constructor(self):
        operator = CloudDataTransferServiceGCSToGCSOperator(
            task_id=TASK_ID,
            source_bucket=GCS_BUCKET_NAME,
            destination_bucket=GCS_BUCKET_NAME,
            project_id=GCP_PROJECT_ID,
            description=DESCRIPTION,
            schedule=SCHEDULE_DICT,
        )

        self.assertEqual(operator.task_id, TASK_ID)
        self.assertEqual(operator.source_bucket, GCS_BUCKET_NAME)
        self.assertEqual(operator.destination_bucket, GCS_BUCKET_NAME)
        self.assertEqual(operator.project_id, GCP_PROJECT_ID)
        self.assertEqual(operator.description, DESCRIPTION)
        self.assertEqual(operator.schedule, SCHEDULE_DICT)

    # Setting all of the operator's input parameters as templated dag_ids
    # (could be anything else) just to test if the templating works for all
    # fields
    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_templates(self, _):
        dag_id = 'test_dag_id'
        args = {'start_date': DEFAULT_DATE}
        self.dag = DAG(dag_id, default_args=args)  # pylint: disable=attribute-defined-outside-init
        op = CloudDataTransferServiceGCSToGCSOperator(
            source_bucket='{{ dag.dag_id }}',
            destination_bucket='{{ dag.dag_id }}',
            description='{{ dag.dag_id }}',
            object_conditions={'exclude_prefixes': ['{{ dag.dag_id }}']},
            gcp_conn_id='{{ dag.dag_id }}',
            task_id=TASK_ID,
            dag=self.dag,
        )
        ti = TaskInstance(op, DEFAULT_DATE)
        ti.render_templates()
        self.assertEqual(dag_id, getattr(op, 'source_bucket'))
        self.assertEqual(dag_id, getattr(op, 'destination_bucket'))
        self.assertEqual(dag_id, getattr(op, 'description'))

        # pylint: disable=unsubscriptable-object
        self.assertEqual(dag_id, getattr(op, 'object_conditions')['exclude_prefixes'][0])
        # pylint: enable=unsubscriptable-object

        self.assertEqual(dag_id, getattr(op, 'gcp_conn_id'))

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_execute(self, mock_transfer_hook):
        operator = CloudDataTransferServiceGCSToGCSOperator(
            task_id=TASK_ID,
            source_bucket=GCS_BUCKET_NAME,
            destination_bucket=GCS_BUCKET_NAME,
            description=DESCRIPTION,
            schedule=SCHEDULE_DICT,
        )

        operator.execute(None)

        mock_transfer_hook.return_value.create_transfer_job.assert_called_once_with(
            body=VALID_TRANSFER_JOB_GCS_RAW
        )
        self.assertTrue(mock_transfer_hook.return_value.wait_for_transfer_job.called)

    @mock.patch(
        'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
    )
    def test_execute_skip_wait(self, mock_transfer_hook):
        operator = CloudDataTransferServiceGCSToGCSOperator(
            task_id=TASK_ID,
            source_bucket=GCS_BUCKET_NAME,
            destination_bucket=GCS_BUCKET_NAME,
            description=DESCRIPTION,
            wait=False,
            schedule=SCHEDULE_DICT,
        )

        operator.execute(None)

        mock_transfer_hook.return_value.create_transfer_job.assert_called_once_with(
            body=VALID_TRANSFER_JOB_GCS_RAW
        )
        self.assertFalse(mock_transfer_hook.return_value.wait_for_transfer_job.called)


text:
layout: default
---

    {{ content }}

      {% assign sorted_posts = site.categories.contractors | sort: 'title' %}
      {% for post in sorted_posts %}

{{  post.content }}

      {% endfor %}


text:
/* global App: true */
App = Ember.Application.create({
  rootElement: '#ember'
});

App.SillyTransform = DS.Transform.extend({
  text: "SILLYTRANSFORM",
  deserialize: function(serialized) {
    return serialized + this.text;
  },
  serialize: function(deserialized) {
    return deserialized.slice(0, deserialized.length - this.text.length);
  }
});

App.ObjectTransform = DS.Transform.extend({
  deserialize: function(serialized) {
    return Ember.isEmpty(serialized) ? {} : JSON.parse(serialized);
  },
  serialize: function(deserialized) {
    return Ember.isNone(deserialized) ? '' : JSON.stringify(deserialized);
  }
});

App.Preserialized = DS.Model.extend({
  // This will contain JSON that will be deserialized by the App.ObjectTransform.
  // If it deserializes to an array with anything other than numbers it will be
  // incorrectly interpreted by extractDjangoPayload as an embedded record.
  config: DS.attr('object')
});

App.Transformer = DS.Model.extend({
  transformed: DS.attr('silly')
});

App.CamelUrl = DS.Model.extend({
  test: DS.attr('string')
});

App.Cart = DS.Model.extend({
  name: DS.attr('string'),
  complete: DS.attr('boolean')
});

App.Camel = DS.Model.extend({
  camelCaseAttribute: DS.attr('string'),
  camelCaseRelationship: DS.hasMany('tag', { async: true })
});

App.Location = DS.Model.extend({
  name:DS.attr('string')
});

App.Session = DS.Model.extend({
  name: DS.attr('string'),
  room: DS.attr('string'),
  tags: DS.hasMany('tag', {async: true }),
  speakers: DS.hasMany('speaker', { async: true }),
  ratings: DS.hasMany('rating', { async: true })
});

App.Speaker = DS.Model.extend({
  name: DS.attr('string'),
  location: DS.attr('string'),
  association: DS.belongsTo('association'),
  personas: DS.hasMany('persona', { async: true }),
  badges: DS.hasMany('badge', { async: true }),
  session: DS.belongsTo('session'),
  zidentity: DS.belongsTo('user'),
  other: DS.belongsTo('other'),
  errors: ''
});

App.Other = DS.Model.extend({
  hat: DS.attr('string'),
  tags: DS.hasMany('tag'),
  speakers: DS.hasMany('speaker'),
  ratings: DS.hasMany('rating'),
  location: DS.belongsTo('location')
});

App.Speaker.reopen({
  becameError: function(errors) {
    var model = this.constructor.typeKey;
    this.set('errors', "operation failed for model: " + model);
  }
});

App.Tag = DS.Model.extend({
  description: DS.attr('string')
});

App.Rating = DS.Model.extend({
  score: DS.attr('number'),
  feedback: DS.attr('string'),
  session: DS.belongsTo('session'),
  other: DS.belongsTo('other')
});

App.Association = DS.Model.extend({
  name: DS.attr('string'),
  speakers: DS.hasMany('speaker', { async: true})
});

App.Author = DS.Model.extend({
});

App.User = App.Author.extend({
  name: DS.attr('string'),
  username: DS.attr('string'),
  aliases: DS.hasMany('speaker', { async: true }),
  image: DS.attr('string', { readOnly: true }),
  messages: DS.hasMany('message', { polymorphic: true })
});

App.Company = App.Author.extend({
  name: DS.attr('string'),
  sponsors: DS.hasMany('sponsor', { async: true}),
  messages: DS.hasMany('message', { polymorphic: true }),
  persona: DS.belongsTo('persona')
});

App.Persona = DS.Model.extend({
  nickname: DS.attr('string'),
  speaker: DS.belongsTo('speaker'),
  company: DS.belongsTo('company')
});

App.Badge = DS.Model.extend({
  city: DS.attr('string'),
  speaker: DS.belongsTo('speaker')
});

App.Sponsor = DS.Model.extend({
  name: DS.attr('string'),
  company: DS.belongsTo('company')
});

App.CarPart = DS.Model.extend({ cars: DS.hasMany('car', {async: true})});
App.Car = DS.Model.extend({ carParts: DS.hasMany('carPart', {async: true})});

App.CamelParent = DS.Model.extend({
  name: DS.attr('string'),
  camelKids: DS.hasMany('camelKid', {async: true})
});

App.CamelKid = DS.Model.extend({
  description: DS.attr('string'),
  camelParent: DS.belongsTo('camelParent')
});

App.Message = DS.Model.extend({
  content: DS.attr('string'),
  author: DS.belongsTo('author', {polymorphic: true}),
  receiver: DS.belongsTo('author', {polymorphic: true})
});

App.Post = App.Message.extend({});

App.Comment = App.Message.extend({});

App.Obituary = DS.Model.extend({
  publishOn: DS.attr('date'),
  timeOfDeath: DS.attr('datetime'),

  publishOnUtc: function() {
    if (!Ember.isEmpty(this.get('publishOn'))) {
      return this.get('publishOn').toUTCString();
    } else {
      return '';
    }
  }.property('publishOn'),

  timeOfDeathUtc: function() {
    if (!Ember.isEmpty(this.get('timeOfDeath'))) {
      return this.get('timeOfDeath').toUTCString();
    } else {
      return '';
    }
  }.property('timeOfDeath')
});

App.NewObituaryController = Ember.Controller.extend({
  publishOn: '',
  timeOfDeath: '',

  actions: {

    createObituary: function() {

      var newObituary = this.store.createRecord('obituary', {
        publishOn: new Date(this.get('publishOn')),
        timeOfDeath: new Date(this.get('timeOfDeath')),
      });

      return newObituary.save();
    }
  }
});

App.ObituariesRoute = Ember.Route.extend({

  model: function() {
    return this.store.find('obituary');
  }
});

App.ObituariesController = Ember.ArrayController.extend({
});

App.OthersRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('other');
  }
});

App.CamelParentRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('camelParent', 1);
  }
});

App.CamelParentController = Ember.ObjectController.extend({
  actions: {
    addCamelKid: function() {
      var parent = this.store.all('camelParent').objectAt(0);
      var hash = {'description': 'firstkid', 'camelParent': parent};
      this.store.createRecord('camelKid', hash).save();
    }
  }
});

App.CartRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.find('cart', params.cart_id);
  }
});

App.CartController = Ember.ObjectController.extend({
  actions: {
    add: function() {
      var name = this.get('name');
      var complete = this.get('complete');
      var hash = {name: name, complete: complete};
      this.store.createRecord('cart', hash).save();
    }
  }
});

App.RatingsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('rating');
  }
});

App.PreserializedRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('preserialized');
  }
});

App.TransformersRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('transformer');
  }
});

App.CamelUrlsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('camelUrl');
  }
});

App.CamelsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('camel');
  }
});

App.SessionsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('session');
  }
});

App.SpeakersRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('speaker', {name: 'Joel Taddei'});
  }
});

App.AssociationsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('association');
  }
});

App.SpeakerController = Ember.ObjectController.extend({
  actions: {
    updateSpeaker: function(model) {
      model.save().then(function() {}, function() { /* errors goes here */ });
    }
  }
});

App.OtherController = Ember.ObjectController.extend({
  actions: {
    addRating: function(other) {
      var score = this.get('score');
      var feedback = this.get('feedback');
      if (score === undefined || feedback === undefined || Ember.$.trim(score) === "" || Ember.$.trim(feedback) === "") {
        return;
      }
      var rating = { score: score, feedback: feedback, other: other};
      this.store.createRecord('rating', rating).save();
      this.set('score', '');
      this.set('feedback', '');
    }
  }
});

App.SessionController = Ember.ObjectController.extend({
  actions: {
    addSpeaker: function(session) {
      var self = this;
      var name = this.get('speaker');
      var location = this.get('location');
      this.store.find('user', 1).then(function(user) {
        //to simulate a record create with multiple parents
        var hash = {zidentity: user, name: name, location: location, session: session};
        self.store.createRecord('speaker', hash).save();
      });
    },
    addSpeakerWithUserSingleParent: function(session) {
      var self = this;
      var name = this.get('speaker');
      var location = this.get('location');
      this.store.find('user', 1).then(function(user) {
        //to simulate a record create with single user parent
        var hash = {zidentity: user, name: name, location: location};
        self.store.createRecord('speaker', hash).save();
      });
    },
    addSpeakerWithSingleParent: function(session) {
      var self = this;
      var name = this.get('speaker');
      var location = this.get('location');
      //to simulate a record create with just a single parent
      var hash = {name: name, location: location, session: session};
      self.store.createRecord('speaker', hash).save();
    },
    addRating: function(session) {
      var score = this.get('score');
      var feedback = this.get('feedback');
      if (score === undefined || feedback === undefined || Ember.$.trim(score) === "" || Ember.$.trim(feedback) === "") {
        return;
      }
      var rating = { score: score, feedback: feedback, session: session};
      this.store.createRecord('rating', rating).save();
      this.set('score', '');
      this.set('feedback', '');
    },
    deleteRating: function(rating) {
      rating.deleteRecord();
      rating.save();
    }
  }
});

App.Router.map(function() {
  this.resource("sessions", { path : "/sessions" });
  this.resource("others", { path : "/others" });
  this.resource("other", { path : "/other/:other_id" });
  this.resource("associations", { path : "/associations" });
  this.resource("speakers", { path : "/speakers" });
  this.resource("ratings", { path : "/ratings" });
  this.resource("session", { path : "/session/:session_id" });
  this.resource("speaker", { path : "/speaker/:speaker_id" });
  this.resource("cart", { path : "/cart/:cart_id" });
  this.resource("camels", { path : "/camels" });
  this.resource("camelParent", { path : "/camelParent" });
  this.resource("camelUrls", { path : "/camelUrls" });
  this.resource("transformers", { path : "/transformers" });
  this.resource("tag", { path : "/tag/:tag_id" });
  this.resource("user", { path : "/user/:user_id" });
  this.resource("preserialized", { path: "/preserialized" });
  this.resource('obituaries');
  this.route('new-obituary');
});

App.ApplicationAdapter = DS.DjangoRESTAdapter.extend({
  namespace: 'api'
});

//monkey patch the ajax method for testing
var ajaxUrl, ajaxType, ajaxHash;
DS.DjangoRESTAdapter.reopen({
  ajax: function(url, type, hash) {
    ajaxUrl = url;
    ajaxType = type;
    ajaxHash = hash;
    hash = hash || {};
    hash.cache = false;
    return this._super(url, type, hash);
  }
});