text:
<?php

namespace MailerBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use MailerBundle\Entity\Template;
use MailerBundle\Form\TemplateType;

/**
 * Template controller.
 *
 */
class TemplateController extends Controller
{

    /**
     * Lists all Template entities.
     *
     */
    public function indexAction($page)
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MailerBundle:Template')->getActiveTemplates();

        $pagination = $this->container->get('knp_paginator');
        $entities = $pagination->paginate($entities, $page, $this->container->getParameter('max_templates_on_page'));

        return $this->render('MailerBundle:Template:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Template entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Template();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('template_show', array('alias' => $entity->getId())));
        }

        return $this->render('MailerBundle:Template:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Template entity.
     *
     * @param Template $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Template $entity)
    {
        $form = $this->createForm(new TemplateType(), $entity, array(
            'action' => $this->generateUrl('template_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Template entity.
     *
     */
    public function newAction()
    {
        $entity = new Template();
        $form   = $this->createCreateForm($entity);

        return $this->render('MailerBundle:Template:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Template entity.
     *
     */
    public function showAction($alias)
    {
        $em = $this->getDoctrine()->getManager();

        /** @var \MailerBundle\Entity\Template $entity */
        $entity = $em->getRepository('MailerBundle:Template')->findOneBy(['alias' => $alias]);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Template entity.');
        }

        $deleteForm = $this->createDeleteForm($entity->getId());

        return $this->render('MailerBundle:Template:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Template entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MailerBundle:Template')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Template entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('MailerBundle:Template:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Template entity.
    *
    * @param Template $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Template $entity)
    {
        $form = $this->createForm(new TemplateType(), $entity, array(
            'action' => $this->generateUrl('template_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Template entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MailerBundle:Template')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Template entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('template_edit', array('id' => $id)));
        }

        return $this->render('MailerBundle:Template:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Template entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MailerBundle:Template')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Template entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('template'));
    }

    /**
     * Creates a form to delete a Template entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('template_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
shared_context "request parameters" do
  let(:config) do
    {
      'quickbooks_access_token'          => "qyprdhjEBfA2BI8sD7fWVPH4wL9esaKrYeWLosiPBir3pa5j",
      'quickbooks_access_secret'         => "yU7RtuM1Lot803jkkCfcyV9GePoNZGnZO8nRbBxo",
      'quickbooks_income_account'        => "Sales of Product Income",
      'quickbooks_realm'                 => "835973000",
      'quickbooks_inventory_costing'     => true,
      'quickbooks_inventory_account'     => "Inventory Asset",
      'quickbooks_deposit_to_account_name' => "Inventory Asset",
      'quickbooks_cogs_account'          => "Cost of Goods Sold",
      'quickbooks_payment_method_name' => [{ "visa" => "Discover" }],
      'quickbooks_account_name' => "Inventory Asset"
    }
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace Eugenie.Server.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;

    using Data.Models.DummyModels;

    using Microsoft.AspNet.Identity;

    using Services.Data.Contracts;

    [Authorize]
    [RoutePrefix("api/deals")]
    public class DealsController : ApiController
    {
        private readonly IDealsService dealsService;

        public DealsController(IDealsService dealsService)
        {
            this.dealsService = dealsService;
        }

        [HttpGet]
        [Authorize(Roles = "Admin")]
        public IHttpActionResult GetDeals(string username, DateTime start, DateTime end)
        {
            var sells = this.dealsService.GetSells(username, start, end.AddDays(1)).Select(x => new
            {
                x.Date,
                x.Total,
                Products = x.Products.Select(pr => new
                {
                    pr.Product.Name,
                    pr.Quantity,
                })
            }).OrderByDescending(x => x.Date);

            var waste = this.dealsService.GetWaste(username, start, end.AddDays(1)).Select(x => new
            {
                x.Date,
                x.Total,
                Products = x.Products.Select(pr => new
                {
                    pr.Product.Name,
                    pr.Quantity,
                })
            }).OrderByDescending(x => x.Date);

            var result = new
                         {
                             Sells = sells,
                             Waste = waste
                         };

            return this.Ok(result);
        }

        [HttpPut]
        [Route("sell")]
        public IHttpActionResult Sell(IEnumerable<IdQuantityPair> model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            try
            {
                this.dealsService.Sell(this.User.Identity.GetUserId(), model);
            }
            catch (ArgumentException ex)
            {
                return this.BadRequest(ex.Message);
            }

            return this.Ok();
        }

        [HttpPut]
        [Route("waste")]
        public IHttpActionResult Waste(IEnumerable<IdQuantityPair> model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            try
            {
                this.dealsService.Waste(this.User.Identity.GetUserId(), model);
            }
            catch (ArgumentException ex)
            {
                return this.BadRequest(ex.Message);
            }

            return this.Ok();
        }
    }
}


text:
/* eslint-disable react/sort-comp */
/* @flow */

import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { Route, Switch,Link,  BrowserRouter as Router } from 'react-router-dom';
import Helmet from 'react-helmet';

import styles from './styles.scss';

// Export this for unit testing more easily
export class Home extends PureComponent {

  constructor(props) {
      super(props);
      this.state = {

      };
    }

  componentDidMount() {
  //  var byDate = this.state.data.slice(0);

  //    byDate.sort(function(a,b) {
  //        return a.order - b.order;
  //      });
  //  this.setState({data:byDate})
  }

  render() {

    return (

      {/*

<Link to="/dashboard">Netflix</Link>

 */}

    {/*   <Switch>
          <Route exact path="/" component={CC} />
          <Route exact path="/dashboard" component={dummyChart} />

      </Switch> */}

    );
  }
}

function mapStateToProps(state) {
    return {

    }
}

export default connect(mapStateToProps)(Home);


text:
#include <jio/messaging/dispatcher.hpp>

jio::messaging::dispatch * callback(jio::messaging::dispatcher *d, const jio::messaging::dispatch * in) {
	printf("\t! Hello World Callback!\n");
	delete in;
	return nullptr;
}
void dispatcher(void) {
	try {
		printf("Dispatcher test started\n");
		jio::messaging::dispatcher d;
		printf("* Adding handler\n");
		d.add(1, "fuck", jio::messaging::dispatch_func_t(&callback));
		printf("* Calling by ID\n");
		auto test_data = new char[255];
		d.call(new jio::messaging::dispatch(1, test_data));
		delete test_data;

		printf("* Calling by Name\n");
		d.call(std::string("fuck"), new jio::messaging::dispatch(1, test_data));
		printf("Dispatcher test ended\n");

	}
	catch (jio::exception e) {
		PRINT_EXCEPTION(e);
	}
}


text:
layout: post
title: 'Embedded learning log - A foray into Linux specifics: dmesg, tty and playing with minicom'
comments: true
categories: [embedded-learning-log]
date: 2021-02-20 20:22:51 +0200
excerpt: 'In a previous post in this log I used `sudo dmesg | grep tty` to find the serial port to which my board was connected. But what does `dmesg` do and why am I looking for `tty`?'
---

{% include embedded-learning-log.html %}

In a previous post in this log I used `sudo dmesg | grep tty` to find the serial port to which my board was connected. But what does `dmesg` do and why am I looking for `tty`?

Here's what I know about `dmesg`: it prints logs from the kernel. And here's all my loose bits of unchecked knowledge about `tty`:

- It stands for TeleTypewriter.
- In Linux, I can go to a different `tty` by using `CTRL+ALT+F#`.
- Some of the `#`s are used by specific processes. In my case, `CTRL+ALT+F1` takes me to GDM (which shows my log-in screen), and `CTRL+ALT+F2` takes me back to my current Xorg session.
- I've used `CTRL+ALT+F#` with numbers other than 1 and 2 to get me out of problems with me Xorg session.
- I suppose that means processes are tied to `tty`s, or `tty`s are somehow pointers to processes.

Time to strengthen this knowledge.

```bash
man tty
```

> `tty` - print the file name of the terminal connected to standard input

```bash
~/Development/toastboard/hello_world => tty
/dev/pts/3
```

I have three terminals open, and that one was number 3 apparently.

A TTY is transitively [a software emulation of a TeleTypewriter](https://www.howtogeek.com/428174/what-is-a-tty-on-linux-and-how-to-use-the-tty-command/), or a pseudoterminal. In Linux, there's the concept of a pseudoterminal master and pseudoterminal slaves.

> The file /dev/ptmx is a character file with major number 5 and minor number 2, usually of mode 0666 and owner.group of root.root. It is used to create a pseudoterminal master and slave pair. When a process opens /dev/ptmx, it gets a file descriptor for a pseudoterminal master (PTM), and a pseudoterminal slave (PTS) device is created in the /dev/pts directory. Each file descriptor obtained by opening /dev/ptmx is an independent PTM with its own associated PTS, whose path can be found by passing the descriptor to ptsname(3).

I suppose this is what terminal emulators such as Kitty do when they open: they get assigned a file under `/dev/pts`. It must also be what `tmux` does when I open a new pane or window.

So now I know! `sudo dmesg` prints kernel logs and we try to find matches for `tty`, which should give us logs for when devices connected. When devices connect, Linux will create files for them under `/dev`, and these show up as `/dev/tty*`, in my case `/dev/ttyUSB0` because my device is the first on the USB serial port adapter.

### Playing with `minicom`

On a first attempt to verify that serial communication to my development board works, I did this:

```
 ~/Development/toastboard/hello_world => minicom -p /dev/ttyS4
minicom: argument to -p must be a pty
```

A `pty` is a pseudoterminal. I guess if I open a new terminal, it'll be assigned `/dev/pts/4` and then I can communicate to it? I'm curious to try it out.

Open a new terminal and then on terminal `/dev/pts/3`:

```
minicom -p /dev/pts/4
```

Type some stuff... and it appears on my newest terminal! Cool! Trying to type on `/dev/pts/4` produces the same characters on `/dev/pts/3`, but some get dropped. I'm curious to find out why, but let's get back to [the main course]({% post_url 2021-02-21-embedded-learning-log-3-running-a-recurring-freertos-task %}).


text:
<?php

namespace Eloquent\Schemer\Loader;

class Content
{
    /**
     * @param string $data
     * @param string $mimeType
     */
    public function __construct($data, $mimeType)
    {
        $this->data = $data;
        $this->mimeType = $mimeType;
    }

    /**
     * @return string
     */
    public function data()
    {
        return $this->data;
    }

    /**
     * @return string
     */
    public function mimeType()
    {
        return $this->mimeType;
    }

    private $data;
    private $mimeType;
}


text:
package generator

import (
	"bytes"
	"fmt"
	"go/format"
	"io"
	"io/ioutil"
	"path/filepath"
	"strings"
	"text/template"
)

// File is a common type for all generator functions.
// It generates Go source code file based on template in tmplPath,
// by parsing the data in fileToParse and linguist's samplesDir
// saving results to an outFile.
type File func(fileToParse, samplesDir, outPath, tmplPath, tmplName, commit string) error

func formatedWrite(outPath string, source []byte) error {
	formatedSource, err := format.Source(source)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(outPath, formatedSource, 0666); err != nil {
		return err
	}
	return nil
}

func executeTemplate(w io.Writer, name, path, commit string, fmap template.FuncMap, data interface{}) error {
	getCommit := func() string {
		return commit
	}
	// stringVal returns escaped string that can be directly placed into go code.
	// for value test`s it would return `test`+"`"+`s`
	stringVal := func(val string) string {
		val = strings.ReplaceAll(val, "`", "`+\"`\"+`")
		return fmt.Sprintf("`%s`", val)
	}

	const headerTmpl = "header.go.tmpl"
	headerPath := filepath.Join(filepath.Dir(path), headerTmpl)

	h := template.Must(template.New(headerTmpl).Funcs(template.FuncMap{
		"getCommit": getCommit,
		"stringVal": stringVal,
	}).ParseFiles(headerPath))

	buf := bytes.NewBuffer(nil)
	if err := h.Execute(buf, data); err != nil {
		return err
	}

	if fmap == nil {
		fmap = make(template.FuncMap)
	}
	fmap["getCommit"] = getCommit
	fmap["stringVal"] = stringVal

	t := template.Must(template.New(name).Funcs(fmap).ParseFiles(path))
	if err := t.Execute(buf, data); err != nil {
		return err
	}

	src, err := format.Source(buf.Bytes())
	if err != nil {
		return err
	}
	_, err = w.Write(src)
	return err
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>My Project: ChatLogger.h Source File</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

<link href="search/search.css" rel="stylesheet" type="text/css"/>

My Project

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

ChatLogger.h

00001 #ifndef CHATLOGGER_H
00002 #define CHATLOGGER_H
00003
00004 #include <iostream>
00005 #include <string>
00006 #include <cstdlib>
00007 #include <cstdio>
00008 #include <cstring>
00009 #include <fstream>
00010 #include <sstream>
00011 #include <time.h>
00012
00013 #include <sqlite3.h>
00014
00015 using namespace std;
00016
00017 class ChatLogger {
00018 public:
00019     static sqlite3      *database;
00020     static const char   *path;
00021
00022     static void     InitChatLogger(const char *path);
00023
00024     static void     OpenLog();
00025     static void     CloseLog();
00026     static void     CreateLogTable();
00027     static void     DropLogTable();
00028     static void     ClearLogTable();
00029
00030     static void         AddLog(const char *date, const char *name, const char *channel, const char *log);
00031     static string       LastSeen(const char *name);
00032     static string       GetLog();
00033
00034 private:
00035
00036 };
00037
00038 #endif

 All Classes

<address class="footer">
Generated on Fri Jun 14 2013 23:54:13 for My Project by

 1.7.6.1
</address>


text:
package com.ruesga.phoenix.jpa.entities;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity(name="employee")
@Table(name="E", schema="T",
        indexes= {@Index(name="E_I0", columnList="GENDER", unique=true)})
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="EMP_NO", nullable=false)
    private int empNo;

    @Column(name="BIRTH_DATE")
    @Temporal(TemporalType.TIMESTAMP)
    private Date birthDate;

    @Column(name="FIRST_NAME", length=255)
    private String firstName;

    @Column(name="LAST_NAME", length=255)
    private String lastName;

    @Column(name="GENDER")
    @Enumerated(EnumType.ORDINAL)
    private Gender gender;

    @Column(name="HIRE_DATE")
    @Temporal(TemporalType.TIMESTAMP)
    private Date hireDate;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "EMP_NO", nullable=false)
    private Set<DepartmentEmployee> departments;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "EMP_NO", nullable=false)
    private Set<Salary> salaries;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "EMP_NO", nullable=false)
    private Set<Title> titles;

    public Employee() {
    }

    public int getEmpNo() {
        return empNo;
    }

    public void setEmpNo(int empNo) {
        this.empNo = empNo;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public Date getHireDate() {
        return hireDate;
    }

    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;
    }

    public Set<DepartmentEmployee> getDepartments() {
        return departments;
    }

    public void setDepartments(Set<DepartmentEmployee> departments) {
        this.departments = departments;
    }

    public Set<Salary> getSalaries() {
        return salaries;
    }

    public void setSalaries(Set<Salary> salaries) {
        this.salaries = salaries;
    }

    public Set<Title> getTitles() {
        return titles;
    }

    public void setTitles(Set<Title> titles) {
        this.titles = titles;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((birthDate == null) ? 0 : birthDate.hashCode());
        result = prime * result + empNo;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((gender == null) ? 0 : gender.hashCode());
        result = prime * result + ((hireDate == null) ? 0 : hireDate.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (birthDate == null) {
            if (other.birthDate != null)
                return false;
        } else if (!birthDate.equals(other.birthDate))
            return false;
        if (empNo != other.empNo)
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (gender != other.gender)
            return false;
        if (hireDate == null) {
            if (other.hireDate != null)
                return false;
        } else if (!hireDate.equals(other.hireDate))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Employee [empNo=" + empNo + ", birthDate=" + birthDate + ", firstName=" + firstName + ", lastName="
                + lastName + ", gender=" + gender + ", hireDate=" + hireDate + "]";
    }
}


text:
import _ from 'underscore';

/* DEFINITIONS
- If window loses focus user needs to scroll or click/touch some place
- On hit ESC enable read, force read of current room and remove unread mark
- When user change room disable read until user interaction
- Only read if mark of *first-unread* is visible for user or if flag *force* was passed
- Always read the opened room
- The default method *read* has a delay of 2000ms to prevent multiple reads and to user be able to see the mark
*/

// Meteor.startup ->
// window.addEventListener 'focus', ->
// readMessage.refreshUnreadMark(undefined, true)

const readMessage = new class {
	constructor() {
		this.debug = false;
		this.callbacks = [];
		this.read = _.debounce((force) => this.readNow(force), 1000);
		this.canReadMessage = false;
	}

	readNow(force) {
		if (force == null) { force = false; }
		if (this.debug) { console.log('--------------'); }
		if (this.debug) { console.log('readMessage -> readNow init process force:', force); }

		const self = this;

		self.refreshUnreadMark();

		if ((force !== true) && (this.canReadMessage === false)) {
			if (this.debug) { console.log('readMessage -> readNow canceled by canReadMessage: false'); }
			return;
		}

		const rid = Session.get('openedRoom');
		if (rid == null) {
			if (this.debug) { console.log('readMessage -> readNow canceled, no rid informed'); }
			return;
		}

		if (force === true) {
			if (this.debug) { console.log('readMessage -> readNow via force rid:', rid); }
			return Meteor.call('readMessages', rid, function() {
				RoomHistoryManager.getRoom(rid).unreadNotLoaded.set(0);
				self.refreshUnreadMark();
				return self.fireRead(rid);
			});
		}

		const subscription = ChatSubscription.findOne({ rid });
		if (subscription == null) {
			if (this.debug) { console.log('readMessage -> readNow canceled, no subscription found for rid:', rid); }
			return;
		}

		if ((subscription.alert === false) && (subscription.unread === 0)) {
			if (this.debug) { console.log('readMessage -> readNow canceled, alert', subscription.alert, 'and unread', subscription.unread); }
			return;
		}

		const room = RoomManager.getOpenedRoomByRid(rid);
		if (room == null) {
			if (this.debug) { console.log('readMessage -> readNow canceled, no room found for typeName:', subscription.t + subscription.name); }
			return;
		}

		// Only read messages if user saw the first unread message
		const unreadMark = $('.message.first-unread');
		if (unreadMark.length > 0) {
			const position = unreadMark.position();
			const visible = (position != null ? position.top : undefined) >= 0;
			if (!visible && (room.unreadSince.get() != null)) {
				if (this.debug) { console.log('readMessage -> readNow canceled, unread mark visible:', visible, 'unread since exists', (room.unreadSince.get() != null)); }
				return;
			}
		// if unread mark is not visible and there is more more not loaded unread messages
		} else if (RoomHistoryManager.getRoom(rid).unreadNotLoaded.get() > 0) {
			return;
		}

		if (this.debug) { console.log('readMessage -> readNow rid:', rid); }
		Meteor.call('readMessages', rid, function() {
			RoomHistoryManager.getRoom(rid).unreadNotLoaded.set(0);
			self.refreshUnreadMark();
			return self.fireRead(rid);
		});
	}

	disable() {
		return this.canReadMessage = false;
	}

	enable() {
		return this.canReadMessage = document.hasFocus();
	}

	isEnable() {
		return this.canReadMessage === true;
	}

	onRead(cb) {
		return this.callbacks.push(cb);
	}

	fireRead(rid) {
		return Array.from(this.callbacks).map((cb) =>	cb(rid));
	}

	refreshUnreadMark(rid, force) {
		if (rid == null) { rid = Session.get('openedRoom'); }
		if (rid == null) {
			return;
		}

		const subscription = ChatSubscription.findOne({ rid }, { reactive: false });
		if (subscription == null) {
			return;
		}

		const room = RoomManager.openedRooms[subscription.t + subscription.name];
		if (room == null) {
			return;
		}

		if (!subscription.alert && (subscription.unread === 0)) {
			room.unreadSince.set(undefined);
			return;
		}

		if ((force == null) && (subscription.rid === Session.get('openedRoom')) && document.hasFocus()) {
			return;
		}

		let lastReadRecord = ChatMessage.findOne({
			rid: subscription.rid,
			ts: {
				$lt: subscription.ls,
			},
		}
			// 'u._id':
			// 	$ne: Meteor.userId()
			, {
			sort: {
				ts: -1,
			},
		}
		);

		if ((lastReadRecord == null) && (RoomHistoryManager.getRoom(room.rid).unreadNotLoaded.get() === 0)) {
			lastReadRecord =
				{ ts: new Date(0) };
		}

		if ((lastReadRecord != null) || (RoomHistoryManager.getRoom(room.rid).unreadNotLoaded.get() > 0)) {
			room.unreadSince.set(subscription.ls);
		} else {
			room.unreadSince.set(undefined);
		}

		if (lastReadRecord != null) {
			const firstUnreadRecord = ChatMessage.findOne({
				rid: subscription.rid,
				ts: {
					$gt: lastReadRecord.ts,
				},
				'u._id': {
					$ne: Meteor.userId(),
				},
			}
				, {
				sort: {
					ts: 1,
				},
			}
			);

			if (firstUnreadRecord != null) {
				room.unreadFirstId = firstUnreadRecord._id;
				$(room.dom).find(`.message.first-unread:not(#${ firstUnreadRecord._id })`).removeClass('first-unread');
				$(room.dom).find(`.message#${ firstUnreadRecord._id }`).addClass('first-unread');
			}
		}
	}
};

Meteor.startup(function() {
	$(window).on('blur', () => readMessage.disable());

	$(window).on('focus', () => {
		readMessage.enable();
		return readMessage.read();
	});

	$(window).on('click', () => {
		readMessage.enable();
		return readMessage.read();
	});

	$(window).on('touchend', () => {
		readMessage.enable();
		return readMessage.read();
	});

	$(window).on('keyup', (e) => {
		const key = e.which;
		if (key === 27) {
			readMessage.enable();
			readMessage.readNow(true);
			return $('.message.first-unread').removeClass('first-unread');
		}
	});
});
export { readMessage };
this.readMessage = readMessage;


text:
package org.wso2.siddhi.core.stream.input.source;

/**
 * Holder object to store mapping information for a given Siddhi Attribute
 * {@link org.wso2.siddhi.query.api.definition.Attribute}
 */
public class AttributeMapping {
    protected String name;
    protected int position;
    private String mapping = null;

    public AttributeMapping(String name, int position, String mapping) {
        this.name = name;
        this.position = position;
        this.mapping = mapping;
    }

    public String getMapping() {
        return mapping;
    }

    public String getName() {
        return name;
    }

    public int getPosition() {
        return position;
    }

    @Override
    public String toString() {
        return "AttributeMapping{" +
                "name='" + name + '\'' +
                ", mapping='" + mapping + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        AttributeMapping that = (AttributeMapping) o;

        if (position != that.position) {
            return false;
        }
        if (name != null ? !name.equals(that.name) : that.name != null) {
            return false;
        }
        return mapping != null ? mapping.equals(that.mapping) : that.mapping == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + position;
        result = 31 * result + (mapping != null ? mapping.hashCode() : 0);
        return result;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="android:Theme.Holo.Light.NoActionBar">
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorPrimary">@color/primary</item>
        <item name="android:textColorHighlight">@color/primary</item>
        <item name="android:textColorHighlightInverse">@color/primary</item>
        <item name="toolbarStyle">@style/MyActionBar</item>
    </style>

    <style name="MyActionBar" parent="@style/Widget.AppCompat.Toolbar">
        <item name="android:background">@color/primary</item>
        <!-- Support library compatibility -->
        <item name="background">@color/primary</item>
        <item name="android:textColor">#FFFFFF</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:textColorHighlight">#FFFFFF</item>
    </style>

</resources>


text:
import {View} from "../../../src/View";
import {Searchfield} from "../../../src/components/Searchfield";
import {GotoMovieAction} from "../actions/GotoMovieAction";
import {FindMoviesAction} from "../actions/FindMoviesAction";
import {Card} from "../../../src/components/Card";
import {BadgeShape, BadgeStyle, Button, ButtonSize, ButtonStyle, Outline} from "../../../src/components/Button";
import {Alert, AlertStyle} from "../../../src/components/Alert";
import {Textfield, TextfieldType} from "../../../src/components/Textfield";
import {Radio} from "../../../src/components/Radio";
import {Checkbox} from "../../../src/components/Checkbox";
import {Pulldown} from "../../../src/components/Pulldown";
import {NumberField} from "../../../src/components/NumberField";
import {Datepicker} from "../../../src/components/Datepicker";
import {Dialog} from "../../../src/components/Dialog";
import {Link} from "../../../src/components/Link";
import {Items} from "../../../src/components/Items";
import {List} from "../../../src/components/List";
import {Media} from "../../../src/components/Media";
import {Navbar} from "../../../src/components/Navbar";
import {Photo} from "../../../src/components/Photo";
import {Progress, ProgressbarStyle} from "../../../src/components/Progress";
import {Spinner} from "../../../src/components/Spinner";
import {Table} from "../../../src/components/Table";
import {Tabs} from "../../../src/components/Tabs";
import {Toolbar} from "../../../src/components/Toolbar";

export class ProgressExamplesView extends View {

  constructor(properties) {
    super(properties);

    this.smartflow = {
      "path": "/examples/progress",
      "components": [

        {
          "type": Progress,
          "value": 30,
          "progressbarStyle": ProgressbarStyle.DANGER,
          "animated": true,
          "striped": true
        },
        {
          "type": Spinner,
        },

      ]
    };
  }

  viewInitialized() {
  }

}


text:
<?php

    namespace Neoform\Request\Parameters\Server;

    class AcceptsEncoding {

        /**
         * @var string[]
         */
        protected $encodings;

        /**
         * @param string[] $encodings
         */
        public function __construct(array $encodings) {
            $this->encodings = $encodings;
        }

        /**
         * @return string[]
         */
        public function toArray() {
            return $this->encodings;
        }

        /**
         * Checks if a specific encoding is accepted
         *
         * @param string $encoding
         *
         * @return bool
         */
        public function accepts($encoding) {
            return in_array($encoding, $this->encodings, true);
        }
    }


text:
package com.apptentive.android.sdk.util;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.os.Build;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import com.apptentive.android.sdk.Log;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Sky Kelsey
 */
public class Util {

	// These date formats are as close as Java can get to ISO 8601 without royally screwing up.
	public static final String PSEUDO_ISO8601_DATE_FORMAT = "yyyy-MM-dd HH:mm:ssZ"; // 2011-01-01 11:59:59-0800
	public static final String PSEUDO_ISO8601_DATE_FORMAT_MILLIS = "yyyy-MM-dd HH:mm:ss.SSSZ"; // 2011-01-01 11:59:59.123-0800 or 2011-01-01 11:59:59.23-0800

	public static String dateToIso8601String(long millis) {
		return dateToString(new SimpleDateFormat(PSEUDO_ISO8601_DATE_FORMAT_MILLIS), new Date(millis));
	}

	public static String secondsToDisplayString(String format, Double seconds) {
		String dateString = dateToString(new SimpleDateFormat(format), new Date(Math.round(seconds * 1000)));
		return dateString.replace("PM", "pm").replace("AM", "am");
	}

	public static String dateToString(DateFormat format, Date date) {
		return format.format(date);
	}

	public static Date parseIso8601Date(final String iso8601DateString) {
		// Normalize timezone.
		String s = iso8601DateString.trim().replace("Z", "+00:00").replace("T", " ");
		try {
			// Remove colon in timezone.
			if (s.charAt(s.length() - 3) == ':') {
				int lastColonIndex = s.lastIndexOf(":");
				s = s.substring(0, lastColonIndex) + s.substring(lastColonIndex + 1);
			}
			// Right pad millis to 3 places. ISO 8601 supplies fractions of seconds, but Java interprets them as millis.
			int milliStart = s.lastIndexOf('.');
			int milliEnd = (s.lastIndexOf('+') != -1) ? s.lastIndexOf('+') : s.lastIndexOf('-');
			if (milliStart != -1) {
				String start = s.substring(0, milliStart + 1);
				String millis = s.substring(milliStart + 1, milliEnd);
				String end = s.substring(milliEnd);
				millis = String.format("%-3s", millis).replace(" ", "0");
				s = start + millis + end;
			}
		} catch (Exception e) {
			Log.e("Error parsing date: " + iso8601DateString, e);
			return new Date();
		}
		// Parse, accounting for millis, if provided.
		try {
			if (s.contains(".")) {
				return new SimpleDateFormat(PSEUDO_ISO8601_DATE_FORMAT_MILLIS).parse(s);
			} else {
				return new SimpleDateFormat(PSEUDO_ISO8601_DATE_FORMAT).parse(s);
			}
		} catch (ParseException e) {
			Log.e("Exception parsing date: " + s, e);
		}

		// Return null as default. Nothing we can do but log it.
		return null;
	}

	public static int getStatusBarHeight(Window window) {
		Rect rectangle = new Rect();
		window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
		return rectangle.top;
	}

	private static List<PackageInfo> getPermissions(Context context) {
		return context.getPackageManager().getInstalledPackages(PackageManager.GET_PERMISSIONS);
	}

	public static boolean packageHasPermission(Context context, String permission) {
		String packageName = context.getApplicationContext().getPackageName();
		return packageHasPermission(context, packageName, permission);
	}

	public static boolean packageHasPermission(Context context, String packageName, String permission) {
		List<PackageInfo> packageInfos = getPermissions(context);
		for (PackageInfo packageInfo : packageInfos) {
			if (packageInfo.packageName.equals(packageName) && packageInfo.requestedPermissions != null) {
				for (String permissionName : packageInfo.requestedPermissions) {
					if (permissionName.equals(permission)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static int pixelsToDips(Context context, int px) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return Math.round(px / scale);
	}

	public static int dipsToPixels(Context context, int dp) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return Math.round(dp * scale);
	}

	public static float dipsToPixelsFloat(Context context, int dp) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return dp * scale;
	}

	/**
	 * Internal use only.
	 */
	public static void hideSoftKeyboard(Activity activity, View view) {
		if (view != null) {
			InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

/*
	public void showSoftKeyboard(Activity activity, View target) {
		if (activity.getCurrentFocus() != null) {
			InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(target, 0);
		}
	}
*/

	public static String[] getAllUserAccountEmailAddresses(Context context) {
		List<String> emails = new ArrayList<String>();
		if (Util.packageHasPermission(context, "android.permission.GET_ACCOUNTS")) {
			AccountManager accountManager = AccountManager.get(context);
			try {
				Account[] accounts = accountManager.getAccountsByType("com.google");
				for (Account account : accounts) {
					emails.add(account.name);
				}
			} catch (VerifyError e) {
				// Ignore here because the phone is on a pre API Level 5 SDK.
			}
		}
		return emails.toArray(new String[emails.size()]);
	}

	public static String getUserEmail(Context context) {
		if (Util.packageHasPermission(context, "android.permission.GET_ACCOUNTS")) {
			String email = getEmail(context);
			if (email != null) {
				return email;
			}
		}
		return null;
	}

	private static String getEmail(Context context) {
		AccountManager accountManager = AccountManager.get(context);
		Account account = getAccount(accountManager);
		if (account == null) {
			return null;
		} else {
			return account.name;
		}
	}

	// TODO: Use reflection to load this so we can drop 2.1 API requirement?
	private static Account getAccount(AccountManager accountManager) {
		Account account = null;
		try {
			Account[] accounts = accountManager.getAccountsByType("com.google");
			if (accounts.length > 0) {
				// It seems that the first google account added will always be at the end of this list. That SHOULD be the main account.
				account = accounts[accounts.length - 1];
			}
		} catch (VerifyError e) {
			// Ignore here because the phone is on a pre API Level 5 SDK.
		}
		return account;
	}

	public static boolean isNetworkConnectionPresent(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		return cm != null && cm.getActiveNetworkInfo() != null;
	}

	public static void ensureClosed(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				// Ignore
			}
		}
	}

	public static Point getScreenSize(Context context) {
		Point ret = new Point();
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = windowManager.getDefaultDisplay();
		// TODO: getWidth(), getHeight(), and getOrientation() are deprecated in API 13 in favor of getSize() and getRotation().
		ret.set(display.getWidth(), display.getHeight());
		return ret;
	}

	public static void printDebugInfo(Context context) {
		// Print screen dimensions.
		// Huawei Comet: Port: PX=240x320  DP=320x427, Land: PX=320x240 DP=427x320
		// Galaxy Nexus: Port: PX=720x1184 DP=360x592, Land: PX=1196x720 DP=598x360
		// Nexus 7:      Port: PX=800x1205 DP=601x905, Land: PX=1280x736 DP=962x553
		Point point = Util.getScreenSize(context);
		Log.e("Screen size: PX=%dx%d DP=%dx%d", point.x, point.y, Util.pixelsToDips(context, point.x), Util.pixelsToDips(context, point.y));
	}

	public static boolean isEmpty(CharSequence charSequence) {
		return charSequence == null || charSequence.length() == 0;
	}

	public static Integer parseCacheControlHeader(String cacheControlHeader) {
		if (cacheControlHeader != null) {
			String[] cacheControlParts = cacheControlHeader.split(",");
			for (String part : cacheControlParts) {
				part = part.trim();
				if (part.startsWith("max-age=")) {
					String[] maxAgeParts = part.split("=");
					if (maxAgeParts.length == 2) {
						String expiration = null;
						try {
							expiration = maxAgeParts[1];
							Integer ret = Integer.parseInt(expiration);
							return ret;
						} catch (NumberFormatException e) {
							Log.e("Error parsing cache expiration as number: %s", e, expiration);
						}
					}
				}
			}
		}
		return null;
	}

	public static boolean isEmailValid(String email) {
		return email.matches("^[^\\s@]+@[^\\s@]+$");
	}

	public static boolean getPackageMetaDataBoolean(Context context, String key) {
		try {
			return context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.getBoolean(key, false);
		} catch (PackageManager.NameNotFoundException e) {
			return false;
		}
	}

	public static Object getPackageMetaData(Context context, String key) {
		try {
			return context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.get(key);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 *
This method will allow you to pass in literal strings. You must wrap the string in single quotes in order to ensure it is not modified
	 * by Android. Android will try to coerce the string to a float, Integer, etc., if it looks like one.

	 *

	 *
Example: <meta-data android:name="sdk_distribution" android:value="'1.00'"/>

	 *
This will evaluate to a String "1.00". If you leave off the single quotes, this method will just cast to a String, so the result would be a String "1.0".

	 */
	public static String getPackageMetaDataSingleQuotedString(Context context, String key) {
		Object object = getPackageMetaData(context, key);
		if (object == null) {
			return null;
		}
		String ret = object.toString();
		if (ret.endsWith("'")) {
			ret = ret.substring(0, ret.length() - 1);
		}
		if (ret.startsWith("'")) {
			ret = ret.substring(1, ret.length());
		}
		return ret;
	}

	public static String stackTraceAsString(Throwable throwable) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		throwable.printStackTrace(pw);
		return sw.toString();
	}

	public static String getAppVersionName(Context context) {
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			Log.e("Error getting app version name.", e);
		}
		return null;
	}

	public static int getAppVersionCode(Context context) {
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			Log.e("Error getting app version code.", e);
		}
		return -1;
	}

	/**
	 * Converts the current time to a double representing seconds, instead of milliseconds. It will have millisecond
	 * precision as fractional seconds. This is the default time format used throughout the Apptentive SDK.
	 *
	 * @return A double representing the current time in seconds.
	 */
	public static double currentTimeSeconds() {
		long millis = System.currentTimeMillis();
		double point = (double) millis;
		return point / 1000;
	}

	public static int getUtcOffset() {
		TimeZone timezone = TimeZone.getDefault();
		return timezone.getOffset(System.currentTimeMillis()) / 1000;
	}

	public static String getInstallerPackageName(Context context) {
		try {
			return context.getPackageManager().getInstallerPackageName(context.getPackageName());
		} catch (Exception e) {
			// Just return.
		}
		return null;
	}

	public static String readStringFromInputStream(InputStream is, String charEncoding) {
		Reader reader = null;
		StringBuilder out = new StringBuilder();
		final char[] buf = new char[8196];
		try {
			reader = new InputStreamReader(is, charEncoding);
			while (true) {
				int read = reader.read(buf, 0, 8196);
				if (read < 0) {
					break;
				}
				out.append(buf, 0, read);
			}
		} catch (Exception e) {
			//
		} finally {
			Util.ensureClosed(reader);
		}
		return out.toString();
	}

	public static Integer getMajorOsVersion() {
		try {
			String release = Build.VERSION.RELEASE;
			String[] parts = release.split("\\.");
			if (parts != null && parts.length != 0) {
				return Integer.parseInt(parts[0]);
			}
		} catch (Exception e) {
			Log.w("Error getting major OS version", e);
		}
		return -1;
	}
}


text:
<?php

namespace dataBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * dresseursRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class dresseursRepository extends EntityRepository
{
}


text:
package tools

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/bitrise-io/bitrise/configs"
	"github.com/bitrise-io/go-utils/cmdex"
)

// UnameGOOS ...
func UnameGOOS() (string, error) {
	switch runtime.GOOS {
	case "darwin":
		return "Darwin", nil
	case "linux":
		return "Linux", nil
	}
	return "", fmt.Errorf("Unsupported platform (%s)", runtime.GOOS)
}

// UnameGOARCH ...
func UnameGOARCH() (string, error) {
	switch runtime.GOARCH {
	case "amd64":
		return "x86_64", nil
	}
	return "", fmt.Errorf("Unsupported architecture (%s)", runtime.GOARCH)
}

// InstallToolFromGitHub ...
func InstallToolFromGitHub(toolname, githubUser, toolVersion string) error {
	unameGOOS, err := UnameGOOS()
	if err != nil {
		return fmt.Errorf("Failed to determine OS: %s", err)
	}
	unameGOARCH, err := UnameGOARCH()
	if err != nil {
		return fmt.Errorf("Failed to determine ARCH: %s", err)
	}
	downloadURL := "https://github.com/" + githubUser + "/" + toolname + "/releases/download/" + toolVersion + "/" + toolname + "-" + unameGOOS + "-" + unameGOARCH

	return InstallFromURL(toolname, downloadURL)
}

// DownloadFile ...
func DownloadFile(downloadURL, targetDirPath string) error {
	outFile, err := os.Create(targetDirPath)
	defer func() {
		if err := outFile.Close(); err != nil {
			log.Warnf("Failed to close (%s)", targetDirPath)
		}
	}()
	if err != nil {
		return fmt.Errorf("failed to create (%s), error: %s", targetDirPath, err)
	}

	resp, err := http.Get(downloadURL)
	if err != nil {
		return fmt.Errorf("failed to download from (%s), error: %s", downloadURL, err)
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			log.Warnf("failed to close (%s) body", downloadURL)
		}
	}()

	_, err = io.Copy(outFile, resp.Body)
	if err != nil {
		return fmt.Errorf("failed to download from (%s), error: %s", downloadURL, err)
	}

	return nil
}

// InstallFromURL ...
func InstallFromURL(toolBinName, downloadURL string) error {
	if len(toolBinName) < 1 {
		return fmt.Errorf("No Tool (bin) Name provided! URL was: %s", downloadURL)
	}

	bitriseToolsDirPath := configs.GetBitriseToolsDirPath()
	destinationPth := filepath.Join(bitriseToolsDirPath, toolBinName)

	if err := DownloadFile(downloadURL, destinationPth); err != nil {
		return fmt.Errorf("Failed to download, error: %s", err)
	}

	if err := os.Chmod(destinationPth, 0755); err != nil {
		return fmt.Errorf("Failed to make file (%s) executable, error: %s", destinationPth, err)
	}

	return nil
}

// ------------------
// --- Stepman

// StepmanSetup ...
func StepmanSetup(collection string) error {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "setup", "--collection", collection}
	return cmdex.RunCommand("stepman", args...)
}

// StepmanActivate ...
func StepmanActivate(collection, stepID, stepVersion, dir, ymlPth string) error {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "activate", "--collection", collection,
		"--id", stepID, "--version", stepVersion, "--path", dir, "--copyyml", ymlPth}
	return cmdex.RunCommand("stepman", args...)
}

// StepmanUpdate ...
func StepmanUpdate(collection string) error {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "update", "--collection", collection}
	return cmdex.RunCommand("stepman", args...)
}

// StepmanRawStepLibStepInfo ...
func StepmanRawStepLibStepInfo(collection, stepID, stepVersion string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "step-info", "--collection", collection,
		"--id", stepID, "--version", stepVersion, "--format", "raw"}
	return cmdex.RunCommandAndReturnCombinedStdoutAndStderr("stepman", args...)
}

// StepmanRawLocalStepInfo ...
func StepmanRawLocalStepInfo(pth string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "step-info", "--step-yml", pth, "--format", "raw"}
	return cmdex.RunCommandAndReturnCombinedStdoutAndStderr("stepman", args...)
}

// StepmanJSONStepLibStepInfo ...
func StepmanJSONStepLibStepInfo(collection, stepID, stepVersion string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "step-info", "--collection", collection,
		"--id", stepID, "--version", stepVersion, "--format", "json"}

	var outBuffer bytes.Buffer
	var errBuffer bytes.Buffer

	if err := cmdex.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "stepman", args...); err != nil {
		return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
	}

	return outBuffer.String(), nil
}

// StepmanJSONLocalStepInfo ...
func StepmanJSONLocalStepInfo(pth string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "step-info", "--step-yml", pth, "--format", "json"}

	var outBuffer bytes.Buffer
	var errBuffer bytes.Buffer

	if err := cmdex.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "stepman", args...); err != nil {
		return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
	}

	return outBuffer.String(), nil
}

// StepmanRawStepList ...
func StepmanRawStepList(collection string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "step-list", "--collection", collection, "--format", "raw"}
	return cmdex.RunCommandAndReturnCombinedStdoutAndStderr("stepman", args...)
}

// StepmanJSONStepList ...
func StepmanJSONStepList(collection string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--debug", "--loglevel", logLevel, "step-list", "--collection", collection, "--format", "json"}

	var outBuffer bytes.Buffer
	var errBuffer bytes.Buffer

	if err := cmdex.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "stepman", args...); err != nil {
		return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
	}

	return outBuffer.String(), nil
}

//
// Share

// StepmanShare ...
func StepmanShare() error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "share", "--toolmode"}
	return cmdex.RunCommand("stepman", args...)
}

// StepmanShareAudit ...
func StepmanShareAudit() error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "share", "audit", "--toolmode"}
	return cmdex.RunCommand("stepman", args...)
}

// StepmanShareCreate ...
func StepmanShareCreate(tag, git, stepID string) error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "share", "create", "--tag", tag, "--git", git, "--stepid", stepID, "--toolmode"}
	return cmdex.RunCommand("stepman", args...)
}

// StepmanShareFinish ...
func StepmanShareFinish() error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "share", "finish", "--toolmode"}
	return cmdex.RunCommand("stepman", args...)
}

// StepmanShareStart ...
func StepmanShareStart(collection string) error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "share", "start", "--collection", collection, "--toolmode"}
	return cmdex.RunCommand("stepman", args...)
}

// ------------------
// --- Envman

// EnvmanInit ...
func EnvmanInit() error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "init"}
	return cmdex.RunCommand("envman", args...)
}

// EnvmanInitAtPath ...
func EnvmanInitAtPath(envstorePth string) error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "--path", envstorePth, "init", "--clear"}
	return cmdex.RunCommand("envman", args...)
}

// EnvmanAdd ...
func EnvmanAdd(envstorePth, key, value string, expand, skipIfEmpty bool) error {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "--path", envstorePth, "add", "--key", key, "--append"}
	if !expand {
		args = append(args, "--no-expand")
	}
	if skipIfEmpty {
		args = append(args, "--skip-if-empty")
	}

	envman := exec.Command("envman", args...)
	envman.Stdin = strings.NewReader(value)
	envman.Stdout = os.Stdout
	envman.Stderr = os.Stderr
	return envman.Run()
}

// EnvmanRun ...
func EnvmanRun(envstorePth, workDirPth string, cmd []string) (int, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "--path", envstorePth, "run"}
	args = append(args, cmd...)

	return cmdex.RunCommandInDirAndReturnExitCode(workDirPth, "envman", args...)
}

// EnvmanJSONPrint ...
func EnvmanJSONPrint(envstorePth string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "--path", envstorePth, "print", "--format", "json", "--expand"}

	var outBuffer bytes.Buffer
	var errBuffer bytes.Buffer

	if err := cmdex.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "envman", args...); err != nil {
		return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
	}

	return outBuffer.String(), nil
}


text:
<?php

namespace Ojs\JournalBundle\Event;

final class JournalEvents
{
    const LISTED = 'ojs.journal.list';

    const PRE_CREATE = 'ojs.journal.pre_create';

    const POST_CREATE = 'ojs.journal.post_create';

    const PRE_UPDATE = 'ojs.journal.pre_update';

    const POST_UPDATE = 'ojs.journal.post_update';

    const PRE_DELETE = 'ojs.journal.pre_delete';

    const POST_DELETE = 'ojs.journal.post_delete';
}


text:
package com.google.security.zynamics.zylib.disassembly;

/**
 * Enumeration type that describes the possible types of operand expressions.
 */
public enum ExpressionType {
  SYMBOL, IMMEDIATE_INTEGER, IMMEDIATE_FLOAT, OPERATOR, REGISTER, SIZE_PREFIX, MEMDEREF, EXPRESSION_LIST
}


text:
TEST(CURRENT_PROCESSOR, within_bounds) {
	ASSERT_TRUE(cpuinfo_initialize());

	const struct cpuinfo_processor* current_processor = cpuinfo_get_current_processor();
	if (current_processor == nullptr) {
		GTEST_SKIP();
	}

	const struct cpuinfo_processor* processors_begin = cpuinfo_get_processors();
	const struct cpuinfo_processor* processors_end = processors_begin + cpuinfo_get_processors_count();
	ASSERT_GE(current_processor, processors_begin);
	ASSERT_LT(current_processor, processors_end);
}

TEST(CURRENT_CORE, within_bounds) {
	ASSERT_TRUE(cpuinfo_initialize());

	const struct cpuinfo_core* current_core = cpuinfo_get_current_core();
	if (current_core == nullptr) {
		GTEST_SKIP();
	}

	const struct cpuinfo_core* cores_begin = cpuinfo_get_cores();
	const struct cpuinfo_core* cores_end = cores_begin + cpuinfo_get_cores_count();
	ASSERT_GE(current_core, cores_begin);
	ASSERT_LT(current_core, cores_end);
}

TEST(CURRENT_UARCH_INDEX, within_bounds) {
	ASSERT_TRUE(cpuinfo_initialize());

	ASSERT_LT(cpuinfo_get_current_uarch_index(), cpuinfo_get_uarchs_count());
}

TEST(CURRENT_UARCH_INDEX_WITH_DEFAULT, within_bounds) {
	ASSERT_TRUE(cpuinfo_initialize());

	ASSERT_LE(cpuinfo_get_current_uarch_index_with_default(cpuinfo_get_uarchs_count()), cpuinfo_get_uarchs_count());
}


text:
@implementation NSObject (JavaObject)

- (id)clone {
  if (![self conformsToProtocol:@protocol(NSCopying)] &&
      ![self conformsToProtocol:@protocol(NSMutableCopying)]) {
    id exception = [[JavaLangCloneNotSupportedException alloc] init];
#if ! __has_feature(objc_arc)
    [exception autorelease];
#endif
    @throw exception;
  }
  // Deliberately not calling "init" on the cloned object. It is expected that
  // any object implementing Cloneable, and all of it's superclasses, will
  // contain a valid implementation of copyAllFieldsTo as is generated by J2ObjC
  // translation.
  id clone = AUTORELEASE([[self class] alloc]);
  [self copyAllFieldsTo:clone];
  return clone;
}

- (IOSClass *)getClass {
  return IOSClass_fromClass([self class]);
}

- (int)compareToWithId:(id)other {
#if __has_feature(objc_arc)
  @throw [[JavaLangClassCastException alloc] init];
#else
  @throw [[[JavaLangClassCastException alloc] init] autorelease];
#endif
  return 0;
}

- (void)notify {
  int result = objc_sync_notify(self);
  if (result == OBJC_SYNC_SUCCESS) {  // Test most likely outcome first.
    return;
  }
  if (result == OBJC_SYNC_NOT_OWNING_THREAD_ERROR) {
    @throw AUTORELEASE([[JavaLangIllegalMonitorStateException alloc] init]);
  } else {
    NSString *msg = [NSString stringWithFormat:@"system error %d", result];
    @throw AUTORELEASE([[JavaLangInternalError alloc] initWithNSString:msg]);
  }
}

- (void)notifyAll {
  int result = objc_sync_notifyAll(self);
  if (result == OBJC_SYNC_SUCCESS) {  // Test most likely outcome first.
    return;
  }
  if (result == OBJC_SYNC_NOT_OWNING_THREAD_ERROR) {
    @throw AUTORELEASE([[JavaLangIllegalMonitorStateException alloc] init]);
  } else {
    NSString *msg = [NSString stringWithFormat:@"system error %d", result];
    @throw AUTORELEASE([[JavaLangInternalError alloc] initWithNSString:msg]);
  }
}

static void doWait(id obj, long long timeout) {
  if (timeout < 0) {
    @throw AUTORELEASE([[JavaLangIllegalArgumentException alloc] init]);
  }
  JavaLangThread *javaThread = JavaLangThread_currentThread();
  int result = OBJC_SYNC_SUCCESS;
  if (!javaThread->interrupted__) {
    assert(javaThread->blocker_ == nil);
    javaThread->blocker_ = obj;
    result = objc_sync_wait(obj, timeout);
    javaThread->blocker_ = nil;
  }
  BOOL wasInterrupted = javaThread->interrupted__;
  javaThread->interrupted__ = NO;
  if (wasInterrupted) {
    @throw AUTORELEASE([[JavaLangInterruptedException alloc] init]);
  }
  if (result == OBJC_SYNC_SUCCESS) {
    return;  // success
  }
  if (result == OBJC_SYNC_TIMED_OUT) {
    return;
  }
  if (result == OBJC_SYNC_NOT_OWNING_THREAD_ERROR) {
    @throw AUTORELEASE([[JavaLangIllegalMonitorStateException alloc] init]);
  } else {
    NSString *msg = [NSString stringWithFormat:@"system error %d", result];
    @throw AUTORELEASE([[JavaLangInternalError alloc] initWithNSString:msg]);
  }
}

- (void)wait {
  doWait(self, 0LL);
}

- (void)waitWithLong:(long long)timeout {
  doWait(self, timeout);
}

- (void)waitWithLong:(long long)timeout withInt:(int)nanos {
  if (nanos < 0) {
    @throw AUTORELEASE([[JavaLangIllegalArgumentException alloc] init]);
  }
  doWait(self, timeout + (nanos == 0 ? 0 : 1));
}

- (void)copyAllFieldsTo:(id)other {
}

+ (J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { "getClass", NULL, "LIOSClass", 0x11, NULL },
    { "isEqual:", "equals", "Z", 0x1, NULL },
    { "clone", NULL, "LJavaLangObject", 0x4, "JavaLangCloneNotSupportedException" },
    { "dealloc", "finalize", "V", 0x4, "JavaLangThrowable" },
    { "notify", NULL, "V", 0x11, NULL },
    { "notifyAll", NULL, "V", 0x11, NULL },
    { "waitWithLong:", "wait", "V", 0x11, "JavaLangInterruptedException" },
    { "waitWithLong:withInt:", "wait", "V", 0x11, "JavaLangInterruptedException" },
    { "wait", NULL, "V", 0x11, "JavaLangInterruptedException" },
    { "description", "toString", "LJavaLangString", 0x1, NULL },
    { "hash", "hashCode", "I", 0x1, NULL },
  };
  static J2ObjcClassInfo _JavaLangObject = {
    1, "Object", "java.lang", NULL, 0x1, 9, methods, 0, NULL, 0, NULL
  };
  return &_JavaLangObject;
}

// Unimplemented private methods for java.lang.ref.Reference. The methods'
// implementations are set when swizzling the Reference's referent class.
- (void)_java_lang_ref_original_dealloc {}
- (void)_java_lang_ref_original_release {}

@end

@implementation JreObjectCategoryDummy
@end

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(NSObject)


text:
using System;
using System.Data;

namespace YesSql.Sql.Schema
{
    public interface IAlterTableCommand : ISchemaCommand
    {
        void AddColumn(string columnName, Type dbType, Action<IAddColumnCommand> column = null);
        void AddColumn<T>(string columnName, Action<IAddColumnCommand> column = null);
        void AlterColumn(string columnName, Action<IAlterColumnCommand> column = null);
        void RenameColumn(string columnName, string newName);
        void DropColumn(string columnName);
        void CreateIndex(string indexName, params string[] columnNames);
        void DropIndex(string indexName);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/lv_left"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:scrollbars="none" >
    </ListView>

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#2b2b2b2b" />

    <ListView
        android:id="@+id/lv_right"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:orientation="horizontal" >
    </ListView>

</LinearLayout>


text:
/**
 *
 */
package org.restexpress.serialization;

import java.io.IOException;
import java.util.List;

import org.jboss.netty.buffer.ChannelBuffer;
import org.restexpress.DeserializationException;
import org.restexpress.SerializationException;
import org.restexpress.domain.MediaType;
import org.restexpress.serialization.jackson.Jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JacksonJsonProcessor.
 *
 * @author Jerome Guibert
 *
 */
public class JacksonJsonProcessor extends JsonProcessor {

	private final ObjectMapper objectMapper;

	/**
	 * Build a new instance.
	 */
	public JacksonJsonProcessor() {
		super();
		this.objectMapper = Jackson.newObjectMapper();
	}

	public JacksonJsonProcessor(List<String> supportedMediaType) {
		super(supportedMediaType);
		this.objectMapper = Jackson.newObjectMapper();
	}

	public JacksonJsonProcessor(MediaType... mediaTypes) {
		super(mediaTypes);
		this.objectMapper = Jackson.newObjectMapper();
	}

	public JacksonJsonProcessor(String... mediaTypes) throws IllegalArgumentException {
		super(mediaTypes);
		this.objectMapper = Jackson.newObjectMapper();
	}

	public JacksonJsonProcessor(ObjectMapper objectMapper, List<String> mediaTypes) throws IllegalArgumentException {
		super(mediaTypes);
		this.objectMapper = objectMapper;
	}

	public JacksonJsonProcessor(ObjectMapper objectMapper, MediaType... mediaTypes) throws IllegalArgumentException {
		super(mediaTypes);
		this.objectMapper = objectMapper;
	}

	public JacksonJsonProcessor(ObjectMapper objectMapper, String... mediaTypes) throws IllegalArgumentException {
		super(mediaTypes);
		this.objectMapper = objectMapper;
	}

	/**
	 * @see org.restexpress.serialization.Processor#write(java.lang.Object,
	 *      org.jboss.netty.buffer.ChannelBuffer)
	 */
	@Override
	public void write(Object value, ChannelBuffer buffer) throws SerializationException {
		try {
			if (value != null) {
				objectMapper.writeValue(getOutputStreamWriter(buffer), value);
			}
		} catch (final JsonProcessingException e) {
			throw new SerializationException(e);
		} catch (IOException e) {
			throw new SerializationException(e);
		}
	}

	/**
	 * @see org.restexpress.serialization.Processor#read(org.jboss.netty.buffer.ChannelBuffer,
	 *      java.lang.Class)
	 */
	@Override
	public <T> T read(ChannelBuffer buffer, Class<T> valueType) throws DeserializationException {
		try {
			return ((buffer == null) || (buffer.readableBytes() == 0) ? null : objectMapper.readValue(getInputStreamReader(buffer), valueType));
		} catch (final JsonProcessingException e) {
			throw new DeserializationException(e);
		} catch (final IOException e) {
			throw new DeserializationException(e);
		}
	}

}


text:
$ProtectionGroupName = "PG name, get from GUI for example";
$DBName = 'DB_Name';
$TargetServerName = 'restoresrv.contoso.com';
$RestoreLocation = 'C:\restored_db';
$DPMServer = 'backup.contoso.com';

Connect-DPMServer $DPMServer | Out-Null

$prot_group = Get-ProtectionGroup -DPMServerName $DPMServer | where {$_.FriendlyName -eq $ProtectionGroupName}
$data_source = Get-Datasource -ProtectionGroup $prot_group | where {$_.Name -like "*$DBName*"}
$rec_point = Get-RecoveryPoint -Datasource $data_source | where {$_.IsIncremental -eq $false } | sort -Property RepresentedPointInTime -Descending | select -first 1
$rec_opt = New-RecoveryOption -SQL -TargetServer $TargetServerName -RecoveryLocation CopyToFolder -RecoveryType Restore -TargetLocation $RestoreLocation
$rec_job = Recover-RecoverableItem -RecoveryOption $rec_opt -RecoverableItem $rec_point

while ($rec_job.HasCompleted -eq $False)
{
    Write-Host "." -NoNewline
    Start-Sleep -Seconds 5
}

if ($rec_job.HasCompleted -eq $True -and $rec_job.Status -eq "Succeeded")
{
    Write-Host -ForegroundColor Green "All is fine";
    exit 0;
} else {
    Write-Host -ForegroundColor Green "Encountered a problem";
    $rec_job | fl;
    exit 2;
}


text:
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
using System.Linq;
using SQLite.CodeFirst.Statement;

namespace SQLite.CodeFirst.Builder
{
    internal class PrimaryKeyStatementBuilder : IStatementBuilder<PrimaryKeyStatement>
    {
        private readonly IEnumerable<EdmMember> keyMembers;

        public PrimaryKeyStatementBuilder(IEnumerable<EdmMember> keyMembers)
        {
            this.keyMembers = keyMembers;
        }

        public PrimaryKeyStatement BuildStatement()
        {
            return new PrimaryKeyStatement(keyMembers.Select(km => km.Name));
        }
    }
}


text:
<?xml version="1.0" encoding="us-ascii"?>
<test-set xmlns="http://www.w3.org/2010/09/qt-fots-catalog" name="xs-base64Binary">
   <description>Tests for conversion to/from base64Binary</description>

   <test-case name="base64-001">
      <description> Convert empty string to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary(""))</test>
      <result>
         <assert-string-value/>
      </result>
   </test-case>

   <test-case name="base64-002">
      <description> Convert single byte to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("00"))</test>
      <result>
         <assert-string-value>AA==</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-003">
      <description> Convert single byte to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("01"))</test>
      <result>
         <assert-string-value>AQ==</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-004">
      <description> Convert single byte to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("ff"))</test>
      <result>
         <assert-string-value>/w==</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-005">
      <description> Convert two bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("0000"))</test>
      <result>
         <assert-string-value>AAA=</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-006">
      <description> Convert two bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("00ff"))</test>
      <result>
         <assert-string-value>AP8=</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-007">
      <description> Convert two bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("80c0"))</test>
      <result>
         <assert-string-value>gMA=</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-008">
      <description> Convert three bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("aabbcc"))</test>
      <result>
         <assert-string-value>qrvM</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-009">
      <description> Convert three bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("010203"))</test>
      <result>
         <assert-string-value>AQID</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-010">
      <description> Convert four bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("01020304"))</test>
      <result>
         <assert-string-value>AQIDBA==</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-011">
      <description> Convert five bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("0102030405"))</test>
      <result>
         <assert-string-value>AQIDBAU=</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-012">
      <description> Convert six bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("010203040506"))</test>
      <result>
         <assert-string-value>AQIDBAUG</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-013">
      <description> Convert seven bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("01020304050607"))</test>
      <result>
         <assert-string-value>AQIDBAUGBw==</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-014">
      <description> Convert a longer byte array to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary(xs:hexBinary("0102030405060708090A0B0C0D0E0F10111213131415161718191A1B1C1D1F202122232425262728292A2B2C2D2E2F"))</test>
      <result>
         <assert-string-value>AQIDBAUGBwgJCgsMDQ4PEBESExMUFRYXGBkaGxwdHyAhIiMkJSYnKCkqKywtLi8=</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-101">
      <description> Convert empty string to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("")</test>
      <result>
         <assert-string-value/>
      </result>
   </test-case>

   <test-case name="base64-102">
      <description> Convert single byte to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AA=="))</test>
      <result>
         <assert-string-value>00</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-103">
      <description> Convert single byte to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AQ=="))</test>
      <result>
         <assert-string-value>01</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-104">
      <description> Convert single byte to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("/w=="))</test>
      <result>
         <assert-string-value>FF</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-105">
      <description> Convert two bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AAA="))</test>
      <result>
         <assert-string-value>0000</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-106">
      <description> Convert two bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AP8="))</test>
      <result>
         <assert-string-value>00FF</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-107">
      <description> Convert two bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("gMA="))</test>
      <result>
         <assert-string-value>80C0</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-108">
      <description> Convert three bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("qrvM"))</test>
      <result>
         <assert-string-value>AABBCC</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-109">
      <description> Convert three bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AQID"))</test>
      <result>
         <assert-string-value>010203</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-110">
      <description> Convert four bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AQIDBA=="))</test>
      <result>
         <assert-string-value>01020304</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-111">
      <description> Convert five bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AQIDBAU="))</test>
      <result>
         <assert-string-value>0102030405</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-112">
      <description> Convert six bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AQIDBAUG"))</test>
      <result>
         <assert-string-value>010203040506</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-113">
      <description> Convert seven bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AQIDBAUGBw=="))</test>
      <result>
         <assert-string-value>01020304050607</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-114">
      <description> Convert a longer string of bytes to b64 </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary("AQIDBAUGBwgJCgsMDQ4PEBESExMUFRYXGBkaGxwdHyAhIiMkJSYnKCkqKywtLi8="))</test>
      <result>
         <assert-string-value>0102030405060708090A0B0C0D0E0F10111213131415161718191A1B1C1D1F202122232425262728292A2B2C2D2E2F</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-115">
      <description> Convert a longer string of bytes to b64; include whitespace </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:hexBinary(xs:base64Binary(" AQIDBAUG BwgJCgsM DQ4PEBES ExMUFRYX
 GBkaGxwdH yAhIiMkJ SYnKCkqK y w t L i 8 = "))</test>
      <result>
         <assert-string-value>0102030405060708090A0B0C0D0E0F10111213131415161718191A1B1C1D1F202122232425262728292A2B2C2D2E2F</assert-string-value>
      </result>
   </test-case>

   <test-case name="base64-901">
      <description> Invalid input: not a multiple of 4 characters </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("AQI")</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-902">
      <description> Invalid input: '=' not at end </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("AQ=I")</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-903">
      <description> Invalid input: '=' not at end </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("=AQI")</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-904">
      <description> Invalid input: too many '=' signs </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("qrvM====")</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-905">
      <description> Invalid input: disallowed character </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("gMA-")</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-906">
      <description> Invalid input: wrong character before final = </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("AP9=")</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-907">
      <description> Invalid input: wrong character before final = </description>
      <created by="Michael Kay" on="2012-07-18"/>
      <test>xs:base64Binary("Ay==")</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-908">
      <description> Invalid input: astral character </description>
      <created by="Michael Kay" on="2016-04-08"/>
      <test>xs:base64Binary(codepoints-to-string((119070, 119070, 119070, 119070) (:treble clef:)))</test>
      <result>
         <error code="FORG0001"/>
      </result>
   </test-case>

   <test-case name="base64-909">
      <description> Invalid input: astral character </description>
      <created by="Michael Kay" on="2016-04-08"/>
      <test>codepoints-to-string((119070, 119070, 119070, 119070) (:treble clef:)) castable as xs:base64Binary</test>
      <result>
         <assert-false/>
      </result>
   </test-case>

   <test-case name="cbcl-base64binary-001">
      <description>Tests for the xs:base64Binary constructor</description>
      <created by="Oliver Hallam" on="2008-04-14"/>
      <test>count(xs:base64Binary(()))</test>
      <result>
         <assert-string-value>0</assert-string-value>
      </result>
   </test-case>

</test-set>


text:
body {
    /* Margin bottom by footer height */
    margin-left: 20px;
}

.outer {
    margin-bottom: 100px;
}

.navbar-fixed-bottom {
    padding-top: 25px;
}

.page-footer {
    text-align: center;
}

textarea.rules {
    font-family:"Courier New", Courier, monospace;
}


text:
using System;
using System.Diagnostics;
using System.IO;

namespace Cake.Bakery
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = string.Concat(
                "\"",
                Path.ChangeExtension(typeof(Program).Assembly.Location, ".dll"),
                "\"",
                " ",
                Environment.CommandLine
                );

            var info = new ProcessStartInfo("dotnet")
            {
                Arguments = path,
                UseShellExecute = false
            };

            var p = Process.Start(info);
            p.WaitForExit();
            Environment.Exit(p.ExitCode);
        }
    }
}


text:
goog.provide('life.web');
goog.require('cljs.core');
goog.require('react_dom');
goog.require('life.page');
goog.require('life.core');
life.web.global$module$react_dom = goog.global.ReactDOM;
if(typeof life.web.app_state !== 'undefined'){
} else {
life.web.app_state = cljs.core.atom.call(null,new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"data","data",-232669377),life.core.RR,new cljs.core.Keyword(null,"gen","gen",142575302),(0)], null));
}
life.web.render_BANG_ = (function life$web$render_BANG_(state){
return ReactDOM.render(life.page.display_data.call(null,state),document.getElementById("app"));
});
cljs.core.add_watch.call(null,life.web.app_state,new cljs.core.Keyword(null,"on-change","on-change",-732046149),(function (_,___$1,___$2,___$3){
return life.web.render_BANG_.call(null,life.web.app_state);
}));
life.web.render_BANG_.call(null,life.web.app_state);
cljs.core.swap_BANG_.call(null,life.web.app_state,cljs.core.assoc,new cljs.core.Keyword(null,"timer","timer",-1266967739),setInterval(life.page.next_life.call(null,life.web.app_state),(125)));

//# sourceMappingURL=web.js.map


text:
namespace Packets
{
	namespace BNet
	{
		bool BNetOldAccountChange::Pack()
		{
			_packet << result;
			return true;
		}
	}
}


text:
import { ts } from "../typescript";

export function matchFiles(
    this: any,
    path: string,
    extensions: ReadonlyArray<string>,
    excludes: ReadonlyArray<string>,
    includes: ReadonlyArray<string>,
    useCaseSensitiveFileNames: boolean,
    currentDirectory: string,
    depth: number | undefined,
    getEntries: (path: string) => FileSystemEntries,
    realpath: (path: string) => string,
): string[] {
    return (ts as any).matchFiles.apply(this, arguments);
}

export interface FileMatcherPatterns {
    /** One pattern for each "include" spec. */
    includeFilePatterns: ReadonlyArray<string>;
    /** One pattern matching one of any of the "include" specs. */
    includeFilePattern: string;
    includeDirectoryPattern: string;
    excludePattern: string;
    basePaths: ReadonlyArray<string>;
}

export function getFileMatcherPatterns(
    this: any,
    path: string,
    excludes: ReadonlyArray<string>,
    includes: ReadonlyArray<string>,
    useCaseSensitiveFileNames: boolean,
    currentDirectory: string,
): FileMatcherPatterns {
    return (ts as any).getFileMatcherPatterns.apply(this, arguments);
}

export interface FileSystemEntries {
    readonly files: ReadonlyArray<string>;
    readonly directories: ReadonlyArray<string>;
}

export function getEmitModuleResolutionKind(this: any, compilerOptions: ts.CompilerOptions) {
    return (ts as any).getEmitModuleResolutionKind.apply(this, arguments);
}


text:
set -eo pipefail

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
# echo an error message before exiting
trap 'echo "\"${last_command}\" command filed with exit code $?."' EXIT

export SCRIPTS_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

source "$SCRIPTS_DIR/common.bash"

ensure_version

export PRODUCT=quorum

export PREVIOUS_RELEASE=$(curl -H "Authorization: token ${GITHUB_PERSONAL_ACCESS_TOKEN}" -s https://api.github.com/repos/web3j/${PRODUCT}/releases/latest | jq -r '.target_commitish' )
export CHANGELOG=$(git rev-list --format=oneline --abbrev-commit --max-count=50 ${PREVIOUS_RELEASE}..HEAD | jq --slurp --raw-input . )

echo "Creating a new release on GitHub with changes"
echo -e "\n${CHANGELOG:1:-1}"

API_JSON="{
  \"tag_name\": \"v${VERSION}\",
  \"target_commitish\": \"$(git rev-parse HEAD)\",
  \"name\": \"v${VERSION}\",
  \"body\": \"Release of version ${VERSION}: \n\n ${CHANGELOG:1:-1}\",
  \"draft\": false,
  \"prerelease\": false
}"

export RESULT=$(curl -H "Authorization: token ${GITHUB_PERSONAL_ACCESS_TOKEN}" --data "$API_JSON" -s https://api.github.com/repos/web3j/${PRODUCT}/releases)
export UPLOAD_URL=$(echo ${RESULT} | jq -r ".upload_url")

for FILE in `find ./build/libs -type f -name "${PRODUCT}-${VERSION}.*"`;
do
  curl -H "Authorization: token ${GITHUB_PERSONAL_ACCESS_TOKEN}" -s "${UPLOAD_URL:0:-13}?name=$(basename -- $FILE)" -H "Content-Type: $(file -b --mime-type $FILE)" --data-binary @"${FILE}"
done

echo "Release finished"


text:
export const APEX_CLASS_DIRECTORY = 'classes';
export const APEX_CLASS_EXTENSION = '.cls';
export const APEX_CLASS_TYPE = 'apexclass';

export const APEX_TRIGGER_DIRECTORY = 'triggers';
export const APEX_TRIGGER_EXTENSION = '.trigger';
export const APEX_TRIGGER_TYPE = 'apextrigger';

export const VISUALFORCE_COMPONENT_DIRECTORY = 'components';
export const VISUALFORCE_COMPONENT_EXTENSION = '.component';
export const VISUALFORCE_COMPONENT_TYPE = 'apexcomponent';

export const VISUALFORCE_PAGE_DIRECTORY = 'pages';
export const VISUALFORCE_PAGE_EXTENSION = '.page';
export const VISUALFORCE_PAGE_TYPE = 'apexpage';

export const AURA_DIRECTORY = 'aura';
export const AURA_APP_EXTENSION = '.app';
export const AURA_COMPONENT_EXTENSION = '.cmp';
export const AURA_EVENT_EXTENSION = '.evt';
export const AURA_INTERFACE_EXTENSION = '.intf';
export const AURA_DEFINITION_FILE_EXTS = [
  AURA_APP_EXTENSION,
  AURA_COMPONENT_EXTENSION,
  AURA_EVENT_EXTENSION,
  AURA_INTERFACE_EXTENSION
];
export const AURA_TYPE = 'auradefinitionbundle';

export const LWC_JS_EXTENSION = '.js';
export const LWC_HTML_EXTENSION = '.html';
export const LWC_DEFINITION_FILE_EXTS = [LWC_JS_EXTENSION, LWC_HTML_EXTENSION];
export const LWC_DIRECTORY = 'lwc';
export const LWC_TYPE = 'lightningcomponentbundle';

export const ANALYTICS_TEMPLATE_TYPE = 'wavetemplatebundle';
export const ANALYTICS_TEMPLATE_DIRECTORY = 'waveTemplates';

export const FUNCTION_TYPE_JS = 'functionjs';
export const FUNCTION_TYPE_JAVA = 'functionjava';


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

package com.google.enterprise.secmgr.http;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.enterprise.secmgr.common.HttpUtil;

import java.util.List;
import java.util.Objects;

import javax.annotation.concurrent.Immutable;

/**
 * A parser and data structure for HTTP WWW-Authenticate and Proxy-Authenticate
 * headers.  Used by {@link HttpAuthenticator} classes to decode HTTP
 * authentication headers.  See RFC 2617 for details.
 */
@Immutable
public final class AuthenticateHeader {
  public static final String PARAM_NAME_REALM = "realm";

  private final String authScheme;
  private final String realm;
  private final ImmutableListMultimap<String, String> parameters;

  private AuthenticateHeader(String authScheme) {
    this.authScheme = authScheme;
    this.realm = null;
    parameters = ImmutableListMultimap.<String, String>builder().build();
  }

  private AuthenticateHeader(String authScheme, String firstRealm,
      ImmutableListMultimap<String, String> parameters) {
    this.authScheme = authScheme;
    this.realm = firstRealm;
    this.parameters = parameters;
  }

  @VisibleForTesting
  static AuthenticateHeader makeForTest(String authScheme, String realm,
      ImmutableListMultimap<String, String> p) {
    return new AuthenticateHeader(authScheme, realm, p);
  }

  /**
   * Parse the value of a WWW-Authenticate header and return the parsed result.
   * The value is always of the form
   *     SCHEME (e.g. Negotiate, NTLM) or
   *     SCHEME NAME1=VALUE1,NAME2=VALUE2, ...
   *
   * If there are some name value pairs then one of them has to be "realm"
   * (case insensitive).
   *
   * @param headerValue The right-hand side of the header.
   * @return A parsed header.
   * @throws IllegalArgumentException if the argument can't be parsed.
   */
  public static AuthenticateHeader parse(String headerValue) {
    int space = headerValue.indexOf(' ');
    if (space < 0) {
      return new AuthenticateHeader(headerValue);
    }
    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
    String authScheme = headerValue.substring(0, space);
    Preconditions.checkArgument(HttpUtil.isHttpToken(authScheme),
        "Authentication scheme must be an HTTP token: %s", authScheme);
    Iterable<String> authParams = Splitter.on(',').trimResults()
        .split(headerValue.substring(space + 1, headerValue.length()));
    int nRealms = 0;
    String firstRealm = null;
    for (String authParam : authParams) {
      List<String> nameValue = HttpUtil.parseHttpParameter(authParam);
      String key = nameValue.get(0);
      String value = nameValue.get(1);
      builder.put(key, value);
      if (PARAM_NAME_REALM.equalsIgnoreCase(key)) {
        nRealms++;
        if (null == firstRealm) {
          firstRealm = value;
        }
      }
    }
    Preconditions.checkArgument(nRealms >= 1,
        "No authentication realm found in header: %s", headerValue);
    ImmutableListMultimap<String, String> parameters = builder.build();
    return new AuthenticateHeader(authScheme, firstRealm, parameters);
  }

  /**
   * @return The authentication scheme for this header.
   */
  public String getAuthScheme() {
    return authScheme;
  }

  /**
   * Does this header have a given authentication scheme?
   *
   * @param theAuthScheme The authentication scheme to test for.
   * @return True if this header has the given authentication scheme.
   */
  public boolean hasAuthScheme(String theAuthScheme) {
    return authScheme.equalsIgnoreCase(theAuthScheme);
  }

  /**
   * @return The authentication realm for this header.  RFC 2617 doesn't forbid
   *     more than one realm; in that case the value is the first realm found.
   */
  public String getRealm() {
    return realm;
  }

  /**
   * @return The authentication parameters for this header, as an immutable
   *     multimap.  The parameter names are always in lower case.
   */
  public ListMultimap<String, String> getParameters() {
    return parameters;
  }

  /**
   * Test whether a given authentication scheme occurs in a list of headers.
   *
   * @param authScheme The authentication scheme to test for.
   * @param headers The list of headers to test.
   * @return True only if the authentication scheme occurs in the given headers.
   */
  public static boolean hasAuthScheme(String authScheme, List<AuthenticateHeader> headers) {
    for (AuthenticateHeader header : headers) {
      if (header.hasAuthScheme(authScheme)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append(authScheme);
    String prefix = " ";
    for (String name : parameters.keySet()) {
      for (String value : parameters.get(name)) {
        builder.append(prefix);
        prefix = ",";
        builder.append(name);
        builder.append("=");
        builder.append(HttpUtil.makeHttpParameterValueString(value));
      }
    }
    return builder.toString();
  }

  @Override
  public boolean equals(Object object) {
    if (!(object instanceof AuthenticateHeader)) { return false; }
    AuthenticateHeader other = (AuthenticateHeader) object;
    return Objects.equals(getAuthScheme(), other.getAuthScheme())
        && Objects.equals(getParameters(), other.getParameters());
  }

  @Override
  public int hashCode() {
    return Objects.hash(getAuthScheme(), getParameters());
  }
}


text:
package com.amazonaws.services.mgn.model.transform;

import java.util.Map;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.mgn.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * SsmDocumentMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class SsmDocumentMarshaller {

    private static final MarshallingInfo<String> ACTIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("actionName").build();
    private static final MarshallingInfo<Boolean> MUSTSUCCEEDFORCUTOVER_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("mustSucceedForCutover").build();
    private static final MarshallingInfo<Map> PARAMETERS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("parameters").build();
    private static final MarshallingInfo<String> SSMDOCUMENTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ssmDocumentName").build();
    private static final MarshallingInfo<Integer> TIMEOUTSECONDS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("timeoutSeconds").build();

    private static final SsmDocumentMarshaller instance = new SsmDocumentMarshaller();

    public static SsmDocumentMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(SsmDocument ssmDocument, ProtocolMarshaller protocolMarshaller) {

        if (ssmDocument == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(ssmDocument.getActionName(), ACTIONNAME_BINDING);
            protocolMarshaller.marshall(ssmDocument.getMustSucceedForCutover(), MUSTSUCCEEDFORCUTOVER_BINDING);
            protocolMarshaller.marshall(ssmDocument.getParameters(), PARAMETERS_BINDING);
            protocolMarshaller.marshall(ssmDocument.getSsmDocumentName(), SSMDOCUMENTNAME_BINDING);
            protocolMarshaller.marshall(ssmDocument.getTimeoutSeconds(), TIMEOUTSECONDS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}