text:
<?php

declare(strict_types=1);

namespace ZendTest\Expressive\Middleware;

use Fig\Http\Message\StatusCodeInterface as StatusCode;
use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
use Whoops\Handler\JsonResponseHandler;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
use Whoops\RunInterface;
use Zend\Expressive\Middleware\WhoopsErrorResponseGenerator;

use function interface_exists;
use function method_exists;

class WhoopsErrorResponseGeneratorTest extends TestCase
{
    /** @var Run|RunInterface|ObjectProphecy */
    private $whoops;

    /** @var ServerRequestInterface|ObjectProphecy */
    private $request;

    /** @var ResponseInterface|ObjectProphecy */
    private $response;

    /** @var StreamInterface|ObjectProphecy */
    private $stream;

    public function setUp()
    {
        // Run is marked final in 2.X, but in that version, we can mock the
        // RunInterface. 1.X has only Run, and it is not final.
        $this->whoops = interface_exists(RunInterface::class)
            ? $this->prophesize(RunInterface::class)
            : $this->prophesize(Run::class);

        $this->request  = $this->prophesize(ServerRequestInterface::class);
        $this->response = $this->prophesize(ResponseInterface::class);
        $this->stream   = $this->prophesize(StreamInterface::class);
    }

    public function testWritesResultsOfWhoopsExceptionsHandlingToResponse()
    {
        $error = new RuntimeException();

        $this->whoops->getHandlers()->willReturn([]);
        $this->whoops->handleException($error)->willReturn('WHOOPS');

        // Could do more assertions here, but these will be sufficent for
        // ensuring that the method for injecting metadata is never called.
        $this->request->getAttribute('originalUri', false)->shouldNotBeCalled();
        $this->request->getAttribute('originalRequest', false)->shouldNotBeCalled();

        $this->response->withStatus(StatusCode::STATUS_INTERNAL_SERVER_ERROR)->will([$this->response, 'reveal']);
        $this->response->getBody()->will([$this->stream, 'reveal']);
        $this->response->getStatusCode()->willReturn(StatusCode::STATUS_INTERNAL_SERVER_ERROR);

        $this->stream->write('WHOOPS')->shouldBeCalled();

        $generator = new WhoopsErrorResponseGenerator($this->whoops->reveal());

        $this->assertSame(
            $this->response->reveal(),
            $generator($error, $this->request->reveal(), $this->response->reveal())
        );
    }

    public function testAddsRequestMetadataToWhoopsPrettyPageHandler()
    {
        $error = new RuntimeException('STATUS_INTERNAL_SERVER_ERROR', StatusCode::STATUS_INTERNAL_SERVER_ERROR);

        $handler = $this->prophesize(PrettyPageHandler::class);
        $handler
            ->addDataTable('Expressive Application Request', [
                'HTTP Method'            => 'POST',
                'URI'                    => 'https://example.com/foo',
                'Script'                 => __FILE__,
                'Headers'                => [],
                'Cookies'                => [],
                'Attributes'             => [],
                'Query String Arguments' => [],
                'Body Params'            => [],
            ])
            ->shouldBeCalled();

        $this->whoops->getHandlers()->willReturn([$handler->reveal()]);
        $this->whoops->handleException($error)->willReturn('WHOOPS');

        $this->request->getAttribute('originalUri', false)->willReturn('https://example.com/foo');
        $this->request->getAttribute('originalRequest', false)->will([$this->request, 'reveal']);
        $this->request->getMethod()->willReturn('POST');
        $this->request->getServerParams()->willReturn(['SCRIPT_NAME' => __FILE__]);
        $this->request->getHeaders()->willReturn([]);
        $this->request->getCookieParams()->willReturn([]);
        $this->request->getAttributes()->willReturn([]);
        $this->request->getQueryParams()->willReturn([]);
        $this->request->getParsedBody()->willReturn([]);

        $this->response->withStatus(StatusCode::STATUS_INTERNAL_SERVER_ERROR)->will([$this->response, 'reveal']);
        $this->response->getStatusCode()->willReturn(StatusCode::STATUS_INTERNAL_SERVER_ERROR);
        $this->response->getBody()->will([$this->stream, 'reveal']);

        $this->stream->write('WHOOPS')->shouldBeCalled();

        $generator = new WhoopsErrorResponseGenerator($this->whoops->reveal());

        $this->assertSame(
            $this->response->reveal(),
            $generator($error, $this->request->reveal(), $this->response->reveal())
        );
    }

    public function testJsonContentTypeResponseWithJsonResponseHandler()
    {
        $error = new RuntimeException('STATUS_NOT_IMPLEMENTED', StatusCode::STATUS_NOT_IMPLEMENTED);

        $handler = $this->prophesize(JsonResponseHandler::class);

        if (method_exists(JsonResponseHandler::class, 'contentType')) {
            $handler->contentType()->willReturn('application/json');
        }

        $this->whoops->getHandlers()->willReturn([$handler->reveal()]);
        $this->whoops->handleException($error)->willReturn('error');

        $this->request->getAttribute('originalUri', false)->willReturn('https://example.com/foo');
        $this->request->getAttribute('originalRequest', false)->will([$this->request, 'reveal']);
        $this->request->getMethod()->willReturn('POST');
        $this->request->getServerParams()->willReturn(['SCRIPT_NAME' => __FILE__]);
        $this->request->getHeaders()->willReturn([]);
        $this->request->getCookieParams()->willReturn([]);
        $this->request->getAttributes()->willReturn([]);
        $this->request->getQueryParams()->willReturn([]);
        $this->request->getParsedBody()->willReturn([]);

        $this->response->withHeader('Content-Type', 'application/json')->will([$this->response, 'reveal']);
        $this->response->withStatus(StatusCode::STATUS_NOT_IMPLEMENTED)->will([$this->response, 'reveal']);
        $this->response->getStatusCode()->willReturn(StatusCode::STATUS_NOT_IMPLEMENTED);
        $this->response->getBody()->will([$this->stream, 'reveal']);

        $this->stream->write('error')->shouldBeCalled();

        $generator = new WhoopsErrorResponseGenerator($this->whoops->reveal());

        $this->assertSame(
            $this->response->reveal(),
            $generator($error, $this->request->reveal(), $this->response->reveal())
        );
    }
}


text:
define(function (require) {
  return function savedSearchObjectFn(savedSearches) {
    return savedSearches;
  };
});

redpajama_set_name: RedPajamaGithub


text:
package easy;

import java.util.Scanner;
/**
 * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
 Could you do it without any loop/recursion in O(1) runtime?

 */

/**
 * @author summer
 */
public class AddDigits {

	public static void main(String args[]){
		Scanner cin = new Scanner(System.in);
		int num = cin.nextInt();
		cin.close();
		while(num  > 9){
			int temp = num;
			int total = 0;
			while(temp > 0){
				total += temp % 10;
				temp = temp / 10;
			}
			num = total;
		}
		System.out.println(num);
	}
}


text: A MWidehatTest is a test class for testing the behavior of MWidehat


text:
package jadeplib

import (
	"fmt"
	"io"
	"strconv"

	"github.com/bazelbuild/tools_jvm_autodeps/bazel"
	"github.com/bazelbuild/tools_jvm_autodeps/color"
)

// ask takes in a list of printable interfaces. It returns the
// input from the user indicating which interfaces is wanted.
// ask keeps asking the user for input until a valid input is given.
// If reading from stdin fails, returns an error.
func ask(in io.Reader, description string, options []bazel.Label) (int, error) {
	if len(options) == 1 {
		return 1, nil
	}
	for i := len(options) - 1; i >= 0; i-- {
		fmt.Printf("[%v] %v\n", i+1, options[i])
	}
	fmt.Println("[0] None")

	fmt.Print(description)
	for {
		var i string
		if _, err := fmt.Fscanln(in, &i); err != nil {
			if err == io.EOF {
				return -1, fmt.Errorf("Error reading stdin: %v", err)
			}
			return 1, nil
		}
		idx, err := strconv.Atoi(i)
		if err != nil {
			fmt.Println("Error occurred when converting input to integer. Please try again.")
			continue
		}
		if idx <= len(options) && idx >= 0 {
			return idx, nil
		}
		fmt.Println("Invalid index inputted. Please try again.")
	}
}

// SelectDepsToAdd asks the user to choose which deps to add to their rules to satisfy missing dependencies.
func SelectDepsToAdd(in io.Reader, missingDepsMap map[*bazel.Rule]map[ClassName][]bazel.Label) (map[*bazel.Rule][]bazel.Label, error) {
	depsToAdd := make(map[*bazel.Rule][]bazel.Label)
	for rule, classToRules := range missingDepsMap {
		addedDeps := make(map[bazel.Label]bool)
		for class, rules := range classToRules {
			if depAlreadySatisfied(addedDeps, rules) {
				continue
			}
			fmt.Println()
			fmt.Printf("The BUILD rule %s is missing a dependency. Choose one of the options below:\n", rule.Label())
			description := fmt.Sprintf(`For class:  %s
Suggestion: %s
Hit Enter to accept, or a number to choose: `, color.Bold(string(class)), color.Bold(string(rules[0])))
			idx, err := ask(in, description, rules)
			if err != nil {
				return nil, err
			}
			if idx != 0 {
				addedDeps[rules[idx-1]] = true
				depsToAdd[rule] = append(depsToAdd[rule], rules[(idx-1)])
			}
		}
	}
	return depsToAdd, nil
}

func depAlreadySatisfied(addedDeps map[bazel.Label]bool, rules []bazel.Label) bool {
	for _, rule := range rules {
		if _, ok := addedDeps[rule]; ok {
			return true
		}
	}
	return false
}


text:
import './footer.style.sass';

import config from 'config/config';
import templateUrl from './footer.view';

const FOOTER_COMPONENT_NAME = 'psFooter';

const footerComponent = {
  templateUrl,
  bindings: {
    linkList: '<',
  },
};

export { FOOTER_COMPONENT_NAME as footerComponentName, footerComponent };


text:
<?php

namespace Eye4web\Zf2Abac\Collections;

use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Selectable;

interface PermissionCollectionInterface extends Collection, Selectable
{

}


text:
require 'spec_helper'

describe CareerBuilder::Client do

  describe "#resume_actions_remaining_today" do
    before do
      stub_request(:post, "http://ws.careerbuilder.com/resumes/resumes.asmx/V2_ResumeActionsRemainingToday").with(:body => 'Packet=%3cPacket%3e%3cSessionToken%3e42%3c%2fSessionToken%3e%3cAccountDID%3eD7D15Q67VKG105ZB12%3c%2fAccountDID%3e%3c%2fPacket%3e').to_return(:body => "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<string xmlns=\"http://ws.careerbuilder.com/resumes/\"><Packet>1</Packet></string>")
      @client = CareerBuilder::Client.new("valid_email", "valid_password")
      @client.stub(:session_token).and_return(42)
      @client.stub(:authenticate).and_return(true)
    end

    it 'should return the number of credits remaining' do
      @client.resume_actions_remaining_today(:account_did => "D7D15Q67VKG105ZB12").should == 1
    end
  end

end


text:
package org.apache.hyracks.storage.am.common.api;

import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;

/**
 * Interface for updating a tuple. Warning: By convention, this interface
 * assumes that the modifications do not change the size of the tuple, and that
 * it does not change keys (e.g., BTree keys). This interface is used to
 * implement update scans.
 *
 */
public interface ITupleUpdater {
	public void updateTuple(ITupleReference tuple);
}


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AzureStack.Management.Models;

namespace Microsoft.AzureStack.Management
{
    /// <summary>
    /// Operations for delegated provider configuration.  (see
    /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
    /// more information)
    /// </summary>
    public partial interface IDelegatedProviderConfigurationOperations
    {
        /// <summary>
        /// Create or update delegated provider configuration.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='parameters'>
        /// The create or update result of delegated provider configuration
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The create or update result of delegated provider configuration
        /// operation.
        /// </returns>
        Task<DelegatedProviderConfigurationOperationsCreateOrUpdateResult> CreateOrUpdateAsync(DelegatedProviderConfigurationOperationsCreateOrUpdateParameters parameters, CancellationToken cancellationToken);

        /// <summary>
        /// Get the configuration for the provider.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The get result for delegated provider configuration.
        /// </returns>
        Task<DelegatedProviderConfigurationGetResult> GetAsync(CancellationToken cancellationToken);
    }
}


text:
jasmine.HtmlReporterHelpers = {};

jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) {
  var el = document.createElement(type);

  for (var i = 2; i < arguments.length; i++) {
    var child = arguments[i];

    if (typeof child === 'string') {
      el.appendChild(document.createTextNode(child));
    } else {
      if (child) {
        el.appendChild(child);
      }
    }
  }

  for (var attr in attrs) {
    if (attr == "className") {
      el[attr] = attrs[attr];
    } else {
      el.setAttribute(attr, attrs[attr]);
    }
  }

  return el;
};

jasmine.HtmlReporterHelpers.getSpecStatus = function(child) {
  var results = child.results();
  var status = results.passed() ? 'passed' : 'failed';
  if (results.skipped) {
    status = 'skipped';
  }

  return status;
};

jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
  var parentDiv = this.dom.summary;
  var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite';
  var parent = child[parentSuite];

  if (parent) {
    if (typeof this.views.suites[parent.id] == 'undefined') {
      this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
    }
    parentDiv = this.views.suites[parent.id].element;
  }

  parentDiv.appendChild(childElement);
};

jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
  for(var fn in jasmine.HtmlReporterHelpers) {
    ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
  }
};

jasmine.HtmlReporter = function(_doc) {
  var self = this;
  var doc = _doc || window.document;

  var reporterView;

  var dom = {};

  // Jasmine Reporter Public Interface
  self.logRunningSpecs = false;

  self.reportRunnerStarting = function(runner) {
    var specs = runner.specs() || [];

    if (specs.length == 0) {
      return;
    }

    createReporterDom(runner.env.versionString());
    $('#content .slide.specs').append(dom.reporter);

    reporterView = new jasmine.HtmlReporter.ReporterView(dom);
    reporterView.addSpecs(specs, self.specFilter);
  };

  self.reportRunnerResults = function(runner) {
    reporterView && reporterView.complete();
  };

  self.reportSuiteResults = function(suite) {
    reporterView.suiteComplete(suite);
  };

  self.reportSpecStarting = function(spec) {
    if (self.logRunningSpecs) {
      self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
    }
  };

  self.reportSpecResults = function(spec) {
    reporterView.specComplete(spec);
  };

  self.log = function() {
    var console = jasmine.getGlobal().console;
    if (console && console.log) {
      if (console.log.apply) {
        console.log.apply(console, arguments);
      } else {
        console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
      }
    }
  };

  self.specFilter = function(spec) {
    if (!focusedSpecName()) {
      return true;
    }

    return spec.getFullName().indexOf(focusedSpecName()) === 0;
  };

  return self;

  function focusedSpecName() {
    var specName;

    (function memoizeFocusedSpec() {
      if (specName) {
        return;
      }

      var paramMap = [];
      var params = jasmine.HtmlReporter.parameters(doc);

      for (var i = 0; i < params.length; i++) {
        var p = params[i].split('=');
        paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
      }

      specName = paramMap.spec;
    })();

    return specName;
  }

  function createReporterDom(version) {
    dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' },
      dom.banner = self.createDom('div', { className: 'banner' },
        self.createDom('span', { className: 'title' }, "Jasmine "),
        self.createDom('span', { className: 'version' }, version)),

      dom.alert = self.createDom('div', {className: 'alert'}),
      dom.results = self.createDom('div', {className: 'results'},
        dom.summary = self.createDom('div', { className: 'summary' }),
        dom.details = self.createDom('div', { id: 'details' }))
    );
  }

};
jasmine.HtmlReporter.parameters = function(doc) {
  var paramStr = doc.location.search.substring(1);
  var params = [];

  if (paramStr.length > 0) {
    params = paramStr.split('&');
  }
  return params;
}
jasmine.HtmlReporter.sectionLink = function(sectionName) {
  var link = '?';
  var params = [];

  if (sectionName) {
    params.push('spec=' + encodeURIComponent(sectionName));
  }
  if (params.length > 0) {
    link += params.join("&");
  }

  return link;
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);
jasmine.HtmlReporter.ReporterView = function(dom) {
  this.startedAt = new Date();
  this.runningSpecCount = 0;
  this.completeSpecCount = 0;
  this.passedCount = 0;
  this.failedCount = 0;
  this.skippedCount = 0;

  this.addSpecs = function(specs, specFilter) {
    this.totalSpecCount = specs.length;

    this.views = {
      specs: {},
      suites: {}
    };

    for (var i = 0; i < specs.length; i++) {
      var spec = specs[i];
      this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
      if (specFilter(spec)) {
        this.runningSpecCount++;
      }
    }
  };

  this.specComplete = function(spec) {
    this.completeSpecCount++;

    if (isUndefined(this.views.specs[spec.id])) {
      this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
    }

    var specView = this.views.specs[spec.id];

    switch (specView.status()) {
      case 'passed':
        this.passedCount++;
        break;

      case 'failed':
        this.failedCount++;
        break;

      case 'skipped':
        this.skippedCount++;
        break;
    }

    specView.refresh();
    this.refresh();
  };

  this.suiteComplete = function(suite) {
    var suiteView = this.views.suites[suite.id];
    if (isUndefined(suiteView)) {
      return;
    }
    suiteView.refresh();
  };

  this.refresh = function() {
    var testsSummary = [];
    if (this.passedCount > 0) {
      testsSummary.push(' ' + this.passedCount);
    }
    if (this.failedCount > 0) {
      testsSummary.push(' ' + this.failedCount);
    }
    $('.specs-summary').html(testsSummary.join(' '));
  };

  this.complete = function() {
    if (this.failedCount === 0) {
      $(dom.alert).text('Passing ' + specPluralizedFor(this.passedCount));
    } else {
      $(dom.alert).text('Failing ' + specPluralizedFor(this.failedCount));
      showDetails();
    }
    var duration = ((new Date().getTime() - this.startedAt.getTime()) / 1000);
    $(dom.banner).append('  ' + duration + 's');
  };

  return this;

  function showDetails() {
    if (dom.reporter.className.search(/showDetails/) === -1) {
      dom.reporter.className += " showDetails";
    }
  }

  function isUndefined(obj) {
    return typeof obj === 'undefined';
  }

  function isDefined(obj) {
    return !isUndefined(obj);
  }

  function specPluralizedFor(count) {
    var str = count + " spec";
    if (count > 1) {
      str += "s"
    }
    return str;
  }

};

jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView);

jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
  this.spec = spec;
  this.dom = dom;
  this.views = views;

  this.symbol = this.createDom('li', { className: 'pending' });
  $('.specs-bullets').append(this.symbol);

  var nth = $('.specs-bullets').children().length - 1,
      rows = Math.round($('.specs-bullets').height() / $(this.symbol).height());
  $(this.symbol).css({
    top: (nth % rows) * $(this.symbol).height(),
    right: Math.floor(nth / rows) * $(this.symbol).width(),
    opacity: Math.random() * 0.3 + 0.1
  });

  this.summary = this.createDom('div', { className: 'specSummary' },
    this.createDom('a', {
      className: 'description',
      href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()),
      title: this.spec.getFullName()
    }, this.spec.description)
  );

  this.detail = this.createDom('div', { className: 'specDetail' },
      this.createDom('a', {
        className: 'description',
        href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
        title: this.spec.getFullName()
      }, this.spec.getFullName())
  );
};

jasmine.HtmlReporter.SpecView.prototype.status = function() {
  return this.getSpecStatus(this.spec);
};

jasmine.HtmlReporter.SpecView.prototype.refresh = function() {
  this.symbol.className = this.status();

  switch (this.status()) {
    case 'skipped':
      break;

    case 'passed':
      this.appendSummaryToSuiteDiv();
      break;

    case 'failed':
      this.appendSummaryToSuiteDiv();
      this.appendFailureDetail();
      break;
  }
};

jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() {
  this.summary.className += ' ' + this.status();
  this.appendToSummary(this.spec, this.summary);
};

jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
  this.detail.className += ' ' + this.status();

  var resultItems = this.spec.results().getItems();
  var messagesDiv = this.createDom('div', { className: 'messages' });

  for (var i = 0; i < resultItems.length; i++) {
    var result = resultItems[i];

    if (result.type == 'expect' && result.passed && !result.passed()) {
      messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));

      if (result.trace.stack) {
        messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
      }
    }
  }

  if (messagesDiv.childNodes.length > 0) {
    this.detail.appendChild(messagesDiv);
    this.dom.details.appendChild(this.detail);
  }
};

jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) {
  this.suite = suite;
  this.dom = dom;
  this.views = views;

  this.element = this.createDom('div', { className: 'suite' },
    this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description)
  );

  this.appendToSummary(this.suite, this.element);
};

jasmine.HtmlReporter.SuiteView.prototype.status = function() {
  return this.getSpecStatus(this.suite);
};

jasmine.HtmlReporter.SuiteView.prototype.refresh = function() {
  this.element.className += " " + this.status();
};

jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView);


text:
using UnityEditor;
using UnityEditor.AnimatedValues;

// For manteinance, every new [SerializeField] variable in Scroller must be declared here

namespace FancyScrollView
{
    [CustomEditor(typeof(Scroller))]
    [CanEditMultipleObjects]
    public class ScrollerEditor : Editor
    {
        SerializedProperty viewport;
        SerializedProperty scrollDirection;
        SerializedProperty movementType;
        SerializedProperty elasticity;
        SerializedProperty scrollSensitivity;
        SerializedProperty inertia;
        SerializedProperty decelerationRate;
        SerializedProperty snap;
        SerializedProperty draggable;
        SerializedProperty scrollbar;

        AnimBool showElasticity;
        AnimBool showInertiaRelatedValues;

        void OnEnable()
        {
            viewport = serializedObject.FindProperty("viewport");
            scrollDirection = serializedObject.FindProperty("scrollDirection");
            movementType = serializedObject.FindProperty("movementType");
            elasticity = serializedObject.FindProperty("elasticity");
            scrollSensitivity = serializedObject.FindProperty("scrollSensitivity");
            inertia = serializedObject.FindProperty("inertia");
            decelerationRate = serializedObject.FindProperty("decelerationRate");
            snap = serializedObject.FindProperty("snap");
            draggable = serializedObject.FindProperty("draggable");
            scrollbar = serializedObject.FindProperty("scrollbar");

            showElasticity = new AnimBool(Repaint);
            showInertiaRelatedValues = new AnimBool(Repaint);
            SetAnimBools(true);
        }

        void OnDisable()
        {
            showElasticity.valueChanged.RemoveListener(Repaint);
            showInertiaRelatedValues.valueChanged.RemoveListener(Repaint);
        }

        void SetAnimBools(bool instant)
        {
            SetAnimBool(showElasticity, !movementType.hasMultipleDifferentValues && movementType.enumValueIndex == (int)MovementType.Elastic, instant);
            SetAnimBool(showInertiaRelatedValues, !inertia.hasMultipleDifferentValues && inertia.boolValue, instant);
        }

        void SetAnimBool(AnimBool a, bool value, bool instant)
        {
            if (instant)
            {
                a.value = value;
            }
            else
            {
                a.target = value;
            }
        }

        public override void OnInspectorGUI()
        {
            SetAnimBools(false);

            serializedObject.Update();
            EditorGUILayout.PropertyField(viewport);
            EditorGUILayout.PropertyField(scrollDirection);
            EditorGUILayout.PropertyField(movementType);
            DrawMovementTypeRelatedValue();
            EditorGUILayout.PropertyField(scrollSensitivity);
            EditorGUILayout.PropertyField(inertia);
            DrawInertiaRelatedValues();
            EditorGUILayout.PropertyField(draggable);
            EditorGUILayout.PropertyField(scrollbar);
            serializedObject.ApplyModifiedProperties();
        }

        void DrawMovementTypeRelatedValue()
        {
            using (var group = new EditorGUILayout.FadeGroupScope(showElasticity.faded))
            {
                if (!group.visible)
                {
                    return;
                }

                using (new EditorGUI.IndentLevelScope())
                {
                    EditorGUILayout.PropertyField(elasticity);
                }
            }
        }

        void DrawInertiaRelatedValues()
        {
            using (var group = new EditorGUILayout.FadeGroupScope(showInertiaRelatedValues.faded))
            {
                if (!group.visible)
                {
                    return;
                }

                using (new EditorGUI.IndentLevelScope())
                {
                    EditorGUILayout.PropertyField(decelerationRate);
                    EditorGUILayout.PropertyField(snap);
                }
            }
        }
    }
}


text:
local M = { }

function M.parse(arg)
  local defaultDir = paths.concat(os.getenv(''), '')  -- directories names to add

  local cmd = torch.CmdLine()
  cmd:text()
  cmd:text('Torch7 Training script')
  cmd:text()
  cmd:text('Options:')

  ------------ General options ---------------------------------------------------------------------------------------------
  cmd:option('-cache', defaultDir .. '/dataset_runs', 'subdirectory in which to save/log experiments')
  cmd:option('-data', defaultDir .. '/raw_images/256', 'Home of dataset')
  cmd:option('-manualSeed', 2, 'Manually set RNG seed')
  cmd:option('-loadSize', {3, 256, 256}, 'a size to load the images to, initially')
  cmd:option('-sampleSize', {3, 96, 96}, 'a consistent sample size to resize the images')
  ------------- Data options -----------------------------------------------------------------------------------------------
  cmd:option('-nDonkeys', 0, 'number of donkeys to initialize (data loading threads)')
  cmd:option('-crop_num', 1, 'number of samples cropped from the original area for training')
  cmd:option('-crop_size', {1}, 'cropping sizes as original area percentage for training')
  cmd:option('-scale_num', 1, 'number of scales for testing')
  cmd:option('-scale_size', {96}, 'shorter dimension of resized samples for testing')
  cmd:option('-sub_crop_num', 1, 'number of scale sub-crops for testing')
  ------------- Training options -------------------------------------------------------------------------------------------
  cmd:option('-nEpochs', 55, 'Number of total epochs to run')
  cmd:option('-epochSize', 10000, 'Number of batches per epoch')
  cmd:option('-epochNumber', 1, 'Manual epoch number (useful on restarts)')
  cmd:option('-batchSize', 128, 'mini-batch size (1 = pure stochastic)')
  cmd:option('-sub_batchSize', 1, 'number of positives & negatives for embedding')
  cmd:option('-testBatchSize', 12, 'mini-batch size for testing')
  ---------- Optimization options ------------------------------------------------------------------------------------------
  cmd:option('-optimization', 'SGD', 'optimization method: SGD | Adagrad')
  cmd:option('-LR', 0.0, 'learning rate ; if set, overrides default LR/WD recipe')
  cmd:option('-LRD', 0.0, 'learning rate decay after each iteration/epoch (pass over the dataset)')
  cmd:option('-momentum', 0.9, 'momentum')
  cmd:option('-weightDecay', 5e-4, 'weight decay')
  ---------- Model options -------------------------------------------------------------------------------------------------
  cmd:option('-netType', 'Options : Google | Home-made')
  cmd:option('-retrain', 'none', 'provide path to model to retrain with')
  cmd:option('-optimState', 'none', 'provide path to an optimState to reload from')
  cmd:text()

  local opt = cmd:parse(arg or {})
  -- add commandline specified options
  opt.save = paths.concat(opt.cache, cmd:string('', opt, {retrain=true, optimState=true, cache=true, data=true}))
  -- add date/time
  opt.save = paths.concat(opt.save, ',' .. os.date():gsub(' ',''))
  return opt
end

return M


text:
{{'label.anchor.system' | translate}} /

{{'label.anchor.managereports' | translate}} /

{{report.reportName}}

            {{'label.button.edit' | translate}}
            <button type="button" class="btn btn-danger" ng-show="noncoreReport" ng-click="deletereport()">{{'label.button.delete' | translate}}</button>

{{report.reportName}}

				{{ 'label.heading.reporttype' | translate }}
				{{report.reportType}}

				{{ 'label.heading.reportsubtype' | translate }}
				{{report.reportSubType}}

				{{ 'label.heading.reportcategory' | translate }}
				{{report.reportCategory}}

				{{ 'label.heading.corereport' | translate }}
				{{report.coreReport}}

				{{ 'label.heading.usereport' | translate }}
				{{report.useReport}}


text:
@interface MyBuyingCollectionViewCell : UICollectionViewCell

@property(strong,nonatomic) UIImageView *img;
@property(strong,nonatomic) UILabel *desc;
@property(strong,nonatomic) UILabel *priceTitle;
@property(strong,nonatomic) UILabel *price;

@end


text:
<!DOCTYPE html>

    <title>Sample SAML Spring Boot Application</title>

Goodbye! Click here if you wanna log back in


text:
Ecognize.me

Environmental Consulting Services


text:
![build status](https://gitlab.com/fcv/simple-web-scraper/badges/master/build.svg "Build Status")

## About

Simple Web Scraper POC project. Aims to retrieve data from a Web Page and expose extracted data through a REST API.

## Development

Simple Web Scraper has been develop on Python3 using [Django](https://www.djangoproject.com/) and [Scrapy](https://scrapy.org/) among other libraries.

### Virtual Environment

In order to build system locally is highly recommended to use a [Virtual Environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/).

In an Ubuntu system Python's virtual environment tool may be installed using  command:

    $ apt-get install virtualenv

After that a new virtual environment may be created executing:

    $ virtualenv ~/path/to/new_virtual_env

Then `new_virtual_env` may be activated by:

    $ . ~/path/to/new_virtual_env/bin/activate

Bash prefix would change prepending virtual environment's name indicating that virtual environment is activated. Example:

    $ (new_virtual_env) user@host:~$

In order to deactivate virtual environment one might execute command `deactivate`.

### Install Project's Dependencies

Project dependencies are declared in `requirements.txt` file and may be installed using [pip](https://en.wikipedia.org/wiki/Pip_(package_manager)) command. Remember installing them within virtual environment.

    $ (new_virtual_env) user@host:~/simple-web-scraper$ pip install -r requirements.txt

### Database

Project has been developed targeting PostgreSQL DBMS. Its default connection property values are defined in [simple_web_scraper/settings.py](simple_web_scraper/settings.py#L84) file and they target CI environment's database, see [.gitlab-ci.yml](.gitlab-ci.yml#L10) file.

There are two ways to overwrite those properties at Development environment. Either by defining connection URL using `DATABASE_URL` environment variable. Example:

    $ (new_virtual_env) user@host:~/simple-web-scraper$ pip install -r requirements.txt

Or by overwriting `simple_web_scraper.settings.DATABASES` values in untracked file `local_settings.py`. Example of `simple_web_scraper/local_settings.py` file:

```python
from simple_web_scraper.settings import *

DATABASES['default']['HOST'] = 'localhost'
DATABASES['default']['PORT'] = '5432'

DEBUG = True
```

#### Database's Sctructure Creation

Database's Tables may be created executing:

    $ (new_virtual_env) user@host:~/simple-web-scraper$ python manage.py migrate

#### Note about PostgreSQL usage

In ubuntu environment, in order to install PostgreSQL database adapter [psycopg2](https://pypi.python.org/pypi/psycopg2) it is necessary first to install `libpq-dev` package in order to avoid error message like one below:

    Error: b'You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.\n'

This could be achieved by executing:

    $ sudo apt-get install libpq-dev

### Web Spider

Web Spider is implemented using [scapy](https://github.com/scrapy/scrapy) library. Web spider crawling process may be triggered by executing `scrapy crawl <spider_name>` command. Example:

    user@host:~/simple-web-scraper$ scrapy crawl tech_crunch

### Web App

Web application maybe started by executing Django's `runserver` command. Example:

    $ (new_virtual_env) user@host:~/simple-web-scraper$ python manage.py runserver

### REST API

Extracted data is accessible through REST API's endpoints.

Available endpoints are `/api/rest/v1/authors/` and `/api/rest/v1/articles/`. Example:

    $ curl -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/api/rest/v1/authors
    [
        {
            "id": 1,
            "name": "Todd Gardner",
            "profile_url": "http://social.techcrunch.com/contributor/todd-gardner/"
        },
        {
            "id": 2,
            "name": "Matthew Hodgson",
            "profile_url": "http://social.techcrunch.com/contributor/matthew-hodgson/"
        }
    ]

Article's endpoint supports a query parameter named `"q"`. When provided system will return Articles whose title or content contains such value. Example:

    $ curl -H 'Accept: application/json; indent=4' 'http://127.0.0.1:8000/api/rest/v1/articles?q=combo'
    [
        {
            "id": 338,
            "title": "Samsung's combo desktop/speaker is a weird sort of art",
            "url": "https://techcrunch.com/2016/10/10/art-pc/",
            "publish_date": "2016-10-10T01:27:09Z",
            "content": "If I'm Samsung, I'm looking for the next big product to capture the public's attention while my public relations wing is attempting to put out all a whole lot of proverbial fires (to go along with the literal variety). This isn't that. In fact, Samsung just kind of let this one loose into the world without any real fanfare. And it's got a name to match.\nThe… "
        }
    ]


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

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.lakeformation.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * TableObject JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TableObjectJsonUnmarshaller implements Unmarshaller<TableObject, JsonUnmarshallerContext> {

    public TableObject unmarshall(JsonUnmarshallerContext context) throws Exception {
        TableObject tableObject = new TableObject();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Uri", targetDepth)) {
                    context.nextToken();
                    tableObject.setUri(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ETag", targetDepth)) {
                    context.nextToken();
                    tableObject.setETag(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Size", targetDepth)) {
                    context.nextToken();
                    tableObject.setSize(context.getUnmarshaller(Long.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return tableObject;
    }

    private static TableObjectJsonUnmarshaller instance;

    public static TableObjectJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new TableObjectJsonUnmarshaller();
        return instance;
    }
}


text:
python setup.py sdist
sudo -H pip install --upgrade dist/*.tar.gz


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

import mdemangler.*;
import mdemangler.datatype.MDDataType;
import mdemangler.datatype.MDDataTypeParser;
import mdemangler.datatype.modifier.MDBasedAttribute;
import mdemangler.datatype.modifier.MDCVMod;

/**
 * This class represents a function within a Microsoft mangled symbol.
 */
public class MDFunctionType extends MDType {
	private MDCallingConvention convention;
	private MDDataType retType;
	private MDArgumentsList argsList;
	private MDCVMod thisPointerCVMod;
	private MDThrowAttribute throwAttribute;
	private boolean hasCVModifier = false;
	private boolean hasReturn;
	private boolean hasArgs;
	private boolean isTypeCast;
	protected boolean fromModifier = false;

	protected MDBasedAttribute based;

	public void setBased(MDBasedAttribute based) {
		this.based = based;
	}

	public MDFunctionType(MDMang dmang) {
		this(dmang, true, true);
	}

	public MDFunctionType(MDMang dmang, boolean hasArgs, boolean hasReturn) {
		super(dmang);
		this.hasArgs = hasArgs;
		this.hasReturn = hasReturn;
	}

	public MDCallingConvention getCallingConvention() {
		return convention;
	}

	public MDDataType getReturnType() {
		return retType;
	}

	public MDArgumentsList getArgumentsList() {
		return argsList;
	}

	public MDCVMod getThisPointerCVMod() {
		return thisPointerCVMod; // for "this" pointer
	}

	public MDThrowAttribute getThrowAttribute() {
		return throwAttribute;
	}

	public void setFromModifier() {
		fromModifier = true;
	}

	public void setThisPointerCVMod(MDCVMod thisPointerCVMod) {
		this.thisPointerCVMod = thisPointerCVMod;
	}

	public void setHasCVModifier() {
		hasCVModifier = true;
	}

	public boolean hasReturn() {
		return hasReturn;
	}

	public boolean hasArgs() {
		return hasArgs;
	}

	public boolean isTypeCast() {
		return isTypeCast;
	}

	public void setTypeCast() {
		isTypeCast = true;
	}

	@Override
	protected void parseInternal() throws MDException {
		super.parseInternal(); // parseInternal or dmang.parse?
		dmang.pushFunctionContext();
		if (hasCVModifier) {
			thisPointerCVMod = new MDCVMod(dmang);
			thisPointerCVMod.setThisPointerMod();
			thisPointerCVMod.parse();
		}
		convention = new MDCallingConvention(dmang);
		convention.parse();
		if (hasReturn) {
			retType = MDDataTypeParser.parseDataType(dmang, isTypeCast);
			retType.parse();
		}
		if (hasArgs) {
			argsList = new MDArgumentsList(dmang);
			argsList.parse();
			// TODO 20170323: might make sense to parse 'Z' here and simplify the internals
			//  of MDThrowAttribute.  If 'Z' not found then throwAttribute would be null here.
			throwAttribute = new MDThrowAttribute(dmang);
			throwAttribute.parse();
		}
		dmang.popContext();
	}

	@Override
	public void insert(StringBuilder builder) {
		super.insert(builder);
		String badChars = "*&( ";
		if (builder.length() != 0 && badChars.indexOf(builder.charAt(0)) == -1) {
			dmang.insertString(builder, " ");
		}
		// Separate conventionBuilder with insertion of MDBasedType is used here to reflect MSFT
		// output on underscore-based access-level types (from MDTypeInfoParser '_' prefix),
		// specifically based5 variants.  This could possibly be put into the MDMangVS2015
		//  demangler, but then we would probably need to describe the standard MDMang output
		//  as "invalid," as based-on-basedptr is supposed to be invalid.
		StringBuilder conventionBuilder = new StringBuilder();
		convention.insert(conventionBuilder);
		if (based != null) {
			based.append(conventionBuilder);
		}
		// Following to to clean the Based5 "bug" if seen.  See comments in MDBasedAttribute.
		dmang.cleanOutput(conventionBuilder);
		dmang.insertString(builder, conventionBuilder.toString());
		//This logic moved to MdSpecialName, so that we can get a qualified name with the
		// appropriate cast-to type in the name.  Keeping here, commented out, for
		// a digestion period (20200506).
//		if (hasReturn && isTypeCast) {
//			StringBuilder retBuilder = new StringBuilder();
//			retType.insert(retBuilder);
//			dmang.appendString(builder, " ");
//			dmang.appendString(builder, retBuilder.toString());
//		}
		if (fromModifier) {
			dmang.insertString(builder, "(");
			dmang.appendString(builder, ")");
		}
		if (hasArgs & argsList != null) {
			dmang.appendString(builder, "(");
			argsList.insert(builder);
			dmang.appendString(builder, ")");
		}
		if (thisPointerCVMod != null) {
			StringBuilder cvBuilder = new StringBuilder();
			thisPointerCVMod.insert(cvBuilder);
			dmang.appendString(builder, cvBuilder.toString());
		}
		if (hasReturn && retType != null && !isTypeCast) {
			retType.insert(builder);
		}
		if (throwAttribute != null) {
			String ta = throwAttribute.toString();
			if (ta.length() != 0) {
				dmang.appendString(builder, " " + ta);
			}
		}
	}
}

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


text:
package org.ovirt.engine.core.bll.scheduling.policyunits;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.ovirt.engine.core.bll.scheduling.PolicyUnitImpl;
import org.ovirt.engine.core.bll.scheduling.PolicyUnitParameter;
import org.ovirt.engine.core.bll.scheduling.SchedulingUnit;
import org.ovirt.engine.core.bll.scheduling.pending.PendingResourceManager;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.scheduling.PolicyUnit;
import org.ovirt.engine.core.common.scheduling.PolicyUnitType;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.compat.Guid;

@SchedulingUnit(
        guid = "3ba8c988-f779-42c0-90ce-caa8243edee7",
        name = "OptimalForEvenGuestDistribution",
        type = PolicyUnitType.WEIGHT,
        parameters = {
                PolicyUnitParameter.SPM_VM_GRACE
        }
)
public class EvenGuestDistributionWeightPolicyUnit extends PolicyUnitImpl {
    final int spmVmGrace;

    public EvenGuestDistributionWeightPolicyUnit (PolicyUnit policyUnit,
            PendingResourceManager pendingResourceManager) {
        super(policyUnit, pendingResourceManager);
        spmVmGrace = Config.<Integer> getValue(ConfigValues.SpmVmGraceForEvenGuestDistribute);
    }

    private int getOccupiedVmSlots(VDS vds, Map<String, String> parameters) {
        int occupiedSlots = vds.getVmActive();
        final int SPMVMCountGrace = NumberUtils.toInt(parameters.get(PolicyUnitParameter.SPM_VM_GRACE.getDbName()),
                spmVmGrace);
        if (vds.isSpm()) {
            occupiedSlots += SPMVMCountGrace;
        }

        return occupiedSlots;
    }

    private int calcEvenGuestDistributionScore(VDS vds, Map<String, String> parameters) {
        return Math.max(0, getOccupiedVmSlots(vds, parameters));
    }

    @Override
    public List<Pair<Guid, Integer>> score(List<VDS> hosts, VM vm, Map<String, String> parameters) {
        List<Pair<Guid, Integer>> scores = new ArrayList<>();
        for (VDS vds : hosts) {
            scores.add(new Pair<>(vds.getId(), calcEvenGuestDistributionScore(vds, parameters)));
        }
        return scores;
    }
}


text:
#include "tensorflow/core/lib/gtl/optional.h"

#include <string>
#include <utility>

#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {
namespace {

using tensorflow::gtl::in_place;
using tensorflow::gtl::in_place_t;
using tensorflow::gtl::make_optional;
using tensorflow::gtl::nullopt;
using tensorflow::gtl::nullopt_t;
using tensorflow::gtl::optional;

template <typename T>
string TypeQuals(T&) {
  return "&";
}
template <typename T>
string TypeQuals(T&&) {
  return "&&";
}
template <typename T>
string TypeQuals(const T&) {
  return "c&";
}
template <typename T>
string TypeQuals(const T&&) {
  return "c&&";
}

struct StructorListener {
  int construct0 = 0;
  int construct1 = 0;
  int construct2 = 0;
  int listinit = 0;
  int copy = 0;
  int move = 0;
  int copy_assign = 0;
  int move_assign = 0;
  int destruct = 0;
};

struct Listenable {
  static StructorListener* listener;

  Listenable() { ++listener->construct0; }
  Listenable(int /*unused*/) { ++listener->construct1; }  // NOLINT
  Listenable(int /*unused*/, int /*unused*/) { ++listener->construct2; }
  Listenable(std::initializer_list<int> /*unused*/) { ++listener->listinit; }
  Listenable(const Listenable& /*unused*/) { ++listener->copy; }
  Listenable(Listenable&& /*unused*/) { ++listener->move; }  // NOLINT
  Listenable& operator=(const Listenable& /*unused*/) {
    ++listener->copy_assign;
    return *this;
  }
  Listenable& operator=(Listenable&& /*unused*/) {  // NOLINT
    ++listener->move_assign;
    return *this;
  }
  ~Listenable() { ++listener->destruct; }
};

StructorListener* Listenable::listener = nullptr;

// clang on macos -- even the latest major version at time of writing (8.x) --
// does not like much of our constexpr business.  clang < 3.0 also has trouble.
#if defined(__clang__) && defined(__APPLE__)
#define SKIP_CONSTEXPR_TEST_DUE_TO_CLANG_BUG
#endif

struct ConstexprType {
  constexpr ConstexprType() : x(0) {}
  constexpr explicit ConstexprType(int i) : x(i) {}
#ifndef SKIP_CONSTEXPR_TEST_DUE_TO_CLANG_BUG
  constexpr ConstexprType(std::initializer_list<int> il) : x(il.size()) {}
#endif
  constexpr ConstexprType(const char* s) : x(-1) {}  // NOLINT
  int x;
};

struct Copyable {
  Copyable() {}
  Copyable(const Copyable&) {}
  Copyable& operator=(const Copyable&) { return *this; }
};

struct MoveableThrow {
  MoveableThrow() {}
  MoveableThrow(MoveableThrow&&) {}
  MoveableThrow& operator=(MoveableThrow&&) { return *this; }
};

struct MoveableNoThrow {
  MoveableNoThrow() {}
  MoveableNoThrow(MoveableNoThrow&&) noexcept {}
  MoveableNoThrow& operator=(MoveableNoThrow&&) noexcept { return *this; }
};

struct NonMovable {
  NonMovable() {}
  NonMovable(const NonMovable&) = delete;
  NonMovable& operator=(const NonMovable&) = delete;
  NonMovable(NonMovable&&) = delete;
  NonMovable& operator=(NonMovable&&) = delete;
};

TEST(optionalTest, DefaultConstructor) {
  optional<int> empty;
  EXPECT_FALSE(!!empty);
  constexpr optional<int> cempty;
  static_assert(!cempty.has_value(), "");
  EXPECT_TRUE(std::is_nothrow_default_constructible<optional<int>>::value);
}

TEST(optionalTest, NullOptConstructor) {
  optional<int> empty(nullopt);
  EXPECT_FALSE(!!empty);
  // Creating a temporary nullopt_t object instead of using nullopt because
  // nullopt cannot be constexpr and have external linkage at the same time.
  constexpr optional<int> cempty{nullopt_t(nullopt_t::init)};
  static_assert(!cempty.has_value(), "");
  EXPECT_TRUE((std::is_nothrow_constructible<optional<int>, nullopt_t>::value));
}

TEST(optionalTest, CopyConstructor) {
  optional<int> empty, opt42 = 42;
  optional<int> empty_copy(empty);
  EXPECT_FALSE(!!empty_copy);
  optional<int> opt42_copy(opt42);
  EXPECT_TRUE(!!opt42_copy);
  EXPECT_EQ(42, opt42_copy);
  // test copyablility
  EXPECT_TRUE(std::is_copy_constructible<optional<int>>::value);
  EXPECT_TRUE(std::is_copy_constructible<optional<Copyable>>::value);
  EXPECT_FALSE(std::is_copy_constructible<optional<MoveableThrow>>::value);
  EXPECT_FALSE(std::is_copy_constructible<optional<MoveableNoThrow>>::value);
  EXPECT_FALSE(std::is_copy_constructible<optional<NonMovable>>::value);
}

TEST(optionalTest, MoveConstructor) {
  optional<int> empty, opt42 = 42;
  optional<int> empty_move(std::move(empty));
  EXPECT_FALSE(!!empty_move);
  optional<int> opt42_move(std::move(opt42));
  EXPECT_TRUE(!!opt42_move);
  EXPECT_EQ(42, opt42_move);
  // test movability
  EXPECT_TRUE(std::is_move_constructible<optional<int>>::value);
  EXPECT_TRUE(std::is_move_constructible<optional<Copyable>>::value);
  EXPECT_TRUE(std::is_move_constructible<optional<MoveableThrow>>::value);
  EXPECT_TRUE(std::is_move_constructible<optional<MoveableNoThrow>>::value);
  EXPECT_FALSE(std::is_move_constructible<optional<NonMovable>>::value);
  // test noexcept
  EXPECT_TRUE(std::is_nothrow_move_constructible<optional<int>>::value);
  EXPECT_FALSE(
      std::is_nothrow_move_constructible<optional<MoveableThrow>>::value);
  EXPECT_TRUE(
      std::is_nothrow_move_constructible<optional<MoveableNoThrow>>::value);
}

TEST(optionalTest, Destructor) {
  struct Trivial {};

  struct NonTrivial {
    ~NonTrivial() {}
  };

  EXPECT_TRUE(std::is_trivially_destructible<optional<int>>::value);
  EXPECT_TRUE(std::is_trivially_destructible<optional<Trivial>>::value);
  EXPECT_FALSE(std::is_trivially_destructible<optional<NonTrivial>>::value);
}

TEST(optionalTest, InPlaceConstructor) {
  constexpr optional<ConstexprType> opt0{in_place_t()};
  static_assert(opt0, "");
  static_assert(opt0->x == 0, "");
  constexpr optional<ConstexprType> opt1{in_place_t(), 1};
  static_assert(opt1, "");
  static_assert(opt1->x == 1, "");
#ifndef SKIP_CONSTEXPR_TEST_DUE_TO_CLANG_BUG
  constexpr optional<ConstexprType> opt2{in_place_t(), {1, 2}};
  static_assert(opt2, "");
  static_assert(opt2->x == 2, "");
#endif

  // TODO(b/34201852): uncomment these when std::is_constructible<T, Args&&...>
  // SFINAE is added to optional::optional(in_place_t, Args&&...).
  // struct I {
  //   I(in_place_t);
  // };

  // EXPECT_FALSE((std::is_constructible<optional<I>, in_place_t>::value));
  // EXPECT_FALSE((std::is_constructible<optional<I>, const
  // in_place_t&>::value));
}

// template<U=T> optional(U&&);
TEST(optionalTest, ValueConstructor) {
  constexpr optional<int> opt0(0);
  static_assert(opt0, "");
  static_assert(*opt0 == 0, "");
  EXPECT_TRUE((std::is_convertible<int, optional<int>>::value));
  // Copy initialization ( = "abc") won't work due to optional(optional&&)
  // is not constexpr. Use list initialization instead. This invokes
  // optional<ConstexprType>::optional<U>(U&&), with U = const char (&) [4],
  // which direct-initializes the ConstexprType value held by the optional
  // via ConstexprType::ConstexprType(const char*).
  constexpr optional<ConstexprType> opt1 = {"abc"};
  static_assert(opt1, "");
  static_assert(-1 == opt1->x, "");
  EXPECT_TRUE(
      (std::is_convertible<const char*, optional<ConstexprType>>::value));
  // direct initialization
  constexpr optional<ConstexprType> opt2{2};
  static_assert(opt2, "");
  static_assert(2 == opt2->x, "");
  EXPECT_FALSE((std::is_convertible<int, optional<ConstexprType>>::value));

  // this invokes optional<int>::optional(int&&)
  // NOTE: this has different behavior than assignment, e.g.
  // "opt3 = {};" clears the optional rather than setting the value to 0
  constexpr optional<int> opt3({});
  static_assert(opt3, "");
  static_assert(*opt3 == 0, "");

  // this invokes the move constructor with a default constructed optional
  // because non-template function is a better match than template function.
  optional<ConstexprType> opt4({});
  EXPECT_FALSE(!!opt4);
}

struct Implicit {};

struct Explicit {};

struct Convert {
  Convert(const Implicit&)  // NOLINT(runtime/explicit)
      : implicit(true), move(false) {}
  Convert(Implicit&&)  // NOLINT(runtime/explicit)
      : implicit(true), move(true) {}
  explicit Convert(const Explicit&) : implicit(false), move(false) {}
  explicit Convert(Explicit&&) : implicit(false), move(true) {}

  bool implicit;
  bool move;
};

struct ConvertFromOptional {
  ConvertFromOptional(const Implicit&)  // NOLINT(runtime/explicit)
      : implicit(true), move(false), from_optional(false) {}
  ConvertFromOptional(Implicit&&)  // NOLINT(runtime/explicit)
      : implicit(true), move(true), from_optional(false) {}
  ConvertFromOptional(const optional<Implicit>&)  // NOLINT(runtime/explicit)
      : implicit(true), move(false), from_optional(true) {}
  ConvertFromOptional(optional<Implicit>&&)  // NOLINT(runtime/explicit)
      : implicit(true), move(true), from_optional(true) {}
  explicit ConvertFromOptional(const Explicit&)
      : implicit(false), move(false), from_optional(false) {}
  explicit ConvertFromOptional(Explicit&&)
      : implicit(false), move(true), from_optional(false) {}
  explicit ConvertFromOptional(const optional<Explicit>&)
      : implicit(false), move(false), from_optional(true) {}
  explicit ConvertFromOptional(optional<Explicit>&&)
      : implicit(false), move(true), from_optional(true) {}

  bool implicit;
  bool move;
  bool from_optional;
};

TEST(optionalTest, ConvertingConstructor) {
  optional<Implicit> i_empty;
  optional<Implicit> i(in_place);
  optional<Explicit> e_empty;
  optional<Explicit> e(in_place);
  {
    // implicitly constructing optional<Convert> from optional<Implicit>
    optional<Convert> empty = i_empty;
    EXPECT_FALSE(!!empty);
    optional<Convert> opt_copy = i;
    EXPECT_TRUE(!!opt_copy);
    EXPECT_TRUE(opt_copy->implicit);
    EXPECT_FALSE(opt_copy->move);
    optional<Convert> opt_move = optional<Implicit>(in_place);
    EXPECT_TRUE(!!opt_move);
    EXPECT_TRUE(opt_move->implicit);
    EXPECT_TRUE(opt_move->move);
  }
  {
    // explicitly constructing optional<Convert> from optional<Explicit>
    optional<Convert> empty(e_empty);
    EXPECT_FALSE(!!empty);
    optional<Convert> opt_copy(e);
    EXPECT_TRUE(!!opt_copy);
    EXPECT_FALSE(opt_copy->implicit);
    EXPECT_FALSE(opt_copy->move);
    EXPECT_FALSE((std::is_convertible<const optional<Explicit>&,
                                      optional<Convert>>::value));
    optional<Convert> opt_move{optional<Explicit>(in_place)};
    EXPECT_TRUE(!!opt_move);
    EXPECT_FALSE(opt_move->implicit);
    EXPECT_TRUE(opt_move->move);
    EXPECT_FALSE(
        (std::is_convertible<optional<Explicit>&&, optional<Convert>>::value));
  }
  {
    // implicitly constructing optional<ConvertFromOptional> from
    // optional<Implicit> via ConvertFromOptional(optional<Implicit>&&)
    // check that ConvertFromOptional(Implicit&&) is NOT called
    static_assert(
        gtl::internal_optional::is_constructible_convertible_from_optional<
            ConvertFromOptional, Implicit>::value,
        "");
    optional<ConvertFromOptional> opt0 = i_empty;
    EXPECT_TRUE(!!opt0);
    EXPECT_TRUE(opt0->implicit);
    EXPECT_FALSE(opt0->move);
    EXPECT_TRUE(opt0->from_optional);
    optional<ConvertFromOptional> opt1 = optional<Implicit>();
    EXPECT_TRUE(!!opt1);
    EXPECT_TRUE(opt1->implicit);
    EXPECT_TRUE(opt1->move);
    EXPECT_TRUE(opt1->from_optional);
  }
  {
    // implicitly constructing optional<ConvertFromOptional> from
    // optional<Explicit> via ConvertFromOptional(optional<Explicit>&&)
    // check that ConvertFromOptional(Explicit&&) is NOT called
    optional<ConvertFromOptional> opt0(e_empty);
    EXPECT_TRUE(!!opt0);
    EXPECT_FALSE(opt0->implicit);
    EXPECT_FALSE(opt0->move);
    EXPECT_TRUE(opt0->from_optional);
    EXPECT_FALSE((std::is_convertible<const optional<Explicit>&,
                                      optional<ConvertFromOptional>>::value));
    optional<ConvertFromOptional> opt1{optional<Explicit>()};
    EXPECT_TRUE(!!opt1);
    EXPECT_FALSE(opt1->implicit);
    EXPECT_TRUE(opt1->move);
    EXPECT_TRUE(opt1->from_optional);
    EXPECT_FALSE((std::is_convertible<optional<Explicit>&&,
                                      optional<ConvertFromOptional>>::value));
  }
}

TEST(optionalTest, StructorBasic) {
  StructorListener listener;
  Listenable::listener = &listener;
  {
    optional<Listenable> empty;
    EXPECT_FALSE(!!empty);
    optional<Listenable> opt0(in_place);
    EXPECT_TRUE(!!opt0);
    optional<Listenable> opt1(in_place, 1);
    EXPECT_TRUE(!!opt1);
    optional<Listenable> opt2(in_place, 1, 2);
    EXPECT_TRUE(!!opt2);
  }
  EXPECT_EQ(1, listener.construct0);
  EXPECT_EQ(1, listener.construct1);
  EXPECT_EQ(1, listener.construct2);
  EXPECT_EQ(3, listener.destruct);
}

TEST(optionalTest, CopyMoveStructor) {
  StructorListener listener;
  Listenable::listener = &listener;
  optional<Listenable> original(in_place);
  EXPECT_EQ(1, listener.construct0);
  EXPECT_EQ(0, listener.copy);
  EXPECT_EQ(0, listener.move);
  optional<Listenable> copy(original);
  EXPECT_EQ(1, listener.construct0);
  EXPECT_EQ(1, listener.copy);
  EXPECT_EQ(0, listener.move);
  optional<Listenable> move(std::move(original));
  EXPECT_EQ(1, listener.construct0);
  EXPECT_EQ(1, listener.copy);
  EXPECT_EQ(1, listener.move);
}

TEST(optionalTest, ListInit) {
  StructorListener listener;
  Listenable::listener = &listener;
  optional<Listenable> listinit1(in_place, {1});
  optional<Listenable> listinit2(in_place, {1, 2});
  EXPECT_EQ(2, listener.listinit);
}

TEST(optionalTest, AssignFromNullopt) {
  optional<int> opt(1);
  opt = nullopt;
  EXPECT_FALSE(!!opt);

  StructorListener listener;
  Listenable::listener = &listener;
  optional<Listenable> opt1(in_place);
  opt1 = nullopt;
  EXPECT_FALSE(opt1);
  EXPECT_EQ(1, listener.construct0);
  EXPECT_EQ(1, listener.destruct);

  EXPECT_TRUE((std::is_nothrow_assignable<optional<int>, nullopt_t>::value));
  EXPECT_TRUE(
      (std::is_nothrow_assignable<optional<Listenable>, nullopt_t>::value));
}

TEST(optionalTest, CopyAssignment) {
  const optional<int> empty, opt1 = 1, opt2 = 2;
  optional<int> empty_to_opt1, opt1_to_opt2, opt2_to_empty;

  EXPECT_FALSE(!!empty_to_opt1);
  empty_to_opt1 = empty;
  EXPECT_FALSE(!!empty_to_opt1);
  empty_to_opt1 = opt1;
  EXPECT_TRUE(!!empty_to_opt1);
  EXPECT_EQ(1, empty_to_opt1.value());

  EXPECT_FALSE(!!opt1_to_opt2);
  opt1_to_opt2 = opt1;
  EXPECT_TRUE(!!opt1_to_opt2);
  EXPECT_EQ(1, opt1_to_opt2.value());
  opt1_to_opt2 = opt2;
  EXPECT_TRUE(!!opt1_to_opt2);
  EXPECT_EQ(2, opt1_to_opt2.value());

  EXPECT_FALSE(!!opt2_to_empty);
  opt2_to_empty = opt2;
  EXPECT_TRUE(!!opt2_to_empty);
  EXPECT_EQ(2, opt2_to_empty.value());
  opt2_to_empty = empty;
  EXPECT_FALSE(!!opt2_to_empty);

  EXPECT_TRUE(std::is_copy_assignable<optional<Copyable>>::value);
  EXPECT_FALSE(std::is_copy_assignable<optional<MoveableThrow>>::value);
  EXPECT_FALSE(std::is_copy_assignable<optional<MoveableNoThrow>>::value);
  EXPECT_FALSE(std::is_copy_assignable<optional<NonMovable>>::value);
}

TEST(optionalTest, MoveAssignment) {
  StructorListener listener;
  Listenable::listener = &listener;

  optional<Listenable> empty1, empty2, set1(in_place), set2(in_place);
  EXPECT_EQ(2, listener.construct0);
  optional<Listenable> empty_to_empty, empty_to_set, set_to_empty(in_place),
      set_to_set(in_place);
  EXPECT_EQ(4, listener.construct0);
  empty_to_empty = std::move(empty1);
  empty_to_set = std::move(set1);
  set_to_empty = std::move(empty2);
  set_to_set = std::move(set2);
  EXPECT_EQ(0, listener.copy);
  EXPECT_EQ(1, listener.move);
  EXPECT_EQ(1, listener.destruct);
  EXPECT_EQ(1, listener.move_assign);

  EXPECT_TRUE(std::is_move_assignable<optional<Copyable>>::value);
  EXPECT_TRUE(std::is_move_assignable<optional<MoveableThrow>>::value);
  EXPECT_TRUE(std::is_move_assignable<optional<MoveableNoThrow>>::value);
  EXPECT_FALSE(std::is_move_assignable<optional<NonMovable>>::value);

  EXPECT_FALSE(std::is_nothrow_move_assignable<optional<MoveableThrow>>::value);
  EXPECT_TRUE(
      std::is_nothrow_move_assignable<optional<MoveableNoThrow>>::value);
}

struct NoConvertToOptional {
  // disable implicit conversion from const NoConvertToOptional&
  // to optional<NoConvertToOptional>.
  NoConvertToOptional(const NoConvertToOptional&) = delete;
};

struct CopyConvert {
  CopyConvert(const NoConvertToOptional&);
  CopyConvert& operator=(const CopyConvert&) = delete;
  CopyConvert& operator=(const NoConvertToOptional&);
};

struct CopyConvertFromOptional {
  CopyConvertFromOptional(const NoConvertToOptional&);
  CopyConvertFromOptional(const optional<NoConvertToOptional>&);
  CopyConvertFromOptional& operator=(const CopyConvertFromOptional&) = delete;
  CopyConvertFromOptional& operator=(const NoConvertToOptional&);
  CopyConvertFromOptional& operator=(const optional<NoConvertToOptional>&);
};

struct MoveConvert {
  MoveConvert(NoConvertToOptional&&);
  MoveConvert& operator=(const MoveConvert&) = delete;
  MoveConvert& operator=(NoConvertToOptional&&);
};

struct MoveConvertFromOptional {
  MoveConvertFromOptional(NoConvertToOptional&&);
  MoveConvertFromOptional(optional<NoConvertToOptional>&&);
  MoveConvertFromOptional& operator=(const MoveConvertFromOptional&) = delete;
  MoveConvertFromOptional& operator=(NoConvertToOptional&&);
  MoveConvertFromOptional& operator=(optional<NoConvertToOptional>&&);
};

// template <class U = T> optional<T>& operator=(U&& v);
TEST(optionalTest, ValueAssignment) {
  optional<int> opt;
  EXPECT_FALSE(!!opt);
  opt = 42;
  EXPECT_TRUE(!!opt);
  EXPECT_EQ(42, opt.value());
  opt = nullopt;
  EXPECT_FALSE(!!opt);
  opt = 42;
  EXPECT_TRUE(!!opt);
  EXPECT_EQ(42, opt.value());
  opt = 43;
  EXPECT_TRUE(!!opt);
  EXPECT_EQ(43, opt.value());
  opt = {};  // this should clear optional
  EXPECT_FALSE(!!opt);

  opt = {44};
  EXPECT_TRUE(!!opt);
  EXPECT_EQ(44, opt.value());

  // U = const NoConvertToOptional&
  EXPECT_TRUE((std::is_assignable<optional<CopyConvert>&,
                                  const NoConvertToOptional&>::value));
  // U = const optional<NoConvertToOptional>&
  EXPECT_TRUE((std::is_assignable<optional<CopyConvertFromOptional>&,
                                  const NoConvertToOptional&>::value));
  // U = const NoConvertToOptional& triggers SFINAE because
  // std::is_constructible_v<MoveConvert, const NoConvertToOptional&> is false
  EXPECT_FALSE((std::is_assignable<optional<MoveConvert>&,
                                   const NoConvertToOptional&>::value));
  // U = NoConvertToOptional
  EXPECT_TRUE((std::is_assignable<optional<MoveConvert>&,
                                  NoConvertToOptional&&>::value));
  // U = const NoConvertToOptional& triggers SFINAE because
  // std::is_constructible_v<MoveConvertFromOptional, const
  // NoConvertToOptional&> is false
  EXPECT_FALSE((std::is_assignable<optional<MoveConvertFromOptional>&,
                                   const NoConvertToOptional&>::value));
  // U = NoConvertToOptional
  EXPECT_TRUE((std::is_assignable<optional<MoveConvertFromOptional>&,
                                  NoConvertToOptional&&>::value));
  // U = const optional<NoConvertToOptional>&
  EXPECT_TRUE(
      (std::is_assignable<optional<CopyConvertFromOptional>&,
                          const optional<NoConvertToOptional>&>::value));
  // U = optional<NoConvertToOptional>
  EXPECT_TRUE((std::is_assignable<optional<MoveConvertFromOptional>&,
                                  optional<NoConvertToOptional>&&>::value));
}

// template <class U> optional<T>& operator=(const optional<U>& rhs);
// template <class U> optional<T>& operator=(optional<U>&& rhs);
TEST(optionalTest, ConvertingAssignment) {
  optional<int> opt_i;
  optional<char> opt_c('c');
  opt_i = opt_c;
  EXPECT_TRUE(!!opt_i);
  EXPECT_EQ(*opt_c, *opt_i);
  opt_i = optional<char>();
  EXPECT_FALSE(!!opt_i);
  opt_i = optional<char>('d');
  EXPECT_TRUE(!!opt_i);
  EXPECT_EQ('d', *opt_i);

  optional<string> opt_str;
  optional<const char*> opt_cstr("abc");
  opt_str = opt_cstr;
  EXPECT_TRUE(!!opt_str);
  EXPECT_EQ(string("abc"), *opt_str);
  opt_str = optional<const char*>();
  EXPECT_FALSE(!!opt_str);
  opt_str = optional<const char*>("def");
  EXPECT_TRUE(!!opt_str);
  EXPECT_EQ(string("def"), *opt_str);

  // operator=(const optional<U>&) with U = NoConvertToOptional
  EXPECT_TRUE(
      (std::is_assignable<optional<CopyConvert>,
                          const optional<NoConvertToOptional>&>::value));
  // operator=(const optional<U>&) with U = NoConvertToOptional
  // triggers SFINAE because
  // std::is_constructible_v<MoveConvert, const NoConvertToOptional&> is false
  EXPECT_FALSE(
      (std::is_assignable<optional<MoveConvert>&,
                          const optional<NoConvertToOptional>&>::value));
  // operator=(optional<U>&&) with U = NoConvertToOptional
  EXPECT_TRUE((std::is_assignable<optional<MoveConvert>&,
                                  optional<NoConvertToOptional>&&>::value));
  // operator=(const optional<U>&) with U = NoConvertToOptional triggers SFINAE
  // because std::is_constructible_v<MoveConvertFromOptional,
  // const NoConvertToOptional&> is false.
  // operator=(U&&) with U = const optional<NoConverToOptional>& triggers SFINAE
  // because std::is_constructible<MoveConvertFromOptional,
  // optional<NoConvertToOptional>&&> is true.
  EXPECT_FALSE(
      (std::is_assignable<optional<MoveConvertFromOptional>&,
                          const optional<NoConvertToOptional>&>::value));
}

TEST(optionalTest, ResetAndHasValue) {
  StructorListener listener;
  Listenable::listener = &listener;
  optional<Listenable> opt;
  EXPECT_FALSE(!!opt);
  EXPECT_FALSE(opt.has_value());
  opt.emplace();
  EXPECT_TRUE(!!opt);
  EXPECT_TRUE(opt.has_value());
  opt.reset();
  EXPECT_FALSE(!!opt);
  EXPECT_FALSE(opt.has_value());
  EXPECT_EQ(1, listener.destruct);
  opt.reset();
  EXPECT_FALSE(!!opt);
  EXPECT_FALSE(opt.has_value());

  constexpr optional<int> empty;
  static_assert(!empty.has_value(), "");
  constexpr optional<int> nonempty(1);
  static_assert(nonempty.has_value(), "");
}

TEST(optionalTest, Emplace) {
  StructorListener listener;
  Listenable::listener = &listener;
  optional<Listenable> opt;
  EXPECT_FALSE(!!opt);
  opt.emplace(1);
  EXPECT_TRUE(!!opt);
  opt.emplace(1, 2);
  EXPECT_EQ(1, listener.construct1);
  EXPECT_EQ(1, listener.construct2);
  EXPECT_EQ(1, listener.destruct);
}

TEST(optionalTest, ListEmplace) {
  StructorListener listener;
  Listenable::listener = &listener;
  optional<Listenable> opt;
  EXPECT_FALSE(!!opt);
  opt.emplace({1});
  EXPECT_TRUE(!!opt);
  opt.emplace({1, 2});
  EXPECT_EQ(2, listener.listinit);
  EXPECT_EQ(1, listener.destruct);
}

TEST(optionalTest, Swap) {
  optional<int> opt_empty, opt1 = 1, opt2 = 2;
  EXPECT_FALSE(!!opt_empty);
  EXPECT_TRUE(!!opt1);
  EXPECT_EQ(1, opt1.value());
  EXPECT_TRUE(!!opt2);
  EXPECT_EQ(2, opt2.value());
  swap(opt_empty, opt1);
  EXPECT_FALSE(!!opt1);
  EXPECT_TRUE(!!opt_empty);
  EXPECT_EQ(1, opt_empty.value());
  EXPECT_TRUE(!!opt2);
  EXPECT_EQ(2, opt2.value());
  swap(opt_empty, opt1);
  EXPECT_FALSE(!!opt_empty);
  EXPECT_TRUE(!!opt1);
  EXPECT_EQ(1, opt1.value());
  EXPECT_TRUE(!!opt2);
  EXPECT_EQ(2, opt2.value());
  swap(opt1, opt2);
  EXPECT_FALSE(!!opt_empty);
  EXPECT_TRUE(!!opt1);
  EXPECT_EQ(2, opt1.value());
  EXPECT_TRUE(!!opt2);
  EXPECT_EQ(1, opt2.value());

  EXPECT_TRUE(noexcept(opt1.swap(opt2)));
  EXPECT_TRUE(noexcept(swap(opt1, opt2)));
}

TEST(optionalTest, PointerStuff) {
  optional<string> opt(in_place, "foo");
  EXPECT_EQ("foo", *opt);
  const auto& opt_const = opt;
  EXPECT_EQ("foo", *opt_const);
  EXPECT_EQ(opt->size(), 3);
  EXPECT_EQ(opt_const->size(), 3);

  constexpr optional<ConstexprType> opt1(1);
  static_assert(opt1->x == 1, "");
}

// gcc has a bug pre 4.9 where it doesn't do correct overload resolution
// between rvalue reference qualified member methods. Skip that test to make
// the build green again when using the old compiler.
#if defined(__GNUC__) && !defined(__clang__)
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 9)
#define SKIP_OVERLOAD_TEST_DUE_TO_GCC_BUG
#endif
#endif

TEST(optionalTest, Value) {
  using O = optional<string>;
  using CO = const optional<string>;
  O lvalue(in_place, "lvalue");
  CO clvalue(in_place, "clvalue");
  EXPECT_EQ("lvalue", lvalue.value());
  EXPECT_EQ("clvalue", clvalue.value());
  EXPECT_EQ("xvalue", O(in_place, "xvalue").value());
#ifndef SKIP_OVERLOAD_TEST_DUE_TO_GCC_BUG
  EXPECT_EQ("cxvalue", CO(in_place, "cxvalue").value());
  EXPECT_EQ("&", TypeQuals(lvalue.value()));
  EXPECT_EQ("c&", TypeQuals(clvalue.value()));
  EXPECT_EQ("&&", TypeQuals(O(in_place, "xvalue").value()));
  EXPECT_EQ("c&&", TypeQuals(CO(in_place, "cxvalue").value()));
#endif
}

TEST(optionalTest, DerefOperator) {
  using O = optional<string>;
  using CO = const optional<string>;
  O lvalue(in_place, "lvalue");
  CO clvalue(in_place, "clvalue");
  EXPECT_EQ("lvalue", *lvalue);
  EXPECT_EQ("clvalue", *clvalue);
  EXPECT_EQ("xvalue", *O(in_place, "xvalue"));
#ifndef SKIP_OVERLOAD_TEST_DUE_TO_GCC_BUG
  EXPECT_EQ("cxvalue", *CO(in_place, "cxvalue"));
  EXPECT_EQ("&", TypeQuals(*lvalue));
  EXPECT_EQ("c&", TypeQuals(*clvalue));
  EXPECT_EQ("&&", TypeQuals(*O(in_place, "xvalue")));
  EXPECT_EQ("c&&", TypeQuals(*CO(in_place, "cxvalue")));
#endif

  constexpr optional<int> opt1(1);
  static_assert(*opt1 == 1, "");

#if !defined(SKIP_CONSTEXPR_TEST_DUE_TO_CLANG_BUG) && \
    !defined(SKIP_OVERLOAD_TEST_DUE_TO_GCC_BUG)
  using COI = const optional<int>;
  static_assert(*COI(2) == 2, "");
#endif
}

TEST(optionalTest, ValueOr) {
  optional<double> opt_empty, opt_set = 1.2;
  EXPECT_EQ(42.0, opt_empty.value_or(42));
  EXPECT_EQ(1.2, opt_set.value_or(42));
  EXPECT_EQ(42.0, optional<double>().value_or(42));
  EXPECT_EQ(1.2, optional<double>(1.2).value_or(42));

#ifndef SKIP_CONSTEXPR_TEST_DUE_TO_CLANG_BUG
  constexpr optional<double> copt_empty;
  static_assert(42.0 == copt_empty.value_or(42), "");

  constexpr optional<double> copt_set = {1.2};
  static_assert(1.2 == copt_set.value_or(42), "");

  using COD = const optional<double>;
  static_assert(42.0 == COD().value_or(42), "");
  static_assert(1.2 == COD(1.2).value_or(42), "");
#endif
}

// make_optional cannot be constexpr until C++17
TEST(optionalTest, make_optional) {
  auto opt_int = make_optional(42);
  EXPECT_TRUE((std::is_same<decltype(opt_int), optional<int>>::value));
  EXPECT_EQ(42, opt_int);

  StructorListener listener;
  Listenable::listener = &listener;

  optional<Listenable> opt0 = make_optional<Listenable>();
  EXPECT_EQ(1, listener.construct0);
  optional<Listenable> opt1 = make_optional<Listenable>(1);
  EXPECT_EQ(1, listener.construct1);
  optional<Listenable> opt2 = make_optional<Listenable>(1, 2);
  EXPECT_EQ(1, listener.construct2);
  optional<Listenable> opt3 = make_optional<Listenable>({1});
  optional<Listenable> opt4 = make_optional<Listenable>({1, 2});
  EXPECT_EQ(2, listener.listinit);
}

TEST(optionalTest, Comparisons) {
  optional<int> ae, be, a2 = 2, b2 = 2, a4 = 4, b4 = 4;

#define optionalTest_Comparisons_EXPECT_LESS(x, y) \
  EXPECT_FALSE((x) == (y));                        \
  EXPECT_TRUE((x) != (y));                         \
  EXPECT_TRUE((x) < (y));                          \
  EXPECT_FALSE((x) > (y));                         \
  EXPECT_TRUE((x) <= (y));                         \
  EXPECT_FALSE((x) >= (y));

#define optionalTest_Comparisons_EXPECT_SAME(x, y) \
  EXPECT_TRUE((x) == (y));                         \
  EXPECT_FALSE((x) != (y));                        \
  EXPECT_FALSE((x) < (y));                         \
  EXPECT_FALSE((x) > (y));                         \
  EXPECT_TRUE((x) <= (y));                         \
  EXPECT_TRUE((x) >= (y));

#define optionalTest_Comparisons_EXPECT_GREATER(x, y) \
  EXPECT_FALSE((x) == (y));                           \
  EXPECT_TRUE((x) != (y));                            \
  EXPECT_FALSE((x) < (y));                            \
  EXPECT_TRUE((x) > (y));                             \
  EXPECT_FALSE((x) <= (y));                           \
  EXPECT_TRUE((x) >= (y));

  // LHS: nullopt, ae, a2, 3, a4
  // RHS: nullopt, be, b2, 3, b4

  // optionalTest_Comparisons_EXPECT_NOT_TO_WORK(nullopt,nullopt);
  optionalTest_Comparisons_EXPECT_SAME(nullopt, be);
  optionalTest_Comparisons_EXPECT_LESS(nullopt, b2);
  // optionalTest_Comparisons_EXPECT_NOT_TO_WORK(nullopt,3);
  optionalTest_Comparisons_EXPECT_LESS(nullopt, b4);

  optionalTest_Comparisons_EXPECT_SAME(ae, nullopt);
  optionalTest_Comparisons_EXPECT_SAME(ae, be);
  optionalTest_Comparisons_EXPECT_LESS(ae, b2);
  optionalTest_Comparisons_EXPECT_LESS(ae, 3);
  optionalTest_Comparisons_EXPECT_LESS(ae, b4);

  optionalTest_Comparisons_EXPECT_GREATER(a2, nullopt);
  optionalTest_Comparisons_EXPECT_GREATER(a2, be);
  optionalTest_Comparisons_EXPECT_SAME(a2, b2);
  optionalTest_Comparisons_EXPECT_LESS(a2, 3);
  optionalTest_Comparisons_EXPECT_LESS(a2, b4);

  // optionalTest_Comparisons_EXPECT_NOT_TO_WORK(3,nullopt);
  optionalTest_Comparisons_EXPECT_GREATER(3, be);
  optionalTest_Comparisons_EXPECT_GREATER(3, b2);
  optionalTest_Comparisons_EXPECT_SAME(3, 3);
  optionalTest_Comparisons_EXPECT_LESS(3, b4);

  optionalTest_Comparisons_EXPECT_GREATER(a4, nullopt);
  optionalTest_Comparisons_EXPECT_GREATER(a4, be);
  optionalTest_Comparisons_EXPECT_GREATER(a4, b2);
  optionalTest_Comparisons_EXPECT_GREATER(a4, 3);
  optionalTest_Comparisons_EXPECT_SAME(a4, b4);
}

TEST(optionalTest, SwapRegression) {
  StructorListener listener;
  Listenable::listener = &listener;

  {
    optional<Listenable> a;
    optional<Listenable> b(in_place);
    a.swap(b);
  }

  EXPECT_EQ(1, listener.construct0);
  EXPECT_EQ(1, listener.move);
  EXPECT_EQ(2, listener.destruct);

  {
    optional<Listenable> a(in_place);
    optional<Listenable> b;
    a.swap(b);
  }

  EXPECT_EQ(2, listener.construct0);
  EXPECT_EQ(2, listener.move);
  EXPECT_EQ(4, listener.destruct);
}

TEST(optionalTest, BigStringLeakCheck) {
  constexpr size_t n = 1 << 16;

  using OS = optional<string>;

  OS a;
  OS b = nullopt;
  OS c = string(n, 'c');
  string sd(n, 'd');
  OS d = sd;
  OS e(in_place, n, 'e');
  OS f;
  f.emplace(n, 'f');

  OS ca(a);
  OS cb(b);
  OS cc(c);
  OS cd(d);
  OS ce(e);

  OS oa;
  OS ob = nullopt;
  OS oc = string(n, 'c');
  string sod(n, 'd');
  OS od = sod;
  OS oe(in_place, n, 'e');
  OS of;
  of.emplace(n, 'f');

  OS ma(std::move(oa));
  OS mb(std::move(ob));
  OS mc(std::move(oc));
  OS md(std::move(od));
  OS me(std::move(oe));
  OS mf(std::move(of));

  OS aa1;
  OS ab1 = nullopt;
  OS ac1 = string(n, 'c');
  string sad1(n, 'd');
  OS ad1 = sad1;
  OS ae1(in_place, n, 'e');
  OS af1;
  af1.emplace(n, 'f');

  OS aa2;
  OS ab2 = nullopt;
  OS ac2 = string(n, 'c');
  string sad2(n, 'd');
  OS ad2 = sad2;
  OS ae2(in_place, n, 'e');
  OS af2;
  af2.emplace(n, 'f');

  aa1 = af2;
  ab1 = ae2;
  ac1 = ad2;
  ad1 = ac2;
  ae1 = ab2;
  af1 = aa2;

  OS aa3;
  OS ab3 = nullopt;
  OS ac3 = string(n, 'c');
  string sad3(n, 'd');
  OS ad3 = sad3;
  OS ae3(in_place, n, 'e');
  OS af3;
  af3.emplace(n, 'f');

  aa3 = nullopt;
  ab3 = nullopt;
  ac3 = nullopt;
  ad3 = nullopt;
  ae3 = nullopt;
  af3 = nullopt;

  OS aa4;
  OS ab4 = nullopt;
  OS ac4 = string(n, 'c');
  string sad4(n, 'd');
  OS ad4 = sad4;
  OS ae4(in_place, n, 'e');
  OS af4;
  af4.emplace(n, 'f');

  aa4 = OS(in_place, n, 'a');
  ab4 = OS(in_place, n, 'b');
  ac4 = OS(in_place, n, 'c');
  ad4 = OS(in_place, n, 'd');
  ae4 = OS(in_place, n, 'e');
  af4 = OS(in_place, n, 'f');

  OS aa5;
  OS ab5 = nullopt;
  OS ac5 = string(n, 'c');
  string sad5(n, 'd');
  OS ad5 = sad5;
  OS ae5(in_place, n, 'e');
  OS af5;
  af5.emplace(n, 'f');

  string saa5(n, 'a');
  string sab5(n, 'a');
  string sac5(n, 'a');
  string sad52(n, 'a');
  string sae5(n, 'a');
  string saf5(n, 'a');

  aa5 = saa5;
  ab5 = sab5;
  ac5 = sac5;
  ad5 = sad52;
  ae5 = sae5;
  af5 = saf5;

  OS aa6;
  OS ab6 = nullopt;
  OS ac6 = string(n, 'c');
  string sad6(n, 'd');
  OS ad6 = sad6;
  OS ae6(in_place, n, 'e');
  OS af6;
  af6.emplace(n, 'f');

  aa6 = string(n, 'a');
  ab6 = string(n, 'b');
  ac6 = string(n, 'c');
  ad6 = string(n, 'd');
  ae6 = string(n, 'e');
  af6 = string(n, 'f');

  OS aa7;
  OS ab7 = nullopt;
  OS ac7 = string(n, 'c');
  string sad7(n, 'd');
  OS ad7 = sad7;
  OS ae7(in_place, n, 'e');
  OS af7;
  af7.emplace(n, 'f');

  aa7.emplace(n, 'A');
  ab7.emplace(n, 'B');
  ac7.emplace(n, 'C');
  ad7.emplace(n, 'D');
  ae7.emplace(n, 'E');
  af7.emplace(n, 'F');
}

TEST(optionalTest, MoveAssignRegression) {
  StructorListener listener;
  Listenable::listener = &listener;

  {
    optional<Listenable> a;
    Listenable b;
    a = std::move(b);
  }

  EXPECT_EQ(1, listener.construct0);
  EXPECT_EQ(1, listener.move);
  EXPECT_EQ(2, listener.destruct);
}

TEST(optionalTest, ValueType) {
  EXPECT_TRUE((std::is_same<optional<int>::value_type, int>::value));
  EXPECT_TRUE((std::is_same<optional<string>::value_type, string>::value));
  EXPECT_FALSE((std::is_same<optional<int>::value_type, nullopt_t>::value));
}

TEST(optionalTest, Hash) {
  std::hash<optional<int>> hash;
  std::set<size_t> hashcodes;
  hashcodes.insert(hash(nullopt));
  for (int i = 0; i < 100; ++i) {
    hashcodes.insert(hash(i));
  }
  EXPECT_GT(hashcodes.size(), 90);
}

struct MoveMeNoThrow {
  MoveMeNoThrow() : x(0) {}
  MoveMeNoThrow(const MoveMeNoThrow& other) : x(other.x) {
    LOG(FATAL) << "Should not be called.";
  }
  MoveMeNoThrow(MoveMeNoThrow&& other) noexcept : x(other.x) {}
  int x;
};

struct MoveMeThrow {
  MoveMeThrow() : x(0) {}
  MoveMeThrow(const MoveMeThrow& other) : x(other.x) {}
  MoveMeThrow(MoveMeThrow&& other) : x(other.x) {}
  int x;
};

TEST(optionalTest, NoExcept) {
  static_assert(
      std::is_nothrow_move_constructible<optional<MoveMeNoThrow>>::value, "");
  static_assert(
      !std::is_nothrow_move_constructible<optional<MoveMeThrow>>::value, "");
  std::vector<optional<MoveMeNoThrow>> v;
  v.reserve(10);
  for (int i = 0; i < 10; ++i) v.emplace_back();
}

}  // namespace
}  // namespace tensorflow


text:
using System;
using System.Linq;

namespace Microsoft.WindowsAzure.Management.VirtualNetworks.Models
{
    public enum GatewayType
    {
        StaticRouting = 0,

        DynamicRouting = 1,
    }
}