text:
namespace XML {

  typedef std::map<std::string,std::string>::iterator it_type;

  class Element {
  public:
    std::map<std::string,std::string> attributes;
    std::string text;
    std::vector<Element> children;
    std::string name;

    Element(std::string name)
      :name(name){}

    template <class X>
    Element(std::string name, X value)
      :name(name){
      set_text(value);
    }

    void append(Element child){
      children.push_back(child);
    }

    template <class X>
    void set_text(std::vector<X>& values, std::string sep=","){
      std::stringstream converter;
      converter << std::setprecision(15);
      for (int ii=0;ii<values.size();ii++){
	converter << values[ii];
	if (ii<values.size()-1)
	  converter << ", ";
      }
      text = converter.str();
    }

    template <class X>
    void set_text(X value){
      std::stringstream converter;
      converter << std::setprecision(15);
      converter << value;
      text = converter.str();
    }

    template <class X>
    void add_attribute(std::string key, X value){
      std::stringstream converter;
      converter << std::setprecision(15);
      converter << "'" << value << "'";
      attributes[key] = converter.str();
    }

    std::string to_string(bool header=false, int level=0){
      std::stringstream xml;

      xml << std::setprecision(15);
      if (header)
	xml << "<?xml version='1.0' encoding='ISO-8859-1'?>\n";

      for (int ii=0;ii<level;ii++)
	xml << "  ";

      xml << "<" << name;
      for (it_type iterator = attributes.begin();
	   iterator != attributes.end();
	   iterator++){
	xml << " " << iterator->first << "=" << iterator->second;
      }
      xml << ">";

      if (children.size() == 0){
	xml << text;
      } else {
	xml << "\n";
	for (int ii=0;ii<children.size();ii++)
	  xml << children[ii].to_string(false,level+1);
	for (int ii=0;ii<level;ii++)
	  xml << "  ";
      }
      xml << "</" << name << ">\n";
      return xml.str();
    }
  };
}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Web.UI.WebControls
{
  public partial interface ICompositeControlDesignerAccessor
  {
    #region Methods and constructors
    void RecreateChildControls ();
    #endregion
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>KafkaConsumer.ConsumerRecord (Edgent v1.0.0)</title>
<meta name="date" content="2016-11-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.edgent.connectors.kafka

Interface KafkaConsumer.ConsumerRecord<K,V>

Type Parameters:

K - key's type

V - the value's type

All Known Subinterfaces:

KafkaConsumer.ByteConsumerRecord, KafkaConsumer.StringConsumerRecord

Enclosing class:

KafkaConsumer

public static interface KafkaConsumer.ConsumerRecord<K,V>

A received Kafka record

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

K
key()

long
offset()

int
partition()

java.lang.String
topic()

V
value()

Method Detail

topic

java.lang.String topic()

partition

int partition()

offset

long offset()

Returns:

message id in the partition.

key

K key()

Returns:

null if no key was published.

value

V value()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Apache Edgent (incubating)

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation. All Rights Reserved - 73539fa-20161119-2136


text:
using System.Windows;

namespace LogoFX.Client.Mvvm.Navigation.Samples.Wpf.Controls
{
    public class NavigationClickEventArgs : RoutedEventArgs
    {
        public object NavigationItem { get; private set; }

        public NavigationClickEventArgs(RoutedEvent routedEvent, object navigationItem)
            : base(routedEvent)
        {
            NavigationItem = navigationItem;
        }
    }
}


text:
using DoStuff.Models;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;

namespace DoStuff
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableDependencyInjection();

            var builder = new ODataConventionModelBuilder()
            {
                Namespace = "DoStuff"
            };
            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
            builder.EntitySet<Asset>("Assets");
            builder.EntitySet<AssetType>("AssetTypes");
            builder.EntitySet<Person>("Persons");
            builder.EntitySet<ServiceRequest>("ServiceRequests");
            builder.EntitySet<Space>("Spaces");
            builder.EntitySet<Service>("Services");
            builder.ComplexType<OpenComplexType>();
            builder.ComplexType<Event>();
            builder.ComplexType<Address>();

            builder.EntityType<Person>()
                .Function("ServicesPerformed")
                .ReturnsCollectionFromEntitySet<Service>("Services");

            var model = builder.GetEdmModel();
            var routeName = "ODataRoute";
            config.MapODataServiceRoute(routeName, null, model);
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
  <title>material-react-components</title>
  <style type='text/css'>
    html, body {
      height: 100%;
      font-family: 'Roboto', sans-serif;
      background-color: #fafafa;
      margin: 0;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
  </style>
</head>
<body>
  <script src="/material-react-components/main.js"></script>
</body>
</html>


text:
import React, { Component } from 'react'
import {
  View,
  StyleSheet
} from 'react-native'
import BookList from '../components/BookList'
import SearchNav_Welcome from '../components/SearchNavHomePage'
import { HEIGHT, getResponsiveHeight } from '../common/styles'
import { Actions } from 'react-native-router-flux'
import { SCENE_SEARCH } from '../constants/scene'
import HttpUtils from '../network/HttpUtils'
import { BOOKS } from '../network/Urls'
import Toast from 'antd-mobile/lib/toast'

const URL = BOOKS.hot_books

export default class Home extends Component {

  state = {
    books: [],
    page: 1,
    isLoading: true
  }

  componentDidMount() {
    this.fetchHotBooks()
  }

  fetchHotBooks = async () => {
    let params = { page: 1 }

    let result
    try {
      result = (await HttpUtils.post(URL, params)) || {}
    } catch (e) {
      Toast.fail('加载失败', 1)
      this.setState({ isLoading: false })
      return
    }

    if (result.status !== 0) {
      return
    }

    this.setState({
      books: result.data,
      isLoading: false
    })
  }

  onEndReached = async () => {
    const params = { page: this.state.page + 1 }

    const result = (await HttpUtils.post(URL, params)) || {}

    const books = [...this.state.books, ...result.data]

    this.setState({
      books,
      page: this.state.page + 1
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.list}>
          <SearchNav_Welcome
            placeholder={'搜索'}
            onFocus={this.onFocus}
          />
          <BookList
            books={this.state.books}
            onEndReached={this.onEndReached}
            style={styles.book_list}
            isLoading={this.state.isLoading}
            onRefresh={this.fetchHotBooks}
          />
        </View>
      </View>
    )
  }

  onFocus = () => {
    Actions[SCENE_SEARCH]()
  }
}

const styles = StyleSheet.create({
  container: {
    // flex:1,
    flexDirection: 'column',
    backgroundColor: 'rgb(242,246,250)',
    alignItems: 'center',
    height: HEIGHT
  },
  book_list: {
    // 一半的输入框高度加上maginBottom
    paddingTop: getResponsiveHeight(10)
  }
})


text:
"use strict";

exports.Patients = function() {
  var MongoLib = require('mongodb'),
    MongoServer,
    MongoDB,
    BSON = MongoLib.BSONPure,
    server,
    db,
    SendEmailLib = require("../email.js");

  this.initDB = function() {
    MongoServer = MongoLib.Server;
    MongoDB = MongoLib.Db;
    var mongoUri = process.env.MONGOLAB_URI ||
      process.env.MONGOHQ_URL ||
      'mongodb://localhost/patientdb';

    console.log('DB URL: ' + mongoUri);
    MongoLib.connect(mongoUri, {}, function dbConnectCallback(error, database) {
      db = database;
      db.addListener("error", function handleError(error) {
        console.log("Error connecting to MongoLab");
      });
    });
  };

  this.populate = function(req, res) {
    db.createCollection("patients", function collectionCallback(error, collection) {
      console.log("Created Collection 'patients'");
      db.collection('patients', function(err, collection) {
        collection.remove({}, {}, function(err, result) {
          console.log("Inserting sample patients");
          db.collection('patients', function(err, collection) {
            collection.insert(getSamplePatients(), {
              safe: true
            }, function(err, result) {
              if (err) {
                res.send(JSON.stringify({
                  status: 'failure'
                }), 500);
              } else {
                res.send(JSON.stringify({
                  status: 'success'
                }), 200);
              }
            });
          });
        });
      });
    });
  };

  this.thisIsAPI = function(req, res) {
    res.send('
 Immunization App API

Hello, this is an API that was developed to serve up patient records to an iPad app.  For more information, check it out on github.');
  };

  this.login = function(req, res) {
    res.header("Content-Type", "application/json");
    var post = req.body;

    if (post && post.username && post.password) {
      var user = authenticateUser(post.username, post.password);
      if (user) {
        req.session.user_id = post.username;
        res.send(JSON.stringify({
          status: 'success',
          firstName: user.firstName
        }), 200);
      } else {
        res.send(JSON.stringify({
          status: 'failure'
        }), 401);
      }
    } else {
      res.send(JSON.stringify({
        status: 'failure',
      }), 400);
    }
  };

  this.logout = function(req, res) {
    res.header("Content-Type", "application/json");
    delete req.session.user_id;
    res.send(JSON.stringify({
      status: "success"
    }), 200);
  };

  this.findAllPatients = function(req, res) {
    db.collection('patients', function(err, collection) {
      collection.find().toArray(function(err, items) {
        res.send(sanitizeRecords(items), 200);
      });
    });
  };

  this.findPatientById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving Patient Record for ID: ' + id);
    db.collection('patients', function(err, collection) {
      collection.findOne({
        _id: new BSON.ObjectID(id)
      }, function(err, item) {
        if (err) {
          res.send(JSON.stringify({
            status: "failure"
          }), 400);
          return;
        }
        if (item) {
          res.send(sanitizeRecords(item), 200);
        } else {
          res.send(JSON.stringify({
            status: "failure"
          }), 404);
        }
      });
    });
  };

  this.addPatient = function(req, res) {
    var patient = req.body;
    console.log('Adding Patient: ' + JSON.stringify(patient));
    db.collection('patients', function(err, collection) {
      collection.insert(patient, {
        safe: true
      }, function(err, result) {
        if (err) {
          res.send(JSON.stringify({
            status: 'failure'
          }));
        } else {
          console.log('Success: ' + JSON.stringify(result[0]));
          res.send(JSON.stringify({
            status: 'success'
          }));
        }
      });
    });
  };

  this.updatePatient = function(req, res) {
    var id = req.params.id;
    var patient = req.body;

    var badFormInfo = validatePatientUpdateRequest(patient);
    if (badFormInfo) {
      res.send(JSON.stringify({
        status: "failure",
        validateMsg: badFormInfo
      }));
      return;
    }

    db.collection('patients', function(err, collection) {
      collection.findOne({
        _id: new BSON.ObjectID(id)
      }, function(err, item) {
        if (err) {
          console.log('failed to fetch patient in update patient!');
        } else if (item) {
          for (var key in patient) {
            item[key] = patient[key];
          }
          console.log('Updating Patient: ' + id);
          collection.update({
            '_id': new BSON.ObjectID(id)
          }, item, {
            safe: true
          }, function(err, result) {
            if (err) {
              console.log('Error updating patient: ' + err);
              res.send(JSON.stringify({
                status: 'failure',
                message: 'An error has occurred'
              }));

            } else {
              console.log('' + result + ' document(s) updated');
              res.send(JSON.stringify({
                status: 'success'
              }));
            }
          });
        }
      });
    });
  };

  this.deletePatient = function(req, res) {
    var id = req.params.id;
    console.log('Deleting Patient: ' + id);
    db.collection('patients', function(err, collection) {
      collection.remove({
        '_id': new BSON.ObjectID(id)
      }, {
        safe: true
      }, function(err, result) {
        if (err) {
          res.send(JSON.stringify({
            status: 'failure'
          }));
        } else {
          console.log('' + result + ' document(s) deleted');
          res.send(JSON.stringify({
            status: 'success'
          }));
        }
      });
    });
  };

  var validatePatientUpdateRequest = function(patient) {

    for (var key in patient) {
      if (key === "contactState") {
        if (!(/^[A-Z]{2}$/).test(patient[key]))
          return "State";
      }
      if (key === "contactZip") {
        if (!(/^\d{5}$/).test(patient[key]))
          return "Zip Code";
      }
      if (key === "contactPhone") {
        if (!(/^\d{3}-\d{3}-\d{4}$/).test(patient[key]))
          return "Phone Number";
      }
      if (key === "contactEmail") {
        if (!(/^\S+@\S+\.\S+$/).test(patient[key]))
          return "Email Address";
      }
      if ((/Name/g).test(key)) {
        if (!(/^[a-zA-Z]+[a-zA-Z. ]*$/).test(patient[key]))
          return key;
      }
      if ((/Administered/g).test(key)) {
        if (patient[key])
          if (!(/^[a-zA-Z]+[a-zA-Z. ]*$/).test(patient[key]))
            return key;
      }
      if ((/Date/g).test(key) || (/Next/g).test(key)) {
        if (patient[key])
          if (!(/^\d{2}\/\d{2}\/\d{4}$/).test(patient[key]))
            return key;
      }
    }
  };

  this.searchPatient = function(req, res) {
    var search = req.body;

    for (var key in search) {
      if (search[key] === "") {
        delete search[key];
      } else if (key === "_id") {
        search[key] = new BSON.ObjectID(search[key]);
      }
    }

    console.log('Searching For Patient: ' + JSON.stringify(search));
    db.collection('patients', function(err, collection) {
      collection.find(search).toArray(function(err, patientRecords) {
        if (err) {
          res.send(JSON.stringify({
            status: "failure"
          }));
        } else {
          res.send(sanitizeRecords(patientRecords));
        }
      });
    });
  };

  var sanitizeRecords = function(userRecord) {
    if (userRecord[0]) {
      for (var i = 0; i < Object.keys(userRecord).length; ++i) {
        delete userRecord[i]['userName'];
        delete userRecord[i]['password'];
      }

    } else {
      delete userRecord['userName'];
      delete userRecord['password'];
    }
    return userRecord;
  };

  this.checkAuth = function(req, res, next) {
    res.header("Content-Type", "application/json");
    if (req.session.user_id) {
      res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
      next();
    } else {
      console.log('Failure: ' + req.session.user_id);
      res.send(JSON.stringify({
        status: 'failure',
        message: 'You are not authorized to view this page'
      }));
    }
  };

  var authenticateUser = function(username, password) {
    for (var user in privilegedUsers) {
      if (privilegedUsers[user].username === username && privilegedUsers[user].password === password)
        return privilegedUsers[user];
    }
    return null;
  };

  var privilegedUsers = [{
    firstName: "Betty",
    lastName: "Crocker",
    username: "betty@gmail.com",
    password: "test"
  }];

  var getSamplePatients = function() {

    var patients = [{
      id: "1",
      userName: "arnold",
      password: "thepump",
      firstName: "Arnold",
      middleName: "Alois",
      lastName: "Schwarzenegger",
      fatherFullName: "Gustav Schwarzenegger",
      motherFullName: "Aurelia Schwarzenegger",
      motherMaidenName: "Peach",
      birthYear: "1963",
      birthMonth: "11",
      birthDay: "22",
      gender: "Male",
      contactPhone: "281-555-1234",
      contactEmail: "arnold.schwarzenegger@gmail.com",
      contactStreetAddress: "3110 Main Street",
      contactCity: "Santa Monica",
      contactState: "CA",
      contactZip: "90405",
      contactCountry: "USA",
      picture: "arnold1.jpg",
      vacPicture: "",
      bloodType: "A-",
      alergies: "Bees and Wasps",
      diseaseHistory: "Chicken Pox at age 4",
      notes: "Steroid use, possible damage to liver",
      BirthBcgDate: '11/24/1963',
      BirthBcgAdministered: 'Jony Java',
      BirthBcgHospital: 'United Childrens',
      BirthBcgNext: '11/30/1963'
    }, {
      id: "2",
      userName: "mary",
      password: "password",
      firstName: "Mary",
      middleName: "Ann",
      lastName: "Whistler",
      fatherFullName: "Michael Whistler",
      motherFullName: "Cleopatra Whistler",
      motherMaidenName: "Berry",
      birthYear: "1997",
      birthMonth: "3",
      birthDay: "2",
      gender: "Female",
      contactPhone: "713-555-4321",
      contactEmail: "mary.whistler@gmail.com",
      contactStreetAddress: "775 West Kingsley",
      contactCity: "Fort Collins",
      contactState: "CO",
      contactZip: "80521",
      contactCountry: "USA",
      picture: "mary1.jpg",
      vacPicture: "",
      bloodType: "O",
      alergies: "Gluten",
      diseaseHistory: "Malaria at age 12",
      notes: "Spent an extensive amount of time in Africa",
      BirthBcgDate: '03/19/1997',
      BirthBcgAdministered: 'Jony Java',
      BirthBcgHospital: 'United Childrens',
      BirthBcgNext: '05/17/1997',
      sixPcvDate: '04/14/1997',
      sixPcvAdministered: 'Jimmy Smalltalk',
      sixPcvHospital: 'Saint Matthews',
      sixPcvNext: '06/12/1997'
    }, {
      id: "3",
      userName: "sherlock",
      password: "irene",
      firstName: "Sherlock",
      middleName: "",
      lastName: "Holmes",
      fatherFullName: "Mark Holmes",
      motherFullName: "Violet Holmes",
      motherMaidenName: "Moriarty",
      birthYear: "1972",
      birthMonth: "5",
      birthDay: "21",
      gender: "Male",
      contactPhone: "616-555-1221",
      contactEmail: "sherlock.holmes@gmail.com",
      contactStreetAddress: "221B Baker Street",
      contactCity: "Houston",
      contactState: "TX",
      contactZip: "77098",
      contactCountry: "England",
      picture: "sherlock1.jpg",
      vacPicture: "",
      bloodType: "O",
      alergies: "None",
      diseaseHistory: "Pneumonia at age 13",
      notes: "Patient may also be suffering from depression",
      BirthOpvDate: '05/29/1972',
      BirthOpvAdministered: 'John Pascal',
      BirthOpvHospital: 'Saint Lukes',
      BirthOpvNext: '06/12/1972'
    }];
    return patients;
  };

  this.sendEmail = function(req, res) {
    db.collection('patients', function(err, collection) {
      collection.findOne({
        _id: new BSON.ObjectID(req.params.id)
      }, function(err, item) {
        if (err) {
          res.send(JSON.stringify({
            status: 'failure'
          }));
        } else if (item) {
          SendEmailLib.sendMail(item, function(success) {
            if (success) {
              res.send(JSON.stringify({
                status: 'success'
              }));
            } else {
              res.send(JSON.stringify({
                status: 'failure'
              }));
            }
          });
        }
      });
    });
  };
};


text:
using NoteEditor.Common;
using NoteEditor.Model;
using NoteEditor.Utility;
using System.Linq;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
using UnityEngine.UI;

namespace NoteEditor.Presenter
{
    public class CanvasWidthScalePresenter : MonoBehaviour
    {
        [SerializeField]
        CanvasEvents canvasEvents = default;
        [SerializeField]
        Slider canvasWidthScaleController = default;

        void Awake()
        {
            Audio.OnLoad.First().Subscribe(_ => Init());
        }

        void Init()
        {
            var operateCanvasScaleObservable = canvasEvents.MouseScrollWheelObservable
                .Where(_ => KeyInput.CtrlKey())
                .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.UpArrow)).Select(_ => 0.05f))
                .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.DownArrow)).Select(_ => -0.05f))
                .Select(delta => NoteCanvas.Width.Value * (1 + delta))
                .Select(x => x / (Audio.Source.clip.samples / 100f))
                .Select(x => Mathf.Clamp(x, 0.1f, 2f))
                .Merge(canvasWidthScaleController.OnValueChangedAsObservable()
                    .DistinctUntilChanged())
                .DistinctUntilChanged()
                .Select(x => Audio.Source.clip.samples / 100f * x);

            operateCanvasScaleObservable.Subscribe(x => NoteCanvas.Width.Value = x);

            operateCanvasScaleObservable.Buffer(operateCanvasScaleObservable.ThrottleFrame(2))
                .Where(b => 2 <= b.Count)
                .Select(x => new { current = x.Last(), prev = x.First() })
                .Subscribe(x => EditCommandManager.Do(
                    new Command(
                        () => NoteCanvas.Width.Value = x.current,
                        () => NoteCanvas.Width.Value = x.prev)));
        }
    }
}


text:
describe Fastlane do
  describe Fastlane::FastFile do
    describe "Clean Cocoapods Cache Integration" do
      it "default use case" do
        result = Fastlane::FastFile.new.parse("lane :test do
          clean_cocoapods_cache
        end").runner.execute(:test)

        expect(result).to eq("pod cache clean --all")
      end

      it "adds pod name to command" do
        result = Fastlane::FastFile.new.parse("lane :test do
          clean_cocoapods_cache(
            name: 'Name'
          )
        end").runner.execute(:test)

        expect(result).to eq("pod cache clean Name --all")
      end

      it "raise an exception if name is empty" do
        expect do
          Fastlane::FastFile.new.parse("lane :test do
            clean_cocoapods_cache(
              name: ''
            )
            end").runner.execute(:test)
        end.to raise_error(RuntimeError)
      end
    end
  end
end


text:
<?php

namespace app\modules\aux_planejamento\controllers\relatorios;

use Yii;
use app\modules\aux_planejamento\models\base\Unidade;
use app\modules\aux_planejamento\models\cadastros\Ano;
use app\modules\aux_planejamento\models\relatorios\RelatorioModeloB;
use app\modules\aux_planejamento\models\planilhas\Planilhadecurso;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

class RelatorioModeloBController extends Controller
{

    public function behaviors()
    {

        $this->AccessAllow(); //Irá ser verificado se o usuário está logado no sistema

        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionGerarRelatorio()
    {
	    $model = new RelatorioModeloB();

	    $unidades = Unidade::find()->where(['uni_codsituacao' => 1])->orderBy('uni_nomeabreviado')->all();
	    $ano      = Ano::find()->orderBy(['an_codano'=>SORT_DESC])->all();

        if ($model->load(Yii::$app->request->post())) {

                return $this->redirect(['relatorio-modelo-b', 'combo_unidade' => $model->relat_unidade, 'combo_ano' => $model->relat_codano]);
        }else{

	            return $this->render('/relatorios/relatorio-modelo-b/gerar-relatorio', [
	                'model'            => $model,
	                'unidades'         => $unidades,
	                'ano'              => $ano,
	                ]);
	        }
    }

    public function actionRelatorioModeloB($combo_unidade, $combo_ano)
    {
       $this->layout = 'main-imprimir';
       $combo_unidade         = $this->findModelUnidade($combo_unidade);
       $combo_ano         = $this->findModelAnoPlanilha($combo_ano);

             return $this->render('/relatorios/relatorio-modelo-b/relatorio-modelo-b', [
              'combo_unidade'         => $combo_unidade,
              'combo_ano'         => $combo_ano,
              ]);
    }

    protected function findModelUnidade($combo_unidade)
    {
        $queryUnidade = "SELECT placu_codunidade, placu_nomeunidade FROM planilhadecurso_placu WHERE placu_codunidade = '".$combo_unidade."'";

        $combo_unidade = Planilhadecurso::findBySql($queryUnidade)->one();

        return $combo_unidade;
    }

    protected function findModelAnoPlanilha($combo_ano)
    {
        $queryAno = "SELECT * FROM ano_an WHERE an_codano = '".$combo_ano."'";

        if (($combo_ano = Ano::findBySql($queryAno)->one()) !== null) {
            return $combo_ano;
        } else {
            throw new NotFoundHttpException('A página solicitada não existe.');
        }
    }

    public function AccessAllow()
    {
        $session = Yii::$app->session;
        if (!isset($session['sess_codusuario']) && !isset($session['sess_codcolaborador']) && !isset($session['sess_codunidade']) && !isset($session['sess_nomeusuario']) && !isset($session['sess_coddepartamento']) && !isset($session['sess_codcargo']) && !isset($session['sess_cargo']) && !isset($session['sess_setor']) && !isset($session['sess_unidade']) && !isset($session['sess_responsavelsetor']))
        {
           return $this->redirect('http://portalsenac.am.senac.br');
        }
    }
}


text:
define('lodash/internal/LazyWrapper', ['exports', 'lodash/internal/baseCreate', 'lodash/internal/baseLodash'], function (exports, _lodashInternalBaseCreate, _lodashInternalBaseLodash) {
  'use strict';

  /** Used as references for `-Infinity` and `Infinity`. */
  var POSITIVE_INFINITY = Number.POSITIVE_INFINITY;

  /**
   * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
   *
   * @private
   * @param {*} value The value to wrap.
   */
  function LazyWrapper(value) {
    this.__wrapped__ = value;
    this.__actions__ = [];
    this.__dir__ = 1;
    this.__filtered__ = false;
    this.__iteratees__ = [];
    this.__takeCount__ = POSITIVE_INFINITY;
    this.__views__ = [];
  }

  LazyWrapper.prototype = (0, _lodashInternalBaseCreate['default'])(_lodashInternalBaseLodash['default'].prototype);
  LazyWrapper.prototype.constructor = LazyWrapper;

  exports['default'] = LazyWrapper;
});


text:
namespace SportingSolutions.Udapi.Sdk.Model
{
    internal class StreamEcho
    {
        public string Host { get; set; }
        public string Queue { get; set; }
        public string Message { get; set; }
    }
}


text:
/**
 * Initialization function
 * @return {nothing} nothing
 */
function initialization(){
	var tcontainer = $('.js-tcont');

	/** EVENTS */

	tcontainer.on('click','.js-tile',function(){
		var self   = $(this),
				href     = self.data('href');

		location.href = href;

	});

	module.exports.cont = tcontainer;

}

module.exports.init = initialization;


text:
namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

template <typename TPos, typename TGapAnchor, typename TSpec, typename TGapPos>
inline bool  // true if removed gap that is not leading/trailing gap
_removeGap2(AlignedReadStoreElement<TPos, TGapAnchor, TSpec> & alignedRead,
            TGapPos const gapPos)
{
    typedef String<TGapAnchor> TGaps;
    typedef typename Iterator<TGaps, Standard>::Type TGapIter;
    if (gapPos < (TGapPos) alignedRead.beginPos)
    {
        --alignedRead.beginPos; --alignedRead.endPos;
    }
    else if (gapPos < (TGapPos) alignedRead.endPos)
    {
        --alignedRead.endPos;
        TGapIter gapIt = upperBoundGapAnchor(alignedRead.gaps, gapPos - alignedRead.beginPos, SortGapPos());
        TGapIter gapItEnd = end(alignedRead.gaps, Standard());
        // Note: We might create empty gaps here
        for(; gapIt != gapItEnd; ++gapIt)
            --(gapIt->gapPos);
        return true;
    }
    return false;
}

// Returns number of returned gaps.
template <typename TAlignedReads, typename TSpec, typename TGapPos, typename TAlignedReadIt>
inline int
_removeGap(String<TAlignedReads, TSpec>& alignedReadStore,
           TGapPos const gapPos,
           TAlignedReadIt const & skipIt)
{
    typedef String<TAlignedReads, TSpec> TAlignedReadStore;
    typedef typename Iterator<TAlignedReadStore, Standard>::Type TAlignIter;
    int result = 0;

    TAlignIter alignIt = begin(alignedReadStore, Standard());
    TAlignIter alignItEnd = end(alignedReadStore, Standard());
    for(;alignIt != alignItEnd; ++alignIt)
        if (alignIt != skipIt)
            result += _removeGap2(*alignIt, gapPos);
    return result;
}

template <typename TAlignedReads, typename TSpec, typename TGapPos, typename TAlignedReadIt>
inline int
_insertGap(String<TAlignedReads, TSpec>& alignedReadStore,
           TGapPos const gapPos,
           TAlignedReadIt const & skipIt)
{
    typedef String<TAlignedReads, TSpec> TAlignedReadStore;
    typedef typename Iterator<TAlignedReadStore, Standard>::Type TAlignIter;

    int numGaps = 0;
    TAlignIter alignIt = begin(alignedReadStore, Standard());
    TAlignIter alignItEnd = end(alignedReadStore, Standard());
    for(;alignIt != alignItEnd; ++alignIt)
        if (alignIt != skipIt)
            numGaps += insertGap(*alignIt, gapPos);
    return numGaps;
}

// ----------------------------------------------------------------------------
// Helper Function _printProfile()
// ----------------------------------------------------------------------------

// 0   - space
// 1-9 - 1..9
// >10 - '!' + ceil(log(count))
inline char _countToLogChar(int count)
{
    if (count <= 0)
        return ' ';
    else if (count <= 9)
        return '0' + count;
    else
        return '!' + int(ceil(log10(1.0 * count)));
}

template <typename TStream, typename TAlphabet, typename TSpec>
void _printProfile(TStream & stream,
                   String<ProfileChar<TAlphabet>, TSpec> const & profile)
{
    stream << "PROFILE (0 - space, 1..9 - 1..9, >10 - ! + int(ceil(log10(count)))\n"
           << "------------------------------------------------------------------\n";

    stream << "   ";
    for (unsigned i = 0 ; i < length(profile); ++i)
    {
        if (i % 10 == 0)
            stream << (i / 100) % 10;
        else if (i % 5 == 0)
            stream << (i / 100) % 10;
        else
            stream << ' ';
    }
    stream << "\n";

    stream << "   ";
    for (unsigned i = 0 ; i < length(profile); ++i)
    {
        if (i % 10 == 0)
            stream << (i / 10) % 10;
        else if (i % 5 == 0)
            stream << (i / 10) % 10;
        else
            stream << ' ';
    }
    stream << "\n";

    stream << "   ";
    for (unsigned i = 0 ; i < length(profile); ++i)
    {
        if (i % 10 == 0)
            stream << '0';
        else if (i % 5 == 0)
            stream << '5';
        else
            stream << ' ';
    }
    stream << "\n";

    stream << "   ";
    for (unsigned i = 0 ; i < length(profile); ++i)
    {
        if (i % 10 == 0)
            stream << ':';
        else if (i % 5 == 0)
            stream << '.';
        else
            stream << ' ';
    }
    stream << "\n";

    for (unsigned i = 0; i <= valueSize<TAlphabet>(); ++i)
    {
        if (i == valueSize<TAlphabet>())
            stream << "-: ";
        else
            stream << TAlphabet(i) << ": ";

        for (unsigned j = 0; j < length(profile); ++j)
            stream << _countToLogChar(profile[j].count[i]);

        stream << "\n";
    }
}

}  // namespace seqan

#endif  // #ifndef INCLUDE_SEQAN_REALIGN_REALIGN_HELPER_FUNCTIONS_H_


text:
/*
 * MEDIATEK SoC power sequencing module for Chrome EC
 *
 * This implements the following features:
 *
 * - Cold reset powers on the AP
 *
 *  When powered off:
 *  - Press pwron turns on the AP
 *  - Hold pwron turns on the AP, and then 8s later turns it off and leaves
 *    it off until pwron is released and pressed again
 *
 *  When powered on:
 *  - The PMIC PWRON signal is released <= 1 second after the power button is
 *    released
 *  - Holding pwron for 8s powers off the AP
 *  - Pressing and releasing pwron within that 8s is ignored
 *  - If POWER_GOOD is dropped by the AP, then we power the AP off
 *  - If SUSPEND_L goes low, enter suspend mode.
 *
 */

#include "battery.h"
#include "chipset.h" /* ./common/chipset.c implements chipset functions too */
#include "common.h"
#include "gpio.h"
#include "hooks.h"
#include "keyboard_scan.h"
#include "lid_switch.h"
#include "power.h"
#include "power_button.h"
#include "power_led.h"
#include "system.h"
#include "task.h"
#include "test_util.h"
#include "util.h"

#define CPRINTS(format, args...) cprints(CC_CHIPSET, format, ## args)

#define INT_BOTH_PULL_UP	(GPIO_INPUT | GPIO_PULL_UP | GPIO_INT_BOTH)

/* masks for power signals */
#define IN_POWER_GOOD POWER_SIGNAL_MASK(MTK_POWER_GOOD)
#define IN_SUSPEND POWER_SIGNAL_MASK(MTK_SUSPEND_ASSERTED)

/* Long power key press to force shutdown */
#define DELAY_FORCE_SHUTDOWN  (8000 * MSEC)	/* 8 seconds */

/*
 * The power signal from SoC should be kept at least 50ms.
 */
#define POWER_DEBOUNCE_TIME     (50 * MSEC)

/*
 * The suspend signal from SoC should be kept at least 50ms.
 */
#define SUSPEND_DEBOUNCE_TIME   (50 * MSEC)

/*
 * The time to bootup the PMIC from power-off to power-on.
 */
#define PMIC_PWRON_PRESS_TIME   (5000 * MSEC)

/*
 * The minimum time to assert the PMIC THERM pin is 32us. However,
 * it needs to be extended to about 50ms to let the 5V rail
 * dissipate fully.
 */
#define PMIC_THERM_HOLD_TIME  (50 * MSEC)

/*
 * If the power key is pressed to turn on, then held for this long, we
 * power off.
 *
 * Normal case: User releases power button and chipset_task() goes
 *    into the inner loop, waiting for next event to occur (power button
 *    press or POWER_GOOD == 0).
 */
#define DELAY_SHUTDOWN_ON_POWER_HOLD	(8000 * MSEC)	/* 8 seconds */

/*
 * The hold time for pulling down the PMIC_WARM_RESET_H pin so that
 * the AP can entery the recovery mode (flash SPI flash from USB).
 */
#define PMIC_WARM_RESET_H_HOLD_TIME (4 * MSEC)

/*
 * The hold time for pulling down the SYSTEM_POWER_H pin.
 */
#define PMIC_COLD_RESET_L_HOLD_TIME \
	(SUSPEND_DEBOUNCE_TIME + POWER_DEBOUNCE_TIME + (20 * MSEC))

/*
 * The first time the PMIC sees power (AC or battery) it needs 200ms (+/-12%
 * oscillator tolerance) for the RTC startup. In addition there is a startup
 * time of approx. 0.5msec until V2_5 regulator starts up. */
#define PMIC_RTC_STARTUP (225 * MSEC)

/* Wait for 5V power source stable */
#define PMIC_WAIT_FOR_5V_POWER_GOOD (1 * MSEC)

/* TODO(crosbug.com/p/25047): move to HOOK_POWER_BUTTON_CHANGE */
/* 1 if the power button was pressed last time we checked */
static char power_button_was_pressed;

/* 1 if lid-open event has been detected */
static char lid_opened;

/* time where we will power off, if power button still held down */
static timestamp_t power_off_deadline;

/* force AP power on (used for recovery keypress) */
static int auto_power_on;

enum power_request_t {
	POWER_REQ_NONE,
	POWER_REQ_OFF,
	POWER_REQ_ON,

	POWER_REQ_COUNT,
};

static enum power_request_t power_request;

/**
 * Return values for check_for_power_off_event().
 */
enum power_off_event_t {
	POWER_OFF_CANCEL,
	POWER_OFF_BY_POWER_BUTTON_PRESSED,
	POWER_OFF_BY_LONG_PRESS,
	POWER_OFF_BY_POWER_GOOD_LOST,
	POWER_OFF_BY_POWER_REQ,

	POWER_OFF_EVENT_COUNT,
};

/**
 * Return values for check_for_power_on_event().
 */
enum power_on_event_t {
	POWER_ON_CANCEL,
	POWER_ON_BY_IN_POWER_GOOD,
	POWER_ON_BY_AUTO_POWER_ON,
	POWER_ON_BY_LID_OPEN,
	POWER_ON_BY_POWER_BUTTON_PRESSED,
	POWER_ON_BY_POWER_REQ_NONE,

	POWER_ON_EVENT_COUNT,
};

/**
 * Parameters of mtk_backlight_override().
 */
enum blacklight_override_t {
	MTK_BACKLIGHT_FORCE_OFF,
	MTK_BACKLIGHT_CONTROL_BY_SOC,

	MTK_BACKLIGHT_OVERRIDE_COUNT,
};

/* Forward declaration */
static void chipset_turn_off_power_rails(void);

/**
 * Check the suspend signal is on after SUSPEND_DEBOUNCE_TIME to avoid transient
 * state.
 *
 * @return non-zero if SUSPEND is asserted.
 */
static int is_suspend_asserted(void)
{
	if ((power_get_signals() & IN_SUSPEND) &&
	    (system_get_board_version() < 4))
		usleep(SUSPEND_DEBOUNCE_TIME);

	return power_get_signals() & IN_SUSPEND;
}

/**
 * Check the suspend signal is off after SUSPEND_DEBOUNCE_TIME to avoid
 * transient state.
 *
 * @return non-zero if SUSPEND is deasserted.
 */
static int is_suspend_deasserted(void)
{
	if (!(power_get_signals() & IN_SUSPEND) &&
	    (system_get_board_version() < 4))
		usleep(SUSPEND_DEBOUNCE_TIME);

	return !(power_get_signals() & IN_SUSPEND);
}

/**
 * Check power good signal is on after POWER_DEBOUNCE_TIME to avoid transient
 * state.
 *
 * @return non-zero if POWER_GOOD is asserted.
 */
static int is_power_good_asserted(void)
{
	if (!gpio_get_level(GPIO_SYSTEM_POWER_H))
		return 0;
	else if ((power_get_signals() & IN_POWER_GOOD) &&
		 (system_get_board_version() < 4))
		usleep(POWER_DEBOUNCE_TIME);

	return power_get_signals() & IN_POWER_GOOD;
}

/**
 * Check power good signal is off after POWER_DEBOUNCE_TIME to avoid transient
 * state.
 *
 * @return non-zero if POWER_GOOD is deasserted.
 */
static int is_power_good_deasserted(void)
{
	/*
	 * Warm reset key from servo board lets the POWER_GOOD signal
	 * deasserted temporarily (about 1~2 seconds) on rev4.
	 * In order to detect this case, check the AP_RESET_L status,
	 * ignore the transient state if reset key is pressing.
	 */
	if (system_get_board_version() >= 4) {
		if (0 == gpio_get_level(GPIO_AP_RESET_L)) {
			return 0;
		}
	}

	if (!(power_get_signals() & IN_POWER_GOOD) &&
	    (system_get_board_version() < 4))
		usleep(POWER_DEBOUNCE_TIME);

	return !(power_get_signals() & IN_POWER_GOOD);
}

/**
 * Set the system power signal.
 *
 * @param asserted	off (=0) or on (=1)
 */
static void set_system_power(int asserted)
{
	CPRINTS("set_system_power(%d)", asserted);
	gpio_set_level(GPIO_SYSTEM_POWER_H, asserted);
}

/**
 * Set the PMIC PWRON signal.
 *
 * Note that asserting requires holding for PMIC_PWRON_PRESS_TIME.
 *
 * @param asserted	Assert (=1) or deassert (=0) the signal.  This is the
 *			logical level of the pin, not the physical level.
 */
static void set_pmic_pwron(int asserted)
{
	timestamp_t poll_deadline;
	/* Signal is active-high */
	CPRINTS("set_pmic_pwron(%d)", asserted);
	/* Oak rev1 power-on sequence:
	 *   raise GPIO_SYSTEM_POWER_H
	 *   wait for 5V power good, timeout 1 second
	 */
	if (asserted) {
		set_system_power(asserted);
		poll_deadline = get_time();
		poll_deadline.val += SECOND;
		while (asserted && !gpio_get_level(GPIO_5V_POWER_GOOD) &&
		       get_time().val < poll_deadline.val)
			usleep(PMIC_WAIT_FOR_5V_POWER_GOOD);
		if (gpio_get_level(GPIO_5V_POWER_GOOD))
			CPRINTS("5V power not ready");
	}

	gpio_set_level(GPIO_PMIC_PWRON_H, asserted);
}

/**
 * Set the WARM RESET signal.
 *
 * @param asserted	off (=0) or on (=1)
 */
static void set_warm_reset(int asserted)
{
	board_set_ap_reset(asserted);
}

/**
 * Check for some event triggering the shutdown.
 *
 * It can be either a long power button press or a shutdown triggered from the
 * AP and detected by reading POWER_GOOD.
 *
 * @return non-zero if a shutdown should happen, 0 if not
 */
static int check_for_power_off_event(void)
{
	timestamp_t now;
	int pressed = 0;

	/*
	 * Check for power button press.
	 */
	if (power_button_is_pressed()) {
		pressed = POWER_OFF_BY_POWER_BUTTON_PRESSED;
	} else if (power_request == POWER_REQ_OFF) {
		power_request = POWER_REQ_NONE;
		/* return non-zero for shudown down */
		return POWER_OFF_BY_POWER_REQ;
	}

#ifdef HAS_TASK_KEYSCAN
	/* Dis/Enable keyboard scanning when the power button state changes */
	if (!pressed || pressed != power_button_was_pressed)
		keyboard_scan_enable(!pressed, KB_SCAN_DISABLE_POWER_BUTTON);
#endif

	now = get_time();
	if (pressed) {
#ifndef CONFIG_PMIC_FW_LONG_PRESS_TIMER
		/*
		 * Only assert PMIC_PWRON if PMIC supports long-press
		 * power off.
		 */
		CPRINTS("PMIC long-press power off\n");
		set_pmic_pwron(1);
#endif

		if (!power_button_was_pressed) {
			power_off_deadline.val = now.val + DELAY_FORCE_SHUTDOWN;
			CPRINTS("power waiting for long press %u",
				power_off_deadline.le.lo);
#ifdef CONFIG_PMIC_FW_LONG_PRESS_TIMER
			/* Ensure we will wake up to check the power key */
			timer_arm(power_off_deadline, TASK_ID_CHIPSET);
#endif
		} else if (timestamp_expired(power_off_deadline, &now)) {
			power_off_deadline.val = 0;
			CPRINTS("power off after long press now=%u, %u",
				now.le.lo, power_off_deadline.le.lo);
			return POWER_OFF_BY_LONG_PRESS;
		}
	} else if (power_button_was_pressed) {
		CPRINTS("power off cancel");
		set_pmic_pwron(0);
#ifdef CONFIG_PMIC_FW_LONG_PRESS_TIMER
		timer_cancel(TASK_ID_CHIPSET);
#endif
	}

	power_button_was_pressed = pressed;

	/* POWER_GOOD released by AP : shutdown immediate */
	if (is_power_good_deasserted()) {
		/*
		 * Cancel long press timer if power is lost and the power button
		 * still press, otherwise EC will crash.
		 */
		if (power_button_was_pressed)
			timer_cancel(TASK_ID_CHIPSET);

		CPRINTS("POWER_GOOD is lost");
		return POWER_OFF_BY_POWER_GOOD_LOST;
	}

	return POWER_OFF_CANCEL;
}

/**
 * Set the LCD backlight enable pin and override the signal from SoC.
 *
 * @param asserted	MTK_BACKLIGHT_FORCE_OFF, force off the panel backlight
 *			MTK_BACKLIGHT_CONTROL_BY_SOC, leave the control to SOC
 */
static void mtk_backlight_override(enum blacklight_override_t asserted)
{
	/* Signal is active-low */
	gpio_set_level(GPIO_EC_BL_OVERRIDE, !asserted);
}

static void mtk_lid_event(void)
{
	enum blacklight_override_t bl_override;

	/* Override the panel backlight enable signal from SoC,
	 * force the backlight off on lid close.
	 */
	bl_override = lid_is_open() ?
		MTK_BACKLIGHT_CONTROL_BY_SOC :
		MTK_BACKLIGHT_FORCE_OFF;
	mtk_backlight_override(bl_override);

	/* Power task only cares about lid-open events */
	if (!lid_is_open())
		return;

	lid_opened = 1;
	task_wake(TASK_ID_CHIPSET);
}
DECLARE_HOOK(HOOK_LID_CHANGE, mtk_lid_event, HOOK_PRIO_DEFAULT);

enum power_state power_chipset_init(void)
{
	int init_power_state;
	uint32_t reset_flags = system_get_reset_flags();

	/*
	 * Force the AP shutdown unless we are doing SYSJUMP. Otherwise,
	 * the AP could stay in strange state.
	 */
	if (!(reset_flags & RESET_FLAG_SYSJUMP)) {
		CPRINTS("not sysjump; forcing AP shutdown");
		chipset_turn_off_power_rails();

		/*
		 * The warm reset triggers AP into the recovery mode (
		 * flash SPI from USB).
		 */
		chipset_reset(0);

		init_power_state = POWER_G3;
	} else {
		/* In the SYSJUMP case, we check if the AP is on */
		if (is_power_good_asserted()) {
			CPRINTS("SOC ON");
			/*
			 * Check and release PMIC power button signal,
			 * if it's deferred callback function is not triggered
			 * in RO before SYSJUMP.
			 */
			if (gpio_get_level(GPIO_PMIC_PWRON_H))
				set_pmic_pwron(0);

			init_power_state = POWER_S0;
			if (is_suspend_asserted())
				enable_sleep(SLEEP_MASK_AP_RUN);
			else
				disable_sleep(SLEEP_MASK_AP_RUN);
		} else {
			CPRINTS("SOC OFF");
			init_power_state = POWER_G3;
			enable_sleep(SLEEP_MASK_AP_RUN);
		}
	}

	/* Leave power off only if requested by reset flags */
	if (!(reset_flags & RESET_FLAG_AP_OFF) &&
	    !(reset_flags & RESET_FLAG_SYSJUMP)) {
		CPRINTS("reset_flag 0x%x", reset_flags);
		auto_power_on = 1;
	}

	/*
	 * Some batteries use clock stretching feature, which requires
	 * more time to be stable. See http://crosbug.com/p/28289
	 */
	battery_wait_for_stable();

	return init_power_state;
}

/*****************************************************************************/
/* Chipset interface */

static void chipset_turn_off_power_rails(void)
{
	/* Release the power on pin, if it was asserted */
	set_pmic_pwron(0);

	/* system power off */
	set_system_power(0);
}

void chipset_force_shutdown(void)
{
	chipset_turn_off_power_rails();

	/* clean-up internal variable */
	power_request = POWER_REQ_NONE;
}

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

/**
 * Power off the AP
 */
static void power_off(void)
{
	/* Check the power off status */
	if (!gpio_get_level(GPIO_SYSTEM_POWER_H))
		return;

	/* Call hooks before we drop power rails */
	hook_notify(HOOK_CHIPSET_SHUTDOWN);
	/* switch off all rails */
	chipset_turn_off_power_rails();

	/* Change SUSPEND_L pin to high-Z to reduce power draw. */
	gpio_set_flags(power_signal_list[MTK_SUSPEND_ASSERTED].gpio,
		       GPIO_INPUT);

	/* Change EC_INT to low */
	gpio_set_level(GPIO_EC_INT_L, 0);

	lid_opened = 0;
	enable_sleep(SLEEP_MASK_AP_RUN);
#ifdef HAS_TASK_POWERLED
	powerled_set_state(POWERLED_STATE_OFF);
#endif
	CPRINTS("power shutdown complete");
}

/**
 * Check if there has been a power-on event
 *
 * This checks all power-on event signals and returns non-zero if any have been
 * triggered (with debounce taken into account).
 *
 * @return non-zero if there has been a power-on event, 0 if not.
 */
static int check_for_power_on_event(void)
{
	int ap_off_flag;

	ap_off_flag = system_get_reset_flags() & RESET_FLAG_AP_OFF;
	system_clear_reset_flags(RESET_FLAG_AP_OFF);
	/* check if system is already ON */
	if (is_power_good_asserted()) {
		if (ap_off_flag) {
			CPRINTS("system is on, but RESET_FLAG_AP_OFF is on");
			return POWER_ON_CANCEL;
		} else {
			CPRINTS("system is on, thus clear " "auto_power_on");
			/* no need to arrange another power on */
			auto_power_on = 0;
			return POWER_ON_BY_IN_POWER_GOOD;
		}
	} else {
		if (ap_off_flag) {
			CPRINTS("RESET_FLAG_AP_OFF is on");
			power_off();
			return POWER_ON_CANCEL;
		}

		CPRINTS("POWER_GOOD is not asserted");
	}

	/* power on requested at EC startup for recovery */
	if (auto_power_on) {
		auto_power_on = 0;
		return POWER_ON_BY_AUTO_POWER_ON;
	}

	/* Check lid open */
	if (lid_opened) {
		lid_opened = 0;
		return POWER_ON_BY_LID_OPEN;
	}

	/* check for power button press */
	if (power_button_is_pressed())
		return POWER_ON_BY_POWER_BUTTON_PRESSED;

	if (power_request == POWER_REQ_ON) {
		power_request = POWER_REQ_NONE;
		return POWER_ON_BY_POWER_REQ_NONE;
	}

	return POWER_OFF_CANCEL;
}

void release_pmic_pwron_deferred(void)
{
	/* Release PMIC power button */
	set_pmic_pwron(0);
}
DECLARE_DEFERRED(release_pmic_pwron_deferred);

/**
 * Power on the AP
 */
static void power_on(void)
{
	uint64_t t;

	/* Set pull-up and enable interrupt */
	gpio_set_flags(power_signal_list[MTK_SUSPEND_ASSERTED].gpio,
		       GPIO_INPUT | GPIO_PULL_UP | GPIO_INT_BOTH);

	/* Make sure we de-assert and GPIO_PMIC_WARM_RESET_H pin. */
	set_warm_reset(0);

	/*
	 * Before we push PMIC power button, wait for the PMI RTC ready, which
	 * takes PMIC_RTC_STARTUP from the AC/battery is plugged in.
	 */
	t = get_time().val;
	if (t < PMIC_RTC_STARTUP) {
		uint32_t wait = PMIC_RTC_STARTUP - t;

		CPRINTS("wait for %dms for PMIC RTC start-up", wait / MSEC);
		usleep(wait);
	}

	/*
	 * When power_on() is called, we are at S5S3. Initialize components
	 * to ready state before AP is up.
	 */
	hook_notify(HOOK_CHIPSET_PRE_INIT);

	/* Push the power button */
	set_pmic_pwron(1);
	hook_call_deferred(release_pmic_pwron_deferred, PMIC_PWRON_PRESS_TIME);

	/* enable interrupt */
	gpio_set_flags(GPIO_SUSPEND_L, INT_BOTH_PULL_UP);

	if(system_get_board_version() <= 3)
		gpio_set_flags(GPIO_EC_INT_L, GPIO_OUTPUT | GPIO_OUT_HIGH);
	else
		gpio_set_flags(GPIO_EC_INT_L, GPIO_ODR_HIGH);

	disable_sleep(SLEEP_MASK_AP_RUN);
#ifdef HAS_TASK_POWERLED
	powerled_set_state(POWERLED_STATE_ON);
#endif
	/* Call hooks now that AP is running */
	hook_notify(HOOK_CHIPSET_STARTUP);

	CPRINTS("AP running ...");
}

/**
 * Wait for the power button to be released
 *
 * @param timeout_us Timeout in microseconds, or -1 to wait forever
 * @return EC_SUCCESS if ok, or
 *         EC_ERROR_TIMEOUT if power button failed to release
 */
static int wait_for_power_button_release(unsigned int timeout_us)
{
	timestamp_t deadline;
	timestamp_t now = get_time();

	deadline.val = now.val + timeout_us;

	while (power_button_is_pressed()) {
		now = get_time();
		if (timeout_us < 0) {
			task_wait_event(-1);
		} else if (timestamp_expired(deadline, &now) ||
			   (task_wait_event(deadline.val - now.val) ==
			    TASK_EVENT_TIMER)) {
			CPRINTS("power button not released in time");
			return EC_ERROR_TIMEOUT;
		}
	}

	CPRINTS("power button released");
	power_button_was_pressed = 0;
	return EC_SUCCESS;
}

void chipset_reset(int is_cold)
{
	if (is_cold) {
		CPRINTS("EC triggered cold reboot");
		set_system_power(0);
		usleep(PMIC_COLD_RESET_L_HOLD_TIME);
		/* Press the PMIC power button */
		set_pmic_pwron(1);
		hook_call_deferred(release_pmic_pwron_deferred,
				   PMIC_PWRON_PRESS_TIME);
	} else {
		CPRINTS("EC triggered warm reboot");
		set_warm_reset(1);
		usleep(PMIC_WARM_RESET_H_HOLD_TIME);
		/* deassert the reset signals */
		set_warm_reset(0);
	}
}

enum power_state power_handle_state(enum power_state state)
{
	int value;
	static int boot_from_g3;

	switch (state) {
	case POWER_G3:
		boot_from_g3 = check_for_power_on_event();
		if (boot_from_g3)
			return POWER_G3S5;
		break;

	case POWER_G3S5:
		return POWER_S5;

	case POWER_S5:
		if (boot_from_g3) {
			value = boot_from_g3;
			boot_from_g3 = 0;
		} else {
			value = check_for_power_on_event();
		}

		if (value) {
			CPRINTS("power on %d", value);
			return POWER_S5S3;
		}
		return state;

	case POWER_S5S3:
		power_on();
		if (power_wait_signals(IN_POWER_GOOD) == EC_SUCCESS) {
			CPRINTS("POWER_GOOD seen");
			if (wait_for_power_button_release
			    (DELAY_SHUTDOWN_ON_POWER_HOLD) == EC_SUCCESS) {
				return POWER_S3;
			} else {
				CPRINTS("long-press button, shutdown");
				power_off();
				/*
				 * Since the AP may be up already, return S0S3
				 * state to go through the suspend hook.
				 */
				return POWER_S0S3;
			}
		} else {
			CPRINTS("POWER_GOOD not seen in time");
		}
		set_pmic_pwron(0);
		return POWER_S5;

	case POWER_S3:
		if (is_power_good_deasserted()) {
			power_off();
			return POWER_S3S5;
		} else if (is_suspend_deasserted())
			return POWER_S3S0;
		return state;

	case POWER_S3S0:
		disable_sleep(SLEEP_MASK_AP_RUN);
#ifdef HAS_TASK_POWERLED
		powerled_set_state(POWERLED_STATE_ON);
#endif
		hook_notify(HOOK_CHIPSET_RESUME);
		return POWER_S0;

	case POWER_S0:
		value = check_for_power_off_event();
		if (value) {
			CPRINTS("power off %d", value);
			power_off();
			return POWER_S0S3;
		} else if (is_suspend_asserted())
			return POWER_S0S3;
		return state;

	case POWER_S0S3:
#ifdef HAS_TASK_POWERLED
		if (lid_is_open())
			powerled_set_state(POWERLED_STATE_SUSPEND);
		else
			powerled_set_state(POWERLED_STATE_OFF);
#endif
		/*
		 * if the power button is pressing, we need cancel the long
		 * press timer, otherwise EC will crash.
		 */
		if (power_button_was_pressed)
			timer_cancel(TASK_ID_CHIPSET);

		/* Call hooks here since we don't know it prior to AP suspend */
		hook_notify(HOOK_CHIPSET_SUSPEND);
		enable_sleep(SLEEP_MASK_AP_RUN);
		return POWER_S3;

	case POWER_S3S5:
		wait_for_power_button_release(-1);
		return POWER_S5;

	case POWER_S5G3:
		return POWER_G3;
	}

	return state;
}

static void powerbtn_mtk_changed(void)
{
	task_wake(TASK_ID_CHIPSET);
}
DECLARE_HOOK(HOOK_POWER_BUTTON_CHANGE, powerbtn_mtk_changed, HOOK_PRIO_DEFAULT);

/*****************************************************************************/
/* Console debug command */

static const char *power_req_name[POWER_REQ_COUNT] = {
	"none",
	"off",
	"on",
};

/* Power states that we can report */
enum power_state_t {
	PSTATE_UNKNOWN,
	PSTATE_OFF,
	PSTATE_SUSPEND,
	PSTATE_ON,

	PSTATE_COUNT,
};

static const char * const state_name[] = {
	"unknown",
	"off",
	"suspend",
	"on",
};

static int command_power(int argc, char **argv)
{
	int v;

	if (argc < 2) {
		enum power_state_t state;

		state = PSTATE_UNKNOWN;
		if (chipset_in_state(CHIPSET_STATE_ANY_OFF))
			state = PSTATE_OFF;
		if (chipset_in_state(CHIPSET_STATE_SUSPEND))
			state = PSTATE_SUSPEND;
		if (chipset_in_state(CHIPSET_STATE_ON))
			state = PSTATE_ON;
		ccprintf("%s\n", state_name[state]);

		return EC_SUCCESS;
	}

	if (!parse_bool(argv[1], &v))
		return EC_ERROR_PARAM1;

	power_request = v ? POWER_REQ_ON : POWER_REQ_OFF;
	ccprintf("Requesting power %s\n", power_req_name[power_request]);
	task_wake(TASK_ID_CHIPSET);

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(power, command_power,
			"on/off",
			"Turn AP power on/off",
			NULL);


text:
using System;
using Skybrud.Social.Spotify.Endpoints.Raw;
using Skybrud.Social.Spotify.Options.Player;
using Skybrud.Social.Spotify.Responses;
using Skybrud.Social.Spotify.Responses.Common;
using Skybrud.Social.Spotify.Responses.Player;
using Skybrud.Social.Spotify.Scopes;

namespace Skybrud.Social.Spotify.Endpoints {

    /// <summary>
    /// Class representing the implementation of the player endpoint.
    /// </summary>
    public class SpotifyPlayerEndpoint {

        #region Properties

        /// <summary>
        /// Gets a reference to the Spotify service.
        /// </summary>
        public SpotifyService Service { get; private set; }

        /// <summary>
        /// Gets a reference to the raw endpoint.
        /// </summary>
        public SpotifyPlayerRawEndpoint Raw => Service.Client.Player;

        #endregion

        #region Constructors

        internal SpotifyPlayerEndpoint(SpotifyService service) {
            Service = service;
        }

        #endregion

        #region Member methods

        // TODO: Implement the "GetPlayer" method

        /// <summary>
        /// Get detailed profile information about the current user (including the current user's username).
        /// </summary>
        /// <returns>An instance of <see cref="SpotifyGetPlayerResponse"/> representing the response.</returns>
        public SpotifyGetPlayerResponse GetCurrentlyPlaying() {
            return SpotifyGetPlayerResponse.ParseResponse(Raw.GetCurrentlyPlaying());
        }

        // TODO: Implement the "GetRecentlyPlayed" methods

        /// <summary>
        /// Starts or resumes the playback of the authenticated user.
        /// </summary>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/start-a-users-playback/</cref>
        /// </see>
        public SpotifyResponse Play() {
            return SpotifyNoContentResponse.ParseResponse(Raw.Play());
        }

        /// <summary>
        /// Pauses the playback of the authenticated user.
        /// </summary>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/pause-a-users-playback/</cref>
        /// </see>
        public SpotifyResponse Pause() {
            return SpotifyNoContentResponse.ParseResponse(Raw.Pause());
        }

        /// <summary>
        /// Changes the volume of the current device of the authenticated user. Requires the <see cref="SpotifyScopes.UserModifyPlaybackState"/> scope.
        /// </summary>
        /// <param name="volume">The volume to set. Must be a value from <c>0</c> to <c>100</c> inclusive.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/set-volume-for-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetVolume(int volume) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetVolume(volume));
        }

        /// <summary>
        /// Changes the volume of the device with the specified <paramref name="deviceId"/>. Requires the <see cref="SpotifyScopes.UserModifyPlaybackState"/> scope.
        /// </summary>
        /// <param name="volume">The volume to set. Must be a value from <c>0</c> to <c>100</c> inclusive.</param>
        /// <param name="deviceId">The ID of the device this command is targeting. If not supplied, the user's currently active device is the target.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/set-volume-for-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetVolume(int volume, string deviceId) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetVolume(volume, deviceId));
        }

        /// <summary>
        /// Skips the user's playback to the next track.
        /// </summary>
        /// <param name="deviceId">The ID of the device this command is targeting. If not supplied, the user's currently active device is the target.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/skip-users-playback-to-next-track/</cref>
        /// </see>
        public SpotifyResponse Next(string deviceId) {
            return SpotifyNoContentResponse.ParseResponse(Raw.Next(deviceId));
        }

        /// <summary>
        /// Skips the user's playback to the previous track.
        /// </summary>
        /// <param name="deviceId">The ID of the device this command is targeting. If not supplied, the user's currently active device is the target.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/skip-users-playback-to-previous-track/</cref>
        /// </see>
        public SpotifyResponse Previous(string deviceId) {
            return SpotifyNoContentResponse.ParseResponse(Raw.Previous(deviceId));
        }

        /// <summary>
        /// Seeks to the given position in the user's currently playing track.
        /// </summary>
        /// <param name="position">The position to seek to. Must be a positive number. Passing in a position that is greater than the length of the track will cause the player to start playing the next song.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/seek-to-position-in-currently-playing-track/</cref>
        /// </see>
        public SpotifyResponse Seek(TimeSpan position) {
            return SpotifyNoContentResponse.ParseResponse(Raw.Seek(position));
        }

        /// <summary>
        /// Seeks to the given position in the user's currently playing track.
        /// </summary>
        /// <param name="position">The position to seek to. Must be a positive number. Passing in a position that is greater than the length of the track will cause the player to start playing the next song.</param>
        /// <param name="deviceId">The ID of the device this command is targeting. If not supplied, the user's currently active device is the target.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/seek-to-position-in-currently-playing-track/</cref>
        /// </see>
        public SpotifyResponse Seek(TimeSpan position, string deviceId) {
            return SpotifyNoContentResponse.ParseResponse(Raw.Seek(position, deviceId));
        }

        /// <summary>
        /// Seeks to the given position in the user's currently playing track.
        /// </summary>
        /// <param name="options">The options for the request to the API.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/seek-to-position-in-currently-playing-track/</cref>
        /// </see>
        public SpotifyResponse Seek(SpotifyPlayerSeekOptions options) {
            return SpotifyNoContentResponse.ParseResponse(Raw.Seek(options));
        }

        /// <summary>
        /// Sets the repeat mode for the user's playback. Options are <see cref="SpotifyPlayerRepeatState.Track"/>, <see cref="SpotifyPlayerRepeatState.Context"/>, and <see cref="SpotifyPlayerRepeatState.Off"/>.
        /// </summary>
        /// <param name="state">The repeat state of the player.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/set-repeat-mode-on-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetRepeat(SpotifyPlayerRepeatState state) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetRepeat(state));
        }

        /// <summary>
        /// Sets the repeat mode for the user's playback. Options are <see cref="SpotifyPlayerRepeatState.Track"/>, <see cref="SpotifyPlayerRepeatState.Context"/>, and <see cref="SpotifyPlayerRepeatState.Off"/>.
        /// </summary>
        /// <param name="state">The repeat state of the player.</param>
        /// <param name="deviceId">The ID of the device this command is targeting. If not supplied, the user's currently active device is the target.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/set-repeat-mode-on-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetRepeat(SpotifyPlayerRepeatState state, string deviceId) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetRepeat(state, deviceId));
        }

        /// <summary>
        /// Sets the repeat mode for the user's playback. Options are <see cref="SpotifyPlayerRepeatState.Track"/>, <see cref="SpotifyPlayerRepeatState.Context"/>, and <see cref="SpotifyPlayerRepeatState.Off"/>.
        /// </summary>
        /// <param name="options">The options for the request to the API.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/set-repeat-mode-on-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetRepeat(SpotifyPlayerSetRepeatOptions options) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetRepeat(options));
        }

        /// <summary>
        /// Toggles shuffle on or off for user's playback.
        /// </summary>
        /// <param name="state">Whether shuffle should be turned on (<c>true</c>) or off (<c>false</c>).</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/toggle-shuffle-for-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetShuffle(bool state) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetShuffle(state));
        }

        /// <summary>
        /// Toggles shuffle on or off for user's playback.
        /// </summary>
        /// <param name="state">Whether shuffle should be turned on (<c>true</c>) or off (<c>false</c>).</param>
        /// <param name="deviceId">The ID of the device this command is targeting. If not supplied, the user's currently active device is the target.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/toggle-shuffle-for-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetShuffle(bool state, string deviceId) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetShuffle(state, deviceId));
        }

        /// <summary>
        /// Toggles shuffle on or off for user's playback.
        /// </summary>
        /// <param name="options">The options for the request to the API.</param>
        /// <returns>An instance of <see cref="SpotifyResponse"/> representing the response.</returns>
        /// <see>
        ///     <cref>https://developer.spotify.com/documentation/web-api/reference/player/toggle-shuffle-for-users-playback/</cref>
        /// </see>
        public SpotifyResponse SetShuffle(SpotifyPlayerSetShuffleOptions options) {
            return SpotifyNoContentResponse.ParseResponse(Raw.SetShuffle(options));
        }

        #endregion

    }

}


text:
require 'commands'
require 'test/unit'

module Commands

  class MockExecutor
    def exec(cmd)
    end
  end

  class MockEMRClient
    attr_accessor :state

    def initialize(config)
      @config = config
      @state = "RUNNING"
      @step_map =
      { "j-hive-installed" =>
        {"ExecutionStatusDetail"=>
          {"StartDateTime"=>1291074747.0, "EndDateTime"=>1291074776.0, "LastStateChangeReason"=>nil,
          "CreationDateTime"=>1291074521.0, "State"=>"COMPLETED"},
          "StepConfig"=>
            {"Name"=>"Setup Hive",
            "HadoopJarStep"=>
              {"Jar"=>"s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar",
              "Args"=>
                ["s3://us-east-1.elasticmapreduce/libs/hive/hive-script",
                "--base-path", "s3://us-east-1.elasticmapreduce/libs/hive/",
                "--install-hive"],
                "Properties"=>[],
                "MainClass"=>nil},
              "ActionOnFailure"=>"CONTINUE"}},
        "j-hive-0.5-installed" =>
        {"ExecutionStatusDetail"=>
          {"StartDateTime"=>1291074747.0, "EndDateTime"=>1291074776.0, "LastStateChangeReason"=>nil,
          "CreationDateTime"=>1291074521.0, "State"=>"COMPLETED"},
          "StepConfig"=>
            {"Name"=>"Setup Hive",
            "HadoopJarStep"=>
              {"Jar"=>"s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar",
              "Args"=>
                ["s3://us-east-1.elasticmapreduce/libs/hive/hive-script",
                "--base-path", "s3://us-east-1.elasticmapreduce/libs/hive/",
                "--install-hive","--hive-versions","0.5"],
                "Properties"=>[],
                "MainClass"=>nil},
              "ActionOnFailure"=>"CONTINUE"}},
        "j-hive-0.7-installed" =>
        {"ExecutionStatusDetail"=>
          {"StartDateTime"=>1291074747.0, "EndDateTime"=>1291074776.0, "LastStateChangeReason"=>nil,
          "CreationDateTime"=>1291074521.0, "State"=>"COMPLETED"},
          "StepConfig"=>
            {"Name"=>"Setup Hive",
            "HadoopJarStep"=>
              {"Jar"=>"s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar",
              "Args"=>
                ["s3://us-east-1.elasticmapreduce/libs/hive/hive-script",
                "--base-path", "s3://us-east-1.elasticmapreduce/libs/hive/",
                "--install-hive","--hive-versions","0.7"],
                "Properties"=>[],
                "MainClass"=>nil},
              "ActionOnFailure"=>"CONTINUE"}},
      }
    end

    def client
      return self
    end

    def describe_job_flows(args)
      steps = []
      if args["JobFlowIds"] != nil and @step_map.has_key? args["JobFlowIds"].first then
        steps = [@step_map[args["JobFlowIds"].first]]
      end
      return {
        "JobFlows" =>
        [
         {
           "LogUri" => "s3n://testing/",
           "Name" => "Development Job Flow  (requires manual termination)",
           "BootstrapActions" =>[],
           "ExecutionStatusDetail" => {
             "EndDateTime" => 1286584312.0,
             "CreationDateTime" => 1286584224.0,
             "LastStateChangeReason" => "Terminated by user request",
             "State" => @state,
             "StartDateTime" => nil,
             "ReadyDateTime" => nil
           },
           "Steps" => steps,
           "JobFlowId" => "j-2HWO50OUKNMHG",
           "Instances" => {
             "Ec2KeyName" => "richcole-test",
             "InstanceCount" =>5,
             "NormalizedInstanceHours" => nil,
             "Placement" => {"AvailabilityZone" => "us-east-1d"},
             "KeepJobFlowAliveWhenNoSteps" => true,
             "SlaveInstanceType" => "m2.xlarge",
             "MasterInstanceType" => "m2.xlarge",
             "MasterPublicDnsName" => nil,
             "MasterInstanceId" => nil,
             "InstanceGroups" => [{
               "SpotPrice" => nil,
               "EndDateTime" => nil,
               "Name" => "Task Instance Group",
               "InstanceRole" => "TASK",
               "CreationDateTime" => 1286862675.0,
               "LaunchGroup" => nil,
               "LastStateChangeReason" => "",
               "InstanceGroupId" => "ig-D2NC23WFSOOU",
               "State" => "RUNNING",
               "Market" => "ON_DEMAND",
               "InstanceType" => "c1.medium",
               "StartDateTime" => 1286862907.0,
               "InstanceRunningCount" => 2,
               "ReadyDateTime" => 1286862907.0,
               "InstanceRequestCount" => 2
               },
               {
               "SpotPrice" => nil,
               "EndDateTime" => nil,
               "Name" => "Master Instance Group",
               "InstanceRole" => "MASTER",
               "CreationDateTime" => 1286862675.0,
               "LaunchGroup" => nil,
               "LastStateChangeReason" => "",
               "InstanceGroupId" => "ig-1BFN7TCX7YE5Y",
               "State" => "RUNNING",
               "Market" => "ON_DEMAND",
               "InstanceType" => "m1.small",
               "StartDateTime" => 1286862866.0,
               "InstanceRunningCount" => 1,
               "ReadyDateTime" => 1286862906.0,
               "InstanceRequestCount" => 1
               },
               {
               "SpotPrice" => nil,
               "EndDateTime" => nil,
               "Name" => "Core Instance Group",
               "InstanceRole" => "CORE",
               "CreationDateTime" => 1286862675.0,
               "LaunchGroup" => nil,
               "LastStateChangeReason" => "Expanding cluster",
               "InstanceGroupId" => "ig-2EUIGTIPDLTXW",
               "State" => "RESIZING",
               "Market" => "ON_DEMAND",
               "InstanceType" => "m1.large",
               "StartDateTime" => 1286862907.0,
               "InstanceRunningCount" => 1,
               "ReadyDateTime" => 1286862907.0,
               "InstanceRequestCount" => 3
               }]
           },
           "HadoopVersion" => "0.20"
         }
        ]
      }
    end

    def run_job_flow(opts)
      return { "JobFlowId" => "j-ABABABABA" }
    end

    def add_job_flow_steps(opts)
      return nil
    end

    def terminate_job_flows(opts)
      return nil
    end

    def modify_instance_groups(opts)
      return nil
    end

    def add_instance_groups(opts)
      return nil
    end

  end

  class MockLogger
    def puts(msg)
    end

    def trace(msg)
    end
  end

  class CommandTest < Test::Unit::TestCase

    def setup
      @client_class = MockEMRClient #FIXME: make this return always the same object
      @logger       = MockLogger.new
      @executor     = MockExecutor.new
    end

    def create_and_execute_commands(args)
      return ::Commands.create_and_execute_commands(args.split(/\s+/), @client_class, @logger, @executor, false)
    end

    def test_modify_instance_group_command
      args = "-c tests/credentials.json --modify-instance-group core --instance-count 10 --jobflow j-ABABABA"
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.size)
      c = @commands.last
      assert(c.is_a?(ModifyInstanceGroupCommand))
      assert_equal(10, c.instance_count)
      assert_not_nil(c.instance_group_id)
      assert_equal(nil, c.instance_type)
      assert_equal("CORE", c.instance_role)
    end

    def test_one
      args = "-c tests/credentials.json --create --alive --num-instances 10 " +
        "--slave-instance-type m1.small --master-instance-type m1.large"
      @commands = create_and_execute_commands(args)
    end

    def test_two
      args = "-c tests/credentials.json --create --alive --num-instances 10 " +
        "--slave-instance-type m1.small --master-instance-type m1.large " +
        "--instance-group TASK --instance-type m1.small --instance-count 10 " +
        "--bootstrap-action s3://elasticmapreduce/scripts/configure-hadoop " +
        "--arg s3://mybucket/config/custom-site-config.xml "
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
    end

    def test_three
      args = "-c tests/credentials.json --create --alive --num-instances 10 " +
        "--slave-instance-type m1.small --master-instance-type m1.large " +
        "--instance-group TASK --instance-type m1.small --instance-count 10 " +
        "--bootstrap-action s3://elasticmapreduce/scripts/configure-hadoop " +
        "--arg s3://mybucket/config/custom-site-config.xml " +
        "--pig-script s3://elasticmapreduce/samples/sample.pig " +
        "--pig-interactive"
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
      cmd1 = @commands.commands.first
      assert_equal(2, cmd1.step_commands.size)
      assert_equal(PigInteractiveCommand, cmd1.step_commands[0].class)
    end

    def test_four
      args = "-a ACCESS_ID -p SECRET_KEY --create --alive " +
        "--hive-script s3://maps.google.com --enable-debugging " +
        "--log-uri s3://somewhere.com/logs/"
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
      assert_equal(3, @commands.commands[0].step_commands.size)
      steps = @commands.commands[0].step_commands
      assert_equal(EnableDebuggingCommand, steps[0].class)
      assert_equal(HiveInteractiveCommand, steps[1].class)
      assert_equal(HiveScriptCommand, steps[2].class)
    end

    def hadoop_jar_step_args(command)
      command.steps[0]["HadoopJarStep"]["Args"]
    end

    def pig_script_command_default_args
      [
        "s3://us-east-1.elasticmapreduce/libs/pig/pig-script",
        "--base-path",
        "s3://us-east-1.elasticmapreduce/libs/pig/",
        "--run-pig-script",
        "--args",
        "-f"
      ]
    end

    def hive_script_command_default_args
      [
        "s3://us-east-1.elasticmapreduce/libs/hive/hive-script",
        "--base-path",
        "s3://us-east-1.elasticmapreduce/libs/hive/",
        "--run-hive-script",
        "--args",
        "-f"
      ]
    end

    def test_pig_arg
      args1 = "-a ACCESS_ID -p SECRET_KEY --create --alive " +
        "--pig-script --args s3://maps.google.com --args -p,INPUT=s3://maps.google.com/test.pig"
      args2 = "-a ACCESS_ID -p SECRET_KEY --create --alive " +
        "--pig-script s3://maps.google.com --args -p,INPUT=s3://maps.google.com/test.pig"
      @commands = create_and_execute_commands(args1)
      steps = @commands.commands.first.step_commands
      pig_command = steps[1]
      assert_equal(pig_command.arg, nil)
      assert_equal(pig_command.args, ["s3://maps.google.com", "-p", "INPUT=s3://maps.google.com/test.pig"])
      assert_equal(pig_command.steps.size, 1)
      args = pig_script_command_default_args
      args.insert(3, "--pig-versions")
      args.insert(4, "latest")
      args << "s3://maps.google.com" << "-p" << "INPUT=s3://maps.google.com/test.pig"
      assert_equal(hadoop_jar_step_args(pig_command), args)

      @commands = create_and_execute_commands(args2)
      steps = @commands.commands.first.step_commands
      pig_command = steps[1]
      assert_equal(pig_command.arg, "s3://maps.google.com")
      assert_equal(pig_command.args, ["-p", "INPUT=s3://maps.google.com/test.pig"])
      assert_equal(pig_command.steps.size, 1)
      assert_equal(hadoop_jar_step_args(pig_command), args)
    end

    def test_hive
      args = "-a ACCESS_ID -p SECRET_KEY --create --alive " +
        "--hive-script --args s3://maps.google.com "
      @commands = create_and_execute_commands(args)
      create_command = @commands.commands.first
      steps = create_command.step_commands
      install_hive_command = steps[0]
      hive_command = steps[1]

      assert_equal(1, @commands.commands.size)
      assert_equal(2, steps.size)
      assert_equal(HiveScriptCommand, hive_command.class)
      assert_equal(hive_command.arg, nil)
      assert_equal(hive_command.args, ["s3://maps.google.com"])
      assert_equal(hive_command.steps.size, 1)
      args = hive_script_command_default_args
      args.insert(3, "--hive-versions")
      args.insert(4, "latest")
      args << "s3://maps.google.com"
      assert_equal(hadoop_jar_step_args(hive_command), args)
    end

    def test_install_hive_version
      args = "-a ACCESS_ID -p SECRET_KEY --create --alive " +
        "--hive-script --args s3://maps.google.com --hive-versions 0.5"
      @commands = create_and_execute_commands(args)
      create_command = @commands.commands.first
      steps = create_command.step_commands
      install_hive_command = steps[0]
      hive_command = steps[1]
      assert_equal(1, @commands.commands.size)
      assert_equal(2, steps.size)
      assert_equal(HiveScriptCommand, hive_command.class)
      assert_equal(hive_command.arg, nil)
      assert_equal(hive_command.args, ["s3://maps.google.com"])
      assert_equal(hive_command.steps.size, 1)
      args = hive_script_command_default_args
      args.insert(3, "--hive-versions")
      args.insert(4, "0.5")
      args  << "s3://maps.google.com"
      assert_equal(hadoop_jar_step_args(hive_command), args)
    end

    def test_run_hive_script_same_version
      args = "-a ACCESS_ID -p SECRET_KEY --jobflow j-hive-0.5-installed " +
        "--hive-script --args s3://maps.google.com --hive-versions 0.5"
      @commands = create_and_execute_commands(args)
      create_command = @commands.commands.first
      steps = create_command.step_commands
      install_hive_command = steps[0]
      hive_command = steps[0]

      assert_equal(1, @commands.commands.size)
      assert_equal(1, steps.size)
      assert_equal(HiveScriptCommand, hive_command.class)
      assert_equal(hive_command.arg, nil)
      assert_equal(hive_command.args, ["s3://maps.google.com"])
      assert_equal(hive_command.steps.size, 1)
      args = hive_script_command_default_args
      args.insert(3, "--hive-versions")
      args.insert(4, "0.5")
      args << "s3://maps.google.com"
      assert_equal(hadoop_jar_step_args(hive_command), args)
    end

    def test_run_hive_script_different_version
      args = "-a ACCESS_ID -p SECRET_KEY --jobflow j-hive-0.5-installed " +
        "--hive-script --args s3://maps.google.com --hive-versions 0.7"
      @commands = create_and_execute_commands(args)
      create_command = @commands.commands.first
      steps = create_command.step_commands
      install_hive_command = steps[0]
      hive_command = steps[1]

      assert_equal(1, @commands.commands.size)
      assert_equal(2, steps.size)
      assert_equal(HiveScriptCommand, hive_command.class)
      assert_equal(hive_command.arg, nil)
      assert_equal(hive_command.args, ["s3://maps.google.com"])
      assert_equal(hive_command.steps.size, 1)
      args = hive_script_command_default_args
      args.insert(3, "--hive-versions")
      args.insert(4, "0.7")
      args << "s3://maps.google.com"
      assert_equal(hadoop_jar_step_args(hive_command), args)
    end

    def test_hive_script_step_action_propogation
      args = "-a ACCESS_ID -p SECRET_KEY --jobflow j-hive-0.5-installed " +
        "--hive-script --args s3://maps.google.com --hive-versions 0.7 " +
        "--step-action CONTINUE"
      @commands = create_and_execute_commands(args)
      create_command = @commands.commands.first
      steps = create_command.step_commands
      install_hive_command = steps[0]
      hive_command = steps[0]
      assert_equal(1, @commands.commands.size)
      assert_equal(2, steps.size)
      assert_equal(HiveInteractiveCommand, hive_command.class)
      assert_equal(hive_command.arg, nil)
      assert_equal(hive_command.args, [])
      assert_equal(hive_command.steps.size, 1)
      assert_equal(hive_command.steps.first["ActionOnFailure"], "CONTINUE")
    end

    def test_hive_no_create
      args = "-a ACCESS_ID -p SECRET_KEY --jobflow j-ABABABABA " +
        "--hive-script --args s3://maps.google.com "
      @commands = create_and_execute_commands(args)
      create_command = @commands.commands.first
      steps = create_command.step_commands
      install_hive_command = steps[0]
      hive_command = steps[1]

      assert_equal(1, @commands.commands.size)
      assert_equal(2, steps.size)
      assert_equal(HiveScriptCommand, hive_command.class)
      assert_equal(hive_command.arg, nil)
      assert_equal(hive_command.args, ["s3://maps.google.com"])
      assert_equal(hive_command.steps.size, 1)
      args = hive_script_command_default_args
      args.insert(3, "--hive-versions")
      args.insert(4, "latest")
      args << "s3://maps.google.com"
      assert_equal(hadoop_jar_step_args(hive_command), args)
    end

    def test_hive_no_create2
      args = "-a ACCESS_ID -p SECRET_KEY --jobflow j-ABABABABA " +
        "--hive-script s3://maps.google.com --args -d,options "
      @commands = create_and_execute_commands(args)
      create_command = @commands.commands.first
      steps = create_command.step_commands
      install_hive_command = steps[0]
      hive_command = steps[1]

      assert_equal(1, @commands.commands.size)
      assert_equal(2, steps.size)
      assert_equal(HiveScriptCommand, hive_command.class)
      assert_equal(hive_command.arg, "s3://maps.google.com")
      assert_equal(hive_command.args, ["-d", "options"])
      assert_equal(hive_command.steps.size, 1)
      args = hive_script_command_default_args
      args.insert(3, "--hive-versions")
      args.insert(4, "latest")
      args << "s3://maps.google.com" << "-d" << "options"
      assert_equal(hadoop_jar_step_args(hive_command), args)
    end

    def test_five
      args = "-a ACCESS_ID -p SECRET_KEY -j j-ABABABAABA --hive-script " +
        "s3://maps.google.com --enable-debugging --log-uri s3://somewhere.com/logs/"
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
      assert_equal(3, @commands.commands[0].step_commands.size)
      steps = @commands.commands[0].step_commands
      assert_equal(EnableDebuggingCommand, steps[0].class)
      assert_equal(HiveInteractiveCommand, steps[1].class)
      assert_equal(HiveScriptCommand, steps[2].class)
    end

    def test_six
      args = "-a ACCESS_ID -p SECRET_KEY --list --active"
      @commands = create_and_execute_commands(args)
    end

    def test_seven
      args = "-a ACCESS_ID -p SECRET_KEY --list --active --terminate"
      @commands = create_and_execute_commands(args)
    end

    def test_eight
      args = "-a ACCESS_ID -p SECRET_KEY --terminate -j j-ABABABABA"
      @commands = create_and_execute_commands(args)
    end

    def test_create_one
      args = "-a ACCESS_ID -p SECRET_KEY --create --alive --name TestFlow"
      @commands = create_and_execute_commands(args)
    end

    def test_ssh_no_jobflow
      args = "-a ACCESS_ID -p SECRET_KEY --ssh"
      assert_raise RuntimeError do
        @commands = create_and_execute_commands(args)
      end
    end

    def test_ssh_too_many_jobflows
      args = "-a ACCESS_ID -p SECRET_KEY -j j-ABABABA j-ABABABA --ssh"
      assert_raise RuntimeError do
        @commands = create_and_execute_commands(args)
      end
    end

    def test_jar_with_mainclass
      args = "-a ACCESS_ID -p SECRET_KEY -j j-3TRNB9E4GU2NI
        --jar s3://my-example-bucket/wordcount.jar
        --main-class org.myorg.WordCount
        --arg s3://elasticmapreduce/samples/wordcount/input/
        --arg hdfs:///wordcount/output/1
      "

      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
      c = @commands.commands.first
      s = c.step_commands.first
      st = s.steps
      assert_equal([{"HadoopJarStep"=>{"Jar"=>"s3://my-example-bucket/wordcount.jar",
        "Args"=>["s3://elasticmapreduce/samples/wordcount/input/", "hdfs:///wordcount/output/1"],
        "MainClass"=>"org.myorg.WordCount"}, "ActionOnFailure"=>"CANCEL_AND_WAIT", "Name"=>"Example Jar Step"}], st)
    end

    def test_ssh
      args = "-a ACCESS_ID -p SECRET_KEY --key-pair-file test.pem -j j-ABABABA --ssh"
      @commands = create_and_execute_commands(args)
    end

    def test_unarrest
      args = "-a ACCESS_ID -p SECRET_KEY --unarrest-instance-group core -j j-ABABABA"
      @commands = create_and_execute_commands(args)
    end

    def test_late_name
      args = "-a ACCESS_ID -p SECRET_KEY --create --alive --enable-debugging --hive-interactive --name MyHiveJobFlow --log-uri=s3://haijun-test/logs"
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
      assert_equal("MyHiveJobFlow", @commands.commands.first.jobflow_name)
    end

    def test_ic_it
      args = "-a ACCESS_ID -p SECRET_KEY --create --alive --enable-debugging --hive-interactive --instance-count 5 --instance-type m1.small --name MyHiveJobFlow --log-uri=s3://haijun-test/logs"
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
      cc = @commands.commands.first
      assert_equal("MyHiveJobFlow", cc.jobflow_name)
      assert_equal(5, cc.instance_count)
      assert_equal("m1.small", cc.instance_type)
    end

    def test_json
      args = "-a ACCESS_ID -p SECRET_KEY --jobflow j-ABABABABA --json tests/example.json --param <bucket>=mybucket --param mybucket=yourbucket"
      @commands = create_and_execute_commands(args)
      assert_equal(1, @commands.commands.size)
      cc = @commands.commands.first.step_commands.first
      assert_equal("tests/example.json", cc.arg)
      assert_equal({:key => "<bucket>", :value => "mybucket"}, cc.variables[0])
      assert_equal({:key => "mybucket", :value => "yourbucket"}, cc.variables[1])

      st = cc.steps.first

      expected_step = {
        "HadoopJarStep" => {
          "Jar"  => "/home/hadoop/contrib/streaming/hadoop-0.18-streaming.jar",
          "Args" => ["-input", "s3n://elasticmapreduce/samples/wordcount/input",
                     "-output", "s3n://yourbucket/result", "-mapper", "s3://yourbucket/lib/mapper"]
        },
        "ActionOnFailure" => "CONTINUE",
        "Name" => "Example Step"
      }

      assert_equal(expected_step, st)
    end

    def test_ic_it2
      args = "-a ACCESS_ID -p SECRET_KEY --jobflow j-ABABABAB --resize-jobflow --add-instance-group task --instance-type m1.large --instance-count 5"
      @commands = create_and_execute_commands(args)
      assert_equal(2, @commands.commands.size)
      cc = @commands.commands[1]
      assert_equal(5, cc.instance_count)
      assert_equal("m1.large", cc.instance_type)
      assert_equal("TASK", cc.instance_role)
    end

    def test_command_option_mismatch
      args = "-c tests/credentials.json --instance-group core --instance-count 10"
      assert_raise RuntimeError do
        @commands = create_and_execute_commands(args)
      end
    end

    def test_region_from_az
      @commands = create_and_execute_commands("-c tests/credentials.json")
      eip_command = EipCommand.new("eip-command", "eip-command", "arg", @commands)
      assert_equal('https://ec2.us-east-1.amazonaws.com', eip_command.ec2_endpoint_from_az('us-east-1a'))
      assert_equal('https://ec2.ap-northeast-1.amazonaws.com', eip_command.ec2_endpoint_from_az('ec2.ap-northeast-1b'))
      assert_equal('https://ec2.us-west-1.amazonaws.com', eip_command.ec2_endpoint_from_az('ec2.us-west-1b'))
      assert_equal('https://ec2.us-west-2.amazonaws.com', eip_command.ec2_endpoint_from_az('ec2.us-west-2b'))
      assert_equal('https://ec2.sa-east-1.amazonaws.com', eip_command.ec2_endpoint_from_az('ec2.sa-east-1b'))
    end

    def test_hbase_instance_types
      assert_raise RuntimeError do
        @commands = create_and_execute_commands("-c tests/credentials.json --create --hbase")
      end
    end

  end
end


text:
package io.fluxcapacitor.javaclient.persisting.search;

import lombok.Value;

import java.time.Instant;
import java.util.function.Function;
import java.util.function.Supplier;

@Value
public class SearchHit<T> {
    String id;
    String collection;
    Instant timestamp;
    Instant end;
    Supplier<T> valueSupplier;

    public T getValue() {
        return valueSupplier.get();
    }

    public <V> SearchHit<V> map(Function<T, V> mapper) {
        return new SearchHit<>(id, collection, timestamp, end, () -> mapper.apply(getValue()));
    }
}


text:
package ble

import (
	"bytes"

	"github.com/hybridgroup/gobot"
)

var _ gobot.Driver = (*BLEDeviceInformationDriver)(nil)

type BLEDeviceInformationDriver struct {
	name       string
	connection gobot.Connection
	gobot.Eventer
}

// NewBLEDeviceInformationDriver creates a BLEDeviceInformationDriver
// by name
func NewBLEDeviceInformationDriver(a *BLEClientAdaptor, name string) *BLEDeviceInformationDriver {
	n := &BLEDeviceInformationDriver{
		name:       name,
		connection: a,
		Eventer:    gobot.NewEventer(),
	}

	return n
}
func (b *BLEDeviceInformationDriver) Connection() gobot.Connection { return b.connection }
func (b *BLEDeviceInformationDriver) Name() string                 { return b.name }

// adaptor returns BLE adaptor for this device
func (b *BLEDeviceInformationDriver) adaptor() *BLEClientAdaptor {
	return b.Connection().(*BLEClientAdaptor)
}

// Start tells driver to get ready to do work
func (b *BLEDeviceInformationDriver) Start() (errs []error) {
	return
}

// Halt stops driver (void)
func (b *BLEDeviceInformationDriver) Halt() (errs []error) { return }

func (b *BLEDeviceInformationDriver) GetModelNumber() (model string) {
	c, _ := b.adaptor().ReadCharacteristic("180a", "2a24")
	buf := bytes.NewBuffer(c)
	val := buf.String()
	return val
}

func (b *BLEDeviceInformationDriver) GetFirmwareRevision() (revision string) {
	c, _ := b.adaptor().ReadCharacteristic("180a", "2a26")
	buf := bytes.NewBuffer(c)
	val := buf.String()
	return val
}

func (b *BLEDeviceInformationDriver) GetHardwareRevision() (revision string) {
	c, _ := b.adaptor().ReadCharacteristic("180a", "2a27")
	buf := bytes.NewBuffer(c)
	val := buf.String()
	return val
}

func (b *BLEDeviceInformationDriver) GetManufacturerName() (manufacturer string) {
	c, _ := b.adaptor().ReadCharacteristic("180a", "2a29")
	buf := bytes.NewBuffer(c)
	val := buf.String()
	return val
}

func (b *BLEDeviceInformationDriver) GetPnPId() (model string) {
	c, _ := b.adaptor().ReadCharacteristic("180a", "2a50")
	buf := bytes.NewBuffer(c)
	val := buf.String()
	return val
}


text:
using MasterDetailApp.Data;
using MasterDetailApp.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

namespace MasterDetailApp
{
    public sealed partial class MasterDetailPage : Page
    {
        private ItemViewModel _lastSelectedItem;

        public MasterDetailPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var items = MasterListView.ItemsSource as List<ItemViewModel>;

            if (items == null)
            {
                items = new List<ItemViewModel>();

                foreach (var item in ItemsDataSource.GetAllItems())
                {
                    items.Add(ItemViewModel.FromItem(item));
                }

                MasterListView.ItemsSource = items;
            }

            if (e.Parameter != null)
            {
                // Parameter is item ID
                var id = (int)e.Parameter;
                _lastSelectedItem =
                    items.Where((item) => item.ItemId == id).FirstOrDefault();
            }
            else
            {
                _lastSelectedItem = null;
            }

            UpdateForVisualState(AdaptiveStates.CurrentState);

            // Don't play a content transition for first item load.
            // Sometimes, this content will be animated as part of the page transition.
            DisableContentTransitions();
        }

        private void AdaptiveStates_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            UpdateForVisualState(e.NewState, e.OldState);
        }

        private void UpdateForVisualState(VisualState newState, VisualState oldState = null)
        {
            var isNarrow = newState == NarrowState;

            if (isNarrow && oldState == DefaultState && _lastSelectedItem != null)
            {
                // Resize down to the detail item. Don't play a transition.
                Frame.Navigate(typeof(DetailPage), _lastSelectedItem.ItemId, new SuppressNavigationTransitionInfo());
            }

            EntranceNavigationTransitionInfo.SetIsTargetElement(MasterListView, isNarrow);
            if (DetailContentPresenter != null)
            {
                EntranceNavigationTransitionInfo.SetIsTargetElement(DetailContentPresenter, !isNarrow);
            }
        }

        private void MasterListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var clickedItem = (ItemViewModel)e.ClickedItem;
            _lastSelectedItem = clickedItem;

            if (AdaptiveStates.CurrentState == NarrowState)
            {
                // Use "drill in" transition for navigating from master list to detail view
                Frame.Navigate(typeof(DetailPage), clickedItem.ItemId, new DrillInNavigationTransitionInfo());
            }
            else
            {
                // Play a refresh animation when the user switches detail items.
                EnableContentTransitions();
            }
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            // Assure we are displaying the correct item. This is necessary in certain adaptive cases.
            MasterListView.SelectedItem = _lastSelectedItem;
        }

        private void EnableContentTransitions()
        {
            DetailContentPresenter.ContentTransitions.Clear();
            DetailContentPresenter.ContentTransitions.Add(new EntranceThemeTransition());
        }

        private void DisableContentTransitions()
        {
            if (DetailContentPresenter != null)
            {
                DetailContentPresenter.ContentTransitions.Clear();
            }
        }
    }
}