text:
require 'rspec'
require_relative 'todo'

describe "Task" do
  let(:task) {Task.new("title", "description")}
  context "#initialize" do
    it "creates a task!" do
      expect(task).to be_an_instance_of Task
    end

    # it "creates a title for Task" do
    # end
  end

  context "#title" do
    it "returns the title" do
      expect(task.title).to eq("title")
    end
  end

  context "#description" do
    it "returns the description" do
      exepct(task.description).to eq("description")
    end
  end

  context "#status" do
    it 'defaults as Incomplete' do
      expect(task.status).to eq("incomplete")
    end
  end

  context "#created_at" do
    it 'defaults to when it was initialized' do
      expect(task.created_at).to be_an_instance_of Time
    end
  end

  context "#mark_as_complete!" do
    it "changes the status of a task to complete" do
      task.mark_as_complete!
      expect(task.status).to eq("complete")
    end
  end

  context "#mark_as_incomplete!" do
    it "changes the status of a task to incomplete" do
      task.stub(:status) {"YOLO"}
      task.mark_as_incomplete!
      expect(task.status).to eq("incomplete")
    end
  end

  context "#complete?" do
    it "returns true when status is complete" do
      task.stub(:status) {"complete"}
      expect(task.complete?).to eq(true)
    end

    it "returns false when status is incomplete" do
      task.stub(:status) {"incomplete"}
      expect(task.complete?).to eq(false)
    end
  end
end


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="@drawable/sf__oauth_background"
    android:orientation="vertical" >

    <include layout="@layout/sf__login_header" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <LinearLayout style="@style/SalesforceSDK.Login.Container">

                <TextView
                    style="@style/SalesforceSDK.ServerPicker.Title"
                    android:text="@string/sf__login_title"
				/>

                <View style="@style/SalesforceSDK.ServerPicker.Spacer" />

                <WebView
                    android:id="@+id/sf__oauth_webview"
                    android:layout_width="@dimen/sf__login_webview_width"
                    android:layout_height="match_parent"
                    android:scrollbars="none"
                />

            </LinearLayout>
        </RelativeLayout>
    </ScrollView>
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
<?php

// JAMNotasFrontendBundle:EstudioORM:recuperarNotas.html.twig
return array (
);


text:
#include "clar_libgit2.h"
#include "fileops.h"
#include "git2/attr.h"
#include "attr.h"

#include "attr_expect.h"

static git_repository *g_repo = NULL;

void test_attr_repo__initialize(void)
{
	/* Before each test, instantiate the attr repo from the fixtures and
	 * rename the .gitted to .git so it is a repo with a working dir.
	 * Also rename gitattributes to .gitattributes, because it contains
	 * macro definitions which are only allowed in the root.
	 */
	g_repo = cl_git_sandbox_init("attr");
}

void test_attr_repo__cleanup(void)
{
	cl_git_sandbox_cleanup();
	g_repo = NULL;
}

void test_attr_repo__get_one(void)
{
	struct attr_expected test_cases[] = {
		{ "root_test1", "repoattr", EXPECT_TRUE, NULL },
		{ "root_test1", "rootattr", EXPECT_TRUE, NULL },
		{ "root_test1", "missingattr", EXPECT_UNDEFINED, NULL },
		{ "root_test1", "subattr", EXPECT_UNDEFINED, NULL },
		{ "root_test1", "negattr", EXPECT_UNDEFINED, NULL },
		{ "root_test2", "repoattr", EXPECT_TRUE, NULL },
		{ "root_test2", "rootattr", EXPECT_FALSE, NULL },
		{ "root_test2", "missingattr", EXPECT_UNDEFINED, NULL },
		{ "root_test2", "multiattr", EXPECT_FALSE, NULL },
		{ "root_test3", "repoattr", EXPECT_TRUE, NULL },
		{ "root_test3", "rootattr", EXPECT_UNDEFINED, NULL },
		{ "root_test3", "multiattr", EXPECT_STRING, "3" },
		{ "root_test3", "multi2", EXPECT_UNDEFINED, NULL },
		{ "sub/subdir_test1", "repoattr", EXPECT_TRUE, NULL },
		{ "sub/subdir_test1", "rootattr", EXPECT_TRUE, NULL },
		{ "sub/subdir_test1", "missingattr", EXPECT_UNDEFINED, NULL },
		{ "sub/subdir_test1", "subattr", EXPECT_STRING, "yes" },
		{ "sub/subdir_test1", "negattr", EXPECT_FALSE, NULL },
		{ "sub/subdir_test1", "another", EXPECT_UNDEFINED, NULL },
		{ "sub/subdir_test2.txt", "repoattr", EXPECT_TRUE, NULL },
		{ "sub/subdir_test2.txt", "rootattr", EXPECT_TRUE, NULL },
		{ "sub/subdir_test2.txt", "missingattr", EXPECT_UNDEFINED, NULL },
		{ "sub/subdir_test2.txt", "subattr", EXPECT_STRING, "yes" },
		{ "sub/subdir_test2.txt", "negattr", EXPECT_FALSE, NULL },
		{ "sub/subdir_test2.txt", "another", EXPECT_STRING, "zero" },
		{ "sub/subdir_test2.txt", "reposub", EXPECT_TRUE, NULL },
		{ "sub/sub/subdir.txt", "another", EXPECT_STRING, "one" },
		{ "sub/sub/subdir.txt", "reposubsub", EXPECT_TRUE, NULL },
		{ "sub/sub/subdir.txt", "reposub", EXPECT_UNDEFINED, NULL },
		{ "does-not-exist", "foo", EXPECT_STRING, "yes" },
		{ "sub/deep/file", "deepdeep", EXPECT_TRUE, NULL },
		{ "sub/sub/d/no", "test", EXPECT_STRING, "a/b/d/*" },
		{ "sub/sub/d/yes", "test", EXPECT_UNDEFINED, NULL },
		{ NULL, NULL, 0, NULL }
	}, *scan;

	for (scan = test_cases; scan->path != NULL; scan++) {
		const char *value;
		cl_git_pass(git_attr_get(&value, g_repo, 0, scan->path, scan->attr));
		attr_check_expected(scan->expected, scan->expected_str, scan->attr, value);
	}

	cl_assert(git_attr_cache__is_cached(g_repo, 0, ".git/info/attributes"));
	cl_assert(git_attr_cache__is_cached(g_repo, 0, ".gitattributes"));
	cl_assert(git_attr_cache__is_cached(g_repo, 0, "sub/.gitattributes"));
}

void test_attr_repo__get_many(void)
{
	const char *names[4] = { "repoattr", "rootattr", "missingattr", "subattr" };
	const char *values[4];

	cl_git_pass(git_attr_get_many(values, g_repo, 0, "root_test1", 4, names));

	cl_assert(GIT_ATTR_TRUE(values[0]));
	cl_assert(GIT_ATTR_TRUE(values[1]));
	cl_assert(GIT_ATTR_UNSPECIFIED(values[2]));
	cl_assert(GIT_ATTR_UNSPECIFIED(values[3]));

	cl_git_pass(git_attr_get_many(values, g_repo, 0, "root_test2", 4, names));

	cl_assert(GIT_ATTR_TRUE(values[0]));
	cl_assert(GIT_ATTR_FALSE(values[1]));
	cl_assert(GIT_ATTR_UNSPECIFIED(values[2]));
	cl_assert(GIT_ATTR_UNSPECIFIED(values[3]));

	cl_git_pass(git_attr_get_many(values, g_repo, 0, "sub/subdir_test1", 4, names));

	cl_assert(GIT_ATTR_TRUE(values[0]));
	cl_assert(GIT_ATTR_TRUE(values[1]));
	cl_assert(GIT_ATTR_UNSPECIFIED(values[2]));
	cl_assert_equal_s("yes", values[3]);
}

void test_attr_repo__get_many_in_place(void)
{
	const char *vals[4] = { "repoattr", "rootattr", "missingattr", "subattr" };

	/* it should be legal to look up values into the same array that has
	 * the attribute names, overwriting each name as the value is found.
	 */

	cl_git_pass(git_attr_get_many(vals, g_repo, 0, "sub/subdir_test1", 4, vals));

	cl_assert(GIT_ATTR_TRUE(vals[0]));
	cl_assert(GIT_ATTR_TRUE(vals[1]));
	cl_assert(GIT_ATTR_UNSPECIFIED(vals[2]));
	cl_assert_equal_s("yes", vals[3]);
}

static int count_attrs(
	const char *name,
	const char *value,
	void *payload)
{
	GIT_UNUSED(name);
	GIT_UNUSED(value);

	*((int *)payload) += 1;

	return 0;
}

static int cancel_iteration(
	const char *name,
	const char *value,
	void *payload)
{
	GIT_UNUSED(name);
	GIT_UNUSED(value);

	*((int *)payload) -= 1;

	if (*((int *)payload) < 0)
		return -1;

	return 0;
}

void test_attr_repo__foreach(void)
{
	int count;

	count = 0;
	cl_git_pass(git_attr_foreach(
		g_repo, 0, "root_test1", &count_attrs, &count));
	cl_assert(count == 2);

	count = 0;
	cl_git_pass(git_attr_foreach(g_repo, 0, "sub/subdir_test1",
		&count_attrs, &count));
	cl_assert(count == 4); /* repoattr, rootattr, subattr, negattr */

	count = 0;
	cl_git_pass(git_attr_foreach(g_repo, 0, "sub/subdir_test2.txt",
		&count_attrs, &count));
	cl_assert(count == 6); /* repoattr, rootattr, subattr, reposub, negattr, another */

	count = 2;
	cl_assert_equal_i(
		GIT_EUSER, git_attr_foreach(
			g_repo, 0, "sub/subdir_test1", &cancel_iteration, &count)
	);
}

void test_attr_repo__manpage_example(void)
{
	const char *value;

	cl_git_pass(git_attr_get(&value, g_repo, 0, "sub/abc", "foo"));
	cl_assert(GIT_ATTR_TRUE(value));

	cl_git_pass(git_attr_get(&value, g_repo, 0, "sub/abc", "bar"));
	cl_assert(GIT_ATTR_UNSPECIFIED(value));

	cl_git_pass(git_attr_get(&value, g_repo, 0, "sub/abc", "baz"));
	cl_assert(GIT_ATTR_FALSE(value));

	cl_git_pass(git_attr_get(&value, g_repo, 0, "sub/abc", "merge"));
	cl_assert_equal_s("filfre", value);

	cl_git_pass(git_attr_get(&value, g_repo, 0, "sub/abc", "frotz"));
	cl_assert(GIT_ATTR_UNSPECIFIED(value));
}

void test_attr_repo__macros(void)
{
	const char *names[5] = { "rootattr", "binary", "diff", "crlf", "frotz" };
	const char *names2[5] = { "mymacro", "positive", "negative", "rootattr", "another" };
	const char *names3[3] = { "macro2", "multi2", "multi3" };
	const char *values[5];

	cl_git_pass(git_attr_get_many(values, g_repo, 0, "binfile", 5, names));

	cl_assert(GIT_ATTR_TRUE(values[0]));
	cl_assert(GIT_ATTR_TRUE(values[1]));
	cl_assert(GIT_ATTR_FALSE(values[2]));
	cl_assert(GIT_ATTR_FALSE(values[3]));
	cl_assert(GIT_ATTR_UNSPECIFIED(values[4]));

	cl_git_pass(git_attr_get_many(values, g_repo, 0, "macro_test", 5, names2));

	cl_assert(GIT_ATTR_TRUE(values[0]));
	cl_assert(GIT_ATTR_TRUE(values[1]));
	cl_assert(GIT_ATTR_FALSE(values[2]));
	cl_assert(GIT_ATTR_UNSPECIFIED(values[3]));
	cl_assert_equal_s("77", values[4]);

	cl_git_pass(git_attr_get_many(values, g_repo, 0, "macro_test", 3, names3));

	cl_assert(GIT_ATTR_TRUE(values[0]));
	cl_assert(GIT_ATTR_FALSE(values[1]));
	cl_assert_equal_s("answer", values[2]);
}

void test_attr_repo__bad_macros(void)
{
	const char *names[6] = { "rootattr", "positive", "negative",
		"firstmacro", "secondmacro", "thirdmacro" };
	const char *values[6];

	cl_git_pass(git_attr_get_many(values, g_repo, 0, "macro_bad", 6, names));

	/* these three just confirm that the "mymacro" rule ran */
	cl_assert(GIT_ATTR_UNSPECIFIED(values[0]));
	cl_assert(GIT_ATTR_TRUE(values[1]));
	cl_assert(GIT_ATTR_FALSE(values[2]));

	/* file contains:
	 *     # let's try some malicious macro defs
	 *     [attr]firstmacro -thirdmacro -secondmacro
	 *     [attr]secondmacro firstmacro -firstmacro
	 *     [attr]thirdmacro secondmacro=hahaha -firstmacro
	 *     macro_bad firstmacro secondmacro thirdmacro
	 *
	 * firstmacro assignment list ends up with:
	 *     -thirdmacro -secondmacro
	 * secondmacro assignment list expands "firstmacro" and ends up with:
	 *     -thirdmacro -secondmacro -firstmacro
	 * thirdmacro assignment don't expand so list ends up with:
	 *     secondmacro="hahaha"
	 *
	 * macro_bad assignment list ends up with:
	 *     -thirdmacro -secondmacro firstmacro &&
	 *     -thirdmacro -secondmacro -firstmacro secondmacro &&
	 *     secondmacro="hahaha" thirdmacro
	 *
	 * so summary results should be:
	 *     -firstmacro secondmacro="hahaha" thirdmacro
	 */
	cl_assert(GIT_ATTR_FALSE(values[3]));
	cl_assert_equal_s("hahaha", values[4]);
	cl_assert(GIT_ATTR_TRUE(values[5]));
}

#define CONTENT "I'm going to be dynamically processed\r\n" \
	"And my line endings...\r\n" \
	"...are going to be\n" \
	"normalized!\r\n"

#define GITATTR "* text=auto\n" \
	"*.txt text\n" \
	"*.data binary\n"

static void add_to_workdir(const char *filename, const char *content)
{
	git_buf buf = GIT_BUF_INIT;

	cl_git_pass(git_buf_joinpath(&buf, "attr", filename));
	cl_git_rewritefile(git_buf_cstr(&buf), content);

	git_buf_free(&buf);
}

static void assert_proper_normalization(git_index *index, const char *filename, const char *expected_sha)
{
	size_t index_pos;
	const git_index_entry *entry;

	add_to_workdir(filename, CONTENT);
	cl_git_pass(git_index_add_bypath(index, filename));

	cl_assert(!git_index_find(&index_pos, index, filename));

	entry = git_index_get_byindex(index, index_pos);
	cl_assert_equal_i(0, git_oid_streq(&entry->oid, expected_sha));
}

void test_attr_repo__staging_properly_normalizes_line_endings_according_to_gitattributes_directives(void)
{
	git_index* index;

	cl_git_pass(git_repository_index(&index, g_repo));

	add_to_workdir(".gitattributes", GITATTR);

	assert_proper_normalization(index, "text.txt", "22c74203bace3c2e950278c7ab08da0fca9f4e9b");
	assert_proper_normalization(index, "huh.dunno", "22c74203bace3c2e950278c7ab08da0fca9f4e9b");
	assert_proper_normalization(index, "binary.data", "66eeff1fcbacf589e6d70aa70edd3fce5be2b37c");

	git_index_free(index);
}


text:
using NBot.Core.Brains;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using ServiceStack;

namespace NBot.AzureTableStorageBrain
{
    public class AzureTableStorageBrain : IBrain
    {
        private readonly string _partitionKey;
        private readonly CloudTable _table;
        private const string NbotTableName = "NBot";

        public AzureTableStorageBrain(string accountName, string accountKey, string partitionKey = "Brain")
            : this(string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountName, accountKey), partitionKey)
        {

        }

        public AzureTableStorageBrain(string connectionString, string partitionKey)
        {
            _partitionKey = partitionKey;
            CloudStorageAccount storrageAccount = CloudStorageAccount.Parse(connectionString);
            CloudTableClient tableClient = storrageAccount.CreateCloudTableClient();
            _table = tableClient.GetTableReference(NbotTableName);
            _table.CreateIfNotExists();
        }

        public object GetValue(string key)
        {
            var result = GetAzureTableResult(key).Result as BrainEntity;
            return result != null ? result.Value.FromJson<object>() : null;
        }

        public void SetValue(string key, object value)
        {
            var tableResult = GetAzureTableResult(key);
            var entity = tableResult.Result as BrainEntity;

            if (entity != null)
            {
                entity.Value = value.ToJson();
                var operation = TableOperation.InsertOrReplace(entity);
                _table.Execute(operation);
            }
            else
            {
                var operation = TableOperation.Insert(new BrainEntity(_partitionKey, key, value));
                _table.Execute(operation);
            }
        }

        public bool ContainsKey(string key)
        {
            return GetAzureTableResult(key).Result != null;
        }

        public void RemoveKey(string key)
        {
            var result = GetAzureTableResult(key).Result as BrainEntity;
            if (result != null)
            {
                var operation = TableOperation.Delete(result);
                _table.Execute(operation);
            }
        }

        private TableResult GetAzureTableResult(string key)
        {
            var operation = TableOperation.Retrieve<BrainEntity>(_partitionKey, key);
            var result = _table.Execute(operation);
            return result;
        }
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonkTinkerDialogue : MonoBehaviour {
	private int step = 0;
	public GameObject kettle;
	public GameObject bunbuku;
	public GameObject monk;
	public GameObject tinker;
	private DialogueSystemBadger dialogueSystemBadger;
	private DialogueSystemMonk dialogueSystemMonk;
	private DialogueSystemTinker dialogueSystemTinker;
	private GameObject monkBox = null;
	private GameObject badgerBox = null;
	private GameObject tinkerBox = null;
	public GameObject speechBubble;
	private bool started = false;
	SpriteAnimationController MonkSAC;
	SpriteAnimationController TinkerSAC;
	SpriteAnimationController kettleSac;
	bool isDoneAnimating = true;

	// Use this for initialization
	void Start () {
		dialogueSystemBadger = GameObject.Find("EventSystem").GetComponent<DialogueSystemBadger>();
		dialogueSystemMonk = GameObject.Find("EventSystem").GetComponent<DialogueSystemMonk>();
		dialogueSystemTinker = GameObject.Find("EventSystem").GetComponent<DialogueSystemTinker>();
		TinkerSAC = tinker.transform.GetChild(0).GetComponent<SpriteAnimationController>();
		MonkSAC = monk.transform.GetChild(0).GetComponent<SpriteAnimationController>();
		kettleSac = kettle.GetComponent<SpriteAnimationController>();
		StartCoroutine(DelayedStart());
		TinkerSAC.sendToIdle();
		MonkSAC.sendToIdle();
	}

	void Update () {
		if(!DialogueSystemMonk.isTalking && !DialogueSystemBadger.isTalking && !DialogueSystemTinker.isTalking && isDoneAnimating && started){
			++step;
			conversation(step);
		}
	}

	void conversation(int i){ //add enumerator
		if(i == 0){
			StartCoroutine(dialogueSystemMonk.speak(0,1, speechBubble, monkBox));
		}
		if(i == 1){
			StartCoroutine(dialogueSystemTinker.speak(0,3, speechBubble, tinkerBox));
			isDoneAnimating = false;
			StartCoroutine(Animation1());
		}
		if(i == 2){
			++step;
			conversation(step);
		}
		if(i == 3){
			StartCoroutine(dialogueSystemBadger.speak(0,2, speechBubble, badgerBox));
		}
		if(i == 4){
			StartCoroutine(dialogueSystemTinker.speak(4,6, speechBubble, tinkerBox));
		}
		if(i == 5){
			StartCoroutine(dialogueSystemBadger.speak(3,8, speechBubble, badgerBox));
			StartCoroutine(DelayedEnd());
		}
	}

	IEnumerator DelayedStart(){
		var loadText = GameObject.Find("EventSystem").GetComponent<LoadText>();
		while(!loadText.isDone){
			yield return null;
		}
		conversation(step);
		started = true;
	}
	IEnumerator DelayedEnd(){
		while(DialogueSystemBadger.isTalking){
			yield return null;
		}
		EndLevel.sceneFinished = true;
	}

	IEnumerator Animation1(){
		while(DialogueSystemTinker.isTalking){
			yield return null;
		}
		yield return new WaitForSecondsRealtime(0.5f);
		MonkSAC.nextAnimation = Enums.AnimStates.MoveForward;
		float elapsedTime = 0f;
		float yPos = monk.transform.position.y;
		while(elapsedTime <= 3f){
			monk.transform.position = new Vector3(monk.transform.position.x, yPos - Mathf.SmoothStep(0f,5,0.5f*elapsedTime),0);
			elapsedTime += Time.deltaTime;
			yield return new WaitForEndOfFrame();
		}
		GameObject.Find("Head Monk").SetActive(false);
		kettle.SetActive(true);
		yield return new WaitForSecondsRealtime(1f);
		kettleSac.nextAnimation = Enums.AnimStates.MoveRight;
		yield return new WaitForSecondsRealtime(3f);
		kettle.SetActive(false);
		bunbuku.SetActive(true);
		isDoneAnimating = true;
	}
}


text:
require 'spec_helper'

module Spree
  describe Api::V1::CountriesController, :type => :controller do
    render_views

    before do
      stub_authentication!
      @state = create(:state)
      @country = @state.country
    end

    it "gets all countries" do
      api_get :index
      expect(json_response['countries'].first['iso3']).to eq @country.iso3
    end

    context "with two countries" do
      before { @zambia = create(:country, :name => "Zambia") }

      it "can view all countries" do
        api_get :index
        expect(json_response['count']).to eq(2)
        expect(json_response['current_page']).to eq(1)
        expect(json_response['pages']).to eq(1)
      end

      it 'can query the results through a paramter' do
        api_get :index, :q => { :name_cont => 'zam' }
        expect(json_response['count']).to eq(1)
        expect(json_response['countries'].first['name']).to eq @zambia.name
      end

      it 'can control the page size through a parameter' do
        api_get :index, :per_page => 1
        expect(json_response['count']).to eq(1)
        expect(json_response['current_page']).to eq(1)
        expect(json_response['pages']).to eq(2)
      end
    end

    it "includes states" do
      api_get :show, :id => @country.id
      states = json_response['states']
      expect(states.first['name']).to eq @state.name
    end
  end
end


text:
import * as fs from 'fs-extra';
import * as path from 'path';

import { ts } from 'ts-morph';

import { Application } from './app/application';
import Configuration from './app/configuration';
import FileEngine from './app/engines/file.engine';
import I18nEngine from './app/engines/i18n.engine';

import { ConfigurationFileInterface } from './app/interfaces/configuration-file.interface';
import AngularVersionUtil from './utils/angular-version.util';
import { COMPODOC_DEFAULTS } from './utils/defaults';
import { logger } from './utils/logger';
import { ParserUtil } from './utils/parser.util.class';
import { readConfig, ignoreDirectory } from './utils/utils';

import { cosmiconfigSync } from 'cosmiconfig';

const os = require('os');
const osName = require('os-name');
const pkg = require('../package.json');
const program = require('commander');

const cosmiconfigModuleName = 'compodoc';

let scannedFiles = [];
let excludeFiles;
let includeFiles;
let cwd = process.cwd();

process.setMaxListeners(0);

export class CliApplication extends Application {
    /**
     * Run compodoc from the command line.
     */
    protected start(): any {
        function list(val) {
            return val.split(',');
        }

        program
            .version(pkg.version)
            .usage('<src> [options]')
            .option(
                '-c, --config [config]',
                'A configuration file : .compodocrc, .compodocrc.json, .compodocrc.yaml or compodoc property in package.json'
            )
            .option('-p, --tsconfig [config]', 'A tsconfig.json file')
            .option(
                '-d, --output [folder]',
                'Where to store the generated documentation',
                COMPODOC_DEFAULTS.folder
            )
            .option('-y, --extTheme [file]', 'External styling theme file')
            .option('-n, --name [name]', 'Title documentation', COMPODOC_DEFAULTS.title)
            .option(
                '-a, --assetsFolder [folder]',
                'External assets folder to copy in generated documentation folder'
            )
            .option('-o, --open [value]', 'Open the generated documentation')
            .option(
                '-t, --silent',
                "In silent mode, log messages aren't logged in the console",
                false
            )
            .option(
                '-s, --serve',
                'Serve generated documentation (default http://localhost:8080/)',
                false
            )
            .option('--host [host]', 'Change default host address')
            .option('-r, --port [port]', 'Change default serving port', COMPODOC_DEFAULTS.port)
            .option(
                '-w, --watch',
                'Watch source files after serve and force documentation rebuild',
                false
            )
            .option(
                '-e, --exportFormat [format]',
                'Export in specified format (json, html)',
                COMPODOC_DEFAULTS.exportFormat
            )
            .option('--files [files]', 'Files provided by external tool, used for coverage test')
            .option(
                '--language [language]',
                'Language used for the generated documentation (de-DE, en-US, es-ES, fr-FR, hu-HU, it-IT, ja-JP, ko-KR, nl-NL, pl-PL, pt-BR, sk-SK, zh-CN, zh-TW)',
                COMPODOC_DEFAULTS.language
            )
            .option(
                '--theme [theme]',
                "Choose one of available themes, default is 'gitbook' (laravel, original, material, postmark, readthedocs, stripe, vagrant)"
            )
            .option(
                '--hideGenerator',
                'Do not print the Compodoc link at the bottom of the page',
                false
            )
            .option(
                '--hideDarkModeToggle',
                'Do not show dark mode toggle button at the top right position of the page',
                false
            )
            .option(
                '--toggleMenuItems <items>',
                "Close by default items in the menu values : ['all'] or one of these ['modules','components','directives','controllers','entities','classes','injectables','guards','interfaces','interceptors','pipes','miscellaneous','additionalPages']",
                list,
                COMPODOC_DEFAULTS.toggleMenuItems
            )
            .option(
                '--navTabConfig <tab configs>',
                `List navigation tab objects in the desired order with two string properties ("id" and "label"). \
Double-quotes must be escaped with '\\'. \
Available tab IDs are "info", "readme", "source", "templateData", "styleData", "tree", and "example". \
Note: Certain tabs will only be shown if applicable to a given dependency`,
                list,
                JSON.stringify(COMPODOC_DEFAULTS.navTabConfig)
            )
            .option(
                '--templates [folder]',
                'Path to directory of Handlebars templates to override built-in templates'
            )
            .option('--includes [path]', 'Path of external markdown files to include')
            .option(
                '--includesName [name]',
                'Name of item menu of externals markdown files',
                COMPODOC_DEFAULTS.additionalEntryName
            )
            .option(
                '--coverageTest [threshold]',
                'Test command of documentation coverage with a threshold (default 70)'
            )
            .option(
                '--coverageMinimumPerFile [minimum]',
                'Test command of documentation coverage per file with a minimum (default 0)'
            )
            .option(
                '--coverageTestThresholdFail [true|false]',
                'Test command of documentation coverage (global or per file) will fail with error or just warn user (true: error, false: warn)',
                COMPODOC_DEFAULTS.coverageTestThresholdFail
            )
            .option('--coverageTestShowOnlyFailed', 'Display only failed files for a coverage test')
            .option(
                '--unitTestCoverage [json-summary]',
                'To include unit test coverage, specify istanbul JSON coverage summary file'
            )
            .option(
                '--disableSourceCode',
                'Do not add source code tab and links to source code',
                false
            )
            .option('--disableDomTree', 'Do not add dom tree tab', false)
            .option('--disableTemplateTab', 'Do not add template tab', false)
            .option('--disableStyleTab', 'Do not add style tab', false)
            .option('--disableGraph', 'Do not add the dependency graph', false)
            .option('--disableCoverage', 'Do not add the documentation coverage report', false)
            .option('--disablePrivate', 'Do not show private in generated documentation', false)
            .option('--disableProtected', 'Do not show protected in generated documentation', false)
            .option('--disableInternal', 'Do not show @internal in generated documentation', false)
            .option(
                '--disableLifeCycleHooks',
                'Do not show Angular lifecycle hooks in generated documentation',
                false
            )
            .option(
                '--disableRoutesGraph',
                'Do not add the routes graph',
                COMPODOC_DEFAULTS.disableRoutesGraph
            )
            .option('--disableSearch', 'Do not add the search input', false)
            .option(
                '--disableDependencies',
                'Do not add the dependencies list',
                COMPODOC_DEFAULTS.disableDependencies
            )
            .option(
                '--disableProperties',
                'Do not add the properties list',
                COMPODOC_DEFAULTS.disableProperties
            )
            .option(
                '--minimal',
                'Minimal mode with only documentation. No search, no graph, no coverage.',
                false
            )
            .option('--customFavicon [path]', 'Use a custom favicon')
            .option('--customLogo [path]', 'Use a custom logo')
            .option('--gaID [id]', 'Google Analytics tracking ID')
            .option('--gaSite [site]', 'Google Analytics site name', COMPODOC_DEFAULTS.gaSite)
            .option(
                '--maxSearchResults [maxSearchResults]',
                'Max search results on the results page. To show all results, set to 0',
                COMPODOC_DEFAULTS.maxSearchResults
            )
            .parse(process.argv);

        let outputHelp = () => {
            program.outputHelp();
            process.exit(1);
        };

        const configExplorer = cosmiconfigSync(cosmiconfigModuleName);

        let configExplorerResult;

        let configFile: ConfigurationFileInterface = {};

        const programOptions = program.opts();

        if (programOptions.config) {
            let configFilePath = programOptions.config;
            let testConfigFilePath = configFilePath.match(process.cwd());
            if (testConfigFilePath && testConfigFilePath.length > 0) {
                configFilePath = configFilePath.replace(process.cwd() + path.sep, '');
            }
            configExplorerResult = configExplorer.load(path.resolve(configFilePath));
        } else {
            configExplorerResult = configExplorer.search();
        }

        if (configExplorerResult) {
            if (typeof configExplorerResult.config !== 'undefined') {
                configFile = configExplorerResult.config;
            }
        }

        if (configFile.output) {
            Configuration.mainData.output = configFile.output;
        }
        if (programOptions.output && programOptions.output !== COMPODOC_DEFAULTS.folder) {
            Configuration.mainData.output = programOptions.output;
        }

        if (configFile.extTheme) {
            Configuration.mainData.extTheme = configFile.extTheme;
        }
        if (programOptions.extTheme) {
            Configuration.mainData.extTheme = programOptions.extTheme;
        }

        if (configFile.language) {
            Configuration.mainData.language = configFile.language;
        }
        if (programOptions.language) {
            Configuration.mainData.language = programOptions.language;
        }

        if (configFile.theme) {
            Configuration.mainData.theme = configFile.theme;
        }
        if (programOptions.theme) {
            Configuration.mainData.theme = programOptions.theme;
        }

        if (configFile.name) {
            Configuration.mainData.documentationMainName = configFile.name;
        }
        if (programOptions.name && programOptions.name !== COMPODOC_DEFAULTS.title) {
            Configuration.mainData.documentationMainName = programOptions.name;
        }

        if (configFile.assetsFolder) {
            Configuration.mainData.assetsFolder = configFile.assetsFolder;
        }
        if (programOptions.assetsFolder) {
            Configuration.mainData.assetsFolder = programOptions.assetsFolder;
        }

        if (configFile.open) {
            Configuration.mainData.open = configFile.open;
        }
        if (programOptions.open) {
            Configuration.mainData.open = programOptions.open;
        }

        if (configFile.toggleMenuItems) {
            Configuration.mainData.toggleMenuItems = configFile.toggleMenuItems;
        }
        if (
            programOptions.toggleMenuItems &&
            programOptions.toggleMenuItems !== COMPODOC_DEFAULTS.toggleMenuItems
        ) {
            Configuration.mainData.toggleMenuItems = programOptions.toggleMenuItems;
        }

        if (configFile.templates) {
            Configuration.mainData.templates = configFile.templates;
        }
        if (programOptions.templates) {
            Configuration.mainData.templates = programOptions.templates;
        }

        if (configFile.navTabConfig) {
            Configuration.mainData.navTabConfig = configFile.navTabConfig;
        }
        if (
            programOptions.navTabConfig &&
            JSON.parse(programOptions.navTabConfig).length !== COMPODOC_DEFAULTS.navTabConfig.length
        ) {
            Configuration.mainData.navTabConfig = JSON.parse(programOptions.navTabConfig);
        }

        if (configFile.includes) {
            Configuration.mainData.includes = configFile.includes;
        }
        if (programOptions.includes) {
            Configuration.mainData.includes = programOptions.includes;
        }

        if (configFile.includesName) {
            Configuration.mainData.includesName = configFile.includesName;
        }
        if (
            programOptions.includesName &&
            programOptions.includesName !== COMPODOC_DEFAULTS.additionalEntryName
        ) {
            Configuration.mainData.includesName = programOptions.includesName;
        }

        if (configFile.silent) {
            logger.silent = false;
        }
        if (programOptions.silent) {
            logger.silent = false;
        }

        if (configFile.serve) {
            Configuration.mainData.serve = configFile.serve;
        }
        if (programOptions.serve) {
            Configuration.mainData.serve = programOptions.serve;
        }

        if (configFile.host) {
            Configuration.mainData.host = configFile.host;
            Configuration.mainData.hostname = configFile.host;
        }
        if (programOptions.host) {
            Configuration.mainData.host = programOptions.host;
            Configuration.mainData.hostname = programOptions.host;
        }

        if (configFile.port) {
            Configuration.mainData.port = configFile.port;
        }
        if (programOptions.port && programOptions.port !== COMPODOC_DEFAULTS.port) {
            Configuration.mainData.port = programOptions.port;
        }

        if (configFile.watch) {
            Configuration.mainData.watch = configFile.watch;
        }
        if (programOptions.watch) {
            Configuration.mainData.watch = programOptions.watch;
        }

        if (configFile.exportFormat) {
            Configuration.mainData.exportFormat = configFile.exportFormat;
        }
        if (
            programOptions.exportFormat &&
            programOptions.exportFormat !== COMPODOC_DEFAULTS.exportFormat
        ) {
            Configuration.mainData.exportFormat = programOptions.exportFormat;
        }

        if (configFile.hideGenerator) {
            Configuration.mainData.hideGenerator = configFile.hideGenerator;
        }
        if (programOptions.hideGenerator) {
            Configuration.mainData.hideGenerator = programOptions.hideGenerator;
        }

        if (configFile.hideDarkModeToggle) {
            Configuration.mainData.hideDarkModeToggle = configFile.hideDarkModeToggle;
        }
        if (programOptions.hideDarkModeToggle) {
            Configuration.mainData.hideDarkModeToggle = programOptions.hideDarkModeToggle;
        }

        if (configFile.coverageTest) {
            Configuration.mainData.coverageTest = true;
            Configuration.mainData.coverageTestThreshold =
                typeof configFile.coverageTest === 'string'
                    ? parseInt(configFile.coverageTest, 10)
                    : COMPODOC_DEFAULTS.defaultCoverageThreshold;
        }
        if (programOptions.coverageTest) {
            Configuration.mainData.coverageTest = true;
            Configuration.mainData.coverageTestThreshold =
                typeof programOptions.coverageTest === 'string'
                    ? parseInt(programOptions.coverageTest, 10)
                    : COMPODOC_DEFAULTS.defaultCoverageThreshold;
        }

        if (configFile.coverageMinimumPerFile) {
            Configuration.mainData.coverageTestPerFile = true;
            Configuration.mainData.coverageMinimumPerFile =
                typeof configFile.coverageMinimumPerFile === 'string'
                    ? parseInt(configFile.coverageMinimumPerFile, 10)
                    : COMPODOC_DEFAULTS.defaultCoverageMinimumPerFile;
        }
        if (programOptions.coverageMinimumPerFile) {
            Configuration.mainData.coverageTestPerFile = true;
            Configuration.mainData.coverageMinimumPerFile =
                typeof programOptions.coverageMinimumPerFile === 'string'
                    ? parseInt(programOptions.coverageMinimumPerFile, 10)
                    : COMPODOC_DEFAULTS.defaultCoverageMinimumPerFile;
        }

        if (configFile.coverageTestThresholdFail) {
            Configuration.mainData.coverageTestThresholdFail =
                configFile.coverageTestThresholdFail === 'false' ? false : true;
        }
        if (programOptions.coverageTestThresholdFail) {
            Configuration.mainData.coverageTestThresholdFail =
                programOptions.coverageTestThresholdFail === 'false' ? false : true;
        }

        if (configFile.coverageTestShowOnlyFailed) {
            Configuration.mainData.coverageTestShowOnlyFailed =
                configFile.coverageTestShowOnlyFailed;
        }
        if (programOptions.coverageTestShowOnlyFailed) {
            Configuration.mainData.coverageTestShowOnlyFailed =
                programOptions.coverageTestShowOnlyFailed;
        }

        if (configFile.unitTestCoverage) {
            Configuration.mainData.unitTestCoverage = configFile.unitTestCoverage;
        }
        if (programOptions.unitTestCoverage) {
            Configuration.mainData.unitTestCoverage = programOptions.unitTestCoverage;
        }

        if (configFile.disableSourceCode) {
            Configuration.mainData.disableSourceCode = configFile.disableSourceCode;
        }
        if (programOptions.disableSourceCode) {
            Configuration.mainData.disableSourceCode = programOptions.disableSourceCode;
        }

        if (configFile.disableDomTree) {
            Configuration.mainData.disableDomTree = configFile.disableDomTree;
        }
        if (programOptions.disableDomTree) {
            Configuration.mainData.disableDomTree = programOptions.disableDomTree;
        }

        if (configFile.disableTemplateTab) {
            Configuration.mainData.disableTemplateTab = configFile.disableTemplateTab;
        }
        if (programOptions.disableTemplateTab) {
            Configuration.mainData.disableTemplateTab = programOptions.disableTemplateTab;
        }

        if (configFile.disableStyleTab) {
            Configuration.mainData.disableStyleTab = configFile.disableStyleTab;
        }
        if (programOptions.disableStyleTab) {
            Configuration.mainData.disableStyleTab = programOptions.disableStyleTab;
        }

        if (configFile.disableGraph) {
            Configuration.mainData.disableGraph = configFile.disableGraph;
        }
        if (programOptions.disableGraph) {
            Configuration.mainData.disableGraph = programOptions.disableGraph;
        }

        if (configFile.disableCoverage) {
            Configuration.mainData.disableCoverage = configFile.disableCoverage;
        }
        if (programOptions.disableCoverage) {
            Configuration.mainData.disableCoverage = programOptions.disableCoverage;
        }

        if (configFile.disablePrivate) {
            Configuration.mainData.disablePrivate = configFile.disablePrivate;
        }
        if (programOptions.disablePrivate) {
            Configuration.mainData.disablePrivate = programOptions.disablePrivate;
        }

        if (configFile.disableProtected) {
            Configuration.mainData.disableProtected = configFile.disableProtected;
        }
        if (programOptions.disableProtected) {
            Configuration.mainData.disableProtected = programOptions.disableProtected;
        }

        if (configFile.disableInternal) {
            Configuration.mainData.disableInternal = configFile.disableInternal;
        }
        if (programOptions.disableInternal) {
            Configuration.mainData.disableInternal = programOptions.disableInternal;
        }

        if (configFile.disableLifeCycleHooks) {
            Configuration.mainData.disableLifeCycleHooks = configFile.disableLifeCycleHooks;
        }
        if (programOptions.disableLifeCycleHooks) {
            Configuration.mainData.disableLifeCycleHooks = programOptions.disableLifeCycleHooks;
        }

        if (configFile.disableRoutesGraph) {
            Configuration.mainData.disableRoutesGraph = configFile.disableRoutesGraph;
        }
        if (programOptions.disableRoutesGraph) {
            Configuration.mainData.disableRoutesGraph = programOptions.disableRoutesGraph;
        }

        if (configFile.disableSearch) {
            Configuration.mainData.disableSearch = configFile.disableSearch;
        }
        if (programOptions.disableSearch) {
            Configuration.mainData.disableSearch = programOptions.disableSearch;
        }

        if (configFile.disableDependencies) {
            Configuration.mainData.disableDependencies = configFile.disableDependencies;
        }
        if (programOptions.disableDependencies) {
            Configuration.mainData.disableDependencies = programOptions.disableDependencies;
        }

        if (configFile.disableProperties) {
            Configuration.mainData.disableProperties = configFile.disableProperties;
        }
        if (programOptions.disableProperties) {
            Configuration.mainData.disableProperties = programOptions.disableProperties;
        }

        if (configFile.minimal) {
            Configuration.mainData.disableSearch = true;
            Configuration.mainData.disableRoutesGraph = true;
            Configuration.mainData.disableGraph = true;
            Configuration.mainData.disableCoverage = true;
        }
        if (programOptions.minimal) {
            Configuration.mainData.disableSearch = true;
            Configuration.mainData.disableRoutesGraph = true;
            Configuration.mainData.disableGraph = true;
            Configuration.mainData.disableCoverage = true;
        }

        if (configFile.customFavicon) {
            Configuration.mainData.customFavicon = configFile.customFavicon;
        }
        if (programOptions.customFavicon) {
            Configuration.mainData.customFavicon = programOptions.customFavicon;
        }

        if (configFile.customLogo) {
            Configuration.mainData.customLogo = configFile.customLogo;
        }
        if (programOptions.customLogo) {
            Configuration.mainData.customLogo = programOptions.customLogo;
        }

        if (configFile.gaID) {
            Configuration.mainData.gaID = configFile.gaID;
        }
        if (programOptions.gaID) {
            Configuration.mainData.gaID = programOptions.gaID;
        }

        if (configFile.gaSite) {
            Configuration.mainData.gaSite = configFile.gaSite;
        }
        if (programOptions.gaSite && programOptions.gaSite !== COMPODOC_DEFAULTS.gaSite) {
            Configuration.mainData.gaSite = programOptions.gaSite;
        }

        if (!this.isWatching) {
            if (!logger.silent) {
                console.log(`Compodoc v${pkg.version}`);
            } else {
                console.log(fs.readFileSync(path.join(__dirname, '../src/banner')).toString());
                console.log(pkg.version);
                console.log('');
                console.log(`TypeScript version used by Compodoc : ${ts.version}`);
                console.log('');

                if (FileEngine.existsSync(cwd + path.sep + 'package.json')) {
                    const packageData = FileEngine.getSync(cwd + path.sep + 'package.json');
                    if (packageData) {
                        const parsedData = JSON.parse(packageData);
                        const projectDevDependencies = parsedData.devDependencies;
                        if (projectDevDependencies && projectDevDependencies.typescript) {
                            const tsProjectVersion = AngularVersionUtil.cleanVersion(
                                projectDevDependencies.typescript
                            );
                            console.log(
                                `TypeScript version of current project : ${tsProjectVersion}`
                            );
                            console.log('');
                        }
                    }
                }
                console.log(`Node.js version : ${process.version}`);
                console.log('');
                console.log(`Operating system : ${osName(os.platform(), os.release())}`);
                console.log('');
            }
        }

        if (configExplorerResult) {
            if (typeof configExplorerResult.config !== 'undefined') {
                logger.info(`Using configuration file : ${configExplorerResult.filepath}`);
            }
        }

        if (!configExplorerResult) {
            logger.warn(`No configuration file found, switching to CLI flags.`);
        }

        if (programOptions.language && !I18nEngine.supportLanguage(programOptions.language)) {
            logger.warn(
                `The language ${programOptions.language} is not available, falling back to ${I18nEngine.fallbackLanguage}`
            );
        }

        if (programOptions.tsconfig && typeof programOptions.tsconfig === 'boolean') {
            logger.error(`Please provide a tsconfig file.`);
            process.exit(1);
        }

        if (configFile.tsconfig) {
            Configuration.mainData.tsconfig = configFile.tsconfig;
        }
        if (programOptions.tsconfig) {
            Configuration.mainData.tsconfig = programOptions.tsconfig;
        }

        if (programOptions.maxSearchResults) {
            Configuration.mainData.maxSearchResults = programOptions.maxSearchResults;
        }

        if (configFile.files) {
            scannedFiles = configFile.files;
        }
        if (configFile.exclude) {
            excludeFiles = configFile.exclude;
        }
        if (configFile.include) {
            includeFiles = configFile.include;
        }

        /**
         * Check --files argument call
         */
        const argv = require('minimist')(process.argv.slice(2));
        if (argv && argv.files) {
            Configuration.mainData.hasFilesToCoverage = true;
            if (typeof argv.files === 'string') {
                super.setFiles([argv.files]);
            } else {
                super.setFiles(argv.files);
            }
        }

        if (programOptions.serve && !Configuration.mainData.tsconfig && programOptions.output) {
            // if -s & -d, serve it
            if (!FileEngine.existsSync(Configuration.mainData.output)) {
                logger.error(`${Configuration.mainData.output} folder doesn't exist`);
                process.exit(1);
            } else {
                logger.info(
                    `Serving documentation from ${Configuration.mainData.output} at http://${Configuration.mainData.hostname}:${programOptions.port}`
                );
                super.runWebServer(Configuration.mainData.output);
            }
        } else if (
            programOptions.serve &&
            !Configuration.mainData.tsconfig &&
            !programOptions.output
        ) {
            // if only -s find ./documentation, if ok serve, else error provide -d
            if (!FileEngine.existsSync(Configuration.mainData.output)) {
                logger.error('Provide output generated folder with -d flag');
                process.exit(1);
            } else {
                logger.info(
                    `Serving documentation from ${Configuration.mainData.output} at http://${Configuration.mainData.hostname}:${programOptions.port}`
                );
                super.runWebServer(Configuration.mainData.output);
            }
        } else if (Configuration.mainData.hasFilesToCoverage) {
            if (programOptions.coverageMinimumPerFile) {
                logger.info('Run documentation coverage test for files');
                super.testCoverage();
            } else {
                logger.error('Missing coverage configuration');
            }
        } else {
            if (programOptions.hideGenerator) {
                Configuration.mainData.hideGenerator = true;
            }

            if (Configuration.mainData.tsconfig && program.args.length === 0) {
                /**
                 * tsconfig file provided only
                 */
                let testTsConfigPath = Configuration.mainData.tsconfig.indexOf(process.cwd());
                if (testTsConfigPath !== -1) {
                    Configuration.mainData.tsconfig = Configuration.mainData.tsconfig.replace(
                        process.cwd() + path.sep,
                        ''
                    );
                }

                if (!FileEngine.existsSync(Configuration.mainData.tsconfig)) {
                    logger.error(
                        `"${Configuration.mainData.tsconfig}" file was not found in the current directory`
                    );
                    process.exit(1);
                } else {
                    let _file = path.join(
                        path.join(process.cwd(), path.dirname(Configuration.mainData.tsconfig)),
                        path.basename(Configuration.mainData.tsconfig)
                    );
                    // use the current directory of tsconfig.json as a working directory
                    cwd = _file.split(path.sep).slice(0, -1).join(path.sep);
                    logger.info('Using tsconfig file ', _file);

                    let tsConfigFile = readConfig(_file);
                    if (tsConfigFile.files) {
                        scannedFiles = tsConfigFile.files;
                        // Normalize path of these files
                        scannedFiles = scannedFiles.map(scannedFile => {
                            return cwd + path.sep + scannedFile;
                        });
                    }

                    // even if files are supplied with "files" attributes, enhance the array with includes
                    excludeFiles = tsConfigFile.exclude || [];
                    includeFiles = tsConfigFile.include || [];

                    if (scannedFiles.length > 0) {
                        includeFiles = [...includeFiles, ...scannedFiles];
                    }

                    let excludeParser = new ParserUtil(),
                        includeParser = new ParserUtil();

                    excludeParser.init(excludeFiles, cwd);
                    includeParser.init(includeFiles, cwd);

                    let startCwd = cwd;

                    let excludeParserTestFilesWithCwdDepth = excludeParser.testFilesWithCwdDepth();
                    if (!excludeParserTestFilesWithCwdDepth.status) {
                        startCwd = excludeParser.updateCwd(
                            cwd,
                            excludeParserTestFilesWithCwdDepth.level
                        );
                    }
                    let includeParserTestFilesWithCwdDepth = includeParser.testFilesWithCwdDepth();
                    if (!includeParser.testFilesWithCwdDepth().status) {
                        startCwd = includeParser.updateCwd(
                            cwd,
                            includeParserTestFilesWithCwdDepth.level
                        );
                    }

                    let finder = require('findit2')(startCwd || '.');

                    finder.on('directory', function (dir, stat, stop) {
                        if (ignoreDirectory(dir)) {
                            stop();
                        }
                    });

                    finder.on('file', (file, stat) => {
                        if (/(spec|\.d)\.ts/.test(file)) {
                            logger.warn('Ignoring', file);
                        } else if (
                            excludeParser.testFile(file) &&
                            (path.extname(file) === '.ts' || path.extname(file) === '.tsx')
                        ) {
                            logger.warn('Excluding', file);
                        } else if (includeFiles.length > 0) {
                            /**
                             * If include provided in tsconfig, use only this source,
                             * and not files found with global findit scan in working directory
                             */
                            if (
                                (path.extname(file) === '.ts' || path.extname(file) === '.tsx') &&
                                includeParser.testFile(file)
                            ) {
                                logger.debug('Including', file);
                                scannedFiles.push(file);
                            } else {
                                if (path.extname(file) === '.ts' || path.extname(file) === '.tsx') {
                                    logger.warn('Excluding', file);
                                }
                            }
                        } else {
                            logger.debug('Including', file);
                            scannedFiles.push(file);
                        }
                    });

                    finder.on('end', () => {
                        super.setFiles(scannedFiles);
                        if (programOptions.coverageTest || programOptions.coverageTestPerFile) {
                            logger.info('Run documentation coverage test');
                            super.testCoverage();
                        } else {
                            super.generate();
                        }
                    });
                }
            } else if (Configuration.mainData.tsconfig && program.args.length > 0) {
                /**
                 * tsconfig file provided with source folder in arg
                 */
                let testTsConfigPath = Configuration.mainData.tsconfig.indexOf(process.cwd());
                if (testTsConfigPath !== -1) {
                    Configuration.mainData.tsconfig = Configuration.mainData.tsconfig.replace(
                        process.cwd() + path.sep,
                        ''
                    );
                }

                let sourceFolder = program.args[0];
                if (!FileEngine.existsSync(sourceFolder)) {
                    logger.error(
                        `Provided source folder ${sourceFolder} was not found in the current directory`
                    );
                    process.exit(1);
                } else {
                    logger.info('Using provided source folder');

                    if (!FileEngine.existsSync(Configuration.mainData.tsconfig)) {
                        logger.error(
                            `"${Configuration.mainData.tsconfig}" file was not found in the current directory`
                        );
                        process.exit(1);
                    } else {
                        let _file = path.join(
                            path.join(process.cwd(), path.dirname(Configuration.mainData.tsconfig)),
                            path.basename(Configuration.mainData.tsconfig)
                        );
                        // use the current directory of tsconfig.json as a working directory
                        cwd = _file.split(path.sep).slice(0, -1).join(path.sep);
                        logger.info('Using tsconfig file ', _file);

                        let tsConfigFile = readConfig(_file);
                        if (tsConfigFile.files) {
                            scannedFiles = tsConfigFile.files;
                            // Normalize path of these files
                            scannedFiles = scannedFiles.map(scannedFile => {
                                return cwd + path.sep + scannedFile;
                            });
                        }

                        // even if files are supplied with "files" attributes, enhance the array with includes
                        excludeFiles = tsConfigFile.exclude || [];
                        includeFiles = tsConfigFile.include || [];

                        if (scannedFiles.length > 0) {
                            includeFiles = [...includeFiles, ...scannedFiles];
                        }

                        let excludeParser = new ParserUtil(),
                            includeParser = new ParserUtil();

                        excludeParser.init(excludeFiles, cwd);
                        includeParser.init(includeFiles, cwd);

                        let startCwd = sourceFolder;

                        let excludeParserTestFilesWithCwdDepth =
                            excludeParser.testFilesWithCwdDepth();
                        if (!excludeParserTestFilesWithCwdDepth.status) {
                            startCwd = excludeParser.updateCwd(
                                cwd,
                                excludeParserTestFilesWithCwdDepth.level
                            );
                        }
                        let includeParserTestFilesWithCwdDepth =
                            includeParser.testFilesWithCwdDepth();
                        if (!includeParser.testFilesWithCwdDepth().status) {
                            startCwd = includeParser.updateCwd(
                                cwd,
                                includeParserTestFilesWithCwdDepth.level
                            );
                        }

                        let finder = require('findit2')(path.resolve(startCwd));

                        finder.on('directory', function (dir, stat, stop) {
                            if (ignoreDirectory(dir)) {
                                stop();
                            }
                        });

                        finder.on('file', (file, stat) => {
                            if (/(spec|\.d)\.ts/.test(file)) {
                                logger.warn('Ignoring', file);
                            } else if (excludeParser.testFile(file)) {
                                logger.warn('Excluding', file);
                            } else if (includeFiles.length > 0) {
                                /**
                                 * If include provided in tsconfig, use only this source,
                                 * and not files found with global findit scan in working directory
                                 */
                                if (path.extname(file) === '.ts' && includeParser.testFile(file)) {
                                    logger.debug('Including', file);
                                    scannedFiles.push(file);
                                } else {
                                    if (path.extname(file) === '.ts') {
                                        logger.warn('Excluding', file);
                                    }
                                }
                            } else {
                                logger.debug('Including', file);
                                scannedFiles.push(file);
                            }
                        });

                        finder.on('end', () => {
                            super.setFiles(scannedFiles);
                            if (programOptions.coverageTest || programOptions.coverageTestPerFile) {
                                logger.info('Run documentation coverage test');
                                super.testCoverage();
                            } else {
                                super.generate();
                            }
                        });
                    }
                }
            } else {
                logger.error('tsconfig.json file was not found, please use -p flag');
                outputHelp();
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReactiveOperators
{
    public static class Generic
    {
        // Licensed under the MIT license with <3 by GitHub

        /// <summary>
        /// An exponential back off strategy which starts with 1 second and then 4, 9, 16...
        /// </summary>
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        public static readonly Func<int, TimeSpan> ExponentialBackoff = n => TimeSpan.FromSeconds(Math.Pow(n, 2));

        /// <summary>
        /// Returns a cold observable which retries (re-subscribes to) the source observable on error up to the
        /// specified number of times or until it successfully terminates. Allows for customizable back off strategy.
        /// </summary>
        /// <param name="source">The source observable.</param>
        /// <param name="retryCount">The number of attempts of running the source observable before failing.</param>
        /// <param name="strategy">The strategy to use in backing off, exponential by default.</param>
        /// <param name="retryOnError">A predicate determining for which exceptions to retry. Defaults to all</param>
        /// <param name="scheduler">The scheduler.</param>
        /// <returns>
        /// A cold observable which retries (re-subscribes to) the source observable on error up to the
        /// specified number of times or until it successfully terminates.
        /// </returns>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        public static IObservable<T> RetryWithBackoffStrategy<T>(
            this IObservable<T> source,
            int retryCount = 3,
            Func<int, TimeSpan> strategy = null,
            Func<Exception, bool> retryOnError = null,
            IScheduler scheduler = null)
        {

            strategy = strategy ?? Generic.ExponentialBackoff;
            scheduler = scheduler ?? Scheduler.Default;

            if (retryOnError == null)
                retryOnError = e => true;

            int attempt = 0;

            return Observable.Defer(() =>
            {
                return ((++attempt == 1) ? source : source.DelaySubscription(strategy(attempt - 1), scheduler))
                    .Select(item => new Tuple<bool, T, Exception>(true, item, null))
                    .Catch<Tuple<bool, T, Exception>, Exception>(e => retryOnError(e)
                        ? Observable.Throw<Tuple<bool, T, Exception>>(e)
                        : Observable.Return(new Tuple<bool, T, Exception>(false, default(T), e)));
            })
            .Retry(retryCount)
            .SelectMany(t => t.Item1
                ? Observable.Return(t.Item2)
                : Observable.Throw<T>(t.Item3));
        }

        /// <summary>
        /// This will start a timer everytime the 'priority' queue produces a value.
        /// Whenever that timer is running, it will unsubscribe from
        /// the 'secondary' queue and resubscribe when the timer expires:
        /// </summary>
        /// <param name="priority">The queue that should push its value over the secondary</param>
        /// <param name="secondary">The queue that will push events while priority is doing nothing</param>
        /// <param name="delay">The timeframe to ignore secondary queue after priority has published a value</param>
        /// <returns></returns>
        public static IObservable<T> PriorityQueueWithinTimeframe<T>(this IObservable<T> priority,
            IObservable<T> secondary,
            TimeSpan delay,
            IScheduler scheduler = null)
        {
            scheduler = scheduler ?? Scheduler.Default;

            return priority
                .Select(_ => Observable.Timer(delay, scheduler).SelectMany(__ => secondary))
                .StartWith(scheduler, secondary)
                .Switch();
        }
    }
}


text:
package org.apache.hadoop.eclipse;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.hadoop.eclipse.preferences.MapReducePreferencePage;
import org.apache.hadoop.eclipse.preferences.PreferenceConstants;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPage;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.jface.preference.PreferenceNode;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;

/**
 * Wizard for creating a new MapReduce Project
 *
 */

public class NewMapReduceProjectWizard extends Wizard implements
    IWorkbenchWizard, IExecutableExtension {
  static Logger log =
      Logger.getLogger(NewMapReduceProjectWizard.class.getName());

  private HadoopFirstPage firstPage;

  private NewJavaProjectWizardPage javaPage;

  public NewDriverWizardPage newDriverPage;

  private IConfigurationElement config;

  public NewMapReduceProjectWizard() {
    setWindowTitle("New MapReduce Project Wizard");
  }

  public void init(IWorkbench workbench, IStructuredSelection selection) {

  }

  @Override
  public boolean canFinish() {
    return firstPage.isPageComplete() && javaPage.isPageComplete()
    // && ((!firstPage.generateDriver.getSelection())
    // || newDriverPage.isPageComplete()
    ;
  }

  @Override
  public IWizardPage getNextPage(IWizardPage page) {
    // if (page == firstPage
    // && firstPage.generateDriver.getSelection()
    // )
    // {
    // return newDriverPage; // if "generate mapper" checked, second page is
    // new driver page
    // }
    // else
    // {
    IWizardPage answer = super.getNextPage(page);
    if (answer == newDriverPage) {
      return null; // dont flip to new driver page unless "generate
      // driver" is checked
    } else if (answer == javaPage) {
      return answer;
    } else {
      return answer;
    }
    // }
  }

  @Override
  public IWizardPage getPreviousPage(IWizardPage page) {
    if (page == newDriverPage) {
      return firstPage; // newDriverPage, if it appears, is the second
      // page
    } else {
      return super.getPreviousPage(page);
    }
  }

  static class HadoopFirstPage extends WizardNewProjectCreationPage
      implements SelectionListener {
    public HadoopFirstPage() {
      super("New Hadoop Project");
      setImageDescriptor(ImageLibrary.get("wizard.mapreduce.project.new"));
    }

    private Link openPreferences;

    private Button workspaceHadoop;

    private Button projectHadoop;

    private Text location;

    private Button browse;

    private String path;

    public String currentPath;

    // private Button generateDriver;

    @Override
    public void createControl(Composite parent) {
      super.createControl(parent);

      setTitle("MapReduce Project");
      setDescription("Create a MapReduce project.");

      Group group = new Group((Composite) getControl(), SWT.NONE);
      group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      group.setText("Hadoop MapReduce Library Installation Path");
      GridLayout layout = new GridLayout(3, true);
      layout.marginLeft =
          convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
      layout.marginRight =
          convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
      layout.marginTop =
          convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
      layout.marginBottom =
          convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
      group.setLayout(layout);

      workspaceHadoop = new Button(group, SWT.RADIO);
      GridData d =
          new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false);
      d.horizontalSpan = 2;
      workspaceHadoop.setLayoutData(d);
      // workspaceHadoop.setText("Use default workbench Hadoop library
      // location");
      workspaceHadoop.setSelection(true);

      updateHadoopDirLabelFromPreferences();

      openPreferences = new Link(group, SWT.NONE);
      openPreferences
          .setText("Configure Hadoop install directory...");
      openPreferences.setLayoutData(new GridData(GridData.END,
          GridData.CENTER, false, false));
      openPreferences.addSelectionListener(this);

      projectHadoop = new Button(group, SWT.RADIO);
      projectHadoop.setLayoutData(new GridData(GridData.BEGINNING,
          GridData.CENTER, false, false));
      projectHadoop.setText("Specify Hadoop library location");

      location = new Text(group, SWT.SINGLE | SWT.BORDER);
      location.setText("");
      d = new GridData(GridData.END, GridData.CENTER, true, false);
      d.horizontalSpan = 1;
      d.widthHint = 250;
      d.grabExcessHorizontalSpace = true;
      location.setLayoutData(d);
      location.setEnabled(false);

      browse = new Button(group, SWT.NONE);
      browse.setText("Browse...");
      browse.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER,
          false, false));
      browse.setEnabled(false);
      browse.addSelectionListener(this);

      projectHadoop.addSelectionListener(this);
      workspaceHadoop.addSelectionListener(this);

      // generateDriver = new Button((Composite) getControl(), SWT.CHECK);
      // generateDriver.setText("Generate a MapReduce driver");
      // generateDriver.addListener(SWT.Selection, new Listener()
      // {
      // public void handleEvent(Event event) {
      // getContainer().updateButtons(); }
      // });
    }

    @Override
    public boolean isPageComplete() {
      boolean validHadoop = validateHadoopLocation();

      if (!validHadoop && isCurrentPage()) {
        setErrorMessage("Invalid Hadoop Runtime specified; please click 'Configure Hadoop install directory' or fill in library location input field");
      } else {
        setErrorMessage(null);
      }

      return super.isPageComplete() && validHadoop;
    }

    private boolean validateHadoopLocation() {
      FilenameFilter gotHadoopJar = new FilenameFilter() {
        public boolean accept(File dir, String name) {
          return (name.startsWith("hadoop") && name.endsWith(".jar")
              && (name.indexOf("test") == -1) && (name.indexOf("examples") == -1));
        }
      };

      if (workspaceHadoop.getSelection()) {
        this.currentPath = path;
        return new Path(path).toFile().exists()
            && (new Path(path).toFile().list(gotHadoopJar).length > 0);
      } else {
        this.currentPath = location.getText();
        File file = new Path(location.getText()).toFile();
        return file.exists()
            && (new Path(location.getText()).toFile().list(gotHadoopJar).length > 0);
      }
    }

    private void updateHadoopDirLabelFromPreferences() {
      path =
          Activator.getDefault().getPreferenceStore().getString(
              PreferenceConstants.P_PATH);

      if ((path != null) && (path.length() > 0)) {
        workspaceHadoop.setText("Use default Hadoop");
      } else {
        workspaceHadoop.setText("Use default Hadoop (currently not set)");
      }
    }

    public void widgetDefaultSelected(SelectionEvent e) {
    }

    public void widgetSelected(SelectionEvent e) {
      if (e.getSource() == openPreferences) {
        PreferenceManager manager = new PreferenceManager();
        manager.addToRoot(new PreferenceNode(
            "Hadoop Installation Directory", new MapReducePreferencePage()));
        PreferenceDialog dialog =
            new PreferenceDialog(this.getShell(), manager);
        dialog.create();
        dialog.setMessage("Select Hadoop Installation Directory");
        dialog.setBlockOnOpen(true);
        dialog.open();

        updateHadoopDirLabelFromPreferences();
      } else if (e.getSource() == browse) {
        DirectoryDialog dialog = new DirectoryDialog(this.getShell());
        dialog
            .setMessage("Select a hadoop installation, containing hadoop-X-core.jar");
        dialog.setText("Select Hadoop Installation Directory");
        String directory = dialog.open();

        if (directory != null) {
          location.setText(directory);

          if (!validateHadoopLocation()) {
            setErrorMessage("No Hadoop jar found in specified directory");
          } else {
            setErrorMessage(null);
          }
        }
      } else if (projectHadoop.getSelection()) {
        location.setEnabled(true);
        browse.setEnabled(true);
      } else {
        location.setEnabled(false);
        browse.setEnabled(false);
      }

      getContainer().updateButtons();
    }
  }

  @Override
  public void addPages() {
    /*
     * firstPage = new HadoopFirstPage(); addPage(firstPage ); addPage( new
     * JavaProjectWizardSecondPage(firstPage) );
     */

    firstPage = new HadoopFirstPage();
    javaPage =
        new NewJavaProjectWizardPage(ResourcesPlugin.getWorkspace()
            .getRoot(), firstPage);
    // newDriverPage = new NewDriverWizardPage(false);
    // newDriverPage.setPageComplete(false); // ensure finish button
    // initially disabled
    addPage(firstPage);
    addPage(javaPage);

    // addPage(newDriverPage);
  }

  @Override
  public boolean performFinish() {
    try {
      PlatformUI.getWorkbench().getProgressService().runInUI(
          this.getContainer(), new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
              try {
                monitor.beginTask("Create Hadoop Project", 300);

                javaPage.getRunnable().run(
                    new SubProgressMonitor(monitor, 100));

                // if( firstPage.generateDriver.getSelection())
                // {
                // newDriverPage.setPackageFragmentRoot(javaPage.getNewJavaProject().getAllPackageFragmentRoots()[0],
                // false);
                // newDriverPage.getRunnable().run(new
                // SubProgressMonitor(monitor,100));
                // }

                IProject project =
                    javaPage.getNewJavaProject().getResource().getProject();
                IProjectDescription description = project.getDescription();
                String[] existingNatures = description.getNatureIds();
                String[] natures = new String[existingNatures.length + 1];
                for (int i = 0; i < existingNatures.length; i++) {
                  natures[i + 1] = existingNatures[i];
                }

                natures[0] = MapReduceNature.ID;
                description.setNatureIds(natures);

                project.setPersistentProperty(new QualifiedName(
                    Activator.PLUGIN_ID, "hadoop.runtime.path"),
                    firstPage.currentPath);
                project.setDescription(description,
                    new NullProgressMonitor());

                String[] natureIds = project.getDescription().getNatureIds();
                for (int i = 0; i < natureIds.length; i++) {
                  log.fine("Nature id # " + i + " > " + natureIds[i]);
                }

                monitor.worked(100);
                monitor.done();

                BasicNewProjectResourceWizard.updatePerspective(config);
              } catch (CoreException e) {
                // TODO Auto-generated catch block
                log.log(Level.SEVERE, "CoreException thrown.", e);
              } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
          }, null);
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return true;
  }

  public void setInitializationData(IConfigurationElement config,
      String propertyName, Object data) throws CoreException {
    this.config = config;
  }
}


text:
require 'svnx/blame/options'
require 'svnx/base/entries_command'

module Svnx::Blame
  class Command < Svnx::Base::EntriesCommand
    caching
  end
end


text:
import type { Dictionary } from '../../typings/utils';

// Use with: `findCallback(arguments)`.
const findCallback = (args: IArguments): ((...args: any[]) => any) | void => {
	const lastArg = args[args.length - 1];
	if (typeof lastArg === 'function') {
		return lastArg;
	}

	return;
};

const isThenable = (a: any): a is PromiseLike<any> => {
	return typeof a === 'object' && typeof a.then === 'function';
};

const addCallbackSupport = <T extends (...args: any[]) => any>(fn: T): T => {
	return function () {
		const callback = findCallback(arguments);
		const result = fn.apply(this, arguments);
		if (!callback || !isThenable(result)) {
			return result;
		}

		result.then((v) => callback(null, v), callback);

		return result;
	} as T;
};

export const addCallbackSupportToModule = <T extends Dictionary<any>>(
	sdkModule: T,
): T => {
	const result = {} as T;
	for (const key of Object.keys(sdkModule) as Array<keyof typeof sdkModule>) {
		const moduleProp = sdkModule[key];
		const shouldAddCallback =
			typeof key === 'string' &&
			!key.startsWith('_') &&
			typeof moduleProp === 'function';

		result[key] = shouldAddCallback
			? addCallbackSupport(moduleProp)
			: moduleProp;
	}
	return result;
};

export const addCallbackSupportToModuleFactory = <
	T extends (...args: any[]) => any,
>(
	moduleFactory: T,
): T => {
	return function () {
		return addCallbackSupportToModule(moduleFactory.apply(this, arguments));
	} as T;
};


text:
namespace base {
namespace trace_event {

class ProcessMemoryDump;

// The contract interface that memory dump providers must implement.
class BASE_EXPORT MemoryDumpProvider {
 public:
  // Optional arguments for MemoryDumpManager::RegisterDumpProvider().
  struct Options {
    Options() : dumps_on_single_thread_task_runner(false) {}

    // |dumps_on_single_thread_task_runner| is true if the dump provider runs on
    // a SingleThreadTaskRunner, which is usually the case. It is faster to run
    // all providers that run on the same thread together without thread hops.
    bool dumps_on_single_thread_task_runner;
  };

  MemoryDumpProvider(const MemoryDumpProvider&) = delete;
  MemoryDumpProvider& operator=(const MemoryDumpProvider&) = delete;
  virtual ~MemoryDumpProvider() = default;

  // Called by the MemoryDumpManager when generating memory dumps.
  // The |args| specify if the embedder should generate light/heavy dumps on
  // dump requests. The embedder should return true if the |pmd| was
  // successfully populated, false if something went wrong and the dump should
  // be considered invalid.
  // (Note, the MemoryDumpManager has a fail-safe logic which will disable the
  // MemoryDumpProvider for the entire trace session if it fails consistently).
  virtual bool OnMemoryDump(const MemoryDumpArgs& args,
                            ProcessMemoryDump* pmd) = 0;

 protected:
  MemoryDumpProvider() = default;
};

}  // namespace trace_event
}  // namespace base

#endif  // BASE_TRACE_EVENT_MEMORY_DUMP_PROVIDER_H_


text:
@import UIKit;

@interface UIImage (MEDAdditons)

+ (UIImage *)med_imageWithImage:(UIImage *)image scaledToSize:(CGSize)size;
+ (UIImage *)med_imageWithImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height;

- (NSData *)med_JPEGdataWithCompressionQuality:(CGFloat)quality;
- (NSData *)med_PNGdata;

@end


text:
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/classes/iron-flex-layout.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-in-animation.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-out-animation.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable-behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animated-pages.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-item/paper-icon-item.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html">

<iron-iconset-svg name="host-pairing-icons" size="48">
  <svg>
    <defs>
      <g id="cast">
        <include src="../../../../app/theme/cast_icon.svg">
      </g>
    </defs>
  </svg>
</iron-iconset-svg>

<dom-module name="host-pairing-page">

  <link rel="stylesheet" href="oobe_screen_host_pairing_page.css">

  <template>

      <content select=".title"></content>

      <content></content>

  </template>
</dom-module>

<dom-module name="host-pairing-screen">

  <link rel="stylesheet" href="oobe_screen_host_pairing.css">

  <template>
    <neon-animated-pages attr-for-selected="name" selected="[[C.page]]"
        entry-animation="fade-in-animation" exit-animation="fade-out-animation">
      <host-pairing-page name="welcome">

      </host-pairing-page>
      <host-pairing-page name="code-confirmation">

{{C.code}}

      </host-pairing-page>
      <host-pairing-page name="update">

      </host-pairing-page>
      <host-pairing-page name="enrollment-introduction">

      </host-pairing-page>
      <host-pairing-page name="enrollment">

      </host-pairing-page>
      <host-pairing-page name="enrollment-error">

      </host-pairing-page>
      <host-pairing-page name="pairing-done">

      </host-pairing-page>
    </neon-animated-pages>
    <paper-icon-item id="device-indicator">
      <iron-icon icon="host-pairing-icons:cast" item-icon></iron-icon>

{{C.deviceName}}

    </paper-icon-item>

  </template>
</dom-module>


text:
import Vue from 'vue';
import relatedLinksComponent from '~/vue_merge_request_widget/components/mr_widget_related_links.vue';
import mountComponent from 'spec/helpers/vue_mount_component_helper';

describe('MRWidgetRelatedLinks', () => {
  let vm;

  const createComponent = (data) => {
    const Component = Vue.extend(relatedLinksComponent);

    return mountComponent(Component, data);
  };

  afterEach(() => {
    vm.$destroy();
  });

  describe('computed', () => {
    describe('closesText', () => {
      it('returns Closes text for open merge request', () => {
        vm = createComponent({ state: 'open', relatedLinks: {} });
        expect(vm.closesText).toEqual('Closes');
      });

      it('returns correct text for closed merge request', () => {
        vm = createComponent({ state: 'closed', relatedLinks: {} });
        expect(vm.closesText).toEqual('Did not close');
      });

      it('returns correct tense for merged request', () => {
        vm = createComponent({ state: 'merged', relatedLinks: {} });
        expect(vm.closesText).toEqual('Closed');
      });
    });
  });

  it('should have only have closing issues text', () => {
    vm = createComponent({
      relatedLinks: {
        closing: '#23 and #42',
      },
    });
    const content = vm.$el.textContent.replace(/\n(\s)+/g, ' ').trim();

    expect(content).toContain('Closes #23 and #42');
    expect(content).not.toContain('Mentions');
  });

  it('should have only have mentioned issues text', () => {
    vm = createComponent({
      relatedLinks: {
        mentioned: '#7',
      },
    });

    expect(vm.$el.innerText).toContain('Mentions #7');
    expect(vm.$el.innerText).not.toContain('Closes');
  });

  it('should have closing and mentioned issues at the same time', () => {
    vm = createComponent({
      relatedLinks: {
        closing: '#7',
        mentioned: '#23 and #42',
      },
    });
    const content = vm.$el.textContent.replace(/\n(\s)+/g, ' ').trim();

    expect(content).toContain('Closes #7');
    expect(content).toContain('Mentions #23 and #42');
  });

  it('should have assing issues link', () => {
    vm = createComponent({
      relatedLinks: {
        assignToMe: 'Assign yourself to these issues',
      },
    });

    expect(vm.$el.innerText).toContain('Assign yourself to these issues');
  });
});


text:
layout: doc
title: Documentation
---

The node you are looking for is at Coq-specific commands.


text:
title: How to Install the Mean Stack on Mac Osx
localeTitle: Как установить средний стек на Mac Osx
---
Чтобы установить MongoDB, вы должны иметь Mac OS X 10.6 (Snow Leopard) или выше. Чтобы узнать, какая версия ОС X у вас есть, щелкните значок  в левом верхнем углу экрана и выберите « `About This Mac` .

![:warning:](//forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=2 ":предупреждение:") **ПРЕДУПРЕЖДЕНИЕ:** выполните резервное копирование Time Machine перед выполнением любого из следующих шагов!

## Шаг 1: установка MongoDB

Самый простой способ установки MongoDB на OS X - использовать [HomeBrew](http://brew.sh/) . Если вы раньше не использовали HomeBrew, просто выполните следующую команду в окне терминала:
```
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```

После того, как HomeBrew успешно установлен, выполните следующую команду:
```
brew update && brew install mongodb
```

HomeBrew автоматически установит все зависимости для вас.

## Шаг 2: установка Node.js

Опять же, мы позволим HomeBrew сделать тяжелый подъем:
```
brew install node
```

Исполняемый файл npm уже включен в пакет Node.js.

Прежде чем продолжить, давайте проверим, что модули Node.js могут быть найдены другими пользователями ( ![:warning:](//forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=2 ":предупреждение:") **ВНИМАНИЕ** : лучше всего скопировать и вставить эти команды, так как вы потеряете исходное содержимое своего `.bashrc` файла, если вы введете `>` вместо `>>` ):
```
echo 'export NODE_PATH="./node_modules:/usr/local/lib/node_modules"' >> ~/.bashrc && source ~/.bashrc
```

Чтобы проверить, действует ли конфигурация, выполните:
```
echo $NODE_PATH
```

Вы должны увидеть `./node_modules:/usr/local/lib/node_modules` напечатанный ниже вашей команды.

Если вы используете другую оболочку, чем Bash, просто замените `~/.bashrc` файлом конфигурации оболочки.

## Шаг 3: установка инструментов fullstack
```
npm install -g express yo grunt grunt-cli generator-angular-fullstack bower
```

## Шаг 4: создание приложения fullstack

Создайте каталог для проектов Back End Project. Предполагая, что ваш рабочий стол - ваше рабочее пространство де-факто:
```
mkdir ~/Desktop/Back End Projects && cd ~/Desktop/Back End Projects
```

Теперь, когда все приготовления на месте, пришло время для главного события:
```
yo angular-fullstack
```

Ответьте на вопросы в соответствии с элементами контрольного списка \# 13-23 [Challenge: Get Set for Back End Projects](http://www.freecodecamp.com/challenges/get-set-for-our-back-end-development-projects) . Проконсультируйтесь с № 24-27, если вы столкнулись с ошибками. Это будет загружать файлы размером ~ 350 МБ в ваш текущий каталог.

Прежде чем идти дальше, нам нужно исправить [известную проблему](https://github.com/clnhll/guidetobasejumps#fixing-exportsupdate) в некоторых сгенерированных файлах:
```
echo "sed -i '' -e 's/_.merge/_.extend/' server/api/*/*.controller.js" > \
 fix-exports-update.sh && chmod +x fix-exports-update.sh && \
 ./fix-exports-update.sh
```

Вам нужно запустить `./fix-exports-update.sh` каждый раз, когда вы создаете новую конечную точку API (до тех пор, пока они не исправят этот восходящий `./fix-exports-update.sh` , то есть).

## Шаг 5: инициализация локального репозитория Git

Скажите Git, чтобы не отслеживать вашу базу данных:
```
echo "data" >> .gitignore
```

Поверните каталог, в котором ваше приложение находится в репозитории Git, выполнив следующие команды:
```
git init && git add . && git commit -am 'initial commit'
```

## Шаг 6: запуск MongoDB

Чтобы запустить MongoDB в первый раз в каталоге вашего приложения, выполните следующие команды в своем терминале:
```
mkdir data && echo 'mongod --config /usr/local/etc/mongod.conf --dbpath=data --rest "$@" --httpinterface' > mongod.sh && chmod a+x mongod.sh && ./mongod.sh
```

С этого момента вы можете просто запустить MongoDB, выполнив `./mongod.sh` . Несколько замечаний:

*   Файл `.conf` направляет `mongod` для записи сообщений в файл журнала вместо stdout. Чтобы просмотреть журнал, выполните следующую команду на отдельной вкладке терминала: `less /usr/local/var/log/mongodb/mongo.log` .
*   Поскольку мы не на Cloud9, нам не нужен параметр `--nojournal` . Журналирование позволяет восстановить базу данных в случае `mongod` .
*   Вы должны создать чистую базу данных для каждого проекта. Если вы скопировали каталог `data` из более раннего проекта, `mongod` не запустится. Если это так, просто `rm -rf data && mkdir data && ./mongod.sh` .

## Шаг 7: запуск Grunt

Откройте новую вкладку терминала, нажав `⌘T` , и выполните следующую команду:
```
grunt serve
```

Grunt автоматически откроет новую страницу индекса Angular Site, как только она закончит запуск.

Теперь вы должны быть в состоянии следовать остальным инструкциям Challenge, чтобы нажать на GitHub и Heroku. Просто проигнорируйте часть ключа SSH (# 33-36) и замените `~/workspace` на путь вашего каталога приложения.

## сноска

Вышеуказанные этапы были протестированы в следующей конфигурации:

*   OS X 10.10.5
*   zsh 5.0.8 (x86\_64-apple-darwin14.3.0)
*   узел v0.12.7
*   npm 2.11.3


text:
using CWiz.RailwayOrientedProgramming;
using FluentAssertions;
using System;
using Xunit;

namespace RailwayOrientedProgrammingTests
{
    public class ResultExtensionsSpec
    {
        [Fact]
        public void EnsureNotEmpty_should_fail_if_the_string_is_empty()
        {
            Maybe<string> emptyString = string.Empty;
            var result = emptyString.EnsureNotNullOrWhiteSpace(new Result.Error("emptyString should not be null or empty", "emptyString"));
            Assert.True(result.IsFailure);
            Assert.Single(result.Errors);
            Assert.Equal("emptyString should not be null or empty", result.Errors[0].Message);
            Assert.Equal("emptyString", result.Errors[0].Field);
        }

        [Fact]
        public void EnsureNotEmpty_should_fail_if_the_string_is_null()
        {
            Maybe<string> emptyString = null;
            var result = emptyString.EnsureNotNullOrWhiteSpace(new Result.Error("emptyString should not be null or empty", "emptyString"));
            Assert.True(result.IsFailure);
            Assert.Single(result.Errors);
            Assert.Equal("emptyString should not be null or empty", result.Errors[0].Message);
            Assert.Equal("emptyString", result.Errors[0].Field);
        }

        [Fact]
        public void EnsureNotEmpty_should_fail_if_the_string_is_whitespaces()
        {
            Maybe<string> emptyString = "   ";
            var result = emptyString.EnsureNotNullOrWhiteSpace(new Result.Error("emptyString should not be null or empty", "emptyString"));
            Assert.True(result.IsFailure);
            Assert.Single(result.Errors);
            Assert.Equal("emptyString should not be null or empty", result.Errors[0].Message);
            Assert.Equal("emptyString", result.Errors[0].Field);
        }

        [Fact]
        public void EnsureNotEmpty_should_pass_if_the_string_is_valid()
        {
            Maybe<string> validString = "This is a valid string";
            var result = validString.EnsureNotNullOrWhiteSpace(new Result.Error("validString should not be null or empty", "validString"));
            Assert.True(result.IsSuccess);
        }

        [Fact]
        public void OnSuccess_should_be_called()
        {
            string validated = null;
            Maybe<string> toValidate = "This is a valid string";
            toValidate.EnsureNotNullOrWhiteSpace(new Result.Error("validString should not be null or empty", nameof(toValidate)))
                .OnSuccess((valid) => { validated = valid; return Result<bool>.Ok(valid); });

            validated.Should().Be(toValidate.Value);
        }

        [Fact]
        public void OnFailure_should_be_called()
        {
            string validated = null;
            bool failureCalled = false;
            Maybe<string> toValidate = string.Empty;
            toValidate.EnsureNotNullOrWhiteSpace(new Result.Error("toValidate should not be null or empty", nameof(toValidate)))
                .OnSuccess((valid) => { validated = valid; return Result<bool>.Ok(valid); })
                .OnFailure(result =>
                  {
                      failureCalled = true;
                      result.Errors.Count.Should().Be(1);
                      result.Errors[0].Message.Should().Be("toValidate should not be null or empty");
                      return result;
                  });

            validated.Should().BeNull();
            failureCalled.Should().BeTrue();
        }
    }
}


text:
namespace AirlineSystem.Web.Areas.Administration.ViewModels
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    using AirlineSystem.Models;
    using AirlineSystem.Web.Areas.Administration.Models.Base;
    using AirlineSystem.Web.Infrastructure.Mapping;

    public class TicketViewModel : AdministrationViewModel, IMapFrom<Ticket>
    {
        [HiddenInput(DisplayValue = false)]
        public int? Id { get; set; }

        [Required]
        public DateTime DepartureTime { get; set; }

        [Required]
        public DateTime ArrivalTime { get; set; }
    }
}


text:
class SimpleForm::Bootstrap::Engine < Rails::Engine
end