text:
require 'spec_helper'

describe LLT::Constants::RegExps do
  def self.example_loop(regexp, negative = false)
    yield.each do |example|
      str = (negative ? "doesn't match" : "matches")
      it "#{str} #{example}" do
        if negative
          regexp.should_not match(example)
        else
          regexp.should match(example)
        end
      end
    end
  end

  context "CASE INSENSITIVE" do
    context "with irregular verbs" do
      iv = LLT::Constants::RegExps::IRREGULAR_VERBS

      context "with esse" do
        context "in praesens" do
          r = iv[:esse][:praesens].first
          example_loop(r) do
            %w{ sum est es eris sis sunt esto esse absumus desint Sunt }
          end

          example_loop(r, :negative) do
            %w{ et eunt eam eum suo satis rite eas }
          end

          it "returns with correct components - esse" do
            m = r.match("esse")
            m.captures.should == ["", "es", "", "", "se"]
          end

          context "with prefix" do
            it "returns with correct components - desum" do
              m = r.match("desum")
              m.captures.should == ["de", "s", "u", "", "m"]
            end
          end
        end

        context "in perfectum" do
          example_loop(iv[:esse][:perfectum].first) do
            %w{ fuerint fuisse fueras }
          end
        end
      end

      context "with posse" do
        context "in praesens" do
          r = iv[:posse][:praesens].first
          example_loop(r) do
            %w{ possum potest potes poteris possis possunt posse possumus }
          end

          example_loop(r, :negative) do
            %w{ post }
          end

          context "returns with correct components" do
            it "posse" do
              m = r.match("posse")
              m.captures.should == ["", "pos", "", "", "se"]
            end

            it "possent" do
              m = r.match("possent")
              m.captures.should == ["", "pos", "", "se", "nt"]
            end

            it "potest" do
              m = r.match("potest")
              m.captures.should == ["", "potes", "", "", "t"]
            end
          end
        end

        context "in perfectum" do
          example_loop(iv[:posse][:perfectum].first) do
            %w{ potuerint potuisse potueras potuisti potui }
          end
        end
      end

      context "with ferre" do
        context "in praesens" do
          r = iv[:ferre][:praesens].first
          example_loop(r) do
            %w{ fer ferre ferri fero fers fert ferrem feret ferat ferimus feruntur ferunto }
          end

          example_loop(r, :negative) do
            %w{ fere ferus feri }
          end

          context "with verbal nouns" do
            example_loop(iv[:ferre][:praesens][1]) do
              %w{ ferendus ferendi ferendo ferendum ferendorum ferendis ferendos ferende
                  ferenda ferendae ferendarum ferendam ferendas
                  ferens ferentis ferenti ferentem ferente ferentes ferentium ferentibus
                  ferentia ferentium }
            end
          end

          it "returns with correct components - ferre" do
            m = r.match("ferre")
            m.captures.should == ["", "fer", "", "", "re"]
          end
        end

        context "in perfectum" do
          example_loop(iv[:ferre][:perfectum].first) do
            %w{ tulerunt tulerim tulero tulerint tulisse tuleras tulisti tuli
                tulissent intulisset
                contulissent }
          end
        end

        context "in ppp" do
          example_loop(iv[:ferre][:ppp].first) do
            %w{ allatus latus lati lato latum late lata latae latorum latis latarum latos laturas
                laturus laturi laturo laturum lature latura laturae laturorum laturis laturarum laturos latas
                conlatus perlatum inlatam }
          end
        end
      end

      context "with ire" do
        context "in praesens" do
          context "with stem i" do
            r = iv[:ire][:praesens].first
            example_loop(r) do
              %w{ is it imus itis ibo ibis ibunt adiberis ire iri
                  inito subito ito itote irem transiretur }
            end

            example_loop(r, :negative) do
              %w{ iam ibi interim iste ista isto }
            end
          end

          context "with stem e" do
            r = iv[:ire][:praesens][1]
            example_loop(r) do
              %w{ eo eunt eam eas eat eamus eatis eunto subeo obeo }
            end

            example_loop(r, :negative) do
              %w{ eos }
            end
          end

          context "with verbal nouns" do
            example_loop(iv[:ire][:praesens][2]) do
              %w{ eundus abeundus eundi eundo eundum eundorum eundis eundos eunde
                  eunda eundae eundarum eundam eundas
                  iens euntis eunti euntem eunte euntes euntium euntibus
                  euntia euntium }
            end
          end
        end

        context "in perfectum" do
          r = iv[:ire][:perfectum].first
          example_loop(r) do
            %w{ ierunt ierim iero ierint isse ieras isti ii }
          end

          example_loop(r, :negative) do
            %w{ interim }
          end

          context "with queo and nequeo" do
          r = iv[:ire][:perfectum][1]
            example_loop(r) do
              %w{ nequivi quivi nequisse }
            end
          end
        end

        context "in ppp" do
          r = iv[:ire][:ppp].first
          example_loop(r) do
            # ita disabled for convenience reasons...
            %w{ aditus itus iti ito itum ite itae itorum itis itarum itos ituras
                iturus ituri ituro iturum iture itura iturae iturorum ituris iturarum ituros itas
                inita subito inito obitum }
          end

          it "returns with correct components" do
            m = r.match("inito")
            m.captures.should == ["in", "it", "", "o"]
          end
        end
      end

      context "with velle" do
        context "in praesens" do
          r = iv[:velle][:praesens].first
          example_loop(r) do
            %w{ volo vis vult volumus vultis volunt velim velint volam voles volebant velle }
          end
        end

        context "in perfectum" do
          r = iv[:velle][:perfectum].first
          example_loop(r) do
            %w{ volui voluerunt voluisti volueram voluero volueritis voluisse }
          end
        end
      end

      context "with nolle" do
        context "in praesens" do
          r = iv[:nolle][:praesens].first
          example_loop(r) do
            %w{ nolo nolumus nolunt nolim nolint nolam noles nolebant nolle noli nolitote nolite nolito }
          end
        end

        context "in perfectum" do
          r = iv[:nolle][:perfectum].first
          example_loop(r) do
            %w{ nolui noluerunt noluisti nolueram noluero nolueritis noluisse }
          end
        end
      end

      context "with malle" do
        context "in praesens" do
          r = iv[:malle][:praesens].first
          example_loop(r) do
            %w{ malo malumus malunt malim malint malam males malebant malle }
          end
        end

        context "in perfectum" do
          r = iv[:malle][:perfectum].first
          example_loop(r) do
            %w{ malui maluerunt maluisti malueram maluero malueritis maluisse }
          end
        end
      end

      context "with fieri" do
        context "in praesens" do
          r = iv[:fieri][:praesens].first
          example_loop(r) do
            %w{ fio fis fit fimus fitis fiunt fiebam fiam fies fiat fierem fi fite fieri }
          end

          it "returns with correct components" do
            m = r.match("fieri")
            m.captures.should == ["fi", "e", "", "ri"]
          end

          it "returns with correct components" do
            m = r.match("fiebam")
            m.captures.should == ["fi", "e", "ba", "m"]
          end

          it "returns with correct components" do
            m = r.match("fiebat")
            m.captures.should == ["fi", "e", "ba", "t"]
          end
        end
      end

    end

    context "with pronouns" do
      pr = LLT::Constants::RegExps::PRONOUNS

      #qui
      example_loop(pr) do
        %w{ qui cuius cui quem quo qui quorum quibus quos quibus
            quae cuius cui Quam qua quae quarum quibus quas quibus
            quod cuius cui quod quo quae quorum quibus quae quibus
            quibuscum quocum quacum }.uniq
      end

      #quis/quid
      example_loop(pr) do
        %w{ quis quid }
      end

      #quisquam
      example_loop(pr) do
        %w{ quisquam quidquam quicquam }
      end

      #quisquis
      example_loop(pr) do
        %w{ quisquis quidquid quoquo }
      end

      #unusquisque
      example_loop(pr) do
        %w{ unusquisque uniuscuiusque }
      end

      example_loop(pr, :negative) do
        %w{ undique }
      end

      # hic
      example_loop(pr) do
        %w{ hic huius huic hunc hoc hi horum his hos his
            haec Huius huic hanc hac hae harum his has his
            hoc huius huic hoc hoc haec horum his haec his }.uniq
      end

      example_loop(pr, :negative) do
        %w{ hiscum }
      end

      # ipse
      example_loop(pr) do
        %w{ ipse ipsa ipsum ipsis }
      end

      # is
      example_loop(pr) do
        %w{ is ea id eius ei }
      end

      example_loop(pr, :negative) do
        %w{ iam }
      end

      # idem
      example_loop(pr) do
        %w{ idem eadem iisdem isdem }
      end

      # quispiam
      example_loop(pr) do
        %w{ quispiam }
      end

      # aliqui
      example_loop(pr) do
        %w{ aliquo alicuius }
      end

      example_loop(pr, :negative) do
        %w{ aliis aliquibuscum }
      end

      it "matches uterque" do
        pr.should match("uterque")
      end

      example_loop(pr, :negative) do
        %w{ quidem }
      end

      it "has proper captures" do
        pr.match("aliqui").captures.should == ["ali", "qu", "i", nil, nil]
        pr.match("hi")    .captures.should == [nil, "h", "i", nil, nil]
        pr.match("hunc")  .captures.should == [nil, "h", "un", "c", nil]
        pr.match("isdem") .captures.should == [nil, "i", "s",  "dem", nil]
        pr.match("quocum").captures.should == [nil, "qu", "o",  nil, "cum"]
        pr.match("quonam").captures.should == [nil, "qu", "o", "nam", nil]
        pr.match("unusquisque").captures.should == ["unus", "qu", "is", "que", nil]
      end
    end
  end
end


text:
<?php

namespace Rocket;

class RedisTool
{
    public $brew;
    public $cli;
    public $files;
    public $configuration;
    public $site;
    const REDIS_CONF = '/usr/local/etc/redis.conf';

    /**
     * Create a new instance.
     *
     * @param Brew          $brew
     * @param CommandLine   $cli
     * @param Filesystem    $files
     * @param Configuration $configuration
     * @param Site          $site
     */
    public function __construct(Brew $brew, CommandLine $cli, Filesystem $files,
                         Configuration $configuration, Site $site)
    {
        $this->cli = $cli;
        $this->brew = $brew;
        $this->site = $site;
        $this->files = $files;
        $this->configuration = $configuration;
    }

    /**
     * Install the service.
     *
     * @return void
     */
    public function install()
    {
        if (!$this->brew->installed('redis')) {
            $this->brew->installOrFail('redis');
            $this->cli->quietly('sudo brew services stop redis');
        }

        $this->installConfiguration();
        $this->restart();
    }

    /**
     * Install the configuration file.
     *
     * @return void
     */
    public function installConfiguration()
    {
        $this->files->copy(__DIR__.'/../stubs/redis.conf', static::REDIS_CONF);
    }

    /**
     * Restart the service.
     *
     * @return void
     */
    public function restart()
    {
        info('[redis] Restarting');
        $this->cli->quietlyAsUser('brew services restart redis');
    }

    /**
     * Stop the service.
     *
     * @return void
     */
    public function stop()
    {
        info('[redis] Stopping');
        $this->cli->quietly('sudo brew services stop redis');
        $this->cli->quietlyAsUser('brew services stop redis');
    }

    /**
     * Prepare for uninstallation.
     *
     * @return void
     */
    public function uninstall()
    {
        $this->stop();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateProductCategoriesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('product_categories', function(Blueprint $table)
		{
			$table->increments('id');
			$table->integer('category_id')->unsigned();
			$table->integer('product_id')->unsigned();

			$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
			$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

			$table->unique(array('product_id', 'category_id'));
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('product_categories');
	}

}


text:
package restjson

//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/rest-json.json build_test.go
//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/rest-json.json unmarshal_test.go

import (
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
	"github.com/aws/aws-sdk-go/private/protocol/rest"
)

// BuildHandler is a named request handler for building restjson protocol
// requests
var BuildHandler = request.NamedHandler{
	Name: "awssdk.restjson.Build",
	Fn:   Build,
}

// UnmarshalHandler is a named request handler for unmarshaling restjson
// protocol requests
var UnmarshalHandler = request.NamedHandler{
	Name: "awssdk.restjson.Unmarshal",
	Fn:   Unmarshal,
}

// UnmarshalMetaHandler is a named request handler for unmarshaling restjson
// protocol request metadata
var UnmarshalMetaHandler = request.NamedHandler{
	Name: "awssdk.restjson.UnmarshalMeta",
	Fn:   UnmarshalMeta,
}

// Build builds a request for the REST JSON protocol.
func Build(r *request.Request) {
	rest.Build(r)

	if t := rest.PayloadType(r.Params); t == "structure" || t == "" {
		if v := r.HTTPRequest.Header.Get("Content-Type"); len(v) == 0 {
			r.HTTPRequest.Header.Set("Content-Type", "application/json")
		}
		jsonrpc.Build(r)
	}
}

// Unmarshal unmarshals a response body for the REST JSON protocol.
func Unmarshal(r *request.Request) {
	if t := rest.PayloadType(r.Data); t == "structure" || t == "" {
		jsonrpc.Unmarshal(r)
	} else {
		rest.Unmarshal(r)
	}
}

// UnmarshalMeta unmarshals response headers for the REST JSON protocol.
func UnmarshalMeta(r *request.Request) {
	rest.UnmarshalMeta(r)
}


text:
<?php
// autogenerated file 30.09.2013 15:20
// $Id: $
// $Log: $
//
//
require_once 'CharityStatusCodeType.php';
require_once 'EbatNs_ComplexType.php';

/**
 * Identifies a Giving Works listing and benefiting nonprofit charity
 * organization.Currently supported through the US and eBay Motors sites only. The
 * Ad Format andMature Audiences categories are not supported.Not applicable for US
 * eBay Motors, international, Real Estate, and Tickets.
 *
 * @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/CharityType.html
 *
 */
class CharityType extends EbatNs_ComplexType
{
	/**
	 * @var string
	 */
	protected $CharityName;
	/**
	 * @var int
	 */
	protected $CharityNumber;
	/**
	 * @var float
	 */
	protected $DonationPercent;
	/**
	 * @var string
	 */
	protected $CharityID;
	/**
	 * @var string
	 */
	protected $Mission;
	/**
	 * @var string
	 */
	protected $LogoURL;
	/**
	 * @var CharityStatusCodeType
	 */
	protected $Status;
	/**
	 * @var boolean
	 */
	protected $CharityListing;

	/**
	 * @return string
	 */
	function getCharityName()
	{
		return $this->CharityName;
	}
	/**
	 * @return void
	 * @param string $value
	 */
	function setCharityName($value)
	{
		$this->CharityName = $value;
	}
	/**
	 * @return int
	 */
	function getCharityNumber()
	{
		return $this->CharityNumber;
	}
	/**
	 * @return void
	 * @param int $value
	 */
	function setCharityNumber($value)
	{
		$this->CharityNumber = $value;
	}
	/**
	 * @return float
	 */
	function getDonationPercent()
	{
		return $this->DonationPercent;
	}
	/**
	 * @return void
	 * @param float $value
	 */
	function setDonationPercent($value)
	{
		$this->DonationPercent = $value;
	}
	/**
	 * @return string
	 */
	function getCharityID()
	{
		return $this->CharityID;
	}
	/**
	 * @return void
	 * @param string $value
	 */
	function setCharityID($value)
	{
		$this->CharityID = $value;
	}
	/**
	 * @return string
	 */
	function getMission()
	{
		return $this->Mission;
	}
	/**
	 * @return void
	 * @param string $value
	 */
	function setMission($value)
	{
		$this->Mission = $value;
	}
	/**
	 * @return string
	 */
	function getLogoURL()
	{
		return $this->LogoURL;
	}
	/**
	 * @return void
	 * @param string $value
	 */
	function setLogoURL($value)
	{
		$this->LogoURL = $value;
	}
	/**
	 * @return CharityStatusCodeType
	 */
	function getStatus()
	{
		return $this->Status;
	}
	/**
	 * @return void
	 * @param CharityStatusCodeType $value
	 */
	function setStatus($value)
	{
		$this->Status = $value;
	}
	/**
	 * @return boolean
	 */
	function getCharityListing()
	{
		return $this->CharityListing;
	}
	/**
	 * @return void
	 * @param boolean $value
	 */
	function setCharityListing($value)
	{
		$this->CharityListing = $value;
	}
	/**
	 * @return
	 */
	function __construct()
	{
		parent::__construct('CharityType', 'urn:ebay:apis:eBLBaseComponents');
		if (!isset(self::$_elements[__CLASS__]))
				self::$_elements[__CLASS__] = array_merge(self::$_elements[get_parent_class()],
				array(
					'CharityName' =>
					array(
						'required' => false,
						'type' => 'string',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'CharityNumber' =>
					array(
						'required' => false,
						'type' => 'int',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'DonationPercent' =>
					array(
						'required' => false,
						'type' => 'float',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'CharityID' =>
					array(
						'required' => false,
						'type' => 'string',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'Mission' =>
					array(
						'required' => false,
						'type' => 'string',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'LogoURL' =>
					array(
						'required' => false,
						'type' => 'string',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					),
					'Status' =>
					array(
						'required' => false,
						'type' => 'CharityStatusCodeType',
						'nsURI' => 'urn:ebay:apis:eBLBaseComponents',
						'array' => false,
						'cardinality' => '0..1'
					),
					'CharityListing' =>
					array(
						'required' => false,
						'type' => 'boolean',
						'nsURI' => 'http://www.w3.org/2001/XMLSchema',
						'array' => false,
						'cardinality' => '0..1'
					)
				));
	}
}
?>


text:
<!DOCTYPE html>
<!--
@license
Copyright (C) 2017 The Android Open Source Project

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.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-admin-group-list</title>

<script src="../../../bower_components/page/page.js"></script>
<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>

<link rel="import" href="../../../test/common-test-setup.html"/>

<link rel="import" href="gr-admin-group-list.html">

<script>void(0);</script>

<test-fixture id="basic">
  <template>
    <gr-admin-group-list></gr-admin-group-list>
  </template>
</test-fixture>

<script>
  let counter = 0;
  const groupGenerator = () => {
    return {
      name: `test${++counter}`,
      id: '59b92f35489e62c80d1ab1bf0c2d17843038df8b',
      url: '#/admin/groups/uuid-59b92f35489e62c80d1ab1bf0c2d17843038df8b',
      options: {
        visible_to_all: false,
      },
      description: 'Gerrit Site Administrators',
      group_id: 1,
      owner: 'Administrators',
      owner_id: '7ca042f4d5847936fcb90ca91057673157fd06fc',
    };
  };

  suite('gr-admin-group-list tests', () => {
    let element;
    let groups;
    let sandbox;
    let value;

    setup(() => {
      sandbox = sinon.sandbox.create();
      element = fixture('basic');
    });

    teardown(() => {
      sandbox.restore();
    });

    suite('list with groups', () => {
      setup(done => {
        groups = _.times(26, groupGenerator);

        stub('gr-rest-api-interface', {
          getGroups(num, offset) {
            return Promise.resolve(groups);
          },
        });

        element._paramsChanged(value).then(() => { flush(done); });
      });

      test('test for test group in the list', done => {
        flush(() => {
          assert.equal(element._groups[1].name, '1');
          assert.equal(element._groups[1].options.visible_to_all, false);
          done();
        });
      });

      test('_shownGroups', () => {
        assert.equal(element._shownGroups.length, 25);
      });

      test('_maybeOpenCreateOverlay', () => {
        const overlayOpen = sandbox.stub(element.$.createOverlay, 'open');
        element._maybeOpenCreateOverlay();
        assert.isFalse(overlayOpen.called);
        const params = {};
        element._maybeOpenCreateOverlay(params);
        assert.isFalse(overlayOpen.called);
        params.openCreateModal = true;
        element._maybeOpenCreateOverlay(params);
        assert.isTrue(overlayOpen.called);
      });
    });

    suite('test with less then 25 groups', () => {
      setup(done => {
        groups = _.times(25, groupGenerator);

        stub('gr-rest-api-interface', {
          getGroups(num, offset) {
            return Promise.resolve(groups);
          },
        });

        element._paramsChanged(value).then(() => { flush(done); });
      });

      test('_shownGroups', () => {
        assert.equal(element._shownGroups.length, 25);
      });
    });

    suite('filter', () => {
      test('_paramsChanged', done => {
        sandbox.stub(element.$.restAPI, 'getGroups', () => {
          return Promise.resolve(groups);
        });
        const value = {
          filter: 'test',
          offset: 25,
        };
        element._paramsChanged(value).then(() => {
          assert.isTrue(element.$.restAPI.getGroups.lastCall
              .calledWithExactly('test', 25, 25));
          done();
        });
      });
    });

    suite('loading', () => {
      test('correct contents are displayed', () => {
        assert.isTrue(element._loading);
        assert.equal(element.computeLoadingClass(element._loading), 'loading');
        assert.equal(getComputedStyle(element.$.loading).display, 'block');

        element._loading = false;
        element._groups = _.times(25, groupGenerator);

        flushAsynchronousOperations();
        assert.equal(element.computeLoadingClass(element._loading), '');
        assert.equal(getComputedStyle(element.$.loading).display, 'none');
      });
    });

    suite('create new', () => {
      test('_handleCreateClicked called when create-click fired', () => {
        sandbox.stub(element, '_handleCreateClicked');
        element.$$('gr-list-view').fire('create-clicked');
        assert.isTrue(element._handleCreateClicked.called);
      });

      test('_handleCreateClicked opens modal', () => {
        const openStub = sandbox.stub(element.$.createOverlay, 'open');
        element._handleCreateClicked();
        assert.isTrue(openStub.called);
      });

      test('_handleCreateGroup called when confirm fired', () => {
        sandbox.stub(element, '_handleCreateGroup');
        element.$.createDialog.fire('confirm');
        assert.isTrue(element._handleCreateGroup.called);
      });

      test('_handleCloseCreate called when cancel fired', () => {
        sandbox.stub(element, '_handleCloseCreate');
        element.$.createDialog.fire('cancel');
        assert.isTrue(element._handleCloseCreate.called);
      });
    });
  });
</script>


text:
public class CountUp{
	public static void main(String[] args){
		for(int i = 1; i <= 10; i++){
			System.out.println(i);
		}
	}
}


text:
"""Boostbook tests

Usage: python build_docs.py [--generate-gold]
"""

import difflib, getopt, os, re, sys
import lxml.ElementInclude
from lxml import etree
from collections import defaultdict

# Globals

def usage_and_exit():
    print __doc__
    sys.exit(2)

def main(argv):
    script_directory = os.path.dirname(sys.argv[0])
    boostbook_directory = os.path.join(script_directory, "../../xsl")

    try:
        opts, args = getopt.getopt(argv, "",
            ["generate-gold"])
        if(len(args)): usage_and_exit()
    except getopt.GetoptError:
        usage_and_exit()

    generate_gold = False

    for opt, arg in opts:
        if opt == '--generate-gold':
            generate_gold = True

    # Walk the test directory

    parser = etree.XMLParser()

    try:
        boostbook_xsl = etree.XSLT(
            etree.parse(os.path.join(boostbook_directory, "docbook.xsl"), parser)
        )
    except lxml.etree.XMLSyntaxError, error:
        print "Error parsing boostbook xsl:"
        print error
        sys.exit(1)

    for root, dirs, files in os.walk(os.path.join(script_directory, 'tests')):
        success = True
        for filename in files:
            (base, ext) = os.path.splitext(filename)
            if (ext == '.xml'):
                for consistent_ids in [False, True]:
                    if not consistent_ids:
                        gold_ext = ".gold"
                    else:
                        gold_ext = ".gold2"
                    src_path = os.path.join(root, filename)
                    gold_path = os.path.join(root, base + gold_ext)
                    try:
                        if consistent_ids:
                            doc_text = run_boostbook_consistent_ids(parser, boostbook_xsl, src_path)
                        else:
                            doc_text = run_boostbook(parser, boostbook_xsl, src_path)
                    except:
                        # TODO: Need better error reporting here:
                        print "Error running boostbook for " + src_path
                        success = False
                        continue

                    if (generate_gold):
                        file = open(gold_path, 'w')
                        try:
                            file.write(doc_text)
                        finally: file.close()
                    else:
                        file = open(gold_path, 'r')
                        try:
                            gold_text = file.read()
                        finally:
                            file.close()
                        if not compare_xml(src_path, doc_text, gold_text):
                            success = False
    if not success:
        sys.exit(1)

def run_boostbook(parser, boostbook_xsl, file):
    doc = boostbook_xsl(etree.parse(file, parser))
    normalize_boostbook_ids(doc)
    return etree.tostring(doc)

def run_boostbook_consistent_ids(parser, boostbook_xsl, file):
    doc = boostbook_xsl(etree.parse(file, parser), **{
        'generate.consistent.ids': '1'
    })
    return etree.tostring(doc)

def normalize_boostbook_ids(doc):
    ids = {}
    id_bases = defaultdict(int)

    for node in doc.xpath("//*[starts-with(@id, 'id') or contains(@id, '_id')]"):
        id = node.get('id')

        if(id in ids):
            print 'Duplicate id: ' + id

        match = re.match("(.+_id|id)([-mp]?[\d_]+)((?:-bb)?)", id)
        if(match):
            # Truncate id name, as it sometimes has different lengths...
            match2 = re.match("(.*?)([^.]*?)(_?id)", match.group(1))
            base = match2.group(1) + match2.group(2)[:7] + match2.group(3)
            count = id_bases[base] + 1
            id_bases[base] = count
            ids[id] = base + str(count) + match.group(3)

    for node in doc.xpath("//*[@linkend or @id]"):
        x = node.get('linkend')
        if(x in ids): node.set('linkend', ids[x])
        x = node.get('id')
        if(x in ids): node.set('id', ids[x])

def compare_xml(file, doc_text, gold_text):
    # Had hoped to use xmldiff but it turned out to be a pain to install.
    # So instead just do a text diff.

    if (doc_text != gold_text):
        print "Error: " + file
        print
        sys.stdout.writelines(
            difflib.unified_diff(
                gold_text.splitlines(True),
                doc_text.splitlines(True)
            )
        )
        print
        print
        return False
    else:
        return True

if __name__ == "__main__":
    main(sys.argv[1:])


text:
package io.shardingsphere.api.config.strategy;

import io.shardingsphere.api.algorithm.sharding.complex.ComplexKeysShardingAlgorithm;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

/**
 * Complex sharding strategy configuration.
 *
 * @author zhangliang
 */
@RequiredArgsConstructor
@Getter
public final class ComplexShardingStrategyConfiguration implements ShardingStrategyConfiguration {

    private final String shardingColumns;

    private final ComplexKeysShardingAlgorithm shardingAlgorithm;
}


text:
	<meta charset="utf-8">

	<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="google-site-verification" content="{{ site.google_site_verification }}" />

	<title>{% if page.title %}{{ site.title }} - {{ page.title }}{% else %}{{ site.title }}{% endif %}</title>

	<meta name="description" content="{% if page.description %}{{ page.description }}{% else %}{{ page.title }}{% endif %}">
	{% if page.canonical_url == nil %}
	{% capture canonical %}{{ page.url | replace:'index.html','' | prepend: site.github.url | prepend: site.url }}{% endcapture %}
	{% else %}
	{% assign canonical = page.canonical_url %}
	{% endif %}
	<link rel="canonical" href="{{ canonical }}">

	<meta property="og:type" content="website" />
	<meta property="og:site_name" content="Just Arrived" />
	<meta property="og:url" content="{{ canonical }}" />
  {% if page.title %}<meta property="og:title" content="Just Arrived - {{ page.title }}" />{% endif %}
	<meta property="og:description" content="{% if page.description %}{{ page.description }}{% else %}{{ page.title }}{% endif %}" />
	<meta property="og:image" content="{{ site.url }}{% if page.og_image %}{{ page.og_image }}{% elsif page.list_cover %}{{ page.list_cover }}{% else %}/assets/images/just-arrived-open-graph-logo.png{% endif %}" />
  <meta property="fb:app_id" content="{{ site.fb_app_id }}"/>

  {% if site.lang == 'sv' %}<meta property="og:locale" content="sv_SE" />{% endif %}
	{% if site.lang == 'en' %}<meta property="og:locale" content="en_US" />{% endif %}
	{% if site.lang == 'ar' %}<meta property="og:locale" content="ar_AR" />{% endif %}
  {% unless site.lang == 'sv' %}<meta property="og:locale:alternate" content="sv_SE" />{% endunless %}
  {% unless site.lang == 'en' %}<meta property="og:locale:alternate" content="en_US" />{% endunless %}
  {% unless site.lang == 'ar' %}<meta property="og:locale:alternate" content="ar_AR" />{% endunless %}

	<meta name="HandheldFriendly" content="True">
	<meta name="MobileOptimized" content="320">
	<meta name="viewport" content="width=device-width, initial-scale=1"/>

	<link rel="apple-touch-icon" href="{{ "/assets/images/apple-touch-icon.png"  | prepend: site.github.url }}">
	<link rel="icon" href="/favicon.png">

	<meta name="msapplication-TileColor" content="#f01d4f">
	<meta name="msapplication-TileImage" content="{{ "/assets/images/win8-tile-icon.png" | prepend: site.github.url }}">
	<meta name="theme-color" content="#222531">

	<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,400italic,600,700' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="{{ "/assets/sass/main.css" | prepend: site.github.url }}?{{site.time | date: '%s%N'}}">


text:
package configs.testutil.instance

import com.typesafe.config.ConfigException
import configs.testutil.instance.string._
import configs.{Config, ConfigError}
import scala.util.control.NoStackTrace
import scalaprops.{Cogen, CogenState, Gen}
import scalaprops.ScalapropsScalaz._
import scalaz.{Equal, NonEmptyList, Semigroup}

object error {

  implicit lazy val configErrorSemigroup: Semigroup[ConfigError] =
    new Semigroup[ConfigError] {
      def append(e1: ConfigError, e2: => ConfigError): ConfigError = e1 + e2
    }

  implicit lazy val configErrorEqual: Equal[ConfigError] =
    Equal.equalA[ConfigError]

  private case class N(n: Int) extends ConfigException.Null(Config.empty.origin(), "p", null) with NoStackTrace

  private case class E(n: Int) extends RuntimeException(n.toString) with NoStackTrace

  implicit lazy val configErrorEntryGen: Gen[ConfigError.Entry] =
    Gen.oneOf(
      Gen[Int].map(N).map(ConfigError.NullValue(_)),
      Gen[Int].map(E).map(ConfigError.Exceptional(_)),
      Gen[String].map(ConfigError.Generic(_))
    )

  implicit lazy val configErrorEntryCogen: Cogen[ConfigError.Entry] =
    new Cogen[ConfigError.Entry] {
      def cogen[B](a: ConfigError.Entry, g: CogenState[B]): CogenState[B] =
        a match {
          case ConfigError.NullValue(N(n), _) => Cogen[Int].cogen(n * 2, g)
          case ConfigError.Exceptional(E(n), _) => Cogen[Int].cogen(n * 2 + 1, g)
          case ConfigError.Generic(m, _) => Cogen[String].cogen(m, g)
          case _ => sys.error("bug or broken")
        }
    }

  implicit lazy val configErrorGen: Gen[ConfigError] =
    Gen[NonEmptyList[ConfigError.Entry]].map(xs => ConfigError(xs.head, xs.tail.toVector))

  implicit lazy val configErrorCogen: Cogen[ConfigError] =
    Cogen[NonEmptyList[ConfigError.Entry]].contramap(e => NonEmptyList.fromSeq(e.head, e.tail))

}


text:
class MainWindow : public QMainWindow
{
  Q_OBJECT

 public :
  MainWindow(QWidget *parent=0);

 signals :
   void showMessage(QString, bool);
   void playKeyFrames(int, int, int);
   void setVolumes(QList<int>);
   void refreshVolInfo(int, VolumeInformation);
   void refreshVolInfo(int, int, VolumeInformation);
   void addView(float,
		float,
		bool, bool,
		Vec,
		Vec, Quaternion,
		float,
		QImage,
		int,
		LightingInformation,
		QList<BrickInformation>,
		Vec, Vec,
		QList<SplineInformation>,
		int, int, QString, QString, QString);
   void histogramUpdated(QImage, QImage);
   void histogramUpdated(int*);

   void dockAdded(QDockWidget*);

 protected :
   virtual void dragEnterEvent(QDragEnterEvent*);
   virtual void dropEvent(QDropEvent*);
   void closeEvent(QCloseEvent*);

 private slots :
   void on_menuFile_aboutToShow();
   void on_menuView_aboutToShow();
   void on_menuImage_Size_aboutToShow();
   void on_menuToggle_aboutToShow();
   void on_menuHelp_aboutToShow();

   void on_menuFile_aboutToHide();
   void on_menuView_aboutToHide();
   void on_menuImage_Size_aboutToHide();
   void on_menuToggle_aboutToHide();
   void on_menuHelp_aboutToHide();

   void on_actionAbout_triggered();
   void on_actionPoints_triggered();
   void on_actionPaths_triggered();
   void on_actionGrids_triggered();
   void on_actionNetwork_triggered();
   void on_actionTriset_triggered();
   void on_actionLandmarks_triggered();
   void on_actionLoad_1_Volume_triggered();
   void on_actionLoad_2_Volumes_triggered();
   void on_actionLoad_3_Volumes_triggered();
   void on_actionLoad_4_Volumes_triggered();
   void on_actionLoad_Project_triggered();
   void on_actionLoad_TFfromproject_triggered();
   void on_actionImport_Keyframes_triggered();
   void on_actionSave_InformationForDrishtiPrayog_triggered();
   void on_actionSave_Project_triggered();
   void on_actionSave_ProjectAs_triggered();
   void on_actionSave_Image_triggered();
   void on_actionSave_ImageSequence_triggered();
   void on_actionSave_Movie_triggered();
   void on_actionExit_triggered();
   void on_actionImage_Size_triggered();
   void on_actionShadowRender_triggered();
   void on_actionPerspective_triggered();
   void on_actionOrthographic_triggered();
   void on_actionRedBlue_triggered();
   void on_actionRedCyan_triggered();
   void on_actionCrosseye_triggered();
   void on_actionFor3DTV_triggered();
   void on_actionMIP_triggered();
   void on_actionStatusBar_triggered();
   void on_actionMouse_Grab_triggered();
   void on_actionSwitch_To1D_triggered();
   void on_actionEnable_Mask_triggered();
   void on_actionLinear_TextureInterpolation_triggered();
   void on_actionSpline_PositionInterpolation_triggered();
   void on_actionFlip_ImageX_triggered();
   void on_actionFlip_ImageY_triggered();
   void on_actionFlip_ImageZ_triggered();
   void on_actionBottom_Text_triggered();
   void on_actionDepthcue_triggered();
   void on_actionEmptySpaceSkip_triggered();
   void on_actionUse_dragvolume_triggered();
   void on_actionUse_dragvolumeforshadows_triggered();
   void on_actionUse_stillvolume_triggered();
   void on_actionVisibility_triggered();
   void on_actionAxes_triggered();
   void on_actionBoundingBox_triggered();

   void on_actionHiresMode_triggered();
   void on_actionNormal_triggered();
   void on_actionLow_triggered();
   void on_actionVeryLow_triggered();

   void quitDrishti();
   void changeTransferFunctionDisplay(int, QList<bool>);
   void updateComposite();
   void checkStateChanged(int, int, bool);
   void openRecentFile();
   void loadProject(const char*);
   void loadTransferFunctionsOnly(const char*);
   void saveProject(QString);
   void GlewInit();
   void loadLookupTable();
   void lightDirectionChanged(Vec);
   void applyLighting(bool);
   void applyEmissive(bool);
   void highlights(Highlights);
   void applyShadow(bool);
   void applyBackplane(bool);
   void lightDistanceOffset(float);
   void shadowBlur(float);
   void shadowScale(float);
   void shadowFOV(float);
   void shadowIntensity(float);
   void applyColoredShadow(bool);
   void shadowColorAttenuation(float, float, float);
   void backplaneShadowScale(float);
   void backplaneIntensity(float);
   void peel(bool);
   void peelInfo(int, float, float, float);
   void updateVolInfo(int);
   void updateVolInfo(int, int);
   void setVolumeNumber(int);
   void setVolumeNumber(int, int);
   void setRepeatType(int, bool);
   void updateScaling();
   void setView(Vec, Quaternion,
		QImage, float);
   void setKeyFrame(Vec, Quaternion,
		    int, float, float,
		   unsigned char*,
		   QImage);
   void moveToKeyframe(int);
   void updateTransferFunctionManager(QList<SplineInformation>);
   void updateMorph(bool);
   void updateFocus(float, float);
   void updateParameters(float, float, int, bool, bool, Vec,
			 QString,
			 int, int, QString, QString, QString);
   void updateParameters(bool, bool, Vec, QString,
			 int, int, QString, QString, QString,
			 int, bool, bool, float, bool, bool,
			 float, float, int, float);
   void changeHistogram(int);
   void resetFlipImage();
   void switchBB();
   void switchAxis();
   void searchCaption(QStringList);

   void addImageCaption(Vec);
   void sculpt(int, QList<Vec>, float, float, int);
   void fillPathPatch(QList<Vec>, int, int);
   void paintPathPatch(QList<Vec>, int, int);
   void addToCameraPath(QList<Vec>,QList<Vec>,QList<Vec>,QList<Vec>);

   void mopClip(Vec, Vec);
   void mopCrop(int);
   void reorientCameraUsingClipPlane(int);
   void saveSliceImage(int, int);
   void saveVolume();
   void maskRawVolume();
   void countIsolatedRegions();
   void getSurfaceArea();
   void getSurfaceArea(unsigned char);

   void viewProfile(int, int, QList<Vec>);
   void viewThicknessProfile(int, int, QList< QPair<Vec, Vec> >);

   void extractClip(int, int, int);
   void extractPath(int, bool, int, int);

   void addRotationAnimation(int, float, int);

   void gridStickToSurface(int, int, QList< QPair<Vec, Vec> >);

   void applyTFUndo(bool);
   void transferFunctionUpdated();

   void loadPlugin();
   void menuViewerFunction();

   void show16BitEditor(bool);

   void addDockFrame(QString, QFrame*);

   void setMeshVisible(int, bool);
   void setMeshActive(int, bool);
   void updateMeshList(QStringList);
   void updateMeshList();

 private :
   Ui::MainWindow ui;

   Volume *m_Volume;

   Viewer *m_Viewer;

   DrawHiresVolume *m_Hires;
   DrawLowresVolume *m_Lowres;

   Bricks *m_bricks;
   BricksWidget *m_bricksWidget;

   KeyFrame *m_keyFrame;
   KeyFrameEditor *m_keyFrameEditor;
   QDockWidget *m_dockKeyframe;
   QDockWidget *m_dockTF;
   QDockWidget *m_dockMesh;

   ViewsEditor *m_gallery;
   QDockWidget *m_dockGallery;

   MeshInfoWidget *m_meshInfoWidget;

   TransferFunctionContainer *m_tfContainer;
   TransferFunctionManager *m_tfManager;
   TransferFunctionEditorWidget *m_tfEditor;
   LightingWidget *m_lightingWidget;
   VolumeInformationWidget *m_volInfoWidget;
   PreferencesWidget *m_preferencesWidget;

   QList <QAction*> m_recentFileActions;

   QList<QString> m_volFiles1, m_volFiles2;
   QList<QString> m_volFiles3, m_volFiles4;

   int m_saveRotationAnimation;
   int m_sraAxis, m_sraFrames;
   float m_sraAngle;

   int m_savePathAnimation;
   Vec m_pathAnimationPrevTang;
   Vec m_pathAnimationPrevSaxis;
   Vec m_pathAnimationPrevTaxis;
   QList<Vec> m_pathAnimationPoints;
   QList<Vec> m_pathAnimationTang;
   QList<Vec> m_pathAnimationSaxis;
   QList<Vec> m_pathAnimationTaxis;
   QList<Vec> m_pathAnimationVd;
   QList<Vec> m_pathAnimationUp;

   QList<QStringList> m_pluginList;
   QStringList m_pluginDll;;

   QMap<QString, MenuViewerFncPtr> m_menuViewerFunctions;

   QAction *m_paintMeshAction;

   void initializeRecentFiles();

   void createHiresLowresWindows();

   void initTagColors();

   void loadDummyVolume(int, int, int);

   void loadVolumeFromUrls(QList<QUrl>);
   void loadVolumeRGBFromUrls(QList<QUrl>);

   void loadViewsAndKeyFrames(const char*);
   void saveViewsAndKeyFrames(const char*);

   void loadVolumeList(QList<QString>, bool);
   void loadVolume(QList<QString>);
   void loadVolumeRGB(char*);

   void loadVolume2List(QList<QString>, QList<QString>, bool);
   bool loadVolume2(QList<QString>, QList<QString>);

   void loadVolume3List(QList<QString>, QList<QString>,
			QList<QString>, bool);
   bool loadVolume3(QList<QString>, QList<QString>,
		    QList<QString>);

   void loadVolume4List(QList<QString>, QList<QString>,
			QList<QString>, QList<QString>, bool);
   bool loadVolume4(QList<QString>, QList<QString>,
		    QList<QString>, QList<QString>);

   void saveVolumeIntoProject(const char*, QString);
   int loadVolumeFromProject(const char*);

   void setTextureMemory(bool bruteforce=false);
   void loadSettings();
   void saveSettings();

   void preLoadVolume();
   void postLoadVolume();

   void updateRecentFileAction();

   void loadProjectRunKeyframesAndExit();
   bool fromStringList(QStringList, BatchJob&);
   bool fromFile(QString, BatchJob&);

   void loadSingleVolume(QStringList);

   bool haveGrid();

   void registerPlugins();
   void registerMenuViewerFunctions();

   void runPlugin(int, bool);
};

#endif


text:
package fakes

import (
	"sync"

	"github.com/cloudfoundry/bosh-init/release/resource"
)

type FakeFingerprinter struct {
	CalculateStub        func([]resource.File, []string) (string, error)
	calculateMutex       sync.RWMutex
	calculateArgsForCall []struct {
		arg1 []resource.File
		arg2 []string
	}
	calculateReturns struct {
		result1 string
		result2 error
	}
}

func (fake *FakeFingerprinter) Calculate(arg1 []resource.File, arg2 []string) (string, error) {
	fake.calculateMutex.Lock()
	fake.calculateArgsForCall = append(fake.calculateArgsForCall, struct {
		arg1 []resource.File
		arg2 []string
	}{arg1, arg2})
	fake.calculateMutex.Unlock()
	if fake.CalculateStub != nil {
		return fake.CalculateStub(arg1, arg2)
	} else {
		return fake.calculateReturns.result1, fake.calculateReturns.result2
	}
}

func (fake *FakeFingerprinter) CalculateCallCount() int {
	fake.calculateMutex.RLock()
	defer fake.calculateMutex.RUnlock()
	return len(fake.calculateArgsForCall)
}

func (fake *FakeFingerprinter) CalculateArgsForCall(i int) ([]resource.File, []string) {
	fake.calculateMutex.RLock()
	defer fake.calculateMutex.RUnlock()
	return fake.calculateArgsForCall[i].arg1, fake.calculateArgsForCall[i].arg2
}

func (fake *FakeFingerprinter) CalculateReturns(result1 string, result2 error) {
	fake.CalculateStub = nil
	fake.calculateReturns = struct {
		result1 string
		result2 error
	}{result1, result2}
}

var _ resource.Fingerprinter = new(FakeFingerprinter)


text:
package org.foxbpm.calendar.mybatis.cmd;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.foxbpm.calendar.mybatis.entity.CalendarRuleEntity;
import org.foxbpm.engine.impl.db.ListQueryParameterObject;
import org.foxbpm.engine.impl.interceptor.Command;
import org.foxbpm.engine.impl.interceptor.CommandContext;

public class GetCalendarRuleCmd implements Command<List<?>> {
	private int pageIndex;
	private int pageSize;
	private String idLike;
	private String nameLike;

	public GetCalendarRuleCmd(int pageIndex, int pageSize) {
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;
	}

	public GetCalendarRuleCmd(int pageIndex, int pageSize, String idLike) {
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;
		this.idLike = idLike;
	}

	public GetCalendarRuleCmd(int pageIndex, int pageSize, String idLike, String nameLike) {
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;
		this.idLike = idLike;
		this.nameLike = nameLike;
	}

	@SuppressWarnings("unchecked")

	public List<CalendarRuleEntity> execute(CommandContext commandContext) {
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("id", idLike);
		queryMap.put("name", nameLike);
		int firstResult = pageIndex * pageSize - pageSize;
		int maxResults = pageSize;
		ListQueryParameterObject queryParams = new ListQueryParameterObject(queryMap, firstResult, maxResults);
		return (List<CalendarRuleEntity>) commandContext.getSqlSession().selectList("selectAllCalendarRule", queryParams);
	}

}


text:
import gspread
from random import randint
from configuration import configuration
from synonym import synonym

class synonyms:

    def __init__(self):
        config = configuration("config.ini")
        self.googleUsername = config.getGoogleUsername()
        self.googlePassword = config.getGooglePassword()

    def random(self, language, page):
        googleSheets = gspread.login(self.googleUsername, self.googlePassword);
        worksheet = googleSheets.open(language).worksheet(page);
        synonyms = worksheet.get_all_values();

        numberOfSynonyms = len(synonyms) - 1
        randomSynonym = synonyms[randint(1,numberOfSynonyms)]

        return synonym(randomSynonym[0], randomSynonym[1], randomSynonym[2], randomSynonym[3], randomSynonym[4])


text:
class Cmdstan < Formula
  desc "Probabilistic programming for Bayesian inference"
  homepage "http://mc-stan.org/"
  # tag "math"
  url "https://github.com/stan-dev/cmdstan/releases/download/v2.15.0/cmdstan-2.15.0.tar.gz"
  sha256 "4334702f8d35ac00516116e49e31c6bf2099d9cbe21e880018064c4a071970ab"

  bottle do
    cellar :any_skip_relocation
    sha256 "57c86c510a5004495f6fd38ef3ab5031b8c97332a6c8ce1ace0736b4cfd24975" => :sierra
    sha256 "c730b7c19296b6ce4a9582615327d35b2978def95dce4c38e5d29f8ba5ee9e00" => :el_capitan
    sha256 "37397ae5a12e65464de876b071981390e0c60224a3f6811f4fcf140e0c509ee5" => :yosemite
  end

  depends_on "boost"
  depends_on "eigen"

  def install
    #
    # Before we build we need to change the make files since cmdstan builds more than binaries
    # into the bin dir. This is not how homebrew prefers things and we were recommended
    # by homebrew-science maintainers to change the makefiles to rather build from and to lib.
    # We need to change in 3 make files below.
    #

    # 1. We need to change make/command file so that lines with "bin/cmdstand" instead uses
    # "lib/cmdstan" and that the libstanc.a library has a lib instead of a bin path:
    inreplace "make/command" do |s|
      s.gsub! "bin/cmdstan/", "lib/cmdstan/"
      s.gsub! "bin/libstanc.a", "lib/libstanc.a"
    end

    # 2. We need to change make/libstan so that libstanc.a is referred to via a lib path instead of a
    # bin path:
    inreplace "make/libstan" do |s|
      s.gsub! "bin/libstanc.a", "lib/libstanc.a"
      s.gsub! "bin/stan/%.o", "lib/stan/%.o"
      s.gsub! "src/%.cpp=bin/%.o", "src/%.cpp=lib/%.o"
    end

    # 3. Several corresponding changes in the main makefile:
    inreplace "makefile" do |s|
      s.gsub! "LDLIBS_STANC = -Lbin", "LDLIBS_STANC = -Llib"
      s.gsub! "bin/%.o", "lib/%.o"
      s.gsub! "bin/stan/%.o :", "lib/stan/%.o :"
      s.gsub! "bin/libstanc.a", "lib/libstanc.a"
      s.gsub! "bin/%.d", "lib/%.d"
    end

    # Now we can build:
    system "make", "build"

    # And install and symlink the commands.
    bin.install "bin/stansummary"
    bin.install "bin/stanc"
    bin.install "bin/print" # Include it for now, it will be obsolete in cmdstan 3.0 but some people might still use it

    # Now install the lib dir with the built object and lib files. They are needed later when we
    # build executables for specific Stan models.
    lib.install Dir["lib/*"]

    # For the standard stan make system to work we also need the following files in prefix:
    prefix.install "src", "makefile", "make", "stan_#{version}", "examples"
  end

  test do
    system bin/"stanc", "--version"
    cp prefix/"examples/bernoulli/bernoulli.stan", testpath
    system bin/"stanc", "bernoulli.stan"
    math = prefix/"stan_#{version}/lib/stan_math_#{version}"
    libraries = File.read(math/"make/libraries")
    cvodes = libraries.match(%r{(lib\/cvodes_([0-9\.]+))\n})[1]
    ENV["CPPFLAGS"] = %W[-I#{prefix}/stan_#{version}/src
                         -I#{math} -I#{math}/#{cvodes}/include
                         -I#{Formula["eigen"].opt_include/"eigen3"}].join(" ")
    system "make", "bernoulli_model.o"
  end
end


text:
<?php defined('C5_EXECUTE') or die("Access Denied."); ?>

<?php if ($this->controller->getTask() == 'view_details') {
	$sv = CollectionVersion::get($stack, 'ACTIVE');
	?>

	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper($sv->getVersionName(), false, 'span10 offset1', false)?>

			<?php echo t('Add')?>

<?php echo t('Block')?>

<a dialog-modal="false" dialog-width="550" dialog-height="380" dialog-title="<?php echo t('Paste From Clipboard')?>" id="stackAddClipboard" href="<?php echo REL_DIR_FILES_TOOLS_REQUIRED?>/edit_area_popup.php?cID=<?php echo $stack->getCollectionID()?>&arHandle=<?php echo STACKS_AREA_NAME?>&atask=paste&addOnly=0"><?php echo t('Paste From Clipboard')?>

		<?php $cpc = new Permissions($stack); ?>

		<?php if ($cpc->canEditPageProperties()) { ?>
			<a class="btn small ccm-main-nav-edit-option"href="<?php echo $this->action('rename', $stack->getCollectionID())?>"><?php echo t('Rename')?>
		<?php } ?>

		<a class="btn small ccm-main-nav-edit-option" dialog-width="640" dialog-height="340" id="stackVersions" dialog-title="<?php echo t('Version History')?>" href="<?php echo REL_DIR_FILES_TOOLS_REQUIRED?>/versions.php?rel=SITEMAP&cID=<?php echo $stack->getCollectionID()?>"><?php echo t('Version History')?>

		<?php $cpc = new Permissions($stack); ?>

		<?php if ($cpc->canEditPagePermissions() && PERMISSIONS_MODEL == 'advanced') { ?>
			<a class="btn small ccm-main-nav-edit-option" dialog-width="580" dialog-append-buttons="true" dialog-height="420" dialog-title="<?php echo t('Stack Permissions')?>" id="stackPermissions" href="<?php echo REL_DIR_FILES_TOOLS_REQUIRED?>/edit_area_popup.php?cID=<?php echo $stack->getCollectionID()?>&arHandle=<?php echo STACKS_AREA_NAME?>&atask=groups"><?php echo t('Permissions')?>
		<?php } ?>

		<?php if ($cpc->canDeletePage()) { ?>
			<a class="btn ccm-button-v2-right small ccm-main-nav-edit-option error" href="javascript:void(0)" onclick="if (confirm('<?php echo t('Are you sure you want to remove this stack?')?>')) { window.location.href='<?php echo $this->url('/dashboard/blocks/stacks/', 'delete', $stack->getCollectionID(), Loader::helper('validation/token')->generate('delete'))?>' }"><?php echo t('Delete Stack')?>
		<?php } ?>

		<?php if ($cpc->canMoveOrCopyPage()) { ?>
			<a class="btn ccm-button-v2-right small ccm-main-nav-edit-option" href="<?php echo $this->action('duplicate', $stack->getCollectionID())?>" style="margin-right: 4px;"><?php echo t('Duplicate Stack')?>
		<?php } ?>

		<?php
		$hasPendingPageApproval = false;
		$workflowList = PageWorkflowProgress::getList($stack);
		foreach($workflowList as $wl) {
			$wr = $wl->getWorkflowRequestObject();
			$wrk = $wr->getWorkflowRequestPermissionKeyObject();
			if ($wrk->getPermissionKeyHandle() == 'approve_page_versions') {
				$hasPendingPageApproval = true;
				break;
			}
		}

		if (!$hasPendingPageApproval) {
			$vo = $stack->getVersionObject();
			if ($cpc->canApprovePageVersions()) {
				$publishTitle = t('Approve Changes');
				$pk = PermissionKey::getByHandle('approve_page_versions');
				$pk->setPermissionObject($stack);
				$pa = $pk->getPermissionAccessObject();
				if (is_object($pa) && count($pa->getWorkflows()) > 0) {
					$publishTitle = t('Submit to Workflow');
				}

				$token = '&' . Loader::helper('validation/token')->getParameter(); ?>
				<a style="margin-right: 8px; <?php if ($vo->isApproved()) { ?> display: none; <?php } ?>" href="javascript:void(0)" onclick="window.location.href='<?php echo DIR_REL . "/" . DISPATCHER_FILENAME . "?cID=" . $stack->getCollectionID() . "&ctask=approve-recent" . $token?>'" class="btn btn-success small ccm-main-nav-edit-option ccm-button-v2-right"><?php echo $publishTitle?>
			<?php
			}
		}
		?>

		<?php
			if (count($workflowList) > 0) { ?>

			<?php }

		$a = Area::get($stack, STACKS_AREA_NAME);
		$bv = new BlockView();
		$bv->renderElement('block_area_header', array('a' => $a));
		$bv->renderElement('block_area_header_view', array('a' => $a));

		foreach($blocks as $b) {
			$bv = new BlockView();
			$bv->setAreaObject($a);
			$p = new Permissions($b);
			if ($p->canViewBlock()) {
				$bv->renderElement('block_controls', array( 'a' => $a, 'b' => $b, 'p' => $p ));
				$bv->renderElement('block_header', array( 'a' => $a, 'b' => $b, 'p' => $p ));
				$bv->render($b);
				$bv->renderElement('block_footer');
			}
		}
		$bv->renderElement('block_area_footer_view', array('a' => $a));
		print '
'; // instead  of loading block area footer view
	?>

	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(false); ?>

<?php } else if ($this->controller->getTask() == 'duplicate') {
	$sv = CollectionVersion::get($stack, 'ACTIVE');
	?>

	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(t("Duplicate %s", $sv->getVersionName()), false, 'span10 offset1', false)?>
	<form name="duplicate_form" action="<?php echo $this->action('duplicate', $stack->getCollectionID())?>" method="POST">
		<?php echo Loader::helper("validation/token")->output('duplicate_stack')?>

				<?php echo $form->label('stackName', t("Name"))?>

					<?php echo $form->text('stackName')?>

			<?php echo $interface->button(t("Cancel"), $this->action('view_details', $stack->getCollectionID()), 'left')?>
			<?php echo $interface->submit(t("Duplicate Stack"), 'duplicate_form', 'right', 'primary')?>

	</form>
	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(false);?>

<?php } else if ($this->controller->getTask() == 'rename') {
	$sv = CollectionVersion::get($stack, 'ACTIVE');
	?>

	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(t("Rename %s", $sv->getVersionName()), false, 'span10 offset1', false)?>
	<form name="duplicate_form" action="<?php echo $this->action('rename', $stack->getCollectionID())?>" method="POST">
		<?php echo Loader::helper("validation/token")->output('rename_stack')?>

				<?php echo $form->label('stackName', t("Name"))?>

					<?php echo $form->text('stackName', $stack->getStackName())?>

			<?php echo $interface->button(t("Cancel"), $this->action('view_details', $stack->getCollectionID()), 'left')?>
			<?php echo $interface->submit(t("Rename"), 'duplicate_form', 'right', 'primary')?>

	</form>
	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(false);?>

<?php } else { ?>

	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(t('Stacks'), t('Stacks give you a central place to stash blocks, where you can control their order, permissions, and even version them.

Add stacks to your site and you can update them in one place.'), 'span10 offset1');?>

<?php echo t('Global Areas')?>

	<?php
	if (count($globalareas) > 0) {
		foreach($globalareas as $st) {
			$sv = CollectionVersion::get($st, 'ACTIVE');
			?>

			<div class="ccm-stack ccm-group" id="stID_<?php echo $st->getCollectionID()?>">
				<?php if ($canMoveStacks) { ?><img class="ccm-group-sort" src="<?php echo ASSETS_URL_IMAGES?>/icons/up_down.png" width="14" height="14" /><?php } ?>
				<a href="<?php echo $this->url('/dashboard/blocks/stacks', 'view_details', $st->getCollectionID())?>"><?php echo $sv->getVersionName()?>

		<?php
		}
	} else {
		print '
';
		print t('No global areas created yet.');
		print '
';
	}
	?>

<?php echo t('Other Stacks')?>

	<?php
	if (count($useradded) > 0) {
		foreach($useradded as $st) {
			$sv = CollectionVersion::get($st, 'ACTIVE');
			?>

			<div class="ccm-stack ccm-group" id="stID_<?php echo $st->getCollectionID()?>">
				<?php if ($canMoveStacks) { ?><img class="ccm-group-sort" src="<?php echo ASSETS_URL_IMAGES?>/icons/up_down.png" width="14" height="14" /><?php } ?>
				<a href="<?php echo $this->url('/dashboard/blocks/stacks', 'view_details', $st->getCollectionID())?>"><?php echo $sv->getVersionName()?>

		<?php
		}
	} else {
		print '
';
		print t('No stacks have been added.');
		print '
';
	}
	?>

<?php echo t('Add Stack')?>

		<form method="post" class="form-stacked" style="padding-left: 0px" action="<?php echo $this->action('add_stack')?>">
		<?php echo Loader::helper("validation/token")->output('add_stack')?>

			<?php echo Loader::helper("form")->label('stackName', t('Name'))?>

				<?php echo Loader::helper('form')->text('stackName')?>
				<?php echo Loader::helper("form")->submit('add', t('Add'))?>

		</form>

	<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper()?>

<?php } ?>


text: This matlab script creates an autocad script and saves it to file.


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:background="#FFFFFF"
    android:orientation="vertical" >
   <TextView
       android:id="@+id/text"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       />

</LinearLayout>


text:
package org.uiautomation.ios.server.utils;

import java.util.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * JSTemplate implements stylized substitution for JavaScript code templates. For example, from SetTimeoutNHandler:
 *
 *   private static final JSTemplate template = new JSTemplate(
 *       "UIAutomation.setTimeout('%:type$s',%:ms$d);" +
 *       "UIAutomation.createJSONResponse('%:sessionId$s',0,'')",
 *       "type", "ms", "sessionId");
 *   ...
 *   protected String generateScript(String type, int timeout, String sessionId) {
 *     return template.generate(type, timeout, sessionId);
 *   }
 *
 * The JSTemplate constructor substitutes the named parameters with indices such that they can later be used for
 * formatted printing. Note that for e.g. "type", the pattern matched during substitution is "%:type$"; the leading and
 * trailing character are critical to proper interaction with Formatter.Internally, the template for the above example
 * becomes:
 *
 *   "UIAutomation.template('%1$s',%2$d);" +
 *   "UIAutomation.createJSONResponse('%3$s',0,'')"
 *
 * The arguments passed to the generate() method are passed directly on to Formatter.format().
 */
public class JSTemplate {

  private static final Logger log = Logger.getLogger(JSTemplate.class.getName());

  private final String format;
  private final int numArgs;

  public JSTemplate(String template, String... args) {
    String s = template;
    for (int i = 0; i < args.length; i++) {
      String arg = args[i];
      // Convert e.g. "%:arg$s' to "%1$s".
      String sPrev = s;
      s = s.replaceAll(String.format("%%:%s[$]", arg), String.format("%%%d\\$", i+1));
      if (s.equals(sPrev)) {
        throw new IllegalArgumentException(String.format("No substitution occurred for \"%s\"", arg));
      }
    }
    if (s.matches("%:[A-Za-z_][A-Za-z_0-9]+[$]")) {
      throw new IllegalArgumentException("Not all template parameters were substituted");
    }
    this.format = s;
    this.numArgs = args.length;
  }

  public String generate(Object... args) {
    // Formatter silently ignores excess arguments. The following check requires strict arity equality to catch all
    // mismatches.
    if (args.length != numArgs) {
      throw new IllegalArgumentException(String.format("Argument count mismatch (%d should be %d)",
          args.length, numArgs));
    }
    String js = new Formatter().format(format, args).toString();
    if (log.isLoggable(Level.FINE))
      log.fine(String.format("JS: %s", js));
    return js;
  }
}


text:
Sitemap
-------

This plugin generates plain-text or XML sitemaps. You can use the ``SITEMAP``
variable in your settings file to configure the behavior of the plugin.

The ``SITEMAP`` variable must be a Python dictionary and can contain these keys:

- ``format``, which sets the output format of the plugin (``xml`` or ``txt``)

- ``priorities``, which is a dictionary with three keys:

  - ``articles``, the priority for the URLs of the articles and their
    translations

  - ``pages``, the priority for the URLs of the static pages

  - ``indexes``, the priority for the URLs of the index pages, such as tags,
     author pages, categories indexes, archives, etc...

  All the values of this dictionary must be decimal numbers between ``0`` and ``1``.

- ``changefreqs``, which is a dictionary with three items:

  - ``articles``, the update frequency of the articles

  - ``pages``, the update frequency of the pages

  - ``indexes``, the update frequency of the index pages

  Valid frequency values are ``always``, ``hourly``, ``daily``, ``weekly``, ``monthly``,
  ``yearly`` and ``never``.

You can exclude URLs from being included in the sitemap via regular expressions.
For example, to exclude all URLs containing ``tag/`` or ``category/`` you can
use the following ``SITEMAP`` setting.

.. code-block:: python

    SITEMAP = {
        'exclude': ['tag/', 'category/']
    }

If a key is missing or a value is incorrect, it will be replaced with the
default value.

You can also exclude an individual URL by adding metadata to it setting ``private``
to ``True``.

The sitemap is saved in ``<output_path>/sitemap.<format>``.

.. note::
   ``priorities`` and ``changefreqs`` are information for search engines.
   They are only used in the XML sitemaps.
   For more information: <http://www.sitemaps.org/protocol.html#xmlTagDefinitions>

**Example**

Here is an example configuration (it's also the default settings):

.. code-block:: python
    # Where your plug-ins reside
    PLUGIN_PATHS = ['/where/you/cloned/it/pelican-plugins/', ]
    PLUGINS=['sitemap',]

    SITEMAP = {
        'format': 'xml',
        'priorities': {
            'articles': 0.5,
            'indexes': 0.5,
            'pages': 0.5
        },
        'changefreqs': {
            'articles': 'monthly',
            'indexes': 'daily',
            'pages': 'monthly'
        }
    }


text:
/* Dooba Firmware - avr8
 * HTTP Library
 *
 * by Eresse <eresse@dooba.io>
 */

#ifndef	__HTTP_H
#define	__HTTP_H

// External Includes
#include <stdint.h>
#include <stdarg.h>

// Port
#define	HTTP_PORT										80

// Commands
#define	HTTP_CMD_UNK									"???"
#define	HTTP_CMD_GET									"GET"
#define	HTTP_CMD_HEAD									"HEAD"
#define	HTTP_CMD_POST									"POST"
#define	HTTP_CMD_PUT									"PUT"
#define	HTTP_CMD_DELETE									"DELETE"
#define	HTTP_CMD_OPTIONS								"OPTIONS"
#define	HTTP_CMD_PATCH									"PATCH"

// Command Codes
#define	HTTP_CMD_CODE_NONE								0x00
#define	HTTP_CMD_CODE_GET								0x01
#define	HTTP_CMD_CODE_HEAD								0x02
#define	HTTP_CMD_CODE_POST								0x03
#define	HTTP_CMD_CODE_PUT								0x04
#define	HTTP_CMD_CODE_DELETE							0x05
#define	HTTP_CMD_CODE_OPTIONS							0x06
#define	HTTP_CMD_CODE_PATCH								0x07

// Responses
#define	HTTP_RESPONSE_CONTINUE							"Continue"
#define	HTTP_RESPONSE_OK								"OK"
#define	HTTP_RESPONSE_FOUND								"Found"
#define	HTTP_RESPONSE_UNAUTHORIZED						"Unauthorized"
#define	HTTP_RESPONSE_NOTFOUND							"Not Found"
#define	HTTP_RESPONSE_UNPROCESSABLE						"Unprocessable Entity"
#define	HTTP_RESPONSE_SRVERROR							"Server Error"

// Response Codes
#define	HTTP_RES_CONTINUE								100
#define	HTTP_RES_OK										200
#define	HTTP_RES_FOUND									302
#define	HTTP_RES_UNAUTHORIZED							401
#define	HTTP_RES_NOTFOUND								404
#define	HTTP_RES_UNPROCESSABLE							422
#define	HTTP_RES_SRVERROR								500

// Basic Delimiter
#define	HTTP_DELIM										" "

// URL Arguments Delimiter
#define	HTTP_URL_ARGS_DELIM								"?"

// Argument Delimiter
#define	HTTP_ARG_DELIM									"&"

// Argument Value Delimiter
#define	HTTP_ARGVAL_DELIM								"="

// Header Value Delimiter
#define	HTTP_HEADER_VAL_DELIM							": "

// Common Headers
#define	HTTP_HEADER_HOST								"Host"
#define	HTTP_HEADER_SERVER								"Server"
#define	HTTP_HEADER_CONTENTLENGTH						"Content-Length"
#define	HTTP_HEADER_CONTENTTYPE							"Content-Type"
#define	HTTP_HEADER_CONNECTION							"Connection"
#define	HTTP_HEADER_COOKIE								"Cookie"
#define	HTTP_HEADER_ACCEPT								"Accept"
#define	HTTP_HEADER_LOCATION							"Location"
#define	HTTP_HEADER_AUTHORIZATION						"Authorization"
#define	HTTP_HEADER_USERAGENT							"User-Agent"
#define	HTTP_HEADER_EXPECT								"Expect"
#define	HTTP_HEADER_HSTS								"Strict-Transport-Security"

// Header - Content Types
#define	HTTP_HEADER_CONTENTTYPE_TEXTPLAIN				"text/plain"
#define	HTTP_HEADER_CONTENTTYPE_APPJSON					"application/json"
#define	HTTP_HEADER_CONTENTTYPE_APPFORMURL				"application/x-www-form-urlencoded"

// Header - Connection Types
#define	HTTP_HEADER_CONNECTIONTYPE_CLOSE				"close"

// Max URL Arguments
#ifndef	HTTP_URL_MAX_ARGS
#define	HTTP_URL_MAX_ARGS								10
#endif

// Max Headers
#ifndef	HTTP_HEADERS_MAX
#define	HTTP_HEADERS_MAX								20
#endif

// Max Form Fields
#ifndef	HTTP_FORM_FIELDS_MAX
#define	HTTP_FORM_FIELDS_MAX							30
#endif

// HTTP Argument Structure
struct http_arg
{
	// Name
	uint16_t name_off;
	uint16_t name_len;

	// Value
	uint16_t val_off;
	uint16_t val_len;
};

// HTTP URL Structure
struct http_url
{
	// URL
	uint8_t url_off;
	uint16_t url_len;

	// Object
	uint16_t obj_len;

	// Arguments
	uint16_t args_off;
	uint16_t args_len;
	struct http_arg args[HTTP_URL_MAX_ARGS];
	uint8_t arg_count;
};

// HTTP Request Structure
struct http_req
{
	// Command
	uint8_t cmd_len;
	uint8_t cmd_code;

	// Version
	uint16_t ver_off;
	uint8_t ver_len;

	// Body
	uint16_t body_off;
	uint16_t body_len;

	// URL
	struct http_url url;

	// Headers
	struct http_arg headers[HTTP_HEADERS_MAX];
	uint8_t header_count;

	// Form Fields
	struct http_arg fields[HTTP_FORM_FIELDS_MAX];
	uint8_t field_count;
};

// HTTP Response
struct http_res
{
	// Version
	uint8_t ver_len;

	// Status
	uint8_t status_off;
	uint16_t status_len;
	uint16_t status_txt_off;
	uint16_t status_txt_len;
	uint16_t status;

	// Body
	uint16_t body_off;
	uint16_t body_len;

	// Headers
	struct http_arg headers[HTTP_HEADERS_MAX];
	uint8_t header_count;
};

// HTTP Argument Splitter Structure
struct http_arg_splitter
{
	// Args
	struct http_arg *args;

	// Size
	uint8_t size;

	// Count
	uint8_t count;
};

// URL Encode Printer Info Structure
struct http_urlenc_printer_info
{
	// Buffer
	char *buf;

	// Buffer Size
	uint16_t buf_l;

	// Position
	uint16_t buf_p;

	// Overflow
	uint8_t overflow;
};

// Split HTTP Request
extern uint8_t http_split_req(char *s, uint16_t l, struct http_req *r);

// Split HTTP Response
extern uint8_t http_split_res(char *s, uint16_t l, struct http_res *r);

// Split HTTP URL
extern uint8_t http_split_url(char *s, uint8_t off, uint16_t l, struct http_url *u);

// Split HTTP Headers
extern void http_split_head(char *s, uint16_t off, uint16_t l, char *line_delim, struct http_arg *h, uint8_t size, uint8_t *header_count);

// Split HTTP Form Content
extern void http_split_form(char *s, uint16_t off, uint16_t l, struct http_arg *args, uint8_t size, uint8_t *field_count);

// Split Generic Arguments
extern void http_split_args(char *s, uint16_t off, uint16_t l, uint16_t *p, struct http_arg *args, uint8_t size, uint8_t *count);

// Generic Argument Splitter
extern void http_arg_splitter(struct http_arg_splitter *s, uint16_t name, uint16_t name_l, uint16_t value, uint16_t value_l);

// Get Argument from List
extern struct http_arg *http_get_arg(char *s, char *name, struct http_arg *args, uint8_t count);

// Set Argument
extern void http_set_arg(uint16_t name, uint16_t name_l, uint16_t val, uint16_t val_l, struct http_arg *args, uint8_t size, uint8_t *arg_count);

// Code to Command
extern char *http_code2cmd(uint8_t code);

// Command to Code
extern uint8_t http_cmd2code(char *cmd, uint8_t len);

// Code to Response
extern char *http_code2resp(uint16_t code);

// URL Encode
extern int16_t http_urlenc(char *buf, uint16_t buf_l, char *s);

// URL Encode - Fixed Length
extern int16_t http_urlenc_n(char *buf, uint16_t buf_l, char *s, uint16_t l);

// URL Encode - Format String
extern int16_t http_urlenc_f(char *buf, uint16_t buf_l, char *fmt, ...);

// URL Encode - Variable Argument List
extern int16_t http_urlenc_v(char *buf, uint16_t buf_l, char *fmt, va_list args, va_list *args_out);

// URL Encode Printer
extern void http_urlenc_printer(struct http_urlenc_printer_info *i, uint8_t x);

// URL Decode
extern int16_t http_urldec(char *buf, uint16_t buf_l, char *s, uint16_t l);

#endif


text:
/**
 */
package com.rockwellcollins.atc.resolute.resolute;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EObject;

import org.osate.aadl2.AnnexLibrary;

/**
 *
 * A representation of the model object 'Library'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link com.rockwellcollins.atc.resolute.resolute.ResoluteLibrary#getDefinitions Definitions}

 *

 *
 * @see com.rockwellcollins.atc.resolute.resolute.ResolutePackage#getResoluteLibrary()
 * @model
 * @generated
 */
public interface ResoluteLibrary extends EObject, AnnexLibrary
{
  /**
   * Returns the value of the 'Definitions' containment reference list.
   * The list contents are of type {@link com.rockwellcollins.atc.resolute.resolute.Definition}.
   *
   *

   * If the meaning of the 'Definitions' containment reference list isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Definitions' containment reference list.
   * @see com.rockwellcollins.atc.resolute.resolute.ResolutePackage#getResoluteLibrary_Definitions()
   * @model containment="true"
   * @generated
   */
  EList<Definition> getDefinitions();

} // ResoluteLibrary


text:
{-# LANGUAGE OverloadedStrings     #-}

module Mail
    ( sendBuiltMail
    , buildVerificationMail
    , buildInvitationMail
    )
where

import           Data.Text         (Text, unpack)
import           Formatting        ((%), stext, format)
import qualified Network.Mail.SMTP as Smtp
import qualified Network.Mail.Mime as Mime
import           Network.Socket    (PortNumber)

import qualified Config            as Cfg
import           Model.CoreTypes   (Email)

sendMail :: Cfg.SmtpConfig -> Mime.Mail -> IO ()
sendMail cfg = Smtp.sendMailWithLogin' host port user password
  where host     = unpack $ Cfg.host cfg
        port     = fromInteger $ Cfg.smtpPort cfg :: PortNumber
        user     = unpack $ Cfg.username cfg
        password = unpack $ Cfg.password cfg

sendBuiltMail :: Cfg.FlatrCfg -> Email
              -> (Cfg.SmtpConfig -> Email -> Mime.Mail)
              -> IO ()
sendBuiltMail cfg emailAddress builder
  | (Just smtpConfig) <- Cfg.smtpConfig cfg =
      sendMail smtpConfig $ builder smtpConfig emailAddress
  | otherwise = putStrLn "No smtp config was set so no verification email was sent"

buildMail :: Text
          -> Maybe Text
          -> Mime.Part
          -> Cfg.SmtpConfig
          -> Text
          -> Mime.Mail
buildMail subject username body smtpConfig toAddress =
  Smtp.simpleMail from to [] [] subject [body]
  where from = Smtp.Address (Just "Flatr Admin") (Cfg.sender smtpConfig)
        to = [Smtp.Address username toAddress]

buildVerificationMail :: Text -> Text -> Cfg.SmtpConfig -> Email -> Mime.Mail
buildVerificationMail code username =
  buildMail subject (Just username) body
  where subject = "Flatr Verification"
        body = Smtp.plainTextPart $ format
                   ( "Please confirm your email adress by visiting this URL"
                     % stext % "/#signup?code=" % stext % "&serverUrl=" % stext
                   ) frontendUrl code serverUrl
        serverUrl = "https://localhost:8080" :: Text
        frontendUrl = "https://localhost:8000" :: Text

buildInvitationMail :: Text -> Cfg.SmtpConfig -> Email -> Mime.Mail
buildInvitationMail code =
  buildMail subject Nothing body
  where subject = "Flatr Invitation"
        body = Smtp.plainTextPart $ format
                   ( "You are invited to join Flatr, to accept visit this URL"
                     % stext % "/#signup?code=" % stext % "&serverUrl=" % stext
                   ) frontendUrl code serverUrl
        serverUrl = "https://localhost:8080" :: Text
        frontendUrl = "https://localhost:8000" :: Text


text:
using UnityEngine;

namespace Atlas.Examples
{
    public sealed class Example_DebugDraw : MonoBehaviour
    {
        private void Update()
        {
            // Draws a billboarded string of text for 1 frame
            DebugDraw.DrawText( Vector3.zero,
                                "Hi, how are ya?",
                                Color.cyan,
                                2f,
                                AnchorPosition.Center );
        }

        private void OnDisable()
        {
            // Draws a billboarded string of text for 3 seconds
            DebugDraw.DrawText( Vector3.zero,
                                "Later, gator",
                                Color.red,
                                1f,
                                3f,
                                AnchorPosition.TopRight );
        }
    }
}


text:
package run

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/spf13/cobra"

	"github.com/kubernetes-incubator/apiserver-builder/cmd/apiserver-boot/boot/build"
	"github.com/kubernetes-incubator/apiserver-builder/cmd/apiserver-boot/boot/util"
)

var localCmd = &cobra.Command{
	Use:   "local",
	Short: "run the etcd, apiserver and controller-manager",
	Long:  `run the etcd, apiserver and controller-manager`,
	Example: `# Regenerate code and build binaries.  Then run them locally.
apiserver-boot run local

# Check the api versions of the locally running server
kubectl --kubeconfig kubeconfig api-versions

# Run locally without rebuilding
apiserver-boot run local --build=false

# Create an instance and fetch it
nano -w samples/<type>.yaml
kubectl --kubeconfig kubeconfig apply -f samples/<type>.yaml
kubectl --kubeconfig kubeconfig get <type>`,
	Run: RunLocal,
}

var etcd string
var config string
var printapiserver bool
var printcontrollermanager bool
var printetcd bool
var buildBin bool

var server string
var controllermanager string
var toRun []string
var disableDelegatedAuth bool
var securePort int32

func AddLocal(cmd *cobra.Command) {
	localCmd.Flags().StringSliceVar(&toRun, "run", []string{"etcd", "apiserver", "controller-manager"}, "path to apiserver binary to run")
	localCmd.Flags().BoolVar(&disableDelegatedAuth, "disable-delegated-auth", true, "If true, disable delegated auth in the apiserver with --delegated-auth=false.")

	localCmd.Flags().StringVar(&server, "apiserver", "", "path to apiserver binary to run")
	localCmd.Flags().StringVar(&controllermanager, "controller-manager", "", "path to controller-manager binary to run")
	localCmd.Flags().StringVar(&etcd, "etcd", "", "if non-empty, use this etcd instead of starting a new one")

	localCmd.Flags().StringVar(&config, "config", "kubeconfig", "path to the kubeconfig to write for using kubectl")

	localCmd.Flags().BoolVar(&printapiserver, "print-apiserver", true, "if true, pipe the apiserver stdout and stderr")
	localCmd.Flags().BoolVar(&printcontrollermanager, "print-controller-manager", true, "if true, pipe the controller-manager stdout and stderr")
	localCmd.Flags().BoolVar(&printetcd, "printetcd", false, "if true, pipe the etcd stdout and stderr")
	localCmd.Flags().BoolVar(&buildBin, "build", true, "if true, build the binaries before running")

	localCmd.Flags().Int32Var(&securePort, "secure-port", 9443, "Secure port from apiserver to serve requests")

	localCmd.Flags().BoolVar(&bazel, "bazel", false, "if true, use bazel to build.  May require updating build rules with gazelle.")
	localCmd.Flags().BoolVar(&gazelle, "gazelle", false, "if true, run gazelle before running bazel.")
	localCmd.Flags().BoolVar(&generate, "generate", true, "if true, generate code before building")

	cmd.AddCommand(localCmd)
}

func RunLocal(cmd *cobra.Command, args []string) {
	if buildBin {
		build.Bazel = bazel
		build.Gazelle = gazelle
		build.GenerateForBuild = generate
		build.RunBuildExecutables(cmd, args)
	}

	WriteKubeConfig()

	r := map[string]interface{}{}
	for _, s := range toRun {
		r[s] = nil
	}

	// Start etcd
	if _, f := r["etcd"]; f {
		etcd = "http://localhost:2379"
		etcdCmd := RunEtcd()
		defer etcdCmd.Process.Kill()
		time.Sleep(time.Second * 2)
	}

	// Start apiserver
	if _, f := r["apiserver"]; f {
		go RunApiserver()
		time.Sleep(time.Second * 2)
	}

	// Start controller manager
	if _, f := r["controller-manager"]; f {
		go RunControllerManager()
	}

	fmt.Printf("to test the server run `kubectl --kubeconfig %s api-versions`\n", config)
	select {} // wait forever
}

func RunEtcd() *exec.Cmd {
	etcdCmd := exec.Command("etcd")
	if printetcd {
		etcdCmd.Stderr = os.Stderr
		etcdCmd.Stdout = os.Stdout
	}

	fmt.Printf("%s\n", strings.Join(etcdCmd.Args, " "))
	go func() {
		err := etcdCmd.Run()
		defer etcdCmd.Process.Kill()
		if err != nil {
			log.Fatalf("Failed to run etcd %v", err)
			os.Exit(-1)
		}
	}()
	return etcdCmd
}

func RunApiserver() *exec.Cmd {
	if len(server) == 0 {
		server = "bin/apiserver"
	}

	flags := []string{
		fmt.Sprintf("--etcd-servers=%s", etcd),
		fmt.Sprintf("--secure-port=%v", securePort),
	}

	if disableDelegatedAuth {
		flags = append(flags, "--delegated-auth=false")
	}

	apiserverCmd := exec.Command(server,
		flags...,
	)
	fmt.Printf("%s\n", strings.Join(apiserverCmd.Args, " "))
	if printapiserver {
		apiserverCmd.Stderr = os.Stderr
		apiserverCmd.Stdout = os.Stdout
	}

	err := apiserverCmd.Run()
	if err != nil {
		defer apiserverCmd.Process.Kill()
		log.Fatalf("Failed to run apiserver %v", err)
		os.Exit(-1)
	}

	return apiserverCmd
}

func RunControllerManager() *exec.Cmd {
	if len(controllermanager) == 0 {
		controllermanager = "bin/controller-manager"
	}
	controllerManagerCmd := exec.Command(controllermanager,
		fmt.Sprintf("--kubeconfig=%s", config),
	)
	fmt.Printf("%s\n", strings.Join(controllerManagerCmd.Args, " "))
	if printcontrollermanager {
		controllerManagerCmd.Stderr = os.Stderr
		controllerManagerCmd.Stdout = os.Stdout
	}

	err := controllerManagerCmd.Run()
	if err != nil {
		defer controllerManagerCmd.Process.Kill()
		log.Fatalf("Failed to run controller-manager %v", err)
		os.Exit(-1)
	}

	return controllerManagerCmd
}

func WriteKubeConfig() {
	// Write a kubeconfig
	dir, err := os.Getwd()
	if err != nil {
		log.Fatalf("Cannot get working directory %v", err)
		os.Exit(-1)
	}
	path := filepath.Join(dir, "apiserver.local.config", "certificates", "apiserver")
	util.WriteIfNotFound(config, "kubeconfig-template", configTemplate, ConfigArgs{Path: path, Port: fmt.Sprintf("%v", securePort)})
}

type ConfigArgs struct {
	Path string
	Port string
}

var configTemplate = `
apiVersion: v1
clusters:
- cluster:
    certificate-authority: {{ .Path }}.crt
    server: https://localhost:{{ .Port }}
  name: apiserver
contexts:
- context:
    cluster: apiserver
    user: apiserver
  name: apiserver
current-context: apiserver
kind: Config
preferences: {}
users:
- name: apiserver
  user:
    client-certificate: {{ .Path }}.crt
    client-key: {{ .Path }}.key
`


text:
function Test-DayProperties {

<# MIT License

    Copyright (c) 2017 Kirill Nikolaev

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
#>

<#
.SYNOPSIS
    Tests the given date against different conditions.

.DESCRIPTION
    The function helps you to detect if today is the third Tuesday in a month, if the date belongs to some quarter, if today is the last day of a month etc.

.PARAMETER Date
    The date object which you are testing. By default, the current date/time.

.PARAMETER DayOfWeek
    Use to test if the day is the defined day in a week (Mon - 1, Tue - 2, Wed - 3 etc).

.PARAMETER NumberInMonth
    Use to detect if the day is the specified number of the day type defined in the DayOfWeek parameter.

.PARAMETER EndOfMonth
    Use to detect if the given day is the last day of the month.

.PARAMETER Quarter
    Use to detect if the given day is belongs to the specified quarter.

.PARAMETER QuarterType
    Use to detect if the given day is the start or the end of the specified quarter.

.PARAMETER Last
    Use to detect if the given day is the last day of some kind in the given month. If the DayOfWeek parameter is omitted, the kind of day is extracted from the Date parameter, otherwise — DayOfWeek is used.

.EXAMPLE
    Test-DayProperties -DayOfWeek 2 -NumberInMonth 2
    Tests if the current day is the second Tuesday in this month.

.EXAMPLE
    Test-DayProperties -Date $Date -DayOfWeek 7 -Last
    Tests if the date in the $Date object is the last Sunday in the month.

.EXAMPLE
    Test-DayProperties -Last
    Tests if today is the last day of its kind in the month.

.EXAMPLE
    Test-DayProperties -EndOfMonth
    Tests if today is the last day of the month.

.EXAMPLE
    Test-DayProperties -Date $Date -Quarter 3 -QuarterType End
    Tests if the date in the $Date object is the end (the last day) of the 3rd quarter.

.EXAMPLE
    Test-DayProperties -QuarterType Start
    Tests if today is the beginning of a quarter.

.EXAMPLE
    Test-DayProperties $Date -Quarter 1
    Tests if the date in the $Date object belonngs to the 1st quarter.

.INPUTS
    [DateTime]

.OUTPUTS
    [boolean]

.NOTES
    Author: Kirill Nikolaev
    Twitter: @exchange12rocks
    Web-site: https://exchange12rocks.org
    GitHub: https://github.com/exchange12rocks

.LINK
    https://exchange12rocks.org/2017/05/29/function-to-test-a-date-against-different-conditions

.LINK
    https://github.com/exchange12rocks/PS/tree/master/Test-DayProperties

#>

#Requires -Version 3.0

    [CmdletBinding(
        DefaultParametersetName='Default'
    )]
    [OutputType([boolean])]
    Param (
        [Parameter(ParameterSetName='Default', Position = 0)]
        [Parameter(ParameterSetName='Quarter', Position = 0)]
        [Parameter(ParameterSetName='QuarterType', Position = 0)]
        [Parameter(ParameterSetName='EndOfMonth', Position = 0)]
        [Parameter(ParameterSetName='Last', Position = 0)]
        [ValidateNotNullorEmpty()]
        [DateTime]$Date = (Get-Date),

        [Parameter(ParameterSetName='Default', Mandatory)]
        [Parameter(ParameterSetName='Last')]
        [ValidateRange(1,7)]
        [int]$DayOfWeek,

        [Parameter(ParameterSetName='Default', Mandatory)]
        [ValidateRange(1,5)] # It's impossible to have more that 5 weeks in a month (on Earth)
        [int]$NumberInMonth,

        [Parameter(ParameterSetName='EndOfMonth')]
        [switch]$EndOfMonth,

        [Parameter(ParameterSetName='Quarter', Mandatory)]
        [Parameter(ParameterSetName='QuarterType')]
        [ValidateRange(1,4)]
        [int]$Quarter,

        [Parameter(ParameterSetName='QuarterType', Mandatory)]
        [ValidateSet('Start','End')]
        [string]$QuarterType,

        [Parameter(ParameterSetName='Last', Mandatory)]
        [switch]$Last

    )

    function GetLastDateOfCurrentMonth {

        Param (
            [ValidateNotNullorEmpty()]
            [DateTime]$Date = (Get-Date)
        )

        $result = $false

        if ($Date.Month -in @(1, 3, 5, 7, 8, 10, 12)) {
            $result = New-Object -TypeName DateTime -ArgumentList @($Date.Year, $Date.Month, 31)
        }
        elseif ($Date.Month -in @(4, 6, 9, 11)) {
            $result = New-Object -TypeName DateTime -ArgumentList @($Date.Year, $Date.Month, 30)
        }
        else { #February
            try {
                $result = New-Object -TypeName DateTime -ArgumentList @($Date.Year, $Date.Month, 29)
            }
            catch {
                if ($Error[0].Exception.InnerException.HResult -eq -2146233086) {
                    $result = New-Object -TypeName DateTime -ArgumentList @($Date.Year, $Date.Month, 28)
                }
            }
        }

        return $result
    }

    function GetDotNETDayOfWeek {
        Param (
            [ValidateRange(1,7)]
            [int]$DayOfWeek
        )

        if ($DayOfWeek -eq 7) {
            return 0
        }
        else {
            return $DayOfWeek
        }
    }

    $result = $false

    switch ($PSCmdlet.ParameterSetName) {
        'QuarterType' {
            if ($QuarterType -eq 'Start') {
                if ($Date.Day -eq 1 -and $Date.Month -in (1,4,7,10)) {
                    $result = $true
                    if ($Quarter) {
                        if ($Date.Month -ne (3*$Quarter-2)) {
                            $result = $false
                        }
                    }
                }
            }
            elseif ($QuarterType -eq 'End') {
                if (($Date.Month -in (3,6,9,12)) -and $Date.Day -eq ((GetLastDateOfCurrentMonth -Date $Date).Day)) {
                    $result = $true
                }
            }
        }
        'Quarter' {
            if ($Date.Month -in ((3*$Quarter-2)..(3*$Quarter))) {
                $result = $true
            }
        }
        'EndOfMonth' {
            if ($Date -eq (GetLastDateOfCurrentMonth -Date $Date)) {
                 $result = $true
            }
        }
        'Last' {
            $LastDateOfCurrentMonth = GetLastDateOfCurrentMonth -Date $Date
            $StartOfLast7Days = $LastDateOfCurrentMonth.AddDays(-6)
            if (!$DayOfWeek) {
                if ($Date -ge $StartOfLast7Days -and $Date -le $LastDateOfCurrentMonth) {
                    $result = $true
                }
            }
            elseif ($Date.DayOfWeek.value__ -eq (GetDotNETDayOfWeek -DayOfWeek $DayOfWeek) -and $Date -ge $StartOfLast7Days -and $Date -le $LastDateOfCurrentMonth) {
                $result = $true
            }
        }
        'Default' {
            $DaysToSubstract = (7*($NumberInMonth-1))
            if ((New-TimeSpan -Days $DaysToSubstract).Ticks -le $Date.Ticks) {
                if ($Date.DayOfWeek.value__ -eq (GetDotNETDayOfWeek -DayOfWeek $DayOfWeek) -and $Date.AddDays(-$DaysToSubstract).Month -eq $Date.Month -and $Date.Day -le (7*$NumberInMonth)) {
                    $result = $true
                }
            }
        }
        Default {
            $result = $false
        }
    }
    return $result
}


text:
#include <iostream>
#include <string>
#include <vector>

#include "Option.h"
#include "MSFileHandler.h"
#include "MSFileExtractor.h"
#include "SpectrumFileList.h"

std::string spectrumOutFN_ = "";
std::string filePathOrig_ = "";
std::string filePathMerged_ = "";
std::string scannrString_ = "";
std::string clusterFile_ = "";

bool parseOptions(int argc, char **argv) {
  std::ostringstream intro;
  intro << "Usage:" << std::endl;
  intro << "  Option 1: extractspec -l spec_list -o spec_out" << std::endl;
  intro << "    spec_list is a tab delimited file of the form:" << std::endl;
  intro << "      filepath <tab> scannr <tab> ..." << std::endl;
  intro << "  Option 2: extractspec -i spec_in -m spec_merged_in \\";
  intro << std::endl;
  intro << "              -o spec_out -s scannr1,...,scannrN" << std::endl;
  intro << "    spec_in is an ms2 format file with original spectra.";
  intro << std::endl;
  intro << "    spec_merged_in is an ms2 format file with merged spectra.";
  intro << std::endl;
  intro << "  spec_out is where the merged spectra will be written.";
  intro << std::endl;
  intro << "  (ensure to have read and write access on the files).";
  intro << std::endl;

  // init
  maracluster::CommandLineParser cmd(intro.str());
  cmd.defineOption("l",
      "clusterFile",
      "File with filepaths and scannrs, separated by tabs",
      "filename");
  cmd.defineOption("i",
      "specIn",
      "File readable by ProteoWizard (e.g. ms2,mzML) with the original spectra",
      "filename");
  cmd.defineOption("o",
      "specOut",
      "File where you want the merged spectra to be written (ms2 format)",
      "filename");
  cmd.defineOption("m",
      "specMergeIn",
      "File readable by ProteoWizard (e.g. ms2, mzML) with the merged spectra",
      "filename");
  cmd.defineOption("s",
      "scannrs",
      "Scannrs as comma seperated string, e.g. 11,12,13",
      "int_list");

  // finally parse and handle return codes (display help etc...)
  cmd.parseArgs(argc, argv);

  // now query the parsing results
  if (cmd.optionSet("l")) clusterFile_ = cmd.options["l"];
  if (cmd.optionSet("o")) spectrumOutFN_ = cmd.options["o"];
  if (cmd.optionSet("i")) filePathOrig_ = cmd.options["i"];
  if (cmd.optionSet("m")) filePathMerged_ = cmd.options["m"];
  if (cmd.optionSet("s")) scannrString_ = cmd.options["s"];

  // if there are arguments left...
  if (cmd.arguments.size() > 0) {
    std::cerr << "Error: too many arguments." << std::endl;
    std::cerr << "Invoke with -h option for help." << std::endl;
    return 0; // ...error
  } else {
    if (!cmd.optionSet("l") && !(cmd.optionSet("s") && cmd.optionSet("i"))) {
      std::cerr << "Error: one of the inputs is missing." << std::endl;
      std::cerr << "Invoke with -h option for help." << std::endl;
      return 0;
    } else if (!cmd.optionSet("o")) {
      std::cerr << "Error: no output file given." << std::endl;
      std::cerr << "Invoke with -h option for help." << std::endl;
      return 0;
    } else if (cmd.optionSet("o") && !maracluster::MSFileHandler::validMs2OutputFN(spectrumOutFN_)) {
      std::cerr << "\nInvoke with -h option for help\n";
      return 0; // ...error
    }
  }
  return true;
}

/* extractspec -i data/be/103111-Yeast-2hr-01.ms2 \
               -m data/be/103111-Yeast-2hr-02.ms2 -o test.mgf -s 11,12,1000003
   extractspec -l cluster001.tsv -o cluster001.mgf */
int main(int argc, char* argv[]) {
  try {
    if (parseOptions(argc, argv)) {
      maracluster::MSFileExtractor msFileExtractor(spectrumOutFN_);

      if (clusterFile_.size() > 0) {
        msFileExtractor.parseClusterFileForExtract(clusterFile_);
      } else if (scannrString_.size() > 0) {
        msFileExtractor.parseScannrStringForExtract(scannrString_, filePathOrig_,
                                                  filePathMerged_);
      }
      msFileExtractor.extractSpectra();
      return EXIT_SUCCESS;
    }
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch (...) {
    std::cerr << "Caught unknown exception.\n";
  }

  return EXIT_FAILURE;
}


text:
<?php

namespace Ddeboer\Imap\Message;

use Ddeboer\Transcoder\Transcoder;

use Exception;

/**
 * An e-mail attachment
 */
class Attachment extends Part
{
    /**
     * Get attachment filename
     *
     * @return string
     */
    public function getFilename()
    {
        $fname =  (string)($this->parameters->get('filename')?: $this->parameters->get('name'));
        //RFCs 2047, 2231 and 5987
        //http://tools.ietf.org/html/rfc5987

        $matches = [];
        if(preg_match("@^([^']+)''(.*)@ui",$fname,$matches)){

            $fname = urldecode($matches[2]);

            try{
                $fname = Transcoder::create()->transcode(
                    $fname,
                    $matches[1],
                    "UTF-8//IGNORE"
                );
            }catch(Exception $e){
                $fname = 'filename_wrong_enc';
            }
        }

        return empty($fname)?'':$fname;
    }

    /**
     * Get attachment file size
     *
     * @return int Number of bytes
     */
    public function getSize()
    {
        return (int)$this->parameters->get('size');
    }
}


text:
package de.torqdev.jegl.filters.matrix;

import de.torqdev.jegl.filters.ImageFilter;
import org.kohsuke.MetaInfServices;

/**
 * @author Christopher Guckes
 * @version 1.0
 */
@MetaInfServices(value = ImageFilter.class)
public class SharpenFilter extends AbstractMatrixFilter {
    private static final float[] MATRIX = new float[]{
            // @formatter:off
            0, -1, 0,
            -1, 5, -1,
            0, -1, 0
            // @formatter:on
    };

    private static final float FACTOR = 1F;

    public SharpenFilter() {
        super(MATRIX, FACTOR);
    }
}


text:
package org.apache.geode.test.junit.rules;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import org.junit.rules.ExternalResource;

/**
 * A {@link org.junit.rules.TestRule} to create temporary files in a given directory that should be
 * deleted when the test method finishes. This is useful in place of
 * {@link org.junit.rules.TemporaryFolder} when a test needs to create files in a particular
 * directory, for example user.home or user.dir.
 *
 *

 * Example of usage:
 *
 *

 * public static class HasTemporaryFile {
 *   @Rule
 *   public TemporaryFileRule temporaryFileRule = TemporaryFileRule.inUserHome();
 *
 *   @Test
 *   public void testUsingTempFolder() throws IOException {
 *     File createdFile = temporaryFileRule.newFile("myfile.txt");
 *     File createdFile = temporaryFileRule.newFile("myfile2.txt");
 *     // ...
 *   }
 * }
 *

 */
public class TemporaryFileRule extends ExternalResource {

  private final String directory;

  private Set<File> files;

  private TemporaryFileRule(String parentDirectory) {
    directory = parentDirectory;
  }

  public static TemporaryFileRule inUserHome() {
    return new TemporaryFileRule(System.getProperty("user.home"));
  }

  public static TemporaryFileRule inCurrentDir() {
    return new TemporaryFileRule(System.getProperty("user.dir"));
  }

  public static TemporaryFileRule inDirectory(String directory) {
    return new TemporaryFileRule(directory);
  }

  @Override
  public void before() {
    files = new HashSet<>();
  }

  @Override
  public void after() {
    files.stream().filter(Objects::nonNull).filter(File::exists).forEach(File::delete);
  }

  /**
   * Creates a new file with the given name in the specified {@link #directory}.
   *
   * @param fileName the name of the file to create.
   *
   * @return the file that was created.
   *
   * @throws IllegalStateException if the file already exists.
   * @throws IllegalStateException if there is an {@link IOException} while creating the file.
   */
  public File newFile(String fileName) {
    return createFile(directory, fileName);
  }

  private File createFile(String directory, String fileName) {
    File file = new File(directory, fileName);
    try {
      if (!file.createNewFile()) {
        throw new IllegalStateException(
            "The specified file " + file.getAbsolutePath() + " already exists.");
      }
    } catch (IOException e) {
      throw new IllegalStateException(
          "IOException attempting to create file " + file.getAbsolutePath() + ".", e);
    }

    file.deleteOnExit();
    files.add(file);
    return file;
  }
}