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

namespace ExampleApp
{
    class Program
    {
        static Random r = new Random();

        static void Main(string[] args)
        {
            SingleFileDataStore<Foo, int> fooStore = new SingleFileDataStore<Foo, int>(@"c:\temp\temp2.txt", item => item.A);

            //// clear all items
            //foreach (var foo in fooStore.All())
            //{
            //    fooStore.Delete(foo);
            //}

            //// generate random foos
            //var foos = GiveMeFoos(10);

            //// Insert a bunch foos
            //foreach (var foo in foos)
            //{
            //    try
            //    {
            //        // Since these are randomly generated items, potential for a clash of ids.
            //        fooStore.Create(foo);

            //        // for good measure, lets 'create' the same item twice and watch it fail
            //        // (this will not get rolled back as part of try/catch since current implementation writes to disk instantly)
            //        fooStore.Create(foo);
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine("Failed to update fooStore: {0}", ex.Message);
            //    }
            //}

            // write out all ours foos (potentially less than we created if Ids were duplicated)

            foreach (Foo foo in fooStore.All())
            {
                Console.WriteLine("ID:{3}\t{0}: {1} (\"{2}\")", foo.A, foo.B, foo.C, fooStore.GetId(foo));
            }
            Console.WriteLine();
            foreach (Foo foo in fooStore.Get(x => x.B > 0.5))
            {
                Console.WriteLine("{0}: {1} (\"{2}\")", foo.A, foo.B, foo.C);
            }
            Console.WriteLine();
            fooStore.Delete(x => x.B <= 0.5);
            foreach (Foo foo in fooStore.All())
            {
                Console.WriteLine("{0}: {1} (\"{2}\")", foo.A, foo.B, foo.C);
            }

            //// more complex items
            //SingleFileDataStore<Bar, Guid> barStore = new SingleFileDataStore<Bar, Guid>(@"c:\temp\bars.txt", b => b.Id);
            //barStore.DeleteAll();

            //for (int i = 0; i < 100; i++)
            //{
            //    barStore.Create(new Bar(Guid.NewGuid(), GiveMeFoos(10).ToList()));
            //}

            //foreach (Bar bar in barStore.All())
            //{
            //    Console.WriteLine(bar.Id);
            //    foreach (Foo foo in bar.Foos)
            //    {
            //        Console.WriteLine("\t{0}", foo.C);
            //    }
            //}

            //// silly ids
            //SingleFileDataStore<Bar, string> barStore2 = new SingleFileDataStore<Bar, string>(@"c:\temp\bars2.txt", b => string.Concat(b.Foos.Select(x => x.C)));

            //for (int i = 0; i < 10; i++)
            //{
            //    Bar b = new Bar(Guid.NewGuid(), GiveMeFoos(5).ToList());
            //    Console.WriteLine("Created item: {0}", barStore2.GetId(b));
            //    barStore2.Create(b);
            //}

            //foreach (Bar bar in barStore2.All())
            //{
            //    Console.WriteLine(barStore2.GetId(bar));
            //}
        }

        static IEnumerable<Foo> GiveMeFoos(uint n)
        {
            string stringChars = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            for (int i = 0; i < n; i++)
            {
                string randomString = null;
                for (int j = 0; j < 8; j++)
                {
                    randomString = string.Concat(randomString, stringChars[r.Next(stringChars.Length)]);
                }

                yield return new Foo(r.Next(int.MaxValue), r.NextDouble(), randomString);
            }
        }

        class Foo
        {
            public int A { get; set; }
            public double B { get; set; }
            public string C { get; set; }

            public Foo()
            {
            }
            public Foo(int i, double d, string s)
            {
                this.A = i;
                this.B = d;
                this.C = s;
            }
        }

        class Bar
        {
            public Bar()
                :this(Guid.Empty, new List<Foo>())
            {
            }

            public Bar(Guid g, List<Foo> foos)
            {
                this.Id = g;
                this.Foos = foos;
            }

            public Guid Id { get; set; }
            public List<Foo> Foos { get; set; }
        }

    }
}


text:
package programmersguide.workingwithasposepdf.workingwithstampsandwatermarks.addingtextinheader.java;

import com.aspose.pdf.*;

public class AddingTextinHeader
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = "src/programmersguide/workingwithasposepdf/workingwithstampsandwatermarks/addingtextinheader/data/";

    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';
var Cylon = require('cylon');

Cylon.robot({
  name: 'Ivan',
  connections: {
    module: { adaptor: 'noolite', device: 'rx2164' }
  },
  devices: {
    corridor: { driver: 'noolite', channel: 1 }
  },
  work: function (my) {
    var devices = my.connections.module;

    // send command 'switch the light' to channel #1
    devices.send(1, 'SWITCH').then(function () {
      console.log('command sent');
    });

    // send command 'switch the light' to named device
    my.corridor.send('SWITCH').then(function () {
      console.log('command sent');
    });

  }

});

Cylon.start();


text:
Sequel.migration do
  up do
    create_table(:tags) do
      primary_key :id
      String :tag_name
      Integer :owner_id, default: nil
      String :tag_message, default: nil
    end
  end

  down do
    drop_table(:tags)
  end
end


text:
using System;
using System.Diagnostics;
using NUnit.Framework;
using Abot.Core;

namespace Abot.Tests.Unit.Core
{
    [TestFixture]
    public class RateLimiterTest
    {
        RateLimiter _unitUnderTest;

        [Test]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Constructor_InvalidOccurrances()
        {
            new RateLimiter(0, TimeSpan.FromSeconds(10));
        }

        [Test]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Constructor_NegativeTimeSpan()
        {
            new RateLimiter(1, TimeSpan.FromSeconds(-10));
        }

        [Test]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Constructor_TimeSpanToBig()
        {
            new RateLimiter(1, TimeSpan.FromDays(1000));
        }

        [Test]
        public void WaitToProceed_ZeroWait_DoesntWait()
        {
            _unitUnderTest = new RateLimiter(1, TimeSpan.FromSeconds(0));

            Stopwatch timer = Stopwatch.StartNew();

            _unitUnderTest.WaitToProceed();
            _unitUnderTest.WaitToProceed();
            _unitUnderTest.WaitToProceed();

            timer.Stop();

            Assert.IsTrue(timer.Elapsed.TotalSeconds < 1);
        }

        [Test]
        public void WaitToProceed_OneSecWait_Waits()
        {
            _unitUnderTest = new RateLimiter(1, TimeSpan.FromSeconds(2));

            Stopwatch timer = Stopwatch.StartNew();

            _unitUnderTest.WaitToProceed();//will not wait for first call
            _unitUnderTest.WaitToProceed();
            _unitUnderTest.WaitToProceed();

            timer.Stop();

            Assert.IsTrue(timer.Elapsed.TotalSeconds > 2);
        }

        [Test]
        public void WaitToProceed_PartialSecWait_Waits()
        {
            _unitUnderTest = new RateLimiter(1, TimeSpan.FromSeconds(1.5));

            Stopwatch timer = Stopwatch.StartNew();

            _unitUnderTest.WaitToProceed();//will not wait for first call
            _unitUnderTest.WaitToProceed();
            _unitUnderTest.WaitToProceed();

            timer.Stop();

            Assert.IsTrue(timer.Elapsed.TotalSeconds > 1.5);
        }

        [Test]
        public void WaitToProceed_ForCoverage()
        {
            _unitUnderTest = new RateLimiter(1, TimeSpan.FromSeconds(1));

            Stopwatch timer = Stopwatch.StartNew();

            _unitUnderTest.WaitToProceed(TimeSpan.FromSeconds(10));
            _unitUnderTest.Dispose();

            timer.Stop();

            Assert.IsTrue(timer.Elapsed.TotalSeconds < 1);
        }

        [Test]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void WaitToProceed_NegativeMilli()
        {
            _unitUnderTest = new RateLimiter(1, TimeSpan.FromSeconds(1));
            _unitUnderTest.WaitToProceed(-10);
        }
    }
}


text:
// The MIT License
//
// Copyright (c) 2014 Gwendal Roué
//
// 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.

#import <Foundation/Foundation.h>
#import "GRMustacheAvailabilityMacros_private.h"

@interface GRMustacheHTMLEscape : NSFormatter

/**
 * Returns the HTML-escaped version of the string parameter.
 *
 * Characters & < > " ' are escaped to & < > " '
 * respectively.
 *
 * Be cautious with mutable string input: this method may return its input.
 *
 * @param string  The string to be HTML-escaped
 * @return An HTML-escaped string
 */
+ (NSString *)escapeHTML:(NSString *)string GRMUSTACHE_API_INTERNAL;

@end


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

<title>com.kamontat.model.management Class Hierarchy (Github-Request 2.2.3)</title>
<meta name="date" content="2017-02-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.kamontat.model.management

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.kamontat.model.management.Cache

com.kamontat.model.management.Device

com.kamontat.model.management.FileUtil

com.kamontat.model.management.Location

com.kamontat.model.management.Size

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
const _ = require('lodash');
const d3 = require('d3');
const React = require('react');
const Motion = require('react-motion').Motion;
const spring = require('react-motion').spring;

const AppActions = require('../actions/app-actions');

const line = d3.svg.line()
  .interpolate('basis')
  .x(function(d) { return d.x; })
  .y(function(d) { return d.y; });

const animConfig = [80, 20]; // stiffness, bounce

const flattenPoints = function(points) {
  const flattened = {};
  points.forEach(function(point, i) {
    flattened['x' + i] = spring(point.x, animConfig);
    flattened['y' + i] = spring(point.y, animConfig);
  });
  return flattened;
};

const extractPoints = function(points) {
  const extracted = [];
  _.each(points, function(value, key) {
    const axis = key[0];
    const index = key.slice(1);
    if (!extracted[index]) {
      extracted[index] = {};
    }
    extracted[index][axis] = value;
  });
  return extracted;
};

const Edge = React.createClass({

  getInitialState: function() {
    return {
      points: []
    };
  },

  componentWillMount: function() {
    this.ensureSameLength(this.props.points);
  },

  componentWillReceiveProps: function(nextProps) {
    this.ensureSameLength(nextProps.points);
  },

  render: function() {
    const classNames = ['edge'];
    const points = flattenPoints(this.props.points);
    const props = this.props;
    const handleMouseEnter = this.handleMouseEnter;
    const handleMouseLeave = this.handleMouseLeave;

    if (this.props.highlighted) {
      classNames.push('highlighted');
    }
    if (this.props.blurred) {
      classNames.push('blurred');
    }
    const classes = classNames.join(' ');

    return (
      <Motion style={points}>
        {function(interpolated) {
          const path = line(extractPoints(interpolated));
          return (
            <g className={classes} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} id={props.id}>
              <path d={path} className="shadow" />
              <path d={path} className="link" />
            </g>
          );
        }}
      </Motion>
    );
  },

  ensureSameLength: function(points) {
    // Spring needs constant list length, hoping that dagre will insert never more than 10
    const length = 10;
    let missing = length - points.length;

    while (missing) {
      points.unshift(points[0]);
      missing = length - points.length;
    }

    return points;
  },

  handleMouseEnter: function(ev) {
    AppActions.enterEdge(ev.currentTarget.id);
  },

  handleMouseLeave: function(ev) {
    AppActions.leaveEdge(ev.currentTarget.id);
  }

});

module.exports = Edge;


text:
define(
	 ({
		queries: "Päringuülesanded",
		addNew: "Lisa uus",
		setSource: "Määra",
		setDataSource: "Määra andmeallikas",
		name: "Nimi",
		querySource: "Andmeallikas",
		queryName: "Ülesande nimi",
		queryDefinition: "Filtri määratlus",
		resultsSetting: "Tulemuste seade",
		symbolSetting: "Sümboli seade",
		resultSettingTip: "Saate määrata, kuidas tulemused kuvatakse ja mida need hõlmavad.",
		resultItemTitle: "Tulemuse pealkiri",
		resultItemContent: "Tulemuse sisu",
		fieldsSetTip: "Kontrollige kuvatavaid välju. Väljade järjestuse muutmiseks, välja vormindamiseks või aliase värskendamiseks valige väli.",
		addField: "Lisa väli",
		visibility: "Nähtavus",
		alias: "Alias",
		specialType: "Eritüüp",
		actions: "Tegevused",
		none: "Pole",
		link: "Link",
		image: "Pilt",
		noField: "Väli puudub",
		operationalLayerTip: "Lisa tulemus töökihina",
		setLayerSymbolTip: "Määrake päringu tulemuste sümbol: ",
		setSelectedSymbolTip: "Määrake valitud objekti sümbol.",
		notUseFilter: "Ära kasuta filtrit",
		setSourceTip: "Määrake päringu allikas.",
		setFilterTip: "Määrake filter õigesti.",
		ok: "OK",
		cancel: "Tühista",
		noFilterTip: "Määratlemata filtriavaldiseta loendab see päringuülesanne kõik määratud andmeallika funktsioonid."
  })
);


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Font Awesome Tests</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="stylesheet" href="assets/css/site.css">
  <link rel="stylesheet" href="assets/css/prettify.css">
  <link rel="stylesheet" href="assets/css/font-awesome.css">

  <link rel="shortcut icon" href="assets/ico/favicon.ico">

Visual tests

Icons Icons should not be clipped

         Building

         Building Large

       Building

       Building Large

         Building

         Building Large

       Building Large

Links with Icons icon should activate link

     Link Here
     Link Here
     Link Here

Navbar  should stay same height

         Font Awesome

Nav Item 1

              Nav Item 2

 Menu Item 1

 Menu Item 2

 Nav Item 3

Plain buttons next to icon buttons should be same height

Buttons

          <button class="btn btn-mini">Button</button>
          <button class="btn btn-mini"> Button</button>
          <button class="btn btn-mini"></button>

          <button class="btn btn-small">Button</button>
          <button class="btn btn-small"> Button</button>
          <button class="btn btn-small"></button>

          <button class="btn">Button</button>
          <button class="btn"> Button</button>
          <button class="btn"></button>

          <button class="btn btn-large">Button</button>
          <button class="btn btn-large"> Button</button>
          <button class="btn btn-large"></button>

          <button class="btn btn-mini">Button</button>
          <button class="btn btn-mini"> Button</button>
          <button class="btn btn-mini"></button>

          <button class="btn btn-small">Button</button>
          <button class="btn btn-small"> Button</button>
          <button class="btn btn-small"></button>

          <button class="btn">Button</button>
          <button class="btn"> Button</button>
          <button class="btn"></button>

          <button class="btn btn-large">Button</button>
          <button class="btn btn-large"> Button</button>
          <button class="btn btn-large"></button>

Anchors

          Button
           Button

          Button
           Button

          Button
           Button

          Button
           Button

          Button
           Button

          Button
           Button

          Button
           Button

          Button
           Button

Buttons with pulled 2x, 3x, 4x should be same height, have correct line height

          Longer
Button

          Longer
Button

          Longer
Button

          Longer
Button

          Longer
Button

          Longer
Button

Nav pills & nav tabs should be same height

Nav Item 1

            Nav Item 2

 Menu Item 1

 Menu Item 2

 Nav Item 3

 Nav Item 4

Nav Item 1

            Nav Item 2

 Menu Item 1

 Menu Item 2

 Nav Item 3

 Nav Item 4

2x, 3x, 4x icons in text should have margins next to and below text

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et lectus id nisl hendrerit varius. Aliquam erat volutpat. Suspendisse potenti. Aliquam erat volutpat. Aliquam ut dolor lectus.

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et lectus id nisl hendrerit varius. Aliquam erat volutpat. Suspendisse potenti. Aliquam erat volutpat. Aliquam ut dolor lectus.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et lectus id nisl hendrerit varius. Aliquam erat volutpat. Suspendisse potenti. Aliquam erat volutpat. Aliquam ut dolor lectus.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et lectus id nisl hendrerit varius. Aliquam erat volutpat. Suspendisse potenti. Aliquam erat volutpat. Aliquam ut dolor lectus.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et lectus id nisl hendrerit varius. Aliquam erat volutpat. Suspendisse potenti. Aliquam erat volutpat. Aliquam ut dolor lectus.

Bullets should wrap appropriately, have proper spacing

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et lectus id nisl hendrerit varius. Aliquam erat volutpat. Suspendisse potenti. Aliquam erat volutpat. Aliquam ut dolor lectus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et lectus id nisl hendrerit varius. Aliquam erat volutpat. Suspendisse potenti. Aliquam erat volutpat. Aliquam ut dolor lectus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Spinning icons icons should be aligned well and on center, buttons should be same height, won't work in ie7

     Loading...
    <button class="btn btn-small"> Loading...</button>
    <button class="btn btn-small">Loading...</button>
     Loading...
    <button class="btn btn-small"> Loading...</button>

     Loading...
    <button class="btn"> Loading...</button>
    <button class="btn">Loading...</button>
     Loading...
    <button class="btn"> Loading...</button>

     Loading...
    <button class="btn btn-large"> Loading...</button>
    <button class="btn btn-large">Loading...</button>
     Loading...
    <button class="btn btn-large"> Loading...</button>

icon-large

     Loading...
    <button class="btn btn-small"> Loading...</button>
    <button class="btn btn-small">Loading...</button>
     Loading...
    <button class="btn btn-small"> Loading...</button>

     Loading...
    <button class="btn"> Loading...</button>
    <button class="btn">Loading...</button>
     Loading...
    <button class="btn"> Loading...</button>

     Loading...
    <button class="btn btn-large"> Loading...</button>
    <button class="btn btn-large">Loading...</button>
     Loading...
    <button class="btn btn-large"> Loading...</button>


text:
require 'aruba/api'
require 'aruba/cucumber'
require 'fileutils'
require 'pathname'
require 'vim-flavor'

class FakeUserEnvironment
  include Vim::Flavor::ShellUtility

  def add_new_versions_to_repo(basename, versions, flavorfile_content = nil, naming_style = :new)
    repository_path = make_repo_path(basename)
    flavorfile_path = naming_style == :new ?
      repository_path.to_flavorfile_path :
      "#{repository_path}/VimFlavor"
    doc_name = basename.split('/').last.sub(/^vim-/, '')
    sh <<-"END"
      {
        cd '#{repository_path}' &&
        mkdir -p doc &&
        for v in #{versions}
        do
          echo "*#{doc_name}* $v" >'doc/#{doc_name}.txt'
          git add doc
          #{
            %Q{
              cat <<'FF' >#{flavorfile_path}
#{expand(flavorfile_content)}
FF
              git add #{flavorfile_path}
            } if flavorfile_content
          }
          git commit -m "Version $v"
          git tag -m "Version $v" "$v"
        done
      } >/dev/null
    END
    versions.split.each do |v|
      variable_table["#{basename}_rev_#{v.gsub('.', '')}"] = sh(<<-"END").chomp
        cd '#{repository_path}' &&
        git rev-list -n1 '#{v}' --
      END
    end
  end

  def expand(virtual_path)
    virtual_path.gsub(/\$([A-Za-z0-9_]+)/) {
      variable_table[$1]
    }
  end

  def path_for_step(path)
    cwd = Pathname.new(expand_path('.'))
    pathd = Pathname.new(path)
    if not pathd.absolute?
      pathd = cwd + pathd
    end

    pathd.relative_path_from(cwd).to_s
  end

  def make_cached_repo_path(repo_name, stash_path)
    "#{stash_path}/repos/#{repo_name.zap}"
  end

  def make_flavor_path(vimfiles_path, repo_name)
    "#{vimfiles_path.to_flavors_path}/#{repo_name.zap}"
  end

  def make_repo_path(basename)
    "#{expand("$tmp")}/repos/#{basename}"
  end

  def make_repo_uri(basename)
    "file://#{make_repo_path(basename)}"
  end

  def variable_table
    @variable_table ||= Hash.new
  end
end

Before do
  variable_table['version'] = Vim::Flavor::VERSION

  variable_table['tmp'] = File.absolute_path(expand_path('.'))

  steps %Q{
    Given a directory named "home"
  }
  variable_table['home'] = File.absolute_path(File.join([expand_path('.'), 'home']))

  @aruba_timeout_seconds = 5

  set_environment_variable 'VIM_FLAVOR_HOME', variable_table['home']
  set_environment_variable 'VIM_FLAVOR_GITHUB_URI_PREFIX', expand('file://$tmp/repos/')
  set_environment_variable 'VIM_FLAVOR_GITHUB_URI_SUFFIX', ''
end

World do
  FakeUserEnvironment.new
end


text:
'use strict';

var should = require('should'),
	request = require('supertest'),
	app = require('../../server'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Kontakt = mongoose.model('Kontakt'),
	agent = request.agent(app);

/**
 * Globals
 */
var credentials, user, kontakt;

/**
 * Kontakt routes tests
 */
describe('Kontakt CRUD tests', function() {
	beforeEach(function(done) {
		// Create user credentials
		credentials = {
			username: 'username',
			password: 'password'
		};

		// Create a new user
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: credentials.username,
			password: credentials.password,
			provider: 'local'
		});

		// Save a user to the test db and create new Kontakt
		user.save(function() {
			kontakt = {
				name: 'Kontakt Name'
			};

			done();
		});
	});

	it('should be able to save Kontakt instance if logged in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Kontakt
				agent.post('/kontakts')
					.send(kontakt)
					.expect(200)
					.end(function(kontaktSaveErr, kontaktSaveRes) {
						// Handle Kontakt save error
						if (kontaktSaveErr) done(kontaktSaveErr);

						// Get a list of Kontakts
						agent.get('/kontakts')
							.end(function(kontaktsGetErr, kontaktsGetRes) {
								// Handle Kontakt save error
								if (kontaktsGetErr) done(kontaktsGetErr);

								// Get Kontakts list
								var kontakts = kontaktsGetRes.body;

								// Set assertions
								(kontakts[0].user._id).should.equal(userId);
								(kontakts[0].name).should.match('Kontakt Name');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to save Kontakt instance if not logged in', function(done) {
		agent.post('/kontakts')
			.send(kontakt)
			.expect(401)
			.end(function(kontaktSaveErr, kontaktSaveRes) {
				// Call the assertion callback
				done(kontaktSaveErr);
			});
	});

	it('should not be able to save Kontakt instance if no name is provided', function(done) {
		// Invalidate name field
		kontakt.name = '';

		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Kontakt
				agent.post('/kontakts')
					.send(kontakt)
					.expect(400)
					.end(function(kontaktSaveErr, kontaktSaveRes) {
						// Set message assertion
						(kontaktSaveRes.body.message).should.match('Please fill Kontakt name');

						// Handle Kontakt save error
						done(kontaktSaveErr);
					});
			});
	});

	it('should be able to update Kontakt instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Kontakt
				agent.post('/kontakts')
					.send(kontakt)
					.expect(200)
					.end(function(kontaktSaveErr, kontaktSaveRes) {
						// Handle Kontakt save error
						if (kontaktSaveErr) done(kontaktSaveErr);

						// Update Kontakt name
						kontakt.name = 'WHY YOU GOTTA BE SO MEAN?';

						// Update existing Kontakt
						agent.put('/kontakts/' + kontaktSaveRes.body._id)
							.send(kontakt)
							.expect(200)
							.end(function(kontaktUpdateErr, kontaktUpdateRes) {
								// Handle Kontakt update error
								if (kontaktUpdateErr) done(kontaktUpdateErr);

								// Set assertions
								(kontaktUpdateRes.body._id).should.equal(kontaktSaveRes.body._id);
								(kontaktUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should be able to get a list of Kontakts if not signed in', function(done) {
		// Create new Kontakt model instance
		var kontaktObj = new Kontakt(kontakt);

		// Save the Kontakt
		kontaktObj.save(function() {
			// Request Kontakts
			request(app).get('/kontakts')
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Array.with.lengthOf(1);

					// Call the assertion callback
					done();
				});

		});
	});

	it('should be able to get a single Kontakt if not signed in', function(done) {
		// Create new Kontakt model instance
		var kontaktObj = new Kontakt(kontakt);

		// Save the Kontakt
		kontaktObj.save(function() {
			request(app).get('/kontakts/' + kontaktObj._id)
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Object.with.property('name', kontakt.name);

					// Call the assertion callback
					done();
				});
		});
	});

	it('should be able to delete Kontakt instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Kontakt
				agent.post('/kontakts')
					.send(kontakt)
					.expect(200)
					.end(function(kontaktSaveErr, kontaktSaveRes) {
						// Handle Kontakt save error
						if (kontaktSaveErr) done(kontaktSaveErr);

						// Delete existing Kontakt
						agent.delete('/kontakts/' + kontaktSaveRes.body._id)
							.send(kontakt)
							.expect(200)
							.end(function(kontaktDeleteErr, kontaktDeleteRes) {
								// Handle Kontakt error error
								if (kontaktDeleteErr) done(kontaktDeleteErr);

								// Set assertions
								(kontaktDeleteRes.body._id).should.equal(kontaktSaveRes.body._id);

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to delete Kontakt instance if not signed in', function(done) {
		// Set Kontakt user
		kontakt.user = user;

		// Create new Kontakt model instance
		var kontaktObj = new Kontakt(kontakt);

		// Save the Kontakt
		kontaktObj.save(function() {
			// Try deleting Kontakt
			request(app).delete('/kontakts/' + kontaktObj._id)
			.expect(401)
			.end(function(kontaktDeleteErr, kontaktDeleteRes) {
				// Set message assertion
				(kontaktDeleteRes.body.message).should.match('User is not logged in');

				// Handle Kontakt error error
				done(kontaktDeleteErr);
			});

		});
	});

	afterEach(function(done) {
		User.remove().exec();
		Kontakt.remove().exec();
		done();
	});
});


text:
using namespace DVLib::UnitTests;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

void DirectoryUtilUnitTests::testDirectoryExists()
{
    std::string path = DVLib::GetTemporaryFileNameA();
    std::cout << std::endl << "Temporary filename: " << path;

    std::string directory = DVLib::GetFileDirectoryA(path);
    std::cout << std::endl << "Directory: " << directory;

    Assert::IsTrue(DVLib::DirectoryExists(directory));
    Assert::IsTrue(! DVLib::DirectoryExists(path));
    DVLib::FileDelete(path);

    Assert::IsTrue(DVLib::DirectoryExists("C:\\"));
    Assert::IsTrue(! DVLib::DirectoryExists(""));

    std::string filename = DVLib::GenerateGUIDStringA();
    std::string guidpath = "C:\\" + filename;
    std::cout << std::endl << "Guid path: " << guidpath;
    Assert::IsTrue(! DVLib::DirectoryExists(guidpath));
}

void DirectoryUtilUnitTests::testDirectoryCreate()
{
    std::wstring root = DVLib::GetTemporaryDirectoryW();
    // check that we can create one level
    std::wstring guid = DVLib::GenerateGUIDStringW();
    std::wstring path1 = root + guid;
    std::wcout << std::endl << L"Creating: " << path1;
    Assert::IsTrue(! DVLib::DirectoryExists(path1));
    std::wstring path1_created = DVLib::DirectoryCreate(path1);
    Assert::IsTrue(DVLib::DirectoryExists(path1));
    Assert::IsTrue(path1 == path1_created);
    // check that we can create two more levels
    std::wstring path2 = path1 + L"\\" + guid;
    std::wstring path3 = path2 + L"\\" + guid;
    std::wcout << std::endl << L"Creating: " << path3;
    Assert::IsTrue(! DVLib::DirectoryExists(path3));
    std::wstring path3_created = DVLib::DirectoryCreate(path3);
    Assert::IsTrue(DVLib::DirectoryExists(path2));
    // the first created directory is path2
    Assert::IsTrue(path2 == path3_created);
    // delete the final result
    DVLib::DirectoryDelete(path1);
}

void DirectoryUtilUnitTests::testDirectoryDelete()
{
    std::wstring root = DVLib::GetTemporaryDirectoryW();
    std::wstring guid = DVLib::GenerateGUIDStringW();
    std::wstring deeppath = root + guid + L"\\" + guid + L"\\" + guid;
    std::wstring newpath = DVLib::DirectoryCreate(deeppath);
    std::wcout << std::endl << "Path: " << newpath;
    // delete files in a directory that doesn't have any files or subdirectories
    DVLib::DirectoryDelete(deeppath, DVLib::DELETE_DIRECTORY_FILES);
    // delete files in a directory that doesn't have any files, but has subdirectories
    DVLib::DirectoryDelete(newpath, DVLib::DELETE_DIRECTORY_FILES);
    Assert::IsTrue(DVLib::DirectoryExists(newpath));
    // create two files
    std::wstring filename1 = newpath + L"\\" + guid + L"-1.tmp";
    std::wstring filename2 = newpath + L"\\" + guid + L"-2.tmp";
    DVLib::FileCreate(filename1);
    DVLib::FileCreate(filename2);
    Assert::IsTrue(DVLib::FileExists(filename1));
    Assert::IsTrue(DVLib::FileExists(filename2));
    // two directories + two files
    std::list<std::wstring> files = DVLib::GetFiles(newpath, L"*.*", DVLib::GET_FILES_ALL);
    Assert::IsTrue(4 == files.size());
    // try to delete effectively nothing, this will fail
    try
    {
        DVLib::DirectoryDelete(newpath, 0);
        throw "DeleteDirectory was expected to throw std::exception";
    }
    catch(std::exception& ex)
    {
        // expected exception, this directory can't be deleted since it has files in it
        std::cout << std::endl << "Expected exception: " << ex.what();
        Assert::IsTrue(DVLib::FileExists(filename1));
        Assert::IsTrue(DVLib::FileExists(filename2));
    }
    // make sure nothing was deleted
    Assert::IsTrue(4 == DVLib::GetFiles(newpath, L"*.*", DVLib::GET_FILES_ALL).size());
    // delete without deleting files, the empty subdirectories will be deleted, leaving us with 2 files
    DVLib::DirectoryDelete(newpath, DVLib::DELETE_DIRECTORY_EMPTY);
    Assert::IsTrue(2 == DVLib::GetFiles(newpath, L"*.*", DVLib::GET_FILES_ALL).size());
    // delete with file and non-empty subdirectories
    DVLib::DirectoryDelete(newpath);
    Assert::IsTrue(! DVLib::FileExists(filename1));
    Assert::IsTrue(! DVLib::FileExists(filename2));
    Assert::IsTrue(! DVLib::DirectoryExists(newpath));
}

void DirectoryUtilUnitTests::testGetFilesRecursive()
{
    std::list<std::wstring> files = DVLib::GetFiles(
        DVLib::GetModuleDirectoryW(), L"*.exe", DVLib::GET_FILES_ALL);

    bool found = false;
    for each (const std::wstring& file in files)
        found |= (file == DVLib::GetModuleFileNameW());

    Assert::IsTrue(found);
}

void DirectoryUtilUnitTests::testGetFilesWithWildcard()
{
    std::list<std::wstring> files = DVLib::GetFiles(
        DVLib::GetModuleDirectoryW() + L"\\*.exe", DVLib::GET_FILES_ALL);

    bool found = false;
    for each (const std::wstring& file in files)
        found |= (file == DVLib::GetModuleFileNameW());

    Assert::IsTrue(found);
}

void DirectoryUtilUnitTests::testGetFilesWithNoWildcard()
{
    std::list<std::wstring> files = DVLib::GetFiles(
        DVLib::GetModuleFileNameW(), DVLib::GET_FILES_FILES);

    Assert::IsTrue(files.size() == 1);
    Assert::IsTrue(* files.begin() == DVLib::GetModuleFileNameW());
}

void DirectoryUtilUnitTests::testGetFilesWithInvalidWildcard()
{
    LPCWSTR file_wildcards[] =
    {
        { L"x:\\temp\\*\\*.txt" },
        { L"x:\\temp\\?\\*.txt" },
        { L"x:\\temp\\?*\\*.txt" },
        { L"x:\\temp\\*?\\*.txt" },
        { L"?*\\no wildcard here" },
    };

    for (int i = 0; i < ARRAYSIZE(file_wildcards); i++)
    {
        try
        {
            DVLib::GetFiles(L"x:\\temp\\*\\*.txt", DVLib::GET_FILES_FILES);
            throw "expected std::exception";
        }
        catch(std::exception&)
        {
            // expected
        }
    }
}

void DirectoryUtilUnitTests::testDirectoryCreateMultipleSlashes()
{
    std::wstring root = DVLib::GetTemporaryDirectoryW();
    // check that we can create one level
    std::wstring guid = DVLib::GenerateGUIDStringW();
    // append various numbers of backslashes
    std::wstring path_0 = root + guid;
    std::wstring path_1 = root + L"\\" + guid;
    std::wstring path_2 = root + L"\\\\" + guid;
    std::wcout << std::endl << L"Creating: " << path_0;
    Assert::IsTrue(! DVLib::DirectoryExists(path_0));
    Assert::IsTrue(! DVLib::DirectoryExists(path_1));
    Assert::IsTrue(! DVLib::DirectoryExists(path_2));
    Assert::IsTrue(path_0 == DVLib::DirectoryCreate(path_0));
    Assert::IsTrue(DVLib::DirectoryDelete(path_0));
    Assert::IsTrue(path_0 == DVLib::DirectoryCreate(path_1));
    Assert::IsTrue(DVLib::DirectoryDelete(path_1));
    Assert::IsTrue(path_0 == DVLib::DirectoryCreate(path_2));
    Assert::IsTrue(DVLib::DirectoryDelete(path_2));
}

void DirectoryUtilUnitTests::testDirectoryNormalize()
{
    struct TestData
    {
        LPCWSTR path;
        LPCWSTR expected;
    };

    TestData testdata[] =
    {
        { L"", L"" },
        { L"C:", L"C:" },
        { L"C:\\", L"C:\\" },
        { L"C:\\\\", L"C:\\" },
        { L"C:\\path", L"C:\\path" },
        { L"D:\\\\path", L"D:\\path" },
        { L"E:\\path\\", L"E:\\path\\" },
        { L"C:\\\\path\\\\", L"C:\\path\\" },
        // { L"C:\\\\\\path\\\\", L"C:\\path\\" },
    };

    for (int i = 0; i < ARRAYSIZE(testdata); i++)
    {
        std::wstring normalized_path = DVLib::DirectoryNormalize(testdata[i].path);
        std::wcout << std::endl << L" " << i << L": " << normalized_path;
        Assert::IsTrue(normalized_path == testdata[i].expected);
    }
}


text:
RSpec.shared_examples_for 'all client drafts' do
  def validate_request
    expect(handshake.to_s).to eql(client_request)

    handshake << server_response

    expect(handshake.error).to be_nil
    expect(handshake).to be_finished
    expect(handshake).to be_valid
  end

  it 'should be valid' do
    handshake << server_response

    expect(handshake.error).to be_nil
    expect(handshake).to be_finished
    expect(handshake).to be_valid
  end

  it 'should return valid version' do
    expect(handshake.version).to eql(version)
  end

  it 'should return valid host' do
    @request_params = { host: 'www.test.cc' }
    expect(handshake.host).to eql('www.test.cc')
  end

  it 'should return valid path' do
    @request_params = { path: '/custom' }
    expect(handshake.path).to eql('/custom')
  end

  it 'should return valid query' do
    @request_params = { query: 'aaa=bbb' }
    expect(handshake.query).to eql('aaa=bbb')
  end

  it 'should return valid port' do
    @request_params = { port: 123 }
    expect(handshake.port).to eql(123)
  end

  it 'should return valid headers' do
    @request_params = { headers: { 'aaa' => 'bbb' } }
    expect(handshake.headers).to eql({ 'aaa' => 'bbb' })
  end

  it 'should parse uri' do
    @request_params = { uri: 'ws://test.example.org:301/test_path?query=true' }
    expect(handshake.host).to eql('test.example.org')
    expect(handshake.port).to eql(301)
    expect(handshake.path).to eql('/test_path')
    expect(handshake.query).to eql('query=true')
  end

  it 'should parse url' do
    @request_params = { url: 'ws://test.example.org:301/test_path?query=true' }
    expect(handshake.host).to eql('test.example.org')
    expect(handshake.port).to eql(301)
    expect(handshake.path).to eql('/test_path')
    expect(handshake.query).to eql('query=true')
  end

  it 'should resolve correct path with root server provided' do
    @request_params = { url: 'ws://test.example.org' }
    expect(handshake.path).to eql('/')
  end

  it 'should return valid response' do
    validate_request
  end

  it 'should allow custom path' do
    @request_params = { path: '/custom' }
    validate_request
  end

  it 'should allow query in path' do
    @request_params = { query: 'test=true' }
    validate_request
  end

  it 'should allow custom port' do
    @request_params = { port: 123 }
    validate_request
  end

  it 'should allow custom headers' do
    @request_params = { headers: { 'aaa' => 'bbb' } }
    validate_request
  end

  it 'should recognize unfinished requests' do
    handshake << server_response[0..-20]

    expect(handshake).not_to be_finished
    expect(handshake).not_to be_valid
  end

  it 'should disallow requests with invalid request method' do
    handshake << server_response.gsub('101', '404')

    expect(handshake).to be_finished
    expect(handshake).not_to be_valid
    expect(handshake.error).to eql(:invalid_status_code)
  end
end


text:
base="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $base/env-setup.sh

set -e
set -u

APP_LOG_NAME="ZooKeeper"
INSTALL_DIR=$ZOOKEEPER_INSTALL_DIR
DATA_DIR=$ZOOKEEPER_DATA_DIR
LOG_DIR=$ZOOKEEPER_LOG_DIR
SVC_NAME=$SVC_NAME_ZOOKEEPER
CLIENT_PORT=$ZOOKEEPER_CLIENT_PORT
ZK_SERVER_ID=$(($SERVER_INDEX + 1))

if [ -f /etc/redhat-release ]; then
  log "[$APP_LOG_NAME]: Installing CentOS dependencies..."
  install_packages java-1.8.0-openjdk-devel
fi
if [ -f /etc/lsb-release ]; then
  log "[$APP_LOG_NAME]: Installing Debian dependencies..."
  install_packages openjdk-8-jdk
fi

log "[$APP_LOG_NAME]: Downloading ${ZOOKEEPER_VERSION}..."
install_zookeeper zk_version=${ZOOKEEPER_VERSION} \
                  zk_install_directory=${INSTALL_DIR} \
                  zk_data_directory=${DATA_DIR} \
                  zk_id=${ZK_SERVER_ID}

log "[$APP_LOG_NAME]: Setting up the service..."
create_service service_name=${SVC_NAME} \
               service_Description=${APP_LOG_NAME} \
               service_Type=forking \
               service_Restart=on-failure \
               service_Environment="ZOO_LOG_DIR=${LOG_DIR} JMXPORT=${ZOOKEEPER_JMX_PORT}" \
               service_ExecStart="${INSTALL_DIR}/bin/zkServer.sh start" \
               service_ExecStop="${INSTALL_DIR}/bin/zkServer.sh stop"

log "[$APP_LOG_NAME]: Enabling the service..."
enable_service ${SVC_NAME}

log "[$APP_LOG_NAME]: Setting up Consul service..."
create_consul_service service_name=${SVC_NAME} \
                      service_id=zookeeper.${ZK_SERVER_ID} \
                      service_address=${IPV4_PRIVATE} \
                      service_port=${CLIENT_PORT}

log "[$APP_LOG_NAME]: Setting up Consul watch..."
create_consul_watch watch_name=watch-${SVC_NAME}-service \
                    watch_type=service \
                    watch_service=${SVC_NAME} \
                    watch_handler=${base}/consul/watch-zookeeper.py

reload_consul

log "[$APP_LOG_NAME]: Done."
log "[$APP_LOG_NAME]: The service will be started by the watch."


text:
package org.keycloak.theme;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;

import org.junit.Test;

/**
 * @author Hiroyuki Wada
 */
public class PropertiesUtilTest {

    @Test
    public void testDetectEncoding() throws Exception {
        Charset encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: utf-8\nkey=value".getBytes()));
        assertEquals(Charset.forName("utf-8"), encoding);

        encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: Shift_JIS\nkey=value".getBytes()));
        assertEquals(Charset.forName("Shift_JIS"), encoding);
    }

    @Test
    public void testDefaultEncoding() throws Exception {
        Charset encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("key=value".getBytes()));
        assertEquals(Charset.forName("ISO-8859-1"), encoding);

        encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: unknown\nkey=value".getBytes()));
        assertEquals(Charset.forName("ISO-8859-1"), encoding);

        encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("\n# encoding: utf-8\nkey=value".getBytes()));
        assertEquals(Charset.forName("ISO-8859-1"), encoding);

        encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("".getBytes()));
        assertEquals(Charset.forName("ISO-8859-1"), encoding);
    }
}


text:
> DOM Handler provides handful methods to manipulate/browse a DOM Document.

[![License](https://poser.pugx.org/wsdltophp/domhandler/license)](https://packagist.org/packages/wsdltophp/domhandler)
[![Latest Stable Version](https://poser.pugx.org/wsdltophp/domhandler/version.png)](https://packagist.org/packages/wsdltophp/domhandler)
[![TeamCity build status](https://teamcity.mikael-delsol.fr/app/rest/builds/buildType:id:WsdlHandler_Build/statusIcon.svg)](https://github.com/WsdlToPhp/DomHandler)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/WsdlToPhp/DomHandler/badges/quality-score.png)](https://scrutinizer-ci.com/g/WsdlToPhp/DomHandler/)
[![Code Coverage](https://scrutinizer-ci.com/g/WsdlToPhp/DomHandler/badges/coverage.png)](https://scrutinizer-ci.com/g/WsdlToPhp/DomHandler/)
[![Total Downloads](https://poser.pugx.org/wsdltophp/domhandler/downloads)](https://packagist.org/packages/wsdltophp/domhandler)
[![StyleCI](https://styleci.io/repos/87977980/shield)](https://styleci.io/repos/87977980)
[![SymfonyInsight](https://insight.symfony.com/projects/93e73feb-60bc-4e99-a3ce-87e537c61fed/mini.svg)](https://insight.symfony.com/projects/93e73feb-60bc-4e99-a3ce-87e537c61fed)

DomHandler uses the [decorator design pattern](https://en.wikipedia.org/wiki/Decorator_pattern) in order to ease DOM handling.

The source code has been originally created into the [PackageGenerator](https://github.com/WsdlToPhp/PackageGenerator) project but it felt that it had the possibility to live by itself and to evolve independtly from the PackageGenerator project if necessary.

## Testing using [Docker](https://www.docker.com/)
Thanks to the [Docker image](https://hub.docker.com/r/splitbrain/phpfarm) of [phpfarm](https://github.com/fpoirotte/phpfarm), tests can be run locally under *any* PHP version using the cli:
- php-7.4

First of all, you need to create your container which you can do using [docker-compose](https://docs.docker.com/compose/) by running the below command line from the root directory of the project:
```bash
$ docker-compose up -d --build
```

You then have a container named `dom_handler` in which you can run `composer` commands and `php cli` commands such as:
```bash
# install deps in container (using update ensure it does use the composer.lock file if there is any)
$ docker exec -it dom_handler php-7.4 /usr/bin/composer update
# run tests in container
$ docker exec -it dom_handler php-7.4 -dmemory_limit=-1 vendor/bin/phpunit
```

## Contributing

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

## Credits

Developers who helped on this project are listed in the [composer.json](composer.json#L8) file as `Contributor` and are:
- [phordijk](https://github.com/phordijk)

## FAQ

Feel free to [create an issue](https://github.com/WsdlToPhp/DomHandler/issues/new).

## License

The MIT License (MIT). Please see [License File](LICENSE) for more information.


text:
require 'spec_helper'

describe Clearance::RackSession do
  it 'injects a clearance session into the environment' do
    headers = { 'X-Roaring-Lobster' => 'Red' }
    app = Rack::Builder.new do
      use Clearance::RackSession
      run lambda { |env| Rack::Response.new(env[:clearance], 200, headers).finish }
    end

    env = Rack::MockRequest.env_for('/')
    expected_session = "the session"
    allow(expected_session).to receive(:add_cookie_to_headers)
    allow(Clearance::Session).to receive(:new).
      with(env).
      and_return(expected_session)

    response = Rack::MockResponse.new(*app.call(env))

    expect(response.body).to eq expected_session
    expect(expected_session).to have_received(:add_cookie_to_headers).
      with(hash_including(headers))
  end
end


text:
This provides guidance on how to contribute various content to `rocksdb.org`.

## Getting started

You should only have to do these one time.

- Rename this file to `CONTRIBUTING.md`.
- Rename `EXAMPLE-README-FOR-RUNNING-DOCS.md` to `README.md` (replacing the existing `README.md` that came with the template).
- Rename `EXAMPLE-LICENSE` to `LICENSE`.
- Review the [template information](./TEMPLATE-INFORMATION.md).
- Review `./_config.yml`.
- Make sure you update `title`, `description`, `tagline` and `gacode` (Google Analytics) in `./_config.yml`.

## Basic Structure

Most content is written in markdown. You name the file `something.md`, then have a header that looks like this:

```
---
docid: getting-started
title: Getting started with ProjectName
layout: docs
permalink: /docs/getting-started.html
---
```

Customize these values for each document, blog post, etc.

> The filename of the `.md` file doesn't actually matter; what is important is the `docid` being unique and the `permalink` correct and unique too).

## Landing page

Modify `index.md` with your new or updated content.

If you want a `GridBlock` as part of your content, you can do so directly with HTML:

```
<div class="gridBlock">
  <div class="blockElement twoByGridBlock alignLeft">
    <div class="blockContent">
      <h3>Your Features</h3>
      <ul>
        <li>The <a href="http://example.org/">Example</a></li>
        <li><a href="http://example.com">Another Example</a></li>
      </ul>
    </div>
  </div>

  <div class="blockElement twoByGridBlock alignLeft">
    <div class="blockContent">
      <h3>More information</h3>
      <p>
         Stuff here
      </p>
    </div>
  </div>
</div>
```

or with a combination of changing `./_data/features.yml` and adding some Liquid to `index.md`, such as:

```
{% include content/gridblocks.html data_source=site.data.features imagealign="bottom"%}
```

## Blog

To modify a blog post, edit the appopriate markdown file in `./_posts/`.

Adding a new blog post is a four-step process.

> Some posts have a `permalink` and `comments` in the blog post YAML header. You will not need these for new blog posts. These are an artifact of migrating the blog from Wordpress to gh-pages.

1. Create your blog post in `./_posts/` in markdown (file extension `.md` or `.markdown`). See current posts in that folder or `./doc-type-examples/2016-04-07-blog-post-example.md` for an example of the YAML format. **If the `./_posts` directory does not exist, create it**.
  - You can add a `<!--truncate-->` tag in the middle of your post such that you show only the excerpt above that tag in the main `/blog` index on your page.
1. If you have not authored a blog post before, modify the `./_data/authors.yml` file with the `author` id you used in your blog post, along with your full name and Facebook ID to get your profile picture.
1. [Run the site locally](./README.md) to test your changes. It will be at `http://127.0.0.1/blog/your-new-blog-post-title.html`
1. Push your changes to GitHub.

## Docs

To modify docs, edit the appropriate markdown file in `./_docs/`.

To add docs to the site....

1. Add your markdown file to the `./_docs/` folder. See `./doc-type-examples/docs-hello-world.md` for an example of the YAML header format. **If the `./_docs/` directory does not exist, create it**.
  - You can use folders in the `./_docs/` directory to organize your content if you want.
1. Update `_data/nav_docs.yml` to add your new document to the navigation bar. Use the `docid` you put in your doc markdown in as the `id` in the `_data/nav_docs.yml` file.
1. [Run the site locally](./README.md) to test your changes. It will be at `http://127.0.0.1/docs/your-new-doc-permalink.html`
1. Push your changes to GitHub.

## Header Bar

To modify the header bar, change `./_data/nav.yml`.

## Top Level Page

To modify a top-level page, edit the appropriate markdown file in `./top-level/`

If you want a top-level page (e.g., http://your-site.com/top-level.html) -- not in `/blog/` or `/docs/`....

1. Create a markdown file in the root `./top-level/`. See `./doc-type-examples/top-level-example.md` for more information.
1. If you want a visible link to that file, update `_data/nav.yml` to add a link to your new top-level document in the header bar.

   > This is not necessary if you just want to have a page that is linked to from another page, but not exposed as direct link to the user.

1. [Run the site locally](./README.md) to test your changes. It will be at `http://127.0.0.1/your-top-level-page-permalink.html`
1. Push your changes to GitHub.

## Other Changes

- CSS: `./css/main.css` or `./_sass/*.scss`.
- Images: `./static/images/[docs | posts]/....`
- Main Blog post HTML: `./_includes/post.html`
- Main Docs HTML: `./_includes/doc.html`