text:
__author__ = 'Shinichi Nakagawa'

import time
import functools
import logging
from crontab import CronTab
from scheduler.job_settings import JobSettings

class JobController(object):
    """
    ジョブ実行Controller
    """

    @classmethod
    def run(cls, crontab):
        """
        処理実行
        :param crontab: job schedule
        """
        def receive_func(job):
            @functools.wraps(job)
            def wrapper():

                job_settings = JobSettings(CronTab(crontab))
                logging.info("->- Process Start")
                while True:
                    try:
                        logging.info(
                            "-?- next running\tschedule:%s" %
                            job_settings.schedule().strftime("%Y-%m-%d %H:%M:%S")
                        )
                        time.sleep(job_settings.interval())
                        logging.info("->- Job Start")
                        job()
                        logging.info("-<- Job Done")
                    except KeyboardInterrupt:
                        break
                logging.info("-<- Process Done.")
            return wrapper
        return receive_func

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<title></title>

			<wicket:extend>
				<form wicket:id="form">
					Select a Locale:
					<select wicket:id="changeLocale"></select>

					Select a Color:
					<select wicket:id="selectColor"></select>

						<input type="submit" value="submit">

				</form>
			</wicket:extend>


text:
@interface GFFetchedResultsController_Tests : XCTestCase

@end

@implementation GFFetchedResultsController_Tests {
	NSURL *_url;
	NSManagedObjectContext *_ctx;
}

- (void)setUp
{
	[super setUp];

	NSURL *modelURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"DemoModel" withExtension:@"momd"];
	NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

	NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: @YES,
							  NSInferMappingModelAutomaticallyOption: @YES};

	NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
	_url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]]];
	NSError *error;
	[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:_url options:options error:&error];

	_ctx = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
	_ctx.persistentStoreCoordinator = psc;

	for (NSUInteger i = 0; i < 20; ++i) {
		DemoObject *obj = [NSEntityDescription insertNewObjectForEntityForName:@"DemoObject" inManagedObjectContext:_ctx];
		obj.age = @(i);
	}

	NSError *saveError;
	XCTAssertTrue([_ctx save:&saveError]);
	XCTAssertNil(saveError, @"%@", saveError);
}

- (void)tearDown
{
	NSError *deleteError;
	[[NSFileManager defaultManager] removeItemAtURL:_url error:&deleteError];
	[super tearDown];
}

- (void)testBasicFetch
{
	NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"DemoObject"];
	GFFetchedResultsController *frc = [[GFFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_ctx];
	NSError *fetchError;
	XCTAssertTrue([frc performFetch:&fetchError]);
	XCTAssertNil(fetchError, @"%@", fetchError);
	XCTAssertEqual(frc.fetchedObjects.count, 20);
}

- (void)testBasicPredicateFetch
{
	NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"DemoObject"];
	fetchRequest.predicate = [NSPredicate predicateWithFormat:@"age < 10"];
	GFFetchedResultsController *frc = [[GFFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_ctx];
	NSError *fetchError;
	XCTAssertTrue([frc performFetch:&fetchError]);
	XCTAssertNil(fetchError, @"%@", fetchError);
	XCTAssertEqual(frc.fetchedObjects.count, 10);
}

@end


text:
package com.opengamma.strata.pricer.rate.future;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;

import com.opengamma.strata.finance.rate.future.IborFuture;
import com.opengamma.strata.market.sensitivity.IborRateSensitivity;
import com.opengamma.strata.market.sensitivity.PointSensitivities;
import com.opengamma.strata.market.value.IborIndexRates;
import com.opengamma.strata.pricer.rate.SimpleRatesProvider;

/**
 * Test {@link DiscountingIborFutureTradePricer}.
 */
@Test
public class DiscountingIborFutureProductPricerTest {

  private static final DiscountingIborFutureProductPricer PRICER = DiscountingIborFutureProductPricer.DEFAULT;
  private static final IborFuture FUTURE = IborFutureDummyData.IBOR_FUTURE;

  private static final double RATE = 0.045;
  private static final double TOLERANCE_PRICE = 1.0e-9;
  private static final double TOLERANCE_PRICE_DELTA = 1.0e-9;

  //-------------------------------------------------------------------------
  public void test_price() {
    IborIndexRates mockIbor = mock(IborIndexRates.class);
    SimpleRatesProvider prov = new SimpleRatesProvider();
    prov.setIborRates(mockIbor);
    when(mockIbor.rate(FUTURE.getFixingDate())).thenReturn(RATE);

    assertEquals(PRICER.price(FUTURE, prov), 1.0 - RATE, TOLERANCE_PRICE);
  }

  //-------------------------------------------------------------------------
  public void test_priceSensitivity() {
    IborIndexRates mockIbor = mock(IborIndexRates.class);
    SimpleRatesProvider prov = new SimpleRatesProvider();
    prov.setIborRates(mockIbor);

    PointSensitivities sensiExpected =
        PointSensitivities.of(IborRateSensitivity.of(FUTURE.getIndex(), FUTURE.getFixingDate(), -1.0d));
    PointSensitivities sensiComputed = PRICER.priceSensitivity(FUTURE, prov);
    assertTrue(sensiComputed.equalWithTolerance(sensiExpected, TOLERANCE_PRICE_DELTA));
  }

}


text:
Puppet module for configuring the 'supervisor' daemon control
utility. Currently tested on CentOS.

Requires supervisor to be packaged properly for CentOS, named
'python-supervisor' at my [fpm recipes](https://github.com/haf/fpm-recipes).

### Example usage

```puppet
  include supervisor

  supervisor::service {
    'scribe':
      ensure      => present,
      enable      => true,
      command     => '/usr/bin/scribed -c /etc/scribe/scribe.conf',
      environment => 'HADOOP_HOME=/usr/lib/hadoop,LD_LIBRARY_PATH=/usr/lib/jvm/java-6-sun/jre/lib/amd64/server',
      user        => 'scribe',
      group       => 'scribe',
      require     => [ Package['scribe'], User['scribe'] ];
  }
```


text:
using System;
using Xunit;
using Xunit.Abstractions;

namespace xUnitTest
{
    // http://xunit.github.io/docs/getting-started.html
    // If need helo to xunit in Visual Studio go to http://xunit.github.io/docs/running-tests-in-vs.html

    public class UnitTest_Util_BRL
    {
        private readonly ITestOutputHelper output;

        public UnitTest_Util_BRL(ITestOutputHelper output)
        {
            this.output = output;
        }

        [Fact]
        public void get_BtcBRLTicker()
        {
            var T = BitcoinLib.BRL.Util_BRL.getBtcBRLTicker();

            var j = Newtonsoft.Json.JsonConvert.SerializeObject(T);
            output.WriteLine(j.ToString());

            Assert.IsType(typeof(Info.Blockchain.API.ExchangeRates.Currency), T);
        }

        [Theory]
        [InlineData(1.2)]
        [InlineData(3.55)]
        [InlineData(10.58)]
        [InlineData(1000.239)]
        [InlineData(10123.998)]
        public void get_BRLtoBtc(double val)
        {
            var T = BitcoinLib.BRL.Util_BRL.getBRLtoBtc(val);
            output.WriteLine(T.ToString());
            Assert.IsType(typeof(double), T);
        }
    }

    public class UnitTest_Receive
    {
        private readonly ITestOutputHelper output;

        public UnitTest_Receive(ITestOutputHelper output)
        {
            this.output = output;
        }

        [Fact]
        public void Check_ReceivePayment()
        {
            string xAddress = "1NF5LNSbeWHzvaeGbnyPNsJtWeEZm62wix";
            try
            {
                var wr = BitcoinLib.BlockchainAPI.Receive.ReceiveFunds(xAddress, "");
                output.WriteLine($"Input: {wr.InputAddress} \r\n Destination: {wr.DestinationAddress} \r\n Fee: {wr.FeePercent} \r\n Call back URL: {wr.CallbackUrl}");

                Assert.True(wr != null);
            }
            catch (Exception e)
            {
                output.WriteLine($"ERROR: {e.Message}");
                Assert.True(false, e.Message);
            }
        }
    }

    public class UnitTest_BlockExplorer
    {
        private readonly ITestOutputHelper output;

        public UnitTest_BlockExplorer(ITestOutputHelper output)
        {
            this.output = output;
        }

        [Theory]
        [InlineData("97472e01b6c517382f83b0f3e26b4117bd02b7f009c406fc63d6af1a03e38bc0")]
        public void Check_Tx_Confirmation(string hash)
        {
            try
            {
                var Conf = BitcoinLib.Bitcoin.TxConfirmation(hash);

                output.WriteLine($"Confirmations: {Conf.Confirmation} \r\nDouble Spend: {Conf.DoubleSpend}");

                Assert.True(Conf != null && Conf.Confirmation > 0);
            }
            catch (Exception e)
            {
                output.WriteLine($"ERROR: {e.Message}");
                Assert.True(false, e.Message);
            }
        }
    }
}


text:
"""Create and edit manifest for session contents"""

import re

from duplicity import log
from duplicity import globals
from duplicity import util

class ManifestError(Exception):
    """
    Exception raised when problem with manifest
    """
    pass

class Manifest:
    """
    List of volumes and information about each one
    """
    def __init__(self, fh = None):
        """
        Create blank Manifest

        @param fh: fileobj for manifest
        @type fh: DupPath

        @rtype: Manifest
        @return: manifest
        """
        self.hostname = None
        self.local_dirname = None
        self.volume_info_dict = {} # dictionary vol numbers -> vol infos
        self.fh = fh

    def set_dirinfo(self):
        """
        Set information about directory from globals,
        and write to manifest file.

        @rtype: Manifest
        @return: manifest
        """
        self.hostname = globals.hostname
        self.local_dirname = globals.local_path.name #@UndefinedVariable
        if self.fh:
            if self.hostname:
                self.fh.write("Hostname %s\n" % self.hostname)
            if self.local_dirname:
                self.fh.write("Localdir %s\n" % Quote(self.local_dirname))
        return self

    def check_dirinfo(self):
        """
        Return None if dirinfo is the same, otherwise error message

        Does not raise an error message if hostname or local_dirname
        are not available.

        @rtype: string
        @return: None or error message
        """
        if globals.allow_source_mismatch:
            return

        if self.hostname and self.hostname != globals.hostname:
            errmsg = _("Fatal Error: Backup source host has changed.\n"
                       "Current hostname: %s\n"
                       "Previous hostname: %s") % (globals.hostname, self.hostname)
            code = log.ErrorCode.hostname_mismatch
            code_extra = "%s %s" % (util.escape(globals.hostname), util.escape(self.hostname))

        elif (self.local_dirname and self.local_dirname != globals.local_path.name): #@UndefinedVariable
            errmsg = _("Fatal Error: Backup source directory has changed.\n"
                       "Current directory: %s\n"
                       "Previous directory: %s") % (globals.local_path.name, self.local_dirname) #@UndefinedVariable
            code = log.ErrorCode.source_dir_mismatch
            code_extra = "%s %s" % (util.escape(globals.local_path.name), util.escape(self.local_dirname)) #@UndefinedVariable
        else:
            return

        log.FatalError(errmsg + "\n\n" +
                       _("Aborting because you may have accidentally tried to "
                         "backup two different data sets to the same remote "
                         "location, or using the same archive directory.  If "
                         "this is not a mistake, use the "
                         "--allow-source-mismatch switch to avoid seeing this "
                         "message"), code, code_extra)

    def add_volume_info(self, vi):
        """
        Add volume info vi to manifest and write to manifest

        @param vi: volume info to add
        @type vi: VolumeInfo

        @return: void
        """
        vol_num = vi.volume_number
        self.volume_info_dict[vol_num] = vi
        if self.fh:
            self.fh.write(vi.to_string() + "\n")

    def del_volume_info(self, vol_num):
        """
        Remove volume vol_num from the manifest

        @param vol_num: volume number to delete
        @type vi: int

        @return: void
        """
        try:
            del self.volume_info_dict[vol_num]
        except Exception:
            raise ManifestError("Volume %d not present in manifest" % (vol_num,))

    def to_string(self):
        """
        Return string version of self (just concatenate vi strings)

        @rtype: string
        @return: self in string form
        """
        result = ""
        if self.hostname:
            result += "Hostname %s\n" % self.hostname
        if self.local_dirname:
            result += "Localdir %s\n" % Quote(self.local_dirname)

        vol_num_list = self.volume_info_dict.keys()
        vol_num_list.sort()
        def vol_num_to_string(vol_num):
            return self.volume_info_dict[vol_num].to_string()
        result = "%s%s\n" % (result,
                             "\n".join(map(vol_num_to_string, vol_num_list)))
        return result

    __str__ = to_string

    def from_string(self, s):
        """
        Initialize self from string s, return self
        """
        def get_field(fieldname):
            """
            Return the value of a field by parsing s, or None if no field
            """
            m = re.search("(^|\\n)%s\\s(.*?)\n" % fieldname, s, re.I)
            if not m:
                return None
            else:
                return Unquote(m.group(2))
        self.hostname = get_field("hostname")
        self.local_dirname = get_field("localdir")

        next_vi_string_regexp = re.compile("(^|\\n)(volume\\s.*?)"
                                           "(\\nvolume\\s|$)", re.I | re.S)
        starting_s_index = 0
        highest_vol = 0
        latest_vol = 0
        while 1:
            match = next_vi_string_regexp.search(s[starting_s_index:])
            if not match:
                break
            vi = VolumeInfo().from_string(match.group(2))
            self.add_volume_info(vi)
            highest_vol = max(highest_vol, vi.volume_number)
            latest_vol = vi.volume_number
            starting_s_index += match.end(2)
        # If we restarted after losing some remote volumes, the highest volume
        # seen may be higher than the last volume recorded.  That is, the
        # manifest could contain "vol1, vol2, vol3, vol2."  If so, we don't
        # want to keep vol3's info.
        for i in range(latest_vol + 1, highest_vol + 1):
            self.del_volume_info(i)
        return self

    def __eq__(self, other):
        """
        Two manifests are equal if they contain the same volume infos
        """
        vi_list1 = self.volume_info_dict.keys()
        vi_list1.sort()
        vi_list2 = other.volume_info_dict.keys()
        vi_list2.sort()

        if vi_list1 != vi_list2:
            log.Notice(_("Manifests not equal because different volume numbers"))
            return False

        for i in range(len(vi_list1)):
            if not vi_list1[i] == vi_list2[i]:
                log.Notice(_("Manifests not equal because volume lists differ"))
                return False

        if (self.hostname != other.hostname or
            self.local_dirname != other.local_dirname):
            log.Notice(_("Manifests not equal because hosts or directories differ"))
            return False

        return True

    def __ne__(self, other):
        """
        Defines !=.  Not doing this always leads to annoying bugs...
        """
        return not self.__eq__(other)

    def write_to_path(self, path):
        """
        Write string version of manifest to given path
        """
        assert not path.exists()
        fout = path.open("wb")
        fout.write(self.to_string())
        assert not fout.close()
        path.setdata()

    def get_containing_volumes(self, index_prefix):
        """
        Return list of volume numbers that may contain index_prefix
        """
        return filter(lambda vol_num:
                      self.volume_info_dict[vol_num].contains(index_prefix),
                      self.volume_info_dict.keys())

class VolumeInfoError(Exception):
    """
    Raised when there is a problem initializing a VolumeInfo from string
    """
    pass

class VolumeInfo:
    """
    Information about a single volume
    """
    def __init__(self):
        """VolumeInfo initializer"""
        self.volume_number = None
        self.start_index = None
        self.start_block = None
        self.end_index = None
        self.end_block = None
        self.hashes = {}

    def set_info(self, vol_number,
                 start_index, start_block,
                 end_index, end_block):
        """
        Set essential VolumeInfo information, return self

        Call with starting and ending paths stored in the volume.  If
        a multivol diff gets split between volumes, count it as being
        part of both volumes.
        """
        self.volume_number = vol_number
        self.start_index = start_index
        self.start_block = start_block
        self.end_index = end_index
        self.end_block = end_block

        return self

    def set_hash(self, hash_name, data):
        """
        Set the value of hash hash_name (e.g. "MD5") to data
        """
        self.hashes[hash_name] = data

    def get_best_hash(self):
        """
        Return pair (hash_type, hash_data)

        SHA1 is the best hash, and MD5 is the second best hash.  None
        is returned if no hash is available.
        """
        if not self.hashes:
            return None
        try:
            return ("SHA1", self.hashes['SHA1'])
        except KeyError:
            pass
        try:
            return ("MD5", self.hashes['MD5'])
        except KeyError:
            pass
        return self.hashes.items()[0]

    def to_string(self):
        """
        Return nicely formatted string reporting all information
        """
        def index_to_string(index):
            """Return printable version of index without any whitespace"""
            if index:
                s = "/".join(index)
                return Quote(s)
            else:
                return "."

        slist = ["Volume %d:" % self.volume_number]
        whitespace = "    "
        slist.append("%sStartingPath   %s %s" %
                     (whitespace, index_to_string(self.start_index), (self.start_block or " ")))
        slist.append("%sEndingPath     %s %s" %
                     (whitespace, index_to_string(self.end_index), (self.end_block or " ")))
        for key in self.hashes:
            slist.append("%sHash %s %s" %
                         (whitespace, key, self.hashes[key]))
        return "\n".join(slist)

    __str__ = to_string

    def from_string(self, s):
        """
        Initialize self from string s as created by to_string
        """
        def string_to_index(s):
            """
            Return tuple index from string
            """
            s = Unquote(s)
            if s == ".":
                return ()
            return tuple(s.split("/"))

        linelist = s.strip().split("\n")

        # Set volume number
        m = re.search("^Volume ([0-9]+):", linelist[0], re.I)
        if not m:
            raise VolumeInfoError("Bad first line '%s'" % (linelist[0],))
        self.volume_number = int(m.group(1))

        # Set other fields
        for line in linelist[1:]:
            if not line:
                continue
            line_split = line.strip().split()
            field_name = line_split[0].lower()
            other_fields = line_split[1:]
            if field_name == "Volume":
                log.Warn(_("Warning, found extra Volume identifier"))
                break
            elif field_name == "startingpath":
                self.start_index = string_to_index(other_fields[0])
                if len(other_fields) > 1:
                    self.start_block = int(other_fields[1])
                else:
                    self.start_block = None
            elif field_name == "endingpath":
                self.end_index = string_to_index(other_fields[0])
                if len(other_fields) > 1:
                    self.end_block = int(other_fields[1])
                else:
                    self.end_block = None
            elif field_name == "hash":
                self.set_hash(other_fields[0], other_fields[1])

        if self.start_index is None or self.end_index is None:
            raise VolumeInfoError("Start or end index not set")
        return self

    def __eq__(self, other):
        """
        Used in test suite
        """
        if not isinstance(other, VolumeInfo):
            log.Notice(_("Other is not VolumeInfo"))
            return None
        if self.volume_number != other.volume_number:
            log.Notice(_("Volume numbers don't match"))
            return None
        if self.start_index != other.start_index:
            log.Notice(_("start_indicies don't match"))
            return None
        if self.end_index != other.end_index:
            log.Notice(_("end_index don't match"))
            return None
        hash_list1 = self.hashes.items()
        hash_list1.sort()
        hash_list2 = other.hashes.items()
        hash_list2.sort()
        if hash_list1 != hash_list2:
            log.Notice(_("Hashes don't match"))
            return None
        return 1

    def __ne__(self, other):
        """
        Defines !=
        """
        return not self.__eq__(other)

    def contains(self, index_prefix, recursive = 1):
        """
        Return true if volume might contain index

        If recursive is true, then return true if any index starting
        with index_prefix could be contained.  Otherwise, just check
        if index_prefix itself is between starting and ending
        indicies.
        """
        if recursive:
            return (self.start_index[:len(index_prefix)] <=
                    index_prefix <= self.end_index)
        else:
            return self.start_index <= index_prefix <= self.end_index

nonnormal_char_re = re.compile("(\\s|[\\\\\"'])")
def Quote(s):
    """
    Return quoted version of s safe to put in a manifest or volume info
    """
    if not nonnormal_char_re.search(s):
        return s # no quoting necessary
    slist = []
    for char in s:
        if nonnormal_char_re.search(char):
            slist.append("\\x%02x" % ord(char))
        else:
            slist.append(char)
    return '"%s"' % "".join(slist)

def Unquote(quoted_string):
    """
    Return original string from quoted_string produced by above
    """
    if not quoted_string[0] == '"' or quoted_string[0] == "'":
        return quoted_string
    assert quoted_string[0] == quoted_string[-1]
    return_list = []
    i = 1 # skip initial char
    while i < len(quoted_string)-1:
        char = quoted_string[i]
        if char == "\\":
            # quoted section
            assert quoted_string[i+1] == "x"
            return_list.append(chr(int(quoted_string[i+2:i+4], 16)))
            i += 4
        else:
            return_list.append(char)
            i += 1
    return "".join(return_list)


text:
// <copyright file="ResponseWriter.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved.
//
// 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.
// </copyright>

using System.IO;
using System.Text;
using Microsoft.AspNet.Razor.Owin.Execution;

namespace Microsoft.AspNet.Razor.Owin
{
    public class ResponseWriter : TextWriter
    {
        public ResponseWriter(IRazorResponse response)
        {
            Response = response;
        }

        public IRazorResponse Response { get; private set; }

        public override Encoding Encoding
        {
            get { return Response.Encoding; }
        }

        public override void Write(string value)
        {
            base.Write(value);
        }

        public override void Write(char[] buffer, int index, int count)
        {
            byte[] bytes = Encoding.GetBytes(buffer, index, count);
            Response.Body.Write(bytes, 0, bytes.Length);
        }
    }
}


text:
package org.apache.ibatis.migration.operations;

import java.io.PrintStream;
import java.io.Reader;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.migration.Change;
import org.apache.ibatis.migration.ConnectionProvider;
import org.apache.ibatis.migration.MigrationException;
import org.apache.ibatis.migration.MigrationLoader;
import org.apache.ibatis.migration.hook.HookContext;
import org.apache.ibatis.migration.hook.MigrationHook;
import org.apache.ibatis.migration.options.DatabaseOperationOption;
import org.apache.ibatis.migration.utils.Util;

public final class PendingOperation extends DatabaseOperation {

  public PendingOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader,
      DatabaseOperationOption option, PrintStream printStream) {
    return operate(connectionProvider, migrationsLoader, option, printStream, null);
  }

  public PendingOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader,
      DatabaseOperationOption option, PrintStream printStream, MigrationHook hook) {
    try (Connection con = connectionProvider.getConnection()) {
      if (option == null) {
        option = new DatabaseOperationOption();
      }
      if (!changelogExists(con, option)) {
        throw new MigrationException("Change log doesn't exist, no migrations applied.  Try running 'up' instead.");
      }
      List<Change> pending = getPendingChanges(con, migrationsLoader, option);
      int stepCount = 0;
      Map<String, Object> hookBindings = new HashMap<String, Object>();
      println(printStream, "WARNING: Running pending migrations out of order can create unexpected results.");
      Reader scriptReader = null;
      try {
        ScriptRunner runner = getScriptRunner(con, option, printStream);
        for (Change change : pending) {
          if (stepCount == 0 && hook != null) {
            hookBindings.put(MigrationHook.HOOK_CONTEXT, new HookContext(connectionProvider, runner, null));
            hook.before(hookBindings);
          }
          if (hook != null) {
            hookBindings.put(MigrationHook.HOOK_CONTEXT, new HookContext(connectionProvider, runner, change.clone()));
            hook.beforeEach(hookBindings);
          }
          println(printStream, Util.horizontalLine("Applying: " + change.getFilename(), 80));
          scriptReader = migrationsLoader.getScriptReader(change, false);
          runner.runScript(scriptReader);
          insertChangelog(change, con, option);
          println(printStream);
          if (hook != null) {
            hookBindings.put(MigrationHook.HOOK_CONTEXT, new HookContext(connectionProvider, runner, change.clone()));
            hook.afterEach(hookBindings);
          }
          stepCount++;
        }
        if (stepCount > 0 && hook != null) {
          hookBindings.put(MigrationHook.HOOK_CONTEXT, new HookContext(connectionProvider, runner, null));
          hook.after(hookBindings);
        }
        return this;
      } catch (Exception e) {
        throw new MigrationException("Error executing command.  Cause: " + e, e);
      } finally {
        if (scriptReader != null) {
          scriptReader.close();
        }
      }
    } catch (Throwable e) {
      while (e instanceof MigrationException && e.getCause() != null) {
        e = e.getCause();
      }
      throw new MigrationException("Error executing command.  Cause: " + e, e);
    }
  }

  private List<Change> getPendingChanges(Connection con, MigrationLoader migrationsLoader,
      DatabaseOperationOption option) {
    List<Change> pending = new ArrayList<Change>();
    List<Change> migrations = migrationsLoader.getMigrations();
    List<Change> changelog = getChangelog(con, option);
    for (Change change : migrations) {
      int index = changelog.indexOf(change);
      if (index < 0) {
        pending.add(change);
      }
    }
    Collections.sort(pending);
    return pending;
  }
}


text:
<?php

namespace Elton\TeacherBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;
use Elton\PaymentBundle\Form\SubscriptionFormType;

class FlyerFormType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('civilite', 'choice', array('label' => 'Civilité', "attr" => array("class" => "form-control"), 'choices' => array("M." => 'M.', "Mme." => 'Mme.')))
            ->add('name', 'text', array('label' => 'Nom', 'attr' => array('placeholder' => 'Entrez le nom que vos élèves verront')))
            ->add('firstName', 'text', array('label' => 'Prénom', 'attr' => array('placeholder' => 'Entrez votre prénom')))
            ->add('postalCode', 'text', array('label' => 'Code postal', 'attr' => array('placeholder' => 'Entrez le code postal de votre école')))
            ->add('email', 'email', array('label' => 'Adresse email', 'attr'=> array('placeholder' => 'Entrez votre adresse email')))
            ->add('school', 'text', array('label' => 'École', 'attr' => array('placeholder' => 'Entrez le nom de votre école')))
            ->add('address', 'text', array('label' => 'Adresse', 'attr' => array('placeholder' => 'Entrez l\'adresse de votre école')))
            ->add('town', 'text', array('label' => 'Ville', 'attr' => array('placeholder' => 'Entrez la ville de votre école')))
            ->add('subscriptions', new SubscriptionFormType())
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Elton\TeacherBundle\Entity\Flyer'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'elton_flyer_registration';
    }
}


text:
more text here even more text here

SYNOPSIS


text:
Travis.ServiceHook = Travis.Record.extend({
  primaryKey: 'uid',

  toggle: function() {
    this.writeAttribute('active', !this.get('active'));
    this.commitRecord({ owner: this.get('owner'), name: this.get('name') });
  },
});

Travis.ServiceHook.reopenClass({
  resource: 'profile/service_hooks'
});


text:
:- module(swish_render_ide,
	  [ term_rendering//3			% +Term, +Vars, +Options
	  ]).
:- use_module(library(option)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/http_json)).
:- use_module(library(http/html_write)).
:- use_module('../render').
:- use_module(library(prolog_code)).

:- register_renderer(ide, "IDE rendering support").

:- http_handler(swish(ide/edit), ide_edit, [id(ide_edit)]).

%!  term_rendering(+Predicate, +Vars, +Options)//
%
%   Renders a predicate indicator.

term_rendering(PI, _Vars, _Options) -->
    { is_predicate_indicator(PI),
      predicate_title(PI, Title),
      pi_link(PI, Attrs)
    },
    html(a([ 'data-render'('Predicate indicator'),
             class('render-predicate-indicator'),
             title(Title)
           | Attrs
           ],
           '~q'-PI)).

predicate_title(PI, Title) :-
    pi_head(PI, Head),
    findall(Line, title_line(user:Head, Line), Lines),
    atomics_to_string(Lines, "\n", Title).

title_line(Head, Title) :-
    predicate_property(Head, tabled),
    (   conj_of_properties(Head, [monotonic,incremental], Conj)
    ->  format(string(Title), 'Tabled as (~q)', [Conj])
    ;   Title = 'Tabled'
    ).
title_line(Head, Title) :-
    predicate_property(Head, dynamic),
    (   conj_of_properties(Head, [monotonic,incremental], Conj)
    ->  format(string(Title), 'Dynamic as (~q)', [Conj])
    ;   Title = 'Dynamic'
    ).
title_line(Head, Title) :-
    predicate_property(Head, file(File)),
    predicate_property(Head, line_count(Line)),
    format(string(Title), 'Defined at ~w:~d', [File, Line]).

conj_of_properties(Head, Candidates, Conj) :-
    findall(P, (predicate_property(Head, P), memberchk(P, Candidates)), Ps),
    comma_list(Conj, Ps).

%!  pi_link(+PI, -HTMLAttributes) is det.
%
%   Create a link for PI. Currently creates  an edit link for predicates
%   with a source.

pi_link(PI, [onClick("$.get('~w')"-[HREF])]) :-
    pi_head(PI, Head),
    predicate_property(user:Head, file(_)),
    predicate_property(user:Head, line_count(_)),
    !,
    format(string(PIs), '~q', [PI]),
    http_link_to_id(ide_edit, [pi(PIs)], HREF).
pi_link(_, []).

%!  ide_edit(+Request)
%
%   HTTP handler to edit a predicate

ide_edit(Request) :-
    http_parameters(Request,
                    [ pi(PIs, [])
                    ]),
    term_string(PI, PIs),
    edit(PI),
    reply_json_dict(true).


text:
require 'monkeypatch/spec_helper'

describe 'DescriptiveStatistics' do
  require 'descriptive_statistics'

  subject { Set.new([2, 6, 9, 3, 5, 1, 8, 3, 6, 9, 2]) }

  context 'with a set' do
    it 'responds to all statistics methods' do
      DescriptiveStatistics.instance_methods.each do |method|
        expect(subject).respond_to? method
      end
    end

    it 'calculates the number' do
      expect(subject.number).to eql(7.0)
    end

    it 'calculates the sum' do
      expect(subject.sum).to eql(34.0)
    end

    it 'calculates the mean' do
      expect(subject.mean).to eql(4.857142857142857)
    end

    it 'calculates the median' do
      expect(subject.median).to eql(5.0)
    end

    it 'calculates the variance' do
      expect(subject.variance).to eql(7.836734693877552)
    end

    it 'calculates the standard_deviation' do
      expect(subject.standard_deviation).to eql(2.799416848895061)
    end

    it 'calculates the percentile' do
      expect(subject.percentile(30)).to eql(2.8)
      expect(subject.percentile(50)).to eql(5.0)
      expect(subject.percentile(70)).to eql(6.399999999999999)
    end

    it 'calculates the same value for the 50th percentile and median' do
      expect(subject.percentile(50)).to eql(subject.median)
    end

    it 'calculates the mode' do
      expect(subject.mode).to eql(2)
    end

    it 'calculates the range' do
      expect(subject.range).to eql(8.0)
    end

    it 'calculates the percentile rank' do
      expect(subject.percentile_rank(8)).to eql(85.71428571428571)
    end
  end
end


text:
package com.google.javascript.jscomp;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.javascript.jscomp.ClosurePrimitiveErrors.INVALID_CLOSURE_CALL_SCOPE_ERROR;
import static com.google.javascript.jscomp.ClosurePrimitiveErrors.INVALID_GET_NAMESPACE;
import static com.google.javascript.jscomp.ClosurePrimitiveErrors.MISSING_MODULE_OR_PROVIDE;
import static com.google.javascript.jscomp.ClosurePrimitiveErrors.MODULE_USES_GOOG_MODULE_GET;
import static com.google.javascript.jscomp.Es6RewriteModules.FORWARD_DECLARE_FOR_ES6_SHOULD_BE_CONST;
import static com.google.javascript.jscomp.Es6RewriteModules.LHS_OF_GOOG_REQUIRE_MUST_BE_CONST;
import static com.google.javascript.jscomp.Es6RewriteModules.REQUIRE_TYPE_FOR_ES6_SHOULD_BE_CONST;
import static com.google.javascript.jscomp.RhinoErrorReporter.UNRECOGNIZED_TYPE_ERROR;
import static com.google.javascript.jscomp.TypeCheck.INEXISTENT_PROPERTY;
import static com.google.javascript.jscomp.TypeCheck.POSSIBLE_INEXISTENT_PROPERTY;
import static com.google.javascript.jscomp.modules.EsModuleProcessor.NAMESPACE_IMPORT_CANNOT_USE_STAR;
import static com.google.javascript.jscomp.modules.ModuleMapCreator.MISSING_NAMESPACE_IMPORT;

import com.google.javascript.jscomp.testing.TestExternsBuilder;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link Es6RewriteModules} that test interop with closure files. */
@RunWith(JUnit4.class)
public final class Es6RewriteModulesWithGoogInteropTest extends CompilerTestCase {
  private static final SourceFile CLOSURE_BASE =
      SourceFile.fromCode("closure_base.js", new TestExternsBuilder().addClosureExterns().build());

  private static final SourceFile CLOSURE_PROVIDE =
      SourceFile.fromCode(
          "closure_provide.js",
          lines(
              "goog.provide('closure.provide'); closure.provide = class {};",
              "closure.provide.Type = class {};",
              "closure.provide.a = class {};",
              "closure.provide.a.d = class {};",
              "closure.provide.b = class {};"));

  private static final SourceFile CLOSURE_MODULE =
      SourceFile.fromCode(
          "closure_module.js",
          lines(
              "goog.module('closure.module');",
              "exports = class {};",
              "exports.x = class {};",
              "exports.y = class {};"));

  private static final SourceFile CLOSURE_MODULE_DESTRUCTURE =
      SourceFile.fromCode(
          "closure_destructured_module.js",
          lines(
              "goog.module('closure.destructured.module');",
              "exports.Bar = 0;",
              "exports.y = 0;",
              "exports.b = class {};",
              "exports.a = class {};",
              "exports.a.d = class {};"));

  private static final SourceFile CLOSURE_LEGACY_MODULE =
      SourceFile.fromCode(
          "closure_legacy_destructured_module.js",
          lines(
              "goog.module('closure.legacy.module');",
              "goog.module.declareLegacyNamespace();",
              "exports = class {};",
              "exports.x = class {};",
              "exports.y = class {};"));

  private static final SourceFile CLOSURE_LEGACY_DESTRUCTURED_MODULE =
      SourceFile.fromCode(
          "closure_legacy_module.js",
          lines(
              "goog.module('closure.legacy.destructured.module');",
              "goog.module.declareLegacyNamespace();",
              "exports.Bar = 0;",
              "exports.y = 0;",
              "exports.b = class {};",
              "exports.a = class {};",
              " exports.a.d = class {};"));

  private boolean runTypeChecker = true;

  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    // ECMASCRIPT5 to trigger module processing after parsing.
    enableTypeInfoValidation();
    enableCreateModuleMap();
  }

  @Override
  protected CompilerOptions getOptions() {
    CompilerOptions options = super.getOptions();
    // ECMASCRIPT5 to Trigger module processing after parsing.
    options.setWarningLevel(DiagnosticGroups.LINT_CHECKS, CheckLevel.ERROR);

    return options;
  }

  @Override
  protected CompilerPass getProcessor(Compiler compiler) {
    return (externs, root) -> {
      final TypedScope globalTypedScope;
      if (runTypeChecker) {
        ReverseAbstractInterpreter rai =
            new SemanticReverseAbstractInterpreter(compiler.getTypeRegistry());
        globalTypedScope =
            checkNotNull(
                new TypeCheck(compiler, rai, compiler.getTypeRegistry())
                    .processForTesting(externs, root));
        compiler.setTypeCheckingHasRun(true);
      } else {
        globalTypedScope = null;
      }

      new Es6RewriteModules(
              compiler,
              compiler.getModuleMetadataMap(),
              compiler.getModuleMap(),
              /* preprocessorSymbolTable= */ null,
              globalTypedScope)
          .process(externs, root);
    };
  }

  void testModules(String input, String expected) {
    test(
        srcs(
            SourceFile.fromCode(
                "closure_base.js", new TestExternsBuilder().addClosureExterns().build()),
            CLOSURE_PROVIDE,
            CLOSURE_MODULE,
            CLOSURE_MODULE_DESTRUCTURE,
            CLOSURE_LEGACY_MODULE,
            CLOSURE_LEGACY_DESTRUCTURED_MODULE,
            SourceFile.fromCode("testcode", input)),
        expected(
            SourceFile.fromCode(
                "closure_base.js", new TestExternsBuilder().addClosureExterns().build()),
            CLOSURE_PROVIDE,
            CLOSURE_MODULE,
            CLOSURE_MODULE_DESTRUCTURE,
            CLOSURE_LEGACY_MODULE,
            CLOSURE_LEGACY_DESTRUCTURED_MODULE,
            SourceFile.fromCode("testcode", expected)));
  }

  void testModulesError(String input, DiagnosticType error) {
    testError(
        srcs(
            CLOSURE_PROVIDE,
            CLOSURE_MODULE,
            CLOSURE_LEGACY_MODULE,
            SourceFile.fromCode("testcode", input)),
        error(error));
  }

  @Test
  public void testClosureFilesUnchanged() {
    testSame(srcs(CLOSURE_BASE, CLOSURE_PROVIDE, CLOSURE_MODULE, CLOSURE_LEGACY_MODULE));
  }

  @Test
  public void testGoogRequireInNonEs6ModuleUnchanged() {
    testSame(
        srcs(new TestExternsBuilder().addClosureExterns().build(), "goog.require('foo.bar');"));
    testSame(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            "var bar = goog.require('foo.bar');"));
  }

  @Test
  public void testGoogRequireTypeInNonEs6ModuleUnchanged() {
    testSame(
        srcs(new TestExternsBuilder().addClosureExterns().build(), "goog.requireType('foo.bar');"));
    testSame(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            "var bar = goog.requireType('foo.bar');"));
  }

  @Test
  public void testForwardDeclareInNonEs6ModuleUnchanged() {
    testSame(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            "goog.forwardDeclare('foo.bar');"));
    testSame(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            "var bar = goog.forwardDeclare('foo.bar');"));
  }

  @Test
  public void testGoogRequireInEs6ModuleDoesNotExistIsError() {
    testError(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            "export var x; goog.require('foo.bar');"),
        error(MISSING_MODULE_OR_PROVIDE));
  }

  @Test
  public void testGoogRequireTypeInEs6ModuleDoesNotExistIsError() {
    testError(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            "export var x; goog.requireType('foo.bar');"),
        error(MISSING_MODULE_OR_PROVIDE));
  }

  // TODO(tjgq): Add tests for require, requireType and forwardDeclare with an invalid namespace.
  // They currently produce a DEPS_PARSE_ERROR in JsFileLineParser.

  @Test
  public void testGoogModuleGetNonStringIsError() {
    testError(lines("const y = goog.module.get();", "export {};"), INVALID_GET_NAMESPACE);
    testError(lines("const y = goog.module.get(0);", "export {};"), INVALID_GET_NAMESPACE);
  }

  @Test
  public void testGoogRequireForProvide() {
    testModules(
        lines("const y = goog.require('closure.provide');", "use(y, y.Type)", "export {};"),
        lines(
            "use(closure.provide, closure.provide.Type);",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireTypeForProvide() {
    testModules(
        lines(
            "const y = goog.requireType('closure.provide');",
            "/**",
            " * @param {y} a",
            " * @param {y.Type} b",
            "*/",
            "function f(a, b) {}",
            "export {};"),
        lines(
            "/**",
            " * @param {closure.provide} a",
            " * @param {closure.provide.Type} b",
            " */",
            "function f$$module$testcode(a, b) {}",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireForProvideWithDestructure() {
    testModules(
        lines("const {a, b:c} = goog.require('closure.provide');", "use(a, a.d, c)", "export {};"),
        lines(
            "use(closure.provide.a, closure.provide.a.d, closure.provide.b);",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireTypeForProvideWithDestructure() {
    testModules(
        lines(
            "const {a, b:c} = goog.requireType('closure.provide');",
            "/**",
            " * @param {a} x",
            " * @param {a.d} y",
            " * @param {c} z",
            "*/",
            "function f(x, y, z) {}",
            "export {};"),
        lines(
            "/**",
            " * @param {closure.provide.a} x",
            " * @param {closure.provide.a.d} y",
            " * @param {closure.provide.b} z",
            " */",
            "function f$$module$testcode(x, y, z) {}",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireForGoogModule() {
    ignoreWarnings(INEXISTENT_PROPERTY);
    testModules(
        lines("const y = goog.require('closure.module');", "use(y, y.x)", "export {};"),
        lines(
            "use(module$exports$closure$module, module$exports$closure$module.x);",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireTypeForGoogModule() {
    ignoreWarnings(UNRECOGNIZED_TYPE_ERROR);
    testModules(
        lines(
            "const y = goog.requireType('closure.module');",
            "/**",
            " * @param {y} a",
            " * @param {y.x} b",
            "*/",
            "function f(a, b) {}",
            "export {};"),
        lines(
            "/**",
            " * @param {module$exports$closure$module} a",
            " * @param {module$exports$closure$module.x} b",
            " */",
            "function f$$module$testcode(a, b) {}",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireForGoogModuleWithDestructure() {
    testModules(
        lines(
            "const {a, b:c} = goog.require('closure.destructured.module');",
            "use(a, a.d, c)",
            "export {};"),
        lines(
            "use(module$exports$closure$destructured$module.a,"
                + " module$exports$closure$destructured$module.a.d,",
            "  module$exports$closure$destructured$module.b);",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireTypeForGoogModuleWithDestructure() {
    testModules(
        lines(
            "const {a, b:c} = goog.requireType('closure.destructured.module');",
            "/**",
            " * @param {a} x",
            " * @param {a.d} y",
            " * @param {c} z",
            "*/",
            "function f(x, y, z) {}",
            "export {};"),
        lines(
            "/**",
            " * @param {module$exports$closure$destructured$module.a} x",
            " * @param {module$exports$closure$destructured$module.a.d} y",
            " * @param {module$exports$closure$destructured$module.b} z",
            " */",
            "function f$$module$testcode(x, y, z) {}",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireForLegacyGoogModule() {
    testModules(
        lines("const y = goog.require('closure.legacy.module');", "use(y, y.x)", "export {};"),
        lines(
            "use(closure.legacy.module, closure.legacy.module.x);",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireTypeForLegacyGoogModule() {
    testModules(
        lines(
            "const y = goog.requireType('closure.legacy.module');",
            "/**",
            " * @param {y} a",
            " * @param {y.x} b",
            "*/",
            "function f(a, b) {}",
            "export {};"),
        lines(
            "/**",
            " * @param {closure.legacy.module} a",
            " * @param {closure.legacy.module.x} b",
            " */",
            "function f$$module$testcode(a, b) {}",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireForLegacyGoogModuleWithDestructure() {
    testModules(
        lines(
            "const {a, b:c} = goog.require('closure.legacy.destructured.module');",
            "use(a, a.d, c)",
            "export {};"),
        lines(
            "use(closure.legacy.destructured.module.a, closure.legacy.destructured.module.a.d,"
                + " closure.legacy.destructured.module.b);",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogRequireTypeForLegacyGoogModuleWithDestructure() {
    testModules(
        lines(
            "const {a, b:c} = goog.requireType('closure.legacy.destructured.module');",
            "/**",
            " * @param {a} x",
            " * @param {a.d} y",
            " * @param {c} z",
            "*/",
            "function f(x, y, z) {}",
            "export {};"),
        lines(
            "/**",
            " * @param {closure.legacy.destructured.module.a} x",
            " * @param {closure.legacy.destructured.module.a.d} y",
            " * @param {closure.legacy.destructured.module.b} z",
            " */",
            "function f$$module$testcode(x, y, z) {}",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogModuleGetForGoogModule() {
    testModules(
        lines("function foo() { const y = goog.module.get('closure.module'); } export {};"),
        lines(
            "function foo$$module$testcode() { const y = module$exports$closure$module; }",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogModuleGetForLegacyGoogModule() {
    testModules(
        "function foo(){ const y = goog.module.get('closure.legacy.module'); }\nexport {};",
        lines(
            "function foo$$module$testcode(){ const y = closure.legacy.module; }",
            "/** @const */ var module$testcode = {};"));
  }

  @Test
  public void testGoogModuleGetForEs6Module() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export {}; goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "closure.js",
                "goog.module('my.module'); function f() { const y = goog.module.get('es6'); }")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "/** @const */ var module$es6 = {};"),
            SourceFile.fromCode(
                "closure.js", "goog.module('my.module'); function f() { const y = module$es6; }")));
  }

  @Test
  public void testGoogModuleGetForEs6ModuleDeclaresNamespace() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export let y; goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "closure.js",
                "goog.module('my.module'); function f() { return goog.module.get('es6').y; }")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "let y$$module$es6;",
                    "/** @const */ var module$es6 = {};",
                    "/** @const */ module$es6.y = y$$module$es6;")),
            SourceFile.fromCode(
                "closure.js", "goog.module('my.module'); function f() { return module$es6.y; }")));
  }

  @Test
  public void testDeclareModuleId() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export var x; goog.declareModuleId('my.es6');"),
            SourceFile.fromCode("goog.js", "const es6 = goog.require('my.es6'); use(es6, es6.x);")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "var x$$module$es6;/** @const */ var module$es6={};",
                    "/** @const */ module$es6.x=x$$module$es6;")),
            SourceFile.fromCode("goog.js", "const es6 = module$es6; use(es6, es6.x);")));
  }

  @Test
  public void testGoogRequireForDeclareModuleId() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export var x; goog.declareModuleId('my.es6');"),
            SourceFile.fromCode("goog.js", "const es6 = goog.require('my.es6'); use(es6, es6.x);")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "var x$$module$es6;/** @const */ var module$es6={};",
                    "/** @const */ module$es6.x=x$$module$es6;")),
            SourceFile.fromCode("goog.js", "const es6 = module$es6; use(es6, es6.x);")));
  }

  @Test
  public void testGoogRequireTypeForDeclareModuleId() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export class x {}; goog.declareModuleId('my.es6');"),
            SourceFile.fromCode(
                "goog.js",
                lines(
                    "goog.module('bar')",
                    "const es6 = goog.requireType('my.es6');",
                    "/** @param {es6.x} a */",
                    "function f(a) {}"))),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "class x$$module$es6 {}",
                    "/** @const */ var module$es6={};",
                    "/** @const */ module$es6.x = x$$module$es6;")),
            SourceFile.fromCode(
                "goog.js",
                lines(
                    "goog.module('bar')",
                    "/**",
                    " * @param {module$es6.x} a",
                    " */",
                    "function f(a) {}"))));
  }

  @Test
  public void testGoogRequireTypeForDeclareModuleId_lateLoaded() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "goog.js",
                lines(
                    "goog.module('bar')",
                    "const es6 = goog.requireType('my.es6');",
                    "/** @param {es6.x} a */",
                    "function f(a) {}")),
            SourceFile.fromCode("es6.js", "export class x {}; goog.declareModuleId('my.es6');")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "goog.js",
                lines(
                    "goog.module('bar')",
                    "/**",
                    " * @param {module$es6.x} a",
                    " */",
                    "function f(a) {}")),
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "class x$$module$es6 {}",
                    "/** @const */ var module$es6={};",
                    "/** @const */ module$es6.x = x$$module$es6;"))));
  }

  @Test
  public void testGoogRequireForDeclareModuleIdWithDestructure() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export var x, z; goog.declareModuleId('my.es6');"),
            SourceFile.fromCode("goog.js", "const {x, z: y} = goog.require('my.es6'); use(x, y);")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "var x$$module$es6, z$$module$es6;",
                    "/** @const */ var module$es6={};",
                    "/** @const */ module$es6.x=x$$module$es6;",
                    "/** @const */ module$es6.z=z$$module$es6;")),
            SourceFile.fromCode(
                "goog.js",
                lines("const x = module$es6.x;", "const y = module$es6.z;", "use(x, y);"))));
  }

  @Test
  public void testGoogRequireTypeForDeclareModuleIdWithDestructure() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js", "export class x {} export class z {} goog.declareModuleId('my.es6');"),
            SourceFile.fromCode(
                "goog.js",
                lines(
                    "const {x, z: y} = goog.requireType('my.es6');",
                    "/**",
                    " * @param {x} a",
                    " * @param {y} b",
                    " */",
                    "function f(a, b) {}"))),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "class x$$module$es6 {}",
                    "class z$$module$es6 {}",
                    "/** @const */ var module$es6={};",
                    "/** @const */ module$es6.x=x$$module$es6;",
                    "/** @const */ module$es6.z=z$$module$es6;")),
            SourceFile.fromCode(
                "goog.js",
                lines(
                    "/**",
                    " * @param {module$es6.x} a",
                    " * @param {module$es6.z} b",
                    " */",
                    "function f(a, b) {}"))));
  }

  @Test
  public void testGoogRequireLhsNonConstIsError() {
    testModulesError(
        lines("var bar = goog.require('closure.provide');", "export var x;"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);

    testModulesError(
        lines("export var x;", "var bar = goog.require('closure.provide');"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);

    testModulesError(
        lines("export {};", "var {foo, bar} = goog.require('closure.provide');", "use(foo, bar);"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);

    testModulesError(
        lines("export {};", "let {foo, bar} = goog.require('closure.provide');", "use(foo, bar);"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);
  }

  @Test
  public void testGoogRequireTypeLhsNonConstIsError() {
    testModulesError(
        lines("var bar = goog.requireType('closure.provide');", "export var x;"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);

    testModulesError(
        lines("export var x;", "var bar = goog.requireType('closure.provide');"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);

    testModulesError(
        lines(
            "export {};",
            "var {foo, bar} = goog.requireType('closure.provide');",
            "/**",
            " * @param {foo} x",
            " * @param {bar} y",
            " */",
            "function f(x, y) {}"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);

    testModulesError(
        lines(
            "export {};",
            "let {foo, bar} = goog.requireType('closure.provide');",
            "/**",
            " * @param {foo} x",
            " * @param {bar} y",
            " */",
            "function f(x, y) {}"),
        LHS_OF_GOOG_REQUIRE_MUST_BE_CONST);
  }

  @Test
  public void testGoogRequireTypeForNonEs6LhsNonConst1() {
    testError(
        srcs(
            SourceFile.fromCode("es6.js", "export var x; goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "closure.js",
                lines("goog.module('my.module');", "var es6 = goog.requireType('es6');"))),
        error(REQUIRE_TYPE_FOR_ES6_SHOULD_BE_CONST));
  }

  @Test
  public void testGoogRequireTypeForNonEs6LhsNonConst2() {
    testError(
        srcs(
            SourceFile.fromCode("es6.js", "export var x; goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "closure.js",
                lines("goog.module('my.module');", "let { x } = goog.requireType('es6');"))),
        error(REQUIRE_TYPE_FOR_ES6_SHOULD_BE_CONST));
  }

  @Test
  public void testNamespaceImports() {
    disableTypeInfoValidation();
    runTypeChecker = false; // typechecker does not support these namespace imports.
    testModules(
        lines("import Foo from 'goog:closure.provide';", "use(Foo);"),
        "use(closure.provide); /** @const */ var module$testcode = {};");

    testModules(
        lines("import {x, y} from 'goog:closure.provide';", "use(x);", "use(y);"),
        "use(closure.provide.x); use(closure.provide.y);/** @const */ var module$testcode = {};");

    testModules(
        lines("import Foo from 'goog:closure.provide';", "/** @type {Foo} */ var foo = new Foo();"),
        lines(
            "/** @type {closure.provide} */",
            "var foo$$module$testcode = new closure.provide();",
            "/** @const */ var module$testcode = {};"));

    testModules(
        lines(
            "import Foo from 'goog:closure.module';",
            "/** @type {Foo.Bar} */ var foo = new Foo.Bar();"),
        lines(
            "/** @type {module$exports$closure$module.Bar} */",
            "var foo$$module$testcode = new module$exports$closure$module.Bar();",
            "/** @const */ var module$testcode = {};"));

    testModules(
        lines(
            "import {Bar} from 'goog:closure.destructured.module';",
            "/** @type {Bar} */ var foo = new Bar();"),
        lines(
            "/** @type {module$exports$closure$destructured$module.Bar} */",
            "var foo$$module$testcode = new module$exports$closure$destructured$module.Bar();",
            "/** @const */ var module$testcode = {};"));

    testModules(
        lines(
            "import Foo from 'goog:closure.legacy.module';",
            "/** @type {Foo.Bar} */ var foo = new Foo.Bar();"),
        lines(
            "/** @type {closure.legacy.module.Bar} */",
            "var foo$$module$testcode = new closure.legacy.module.Bar();",
            "/** @const */ var module$testcode = {};"));

    testModules(
        lines(
            "import {Bar} from 'goog:closure.legacy.destructured.module';",
            "/** @type {Bar} */ var foo = new Bar();"),
        lines(
            "/** @type {closure.legacy.destructured.module.Bar} */",
            "var foo$$module$testcode = new closure.legacy.destructured.module.Bar();",
            "/** @const */ var module$testcode = {};"));

    testModulesError(
        "import * as Foo from 'goog:closure.provide';", NAMESPACE_IMPORT_CANNOT_USE_STAR);
  }

  @Test
  public void testGoogRequireMustBeModuleScope() {
    testModulesError(
        "{ goog.require('closure.provide'); } export {}", INVALID_CLOSURE_CALL_SCOPE_ERROR);
  }

  @Test
  public void testGoogRequireTypeMustBeModuleScope() {
    testModulesError(
        "{ goog.requireType('closure.provide'); } export {}", INVALID_CLOSURE_CALL_SCOPE_ERROR);
  }

  @Test
  public void testGoogModuleGetCannotBeModuleHoistScope() {
    testModulesError("goog.module.get('closure.module'); export {}", MODULE_USES_GOOG_MODULE_GET);
    testModulesError(
        "{ goog.module.get('closure.module'); } export {}", MODULE_USES_GOOG_MODULE_GET);
  }

  @Test
  public void testExportSpecGoogRequire() {
    testModules(
        lines("const {a} = goog.require('closure.provide');", "export {a};"),
        lines(
            "/** @const */ var module$testcode={};",
            "/** @const */ module$testcode.a = closure.provide.a;"));
  }

  @Test
  public void testRequireAndStoreGlobalUnqualifiedProvide() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("provide.js", "goog.provide('foo')"),
            SourceFile.fromCode(
                "testcode", lines("const foo = goog.require('foo');", "use(foo);", "export {};"))),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode("provide.js", "goog.provide('foo')"),
            SourceFile.fromCode(
                "testcode", lines("use(foo);", "/** @const */ var module$testcode={};"))));
  }

  @Test
  public void testGoogRequireAnnotationIsRenamed() {
    testModules(
        lines("const {Type} = goog.require('closure.provide');", "export let /** !Type */ value;"),
        lines(
            "let /** !closure.provide.Type */ value$$module$testcode;",
            "/** @const */ var module$testcode={};",
            "/** @const */ module$testcode.value = value$$module$testcode;"));

    testModules(
        lines("const Type = goog.require('closure.provide');", "export let /** !Type */ value;"),
        lines(
            "let /** !closure.provide */ value$$module$testcode;",
            "/** @const */ var module$testcode={};",
            "/** @const */ module$testcode.value = value$$module$testcode;"));
  }

  @Test
  public void testGoogRequireTypeAnnotationIsRenamed() {
    testModules(
        lines(
            "const {Type} = goog.requireType('closure.provide');",
            "export let /** !Type */ value;"),
        lines(
            "let /** !closure.provide.Type */ value$$module$testcode;",
            "/** @const */ var module$testcode={};",
            "/** @const */ module$testcode.value = value$$module$testcode;"));

    testModules(
        lines(
            "const Type = goog.requireType('closure.provide');", "export let /** !Type */ value;"),
        lines(
            "let /** !closure.provide */ value$$module$testcode;",
            "/** @const */ var module$testcode={};",
            "/** @const */ module$testcode.value = value$$module$testcode;"));
  }

  @Test
  public void testGoogRequireCorrectAnnotationIsRenamed() {
    testModules(
        lines(
            "const {Type} = goog.require('closure.provide');",
            "export let /** !Type */ value;",
            "function foo() {",
            "  class Type {}",
            "  let /** !Type */ value;",
            "}"),
        lines(
            "let /** !closure.provide.Type */ value$$module$testcode;",
            "function foo$$module$testcode() {",
            "  class Type {}",
            "  let /** !Type */ value;",
            "}",
            "/** @const */ var module$testcode={};",
            "/** @const */ module$testcode.value = value$$module$testcode;"));
  }

  @Test
  public void testGoogRequireTypeCorrectAnnotationIsRenamed() {
    testModules(
        lines(
            "const {Type} = goog.requireType('closure.provide');",
            "export let /** !Type */ value;",
            "function foo() {",
            "  class Type {}",
            "  let /** !Type */ value;",
            "}"),
        lines(
            "let /** !closure.provide.Type */ value$$module$testcode;",
            "function foo$$module$testcode() {",
            "  class Type {}",
            "  let /** !Type */ value;",
            "}",
            "/** @const */ var module$testcode={};",
            "/** @const */ module$testcode.value = value$$module$testcode;"));
  }

  @Test
  public void testForwardDeclareEs6Module() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js", "export {}; goog.declareModuleId('es6'); export class Type {}"),
            SourceFile.fromCode(
                "closure.js",
                lines(
                    "goog.module('my.module');",
                    "const alias = goog.forwardDeclare('es6');",
                    "let /** !alias.Type */ x;",
                    "alias;"))),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "class Type$$module$es6 {}",
                    "/** @const */ var module$es6 = {};",
                    "/** @const */ module$es6.Type = Type$$module$es6;")),
            SourceFile.fromCode(
                "closure.js",
                lines("goog.module('my.module');", "let /** !module$es6.Type */ x;", "alias;"))));

    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js", "export {}; goog.declareModuleId('es6'); export class Type {}"),
            SourceFile.fromCode(
                "closure.js",
                lines(
                    "goog.module('my.module');",
                    "goog.forwardDeclare('es6');",
                    "let /** !es6.Type */ x;",
                    "es6;"))),
        warning(UNRECOGNIZED_TYPE_ERROR));

    testError(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export {}; goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "closure.js",
                lines(
                    "goog.module('my.module');",
                    "let alias = goog.forwardDeclare('es6');",
                    "let /** !alias.Type */ x;",
                    "alias = goog.modle.get('es6');"))),
        error(FORWARD_DECLARE_FOR_ES6_SHOULD_BE_CONST));
  }

  @Test
  public void testWarnAboutRequireEs6FromEs6() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("first.js", "goog.declareModuleId('first'); export {};"),
            SourceFile.fromCode(
                "second.js", "const first = goog.require('first'); export {first};")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode("first.js", "/** @const */ var module$first = {};"),
            SourceFile.fromCode(
                "second.js",
                lines(
                    "const first$$module$second = module$first;",
                    "/** @const */ var module$second = {};",
                    "/** @const */ module$second.first = first$$module$second;"))),
        warning(Es6RewriteModules.SHOULD_IMPORT_ES6_MODULE));

    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("first.js", "goog.declareModuleId('no.alias'); export {};"),
            SourceFile.fromCode("second.js", "goog.require('no.alias'); export {};")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode("first.js", "/** @const */ var module$first = {};"),
            SourceFile.fromCode("second.js", "/** @const */ var module$second = {};")),
        warning(Es6RewriteModules.SHOULD_IMPORT_ES6_MODULE));
  }

  @Test
  public void testGoogRequireTypeEs6ModuleInEs6Module() {
    // TODO(tjgq): Make these warn once there's a requireType equivalent for ES6 modules.

    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "goog.declareModuleId('es6'); export class Type {};"),
            SourceFile.fromCode(
                "requiretype.js",
                lines(
                    "export {}", //
                    "const alias = goog.requireType('es6');",
                    "let /** !alias.Type */ x;"))),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "class Type$$module$es6 {}",
                    "/** @const */ var module$es6 = {};",
                    "/** @const */ module$es6.Type = Type$$module$es6;")),
            SourceFile.fromCode(
                "requiretype.js",
                lines(
                    "let /** !module$es6.Type */ x$$module$requiretype;",
                    "/** @const */ var module$requiretype = {};"))));

    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "goog.declareModuleId('es6'); export class Type {}"),
            SourceFile.fromCode(
                "requiretype.js",
                lines(
                    "export {};", //
                    "goog.requireType('es6');",
                    "let /** !es6.Type */ x;"))),
        warning(UNRECOGNIZED_TYPE_ERROR));
  }

  @Test
  public void testGoogModuleGetEs6ModuleInEs6Module() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("first.js", "goog.declareModuleId('first'); export let x;"),
            SourceFile.fromCode(
                "second.js", "export function foo() { return goog.module.get('first').x; }")),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "first.js",
                lines(
                    "let x$$module$first;",
                    "/** @const */ var module$first = {};",
                    "/** @const */ module$first.x = x$$module$first;")),
            SourceFile.fromCode(
                "second.js",
                lines(
                    "function foo$$module$second() {",
                    "  return module$first.x;",
                    "}",
                    "/** @const */ var module$second = {};",
                    "/** @const */ module$second.foo = foo$$module$second;"))));
  }

  @Test
  public void testForwardDeclareEs6ModuleInEs6Module() {
    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export class Type {} goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "forwarddeclare.js",
                lines(
                    "export {}",
                    "const alias = goog.forwardDeclare('es6');",
                    "let /** !alias.Type */ x;",
                    "alias;"))),
        expected(
            CLOSURE_BASE,
            SourceFile.fromCode(
                "es6.js",
                lines(
                    "class Type$$module$es6 {}",
                    "/** @const */ var module$es6 = {};",
                    "/** @const */ module$es6.Type = Type$$module$es6;")),
            SourceFile.fromCode(
                "forwarddeclare.js",
                lines(
                    "let /** !module$es6.Type */ x$$module$forwarddeclare;",
                    "alias;",
                    "/** @const */ var module$forwarddeclare = {};"))));

    test(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export class Type {} goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "forwarddeclare.js",
                lines(
                    "export {};",
                    "goog.forwardDeclare('es6');",
                    "let /** !es6.Type */ x;",
                    "es6;"))),
        warning(UNRECOGNIZED_TYPE_ERROR));

    testError(
        srcs(
            CLOSURE_BASE,
            SourceFile.fromCode("es6.js", "export class Type {} goog.declareModuleId('es6');"),
            SourceFile.fromCode(
                "closure.js",
                lines(
                    "export {};",
                    "let alias = goog.forwardDeclare('es6');",
                    "let /** !alias.Type */ x;",
                    "alias = goog.modle.get('es6');"))),
        error(FORWARD_DECLARE_FOR_ES6_SHOULD_BE_CONST));
  }

  @Test
  public void testMissingRequireAssumesGoogProvide() {
    ignoreWarnings(
        MISSING_MODULE_OR_PROVIDE, MISSING_NAMESPACE_IMPORT, POSSIBLE_INEXISTENT_PROPERTY);

    test(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            lines(
                "const missing = goog.require('is.missing');", //
                "use(missing, missing.x);",
                "export {};")),
        expected(
            new TestExternsBuilder().addClosureExterns().build(),
            lines(
                "use(is.missing, is.missing.x);", //
                "/** @const */ var module$testcode1 = {};")));

    test(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            lines(
                "const {prop} = goog.require('is.missing');", //
                "use(prop, prop.x);",
                "export {};")),
        expected(
            new TestExternsBuilder().addClosureExterns().build(),
            lines(
                "use(is.missing.prop, is.missing.prop.x);", //
                "/** @const */ var module$testcode1 = {};")));

    test(
        srcs(
            new TestExternsBuilder().addClosureExterns().build(),
            lines(
                "import missing, {y} from 'goog:is.missing';", //
                "use(missing, missing.x, y);",
                "export {};")),
        expected(
            new TestExternsBuilder().addClosureExterns().build(),
            lines(
                "use(is.missing, is.missing.x, is.missing.y);", //
                "/** @const */ var module$testcode1 = {};")));
  }
}