text:
import datetime
import time

def to_datetime(timestamp):
    """ Converts timestamp (str) in datetime object. """
    return datetime.datetime(*time.strptime(timestamp[:19], '%Y-%m-%dT%H:%M:%S')[:6])

def _fields(isu):
    """Returns field names of Issue object."""
    no_method = lambda x: not callable(getattr(isu.fields, x))
    no_magic = lambda x: not x.startswith('_')
    no_constant = lambda x: not x[0].isupper()
    return filter(lambda x: no_magic(x) and no_method(x) and no_constant(x), dir(isu.fields))

def copy_resource(rsc):
    """
    Creates copy of resource object.

    :param rsc: Jira resource object
    :type resource: jira.resources.Resource
    """
    kls = type(rsc)
    obj = kls(rsc._options, rsc._session, rsc.raw)
    return obj

class Changelog(object):

    """
    Changelog handling made easy::

        >>> issue = jira.issue('JIRA-2204')
        >>> add_history(issue)
        >>> issue.history
        <Changelog 3 entries>

        >>> one_week_ago = datetime.timedelta(datetime.datetime.now(), days=-7)
        >>> issue.history.at(one_week_ago)
        {'resolution': <Resolution Closed>, ...}

    """

    def __init__(self, resource):
        """
        Initiates a Changelog object from a resource.

        :type resource: jira.resources.Resource
        """
        self._resource = resource
        self.changes = [Change(item) for item in resource.changelog.histories]

    @classmethod
    def _clone_resource(cls, rsc, fields=None):
        """
        Returns resource values as dict.

        :param rsc: Jira resource object
        :type resource: jira.resources.Resource
        :param fields: list of fields to be copied
        :type fields: list
        """
        fields = fields or _fields(rsc)
        return {field: getattr(rsc.fields, field) for field in fields}

    @staticmethod
    def rollback(change, values):
        """
        Rolls back a particular set of changes to restore values to what they
        were before the change was applied.

        ATTENTION: This will not change the raw data nor will it reload resource
        objects!

        :param change: change to be rolled back
        :type change: Change
        :param values: values change will be applied to
        :type values: dict
        """
        for item in change.items:
            key = item.field
            if key in values:
                # create a copy of original Jira object
                if hasattr(values[key], 'raw'):
                    values[key] = copy_resource(values[key])
                values[key].id = getattr(item, 'from')
                values[key].name = item.fromString

    def at(self, dt):
        """
        Returns values for resource at a certain time

        :param dt: point in time for which values should be recovered
        :type dt: datetime.datetime
        """
        # apply all changes in reverse succession
        changes = sorted(self.changes, key=lambda ch: ch.created, reverse=True)
        values = self._clone_resource(self._resource)

        # return values directly if no changes were made since creation
        if not changes:
            return values

        # return values if next change was applied before dt
        # otherwise rollback all changes
        while changes:
            next_change = changes.pop(0)
            if next_change.created < dt:
                return values
            self.rollback(next_change, values)

        # all changes have been rolled back
        # return virgin values
        return values

class Change(object):

    """
    Convenience class for handling change information.
    """

    def __init__(self, raw):
        self.id = raw.id
        self.created = to_datetime(raw.created)
        self.author = raw.author
        self.items = raw.items

def add_history(resource):
    """
    Injects a Changelog instance into a resource object.

    :param rsc: Jira resource object
    :type resource: jira.resources.Resource
    """
    assert hasattr(resource, 'changelog')
    changelog = Changelog(resource)
    resource.history = changelog


text:
class Cat extends Component {
  // Allow only: A-Ö a-ö 0-9 & . : ; - + / * = > < ( ) %
  ALPHA_NUMERIC_REGEX = /^[A-ZÅÄÖa-zåäö0-9\s&.:;\-+/*=><()%]*$/g;
  // Allow the following characters: A-Ö a-ö 0-9 ! - + % " / ? , . §
  REFERENCES_REGEX = /^[A-ZÅÄÖa-zåäö0-9\s!\-+%"/?,.§]*$/g;

  constructor(props) {
    super(props);
    const { kettleData } = props;

    this.state = this.clearState(kettleData.referenceId);

    this.storeTransaction = this.storeTransaction.bind(this);
    this.onChange = this.onChange.bind(this);
    this.mapStateToTransactionType = this.mapStateToTransactionType.bind(this);
    this.checkRequiredFields = this.checkRequiredFields.bind(this);
    props.setTransactionIsDirty(false);
  }

  // Allow only: A-Ö a-ö 0-9 & . : ; - + / * = > < ( ) %
  ALPHA_NUMERIC_REGEX = /^[A-ZÅÄÖa-zåäö0-9\s&.:;\-+/*=><()%]*$/g;

  constructor(props) {
    super(props);
    const { kettleData } = props;

    this.state = this.clearState(kettleData.referenceId);

    this.storeTransaction = this.storeTransaction.bind(this);
    this.onChange = this.onChange.bind(this);
    this.mapStateToTransactionType = this.mapStateToTransactionType.bind(this);
    this.checkRequiredFields = this.checkRequiredFields.bind(this);
    props.setTransactionIsDirty(false);
  }
}

redpajama_set_name: RedPajamaGithub


text:
module StateMachines
  module Integrations
    module ActiveModel
      VERSION = '0.3.0'
    end
  end
end


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>UnlockMutex</title>

UnlockMutex()

语法

UnlockMutex(Mutex)

概要

Unlocks a mutex previously locked by LockMutex(). The mutex is then available
again for other threads to lock it.

参数

Mutex

The mutex to unlock.

返回值

无.

备注

A mutex can only be unlocked by the thread that also locked it.

See CreateMutex() for a code example.

参阅

LockMutex(), CreateMutex()

已支持操作系统
所有

<- TrySemaphore() - Thread Index - WaitSemaphore() ->


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Windows.ApplicationModel.Background;

namespace Jasily.ApplicationModel.Background
{
    public abstract class BackgroundTaskRegister
    {
        private readonly Type taskEntryPoint;

        protected BackgroundTaskRegister([NotNull] string taskName, [NotNull] Type taskEntryPoint)
        {
            this.TaskName = taskName ?? throw new ArgumentNullException(nameof(taskName));
            this.taskEntryPoint = taskEntryPoint ?? throw new ArgumentNullException(nameof(taskEntryPoint));
        }

        protected string TaskName { get; }

        private void Register()
        {
            var builder = new BackgroundTaskBuilder
            {
                Name = this.TaskName,
                TaskEntryPoint = this.taskEntryPoint.FullName
            };
            this.Configuration(builder);
            builder.Register();
        }

        protected abstract void Configuration(BackgroundTaskBuilder builder);

        public static Task<bool> TryRegister(bool removeOther, params BackgroundTaskRegister[] registers)
            => TryRegister(removeOther, (IEnumerable<BackgroundTaskRegister>)registers);

        public static async Task<bool> TryRegister(bool removeOther, IEnumerable<BackgroundTaskRegister> registers)
        {
            if (registers == null) throw new ArgumentNullException(nameof(registers));

            var status = await BackgroundExecutionManager.RequestAccessAsync();
            if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.Denied)
            {
                return false;
            }

            var dict = registers.ToDictionary(z => z.TaskName);

            foreach (var task in BackgroundTaskRegistration.AllTasks.Values)
            {
                if (!dict.Remove(task.Name) && removeOther)
                {
                    task.Unregister(false);
                }
            }

            foreach (var kvp in dict) // newest.
            {
                kvp.Value.Register();
            }

            return true;
        }

        public static BackgroundTaskRegister Create<T>(string taskName, Action<BackgroundTaskBuilder> builder)
            where T : IBackgroundTask
            => new BackgroundTaskRegisterImpl<T>(taskName, builder);

        private sealed class BackgroundTaskRegisterImpl<T> : BackgroundTaskRegister where T : IBackgroundTask
        {
            private readonly Action<BackgroundTaskBuilder> builder;

            public BackgroundTaskRegisterImpl([NotNull] string taskName, [NotNull] Action<BackgroundTaskBuilder> builder)
                : base(taskName, typeof(T))
            {
                this.builder = builder ?? throw new ArgumentNullException(nameof(builder));
            }

            protected override void Configuration(BackgroundTaskBuilder builder) => this.builder(builder);
        }
    }
}


text:
#ifndef CAF_BINARY_SERIALIZER_HPP
#define CAF_BINARY_SERIALIZER_HPP

#include <utility>
#include <sstream>
#include <iomanip>
#include <functional>
#include <type_traits>

#include "caf/serializer.hpp"
#include "caf/primitive_variant.hpp"

#include "caf/detail/ieee_754.hpp"
#include "caf/detail/type_traits.hpp"

namespace caf {

/// Implements the serializer interface with a binary serialization protocol.
class binary_serializer : public serializer {

  using super = serializer;

public:

  using write_fun = std::function<void(const char*, size_t)>;

  /// Creates a binary serializer writing to given iterator position.
  template <class OutIter>
  explicit binary_serializer(OutIter iter, actor_namespace* ns = nullptr)
      : super(ns) {
    struct fun {
      fun(OutIter pos) : pos_(pos) {}
      void operator()(const char* first, size_t num_bytes) {
        pos_ = std::copy(first, first + num_bytes, pos_);
      }
      OutIter pos_;
    };
    out_ = fun{iter};
  }

  void begin_object(const uniform_type_info* uti) override;

  void end_object() override;

  void begin_sequence(size_t list_size) override;

  void end_sequence() override;

  void write_value(const primitive_variant& value) override;

  void write_raw(size_t num_bytes, const void* data) override;

private:
  write_fun out_;
};

template <class T,
          class = typename std::enable_if<detail::is_primitive<T>::value>::type>
binary_serializer& operator<<(binary_serializer& bs, const T& value) {
  bs.write_value(value);
  return bs;
}

} // namespace caf

#endif // CAF_BINARY_SERIALIZER_HPP


text:
works-grepcode-android
======================

Collection of internal code from other open source library source that is not exposed to be used because of access modifier or unavailable due to future version


text:
describe('stateProviderApp', function () {
	var states = {};

	beforeEach(module('ui.state', function ($stateProvider) {
		states = {};
		$stateProvider.state = function (name, config) {
			states[name] = config;
		};
	}, 'MyApp'));

	describe('ordersProvider(myDataService)', function () {
		var ordersProvider;

		beforeEach(inject(function () {
			ordersProvider = states.orders.resolve.orders[1];
		}));

		it('Gets orders from myDataService', function () {
			var myDataService = {
				get: jasmine.createSpy().andReturn('test')
			};
			expect(ordersProvider(myDataService)).toEqual('test');
			expect(myDataService.get).toHaveBeenCalledWith('orders');
		});
	});
});


text:
using namespace ngraph;
using namespace ngraph::onnx_import;

static std::string s_manifest = "${MANIFEST}";

namespace
{
    template <typename T>
    void test_constant_folding(std::shared_ptr<ngraph::Function> ng_function,
                               const std::vector<T> expected_output,
                               const PartialShape expected_shape = PartialShape::dynamic())
    {
        ngraph::pass::Manager pass_manager;
        pass_manager.register_pass<pass::ConstantFolding>();
        pass_manager.run_passes(ng_function);

        for (auto ng_node : ng_function->get_ordered_ops())
        {
            if (ng_node->is_constant())
            {
                const auto folded_node = as_type_ptr<default_opset::Constant>(ng_node);
                const auto output_values = folded_node->cast_vector<T>();

                EXPECT_TRUE(ngraph::test::all_close(expected_output, output_values));

                if (expected_shape.is_static())
                {
                    EXPECT_EQ(folded_node->get_output_shape(0), expected_shape.to_shape());
                }

                return;
            }
        }

        FAIL() << "ONNX model import with constant folding failed.";
    }
}

NGRAPH_TEST(${BACKEND_NAME}, onnx_const_folding_model_scatter_elements)
{
    const auto fn = onnx_import::import_onnx_model(
        file_util::path_join(SERIALIZED_ZOO, "onnx/scatter_elements_opset11.prototxt"));

    test_constant_folding<float>(fn, {1.0, 1.1, 3.0, 2.1, 5.0}, Shape{1, 5});
}

NGRAPH_TEST(${BACKEND_NAME}, onnx_const_folding_model_non_zero_scalar)
{
    const auto fn = onnx_import::import_onnx_model(
        file_util::path_join(SERIALIZED_ZOO, "onnx/non_zero_scalar.prototxt"));

    test_constant_folding<int64_t>(fn, {0}, Shape{1, 1});
}

NGRAPH_TEST(${BACKEND_NAME}, onnx_const_folding_model_non_zero_1d)
{
    const auto fn = onnx_import::import_onnx_model(
        file_util::path_join(SERIALIZED_ZOO, "onnx/non_zero_1d.prototxt"));

    test_constant_folding<int64_t>(fn, {1, 2, 4}, Shape{1, 3});
}

NGRAPH_TEST(${BACKEND_NAME}, onnx_const_folding_model_non_zero_1d_float)
{
    const auto fn = onnx_import::import_onnx_model(
        file_util::path_join(SERIALIZED_ZOO, "onnx/non_zero_1d_float.prototxt"));

    test_constant_folding<int64_t>(fn, {0, 1, 3, 4, 5, 6, 7, 8, 9});
}

NGRAPH_TEST(${BACKEND_NAME}, onnx_const_folding_model_non_zero_3d)
{
    const auto fn = onnx_import::import_onnx_model(
        file_util::path_join(SERIALIZED_ZOO, "onnx/non_zero_3d.prototxt"));

    // Vertical slices are 3D indices of non-zero elements in the input tensor
    // {0, 0, 0, 1, 1, 2, 2}
    // {0, 0, 1, 0, 1, 0, 1}
    // {0, 1, 1, 1, 0, 0, 1}
    test_constant_folding<int64_t>(fn,
                                   {0, 0, 0, 1, 1, 2, 2, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1});
}

NGRAPH_TEST(${BACKEND_NAME}, onnx_const_folding_model_non_zero_2d_bool)
{
    const auto fn = onnx_import::import_onnx_model(
        file_util::path_join(SERIALIZED_ZOO, "onnx/non_zero_2d_bool.prototxt"));

    test_constant_folding<int64_t>(fn, {0, 1, 1, 0});
}


text:
from src.settings_default import *

######################################################################
# Custom settings
######################################################################
BASE_CHARACTER_TYPECLASS = "game.gamesrc.objects.world.character.Hero"
CMDSET_UNLOGGEDIN = "game.gamesrc.menu_login.UnloggedInCmdSet"
LOCK_FUNC_MODULES = ("src.locks.lockfuncs", "game.gamesrc.overrides.lockfuncs")
CMDSET_PLAYER = "game.gamesrc.commands.player_cmdset.PlayerCmdSet"
DEFAULT_HOME = "#4"
######################################################################
# SECRET_KEY was randomly seeded when settings.py was first created.
# Don't share this with anybody. It is used by Evennia to handle
# cryptographic hashing for things like cookies on the web side.
######################################################################
SECRET_KEY = 'q2fwpKc%mV7gysxt`L#0rXl~FBD-}ZMaboR_d?+{'


text:
using ConvertKitSharp.Entities;
using ConvertKitSharp.Infrastructure;
using RestSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConvertKitSharp.Services
{
    /// <summary>
    /// A service for interacting with <see cref="ConvertKitForm"/>s.
    /// </summary>
    public class ConvertKitFormService : ConvertKitService
    {
        public ConvertKitFormService(string apiKey) : base(apiKey) { }

        /// <summary>
        /// Lists all <see cref="ConvertKitForm"/>s on the user's account.
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<ConvertKitForm>> ListAsync()
        {
            var req = RequestEngine.CreateRequest("forms", Method.GET, "forms");

            return await RequestEngine.ExecuteRequestAsync<List<ConvertKitForm>>(_RestClient, req);
        }

        /// <summary>
        /// Subscribes a person to a <see cref="ConvertKitForm"/>.
        /// </summary>
        /// <param name="email">The subscriber's email address.</param>
        /// <param name="firstName">The subscriber's first name.</param>
        /// <param name="formId">The id of the form to subscribe them to.</param>
        /// <returns>The subscriber.</returns>
        public async Task<ConvertKitSubscriber> SubscribeToForm(string email, string firstName, long formId)
        {
            var req = RequestEngine.CreateRequest($"forms/{formId}/subscribe", Method.POST, "subscription");

            return await RequestEngine.ExecuteRequestAsync<ConvertKitSubscriber>(_RestClient, req);
        }

        /// <summary>
        /// Subscribes a person to multiple <see cref="ConvertKitForm" />s.
        /// </summary>
        /// <param name="email">The subscriber's email address.</param>
        /// <param name="firstName">The subscriber's first name.</param>
        /// <param name="formIds">A list of form ids to subscribe them to.</param>
        /// <returns>The subscriber.</returns>
        public async Task<ConvertKitSubscriber> SubscribeToForms(string email, string firstName, IEnumerable<long> formIds)
        {
            long? defaultForm = formIds.FirstOrDefault();

            if(defaultForm == null)
            {
                throw new NullReferenceException("You must specify at least one form id to subscribe to.");
            }

            var req = RequestEngine.CreateRequest($"forms/{defaultForm}/subscribe", Method.POST, "subscription");

            if(formIds.Count() > 1)
            {
                req.AddQueryParameter("forms", string.Join(",", formIds.Where(f => f != defaultForm)));
            }

            return await RequestEngine.ExecuteRequestAsync<ConvertKitSubscriber>(_RestClient, req);
        }
    }
}


text:
package com.github.niwaniwa.we.core.twitter;

import java.util.Arrays;

import com.github.niwaniwa.we.core.WhiteEggCore;
import com.github.niwaniwa.we.core.api.callback.Callback;
import com.github.niwaniwa.we.core.player.WhitePlayer;

public class PlayerTwitterManager extends TwitterManager {

    private WhitePlayer player;

    public PlayerTwitterManager(WhitePlayer p) {
        super();
        this.player = p;
    }

    @Override
    public void tweet(String tweet, Callback callback) {
        TweetScheduler task = new TweetScheduler(this, tweet, callback);
        task.runTaskAsynchronously(WhiteEggCore.getInstance());
    }

    @Override
    public void tweet(String[] tweet) {
        StringBuilder sb = new StringBuilder();
        Arrays.asList(tweet).forEach(s -> sb.append(s));
        tweet(sb.toString());
    }

    public WhitePlayer getPlayer() {
        return player;
    }

}


text:
<?php

namespace ApplicationTest\Navigation\Breadcrumbs;

use Application\Navigation\Breadcrumbs\BreadcrumbsBuilder;
use Application\Navigation\Breadcrumbs\Handler\BreadcrumbsPartResolver;
use DvsaCommonTest\TestUtils\XMock;
use Zend\ServiceManager\ServiceManager;
use Zend\View\Helper\Layout;
use Zend\View\Model\ViewModel;

class BreadcrumbsBuilderTest extends \Dvsa\Mot\Frontend\Test\TestCase
{
    /**
     * @var BreadcrumbsBuilder
     */
    private $builder;

    private $siteHandler;
    private $organisationBySiteHandler;
    private $simpleHandler;
    private $serviceLocator;
    private $viewModel;

    public function setUp()
    {
        $this->siteHandler = XMock::of(BreadcrumbsPartResolver::class);
        $this->organisationBySiteHandler = XMock::of(BreadcrumbsPartResolver::class);
        $this->simpleHandler = XMock::of(BreadcrumbsPartResolver::class);
        $this->serviceLocator = new ServiceManager();
        $this->serviceLocator->setService('site', $this->siteHandler);
        $this->serviceLocator->setService('organisation', $this->organisationBySiteHandler);
        $this->serviceLocator->setService('simple', $this->simpleHandler);
        $theLayout = XMock::of(Layout::class);
        $this->viewModel = new ViewModel();
        $theLayout->expects($this->any())->method('__invoke')->willReturn($this->viewModel);

        $resolvers = [
            'site' => 'site',
            'organisationBySite' => 'organisation',
            'simple' => 'simple',
        ];
        $this->builder = new BreadcrumbsBuilder($resolvers, $this->serviceLocator, $theLayout);
    }

    public function testSite()
    {
        $siteId = 5;
        $this->siteHandler->expects($this->once())->method('resolve')->with($siteId);
        $this->builder->site($siteId);
    }

    public function testOrganisationBySite()
    {
        $siteId = 5;
        $this->organisationBySiteHandler->expects($this->once())->method('resolve')->with($siteId);
        $this->builder->organisationBySiteId($siteId);
    }

    public function testSimple()
    {
        $label = 'label1';
        $route = 'route1';
        $params = ['params1'];
        $this->simpleHandler->expects($this->once())->method('resolve')
            ->with(['label' => $label, 'link' => ['route' => $route, 'params' => $params]]);
        $this->builder->simple($label, $route, $params);
    }

    public function testBuild()
    {
        $this->siteHandler->expects($this->any())->method('resolve')
            ->willReturn(['SiteName' => 'siteLink']);
        $this->organisationBySiteHandler->expects($this->any())->method('resolve')
            ->willReturn(['OrganisationName' => 'organisationLink']);

        $this->builder->site(5)->organisationBySiteId(3)->build();
        $expectedBreadcrumbs = [
            'breadcrumbs' => [
                ['SiteName' => 'siteLink'],
                ['OrganisationName' => 'organisationLink'],
            ],
        ];
        $this->assertEquals($expectedBreadcrumbs, $this->viewModel->getVariables()['breadcrumbs']);
    }

    public function testBuild_whenElementCannotBeResolved_shouldBeSkipped()
    {
        $this->siteHandler->expects($this->any())->method('resolve')
            ->willReturn([]);
        $this->organisationBySiteHandler->expects($this->any())->method('resolve')
            ->willReturn(['OrganisationName' => 'organisationLink']);

        $this->builder->site(5)->organisationBySiteId(3)->build();
        $expectedBreadcrumbs = [
            'breadcrumbs' => [
                ['OrganisationName' => 'organisationLink'],
            ],
        ];
        $this->assertEquals($expectedBreadcrumbs, $this->viewModel->getVariables()['breadcrumbs']);
    }
}


text:
<!DOCTYPE html>

			<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
		<meta content="utf-8" http-equiv="encoding">
		<title>Game</title>

Challenge: Win best of 3 against the computer!

	<canvas id="gameCanvas" width="700" height="400"></canvas>


text:
declare module scenario
{
    interface ISleep
    {
        (timeSeconds: number): void;
    }

    interface IBrowser
    {
        (): IBrowser;
        navigateTo(url: string);
        navigateTo(url: string, delegate: (url: string) => string);
        reload();
        window():  IWindowApi;
        location():  ILocationApi;
    }

    interface IWindowApi
    {
        href():  void;
        path():  void;
        search():  void;
        hash(): void;
    }

    interface ILocationApi
    {
        url():  void;
        path():  void;
        search():  void;
        hash(): void;
    }

    interface IElement
    {
        (): IElement;
        (selector: string): IElement;
        count(): number;
        click(): void;

    }

}

declare var browser: scenario.IBrowser;
declare var element: scenario.IElement;
declare var sleep: scenario.ISleep;


text:
package es.upm.fi.oeg.morph.tc

class D017Test extends R2RMLTest("D017-I18NnoSpecialChars") {
}


text:
#include "config.h"
#include "Autocapitalize.h"

#include <wtf/NeverDestroyed.h>

namespace WebCore {

static const AtomicString& valueOn()
{
    static NeverDestroyed<const AtomicString> valueOn("on", AtomicString::ConstructFromLiteral);
    return valueOn;
}

static const AtomicString& valueOff()
{
    static NeverDestroyed<const AtomicString> valueOff("off", AtomicString::ConstructFromLiteral);
    return valueOff;
}

static const AtomicString& valueNone()
{
    static NeverDestroyed<const AtomicString> valueNone("none", AtomicString::ConstructFromLiteral);
    return valueNone;
}

static const AtomicString& valueWords()
{
    static NeverDestroyed<const AtomicString> valueWords("words", AtomicString::ConstructFromLiteral);
    return valueWords;
}

static const AtomicString& valueSentences()
{
    static NeverDestroyed<const AtomicString> valueSentences("sentences", AtomicString::ConstructFromLiteral);
    return valueSentences;
}

static const AtomicString& valueAllCharacters()
{
    static NeverDestroyed<const AtomicString> valueAllCharacters("characters", AtomicString::ConstructFromLiteral);
    return valueAllCharacters;
}

WebAutocapitalizeType autocapitalizeTypeForAttributeValue(const AtomicString& attributeValue)
{
    // Omitted / missing values are the Default state.
    if (attributeValue.isNull() || attributeValue.isEmpty())
        return WebAutocapitalizeTypeDefault;

    if (equalIgnoringCase(attributeValue, valueOn()) || equalIgnoringCase(attributeValue, valueSentences()))
        return WebAutocapitalizeTypeSentences;
    if (equalIgnoringCase(attributeValue, valueOff()) || equalIgnoringCase(attributeValue, valueNone()))
        return WebAutocapitalizeTypeNone;
    if (equalIgnoringCase(attributeValue, valueWords()))
        return WebAutocapitalizeTypeWords;
    if (equalIgnoringCase(attributeValue, valueAllCharacters()))
        return WebAutocapitalizeTypeAllCharacters;

    // Unrecognized values fall back to "on".
    return WebAutocapitalizeTypeSentences;
}

const AtomicString& stringForAutocapitalizeType(WebAutocapitalizeType type)
{
    switch (type) {
    case WebAutocapitalizeTypeDefault:
        return nullAtom;
    case WebAutocapitalizeTypeNone:
        return valueNone();
    case WebAutocapitalizeTypeSentences:
        return valueSentences();
    case WebAutocapitalizeTypeWords:
        return valueWords();
    case WebAutocapitalizeTypeAllCharacters:
        return valueAllCharacters();
    }

    ASSERT_NOT_REACHED();
    return nullAtom;
}

} // namespace WebCore


text:
from scipy.fftpack import fft, fftfreq
import numpy as np

def cycle_length_est(data, top_k=3):
    '''
    Detect the cycle of a time series.
    code adaptted from https://zhuanlan.zhihu.com/p/394327245

    :param data: 1 dim ndarray for time series.
    :param top_k: The freq with top top_k power after fft will be
           used to check the autocorrelation. Higher top_k might be time-consuming.
           The value is default to 3.
    '''
    from bigdl.nano.utils.log4Error import invalidInputError
    invalidInputError((data.size//2) > abs(top_k)+1,
                      "top_k must be less than half the length of the time series,"
                      " but top_k and data length are {top_k} and {data.size} respectively.")
    invalidInputError(np.any(np.diff(data) != 0), "Data elements cannot all be the same.")

    fft_series = fft(data)
    power = np.abs(fft_series)
    sample_freq = fftfreq(fft_series.size)

    pos_mask = np.where(sample_freq > 0)
    freqs = sample_freq[pos_mask]
    powers = power[pos_mask]

    # top_k index
    top_k_idxs = np.argpartition(powers, -top_k)[-top_k:]
    top_k_power = powers[top_k_idxs]
    fft_periods = (1 / freqs[top_k_idxs]).astype(int)

    # Expected time period
    largest_acf_score = -float("inf")
    cycle_length_est = None
    from statsmodels.tsa.stattools import acf
    for lag in fft_periods:
        acf_score = acf(data, nlags=lag)[-1]
        if acf_score > largest_acf_score:
            cycle_length_est = lag
            largest_acf_score = acf_score

    return cycle_length_est


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace Ploeh.Samples.Menu.Mef
{
    public class SauceFilterCatalogFacts
    {
        [Fact]
        public void SutIsCatalog()
        {
            // Fixture setup
            var dummyCatalog = new AggregateCatalog();
            // Exercise system
            var sut = new SauceCatalog(dummyCatalog);
            // Verify outcome
            Assert.IsAssignableFrom<ComposablePartCatalog>(sut);
            // Teardown
        }

        [Fact]
        public void InitializeWithNullCatalogThrows()
        {
            // Fixture setup
            // Exercise system and verify outcome
            Assert.Throws<ArgumentNullException>(() =>
                new SauceCatalog(null));
            // Teardown
        }
    }
}


text:
import { TO_STRING_TAG } from '../constants/Symbol'

/**
 * Note: This class is **immutable**
 */
class Protocol {
  /**
   * @param {ImmutableMap<String, ImmutableList<Type>>} definitions
   */
  constructor(definitions) {
    this.definitions = definitions
  }

  get [TO_STRING_TAG]() {
    return 'Protocol'
  }

  /**
   * @returns {ImmutableMap<String, ImmutableList<Type>>}
   */
  getDefinitions() {
    return this.definitions
  }
}

export default Protocol


text:
from .bases import EndpointBase
from aioconsul.util import extract_attr

class MembersEndpoint(EndpointBase):
    """Interact with the local Consul agent.
    """

    async def items(self, *, wan=None):
        """Returns the members as seen by the local serf agent

        Parameters:
            wan (bool): List of WAN members instead of the LAN members
        Returns:
            Collection: List of cluster's members

        This endpoint returns an object like::

            [
                {
                    "Name": "foobar",
                    "Addr": "10.1.10.12",
                    "Port": 8301,
                    "Tags": {
                        "bootstrap": "1",
                        "dc": "dc1",
                        "port": "8300",
                        "role": "consul"
                    },
                    "Status": 1,
                    "ProtocolMin": 1,
                    "ProtocolMax": 2,
                    "ProtocolCur": 2,
                    "DelegateMin": 1,
                    "DelegateMax": 3,
                    "DelegateCur": 3
                }
            ]
        """
        response = await self._api.get("/v1/agent/members",
                                       params={"wan": wan})
        return response.body

    async def join(self, address, *, wan=None):
        """Triggers the local agent to join a node

        Parameters:
            address (str): Address of node
            wan (bool): Attempt to join using the WAN pool
        Returns:
            bool: ``True`` on success

        This endpoint is used to instruct the agent to attempt to connect to
        a given address. For agents running in server mode, providing ``wan``
        parameter causes the agent to attempt to join using the WAN pool.
        """
        response = await self._api.get("/v1/agent/join", address,
                                       params={"wan": wan})
        return response.status == 200

    async def force_leave(self, node):
        """Forces removal of a node

        Parameters:
            node (ObjectID): Node name
        Returns:
            bool: ``True`` on success

        This endpoint is used to instruct the agent to force a node into the
        ``left`` state. If a node fails unexpectedly, then it will be in a
        ``failed`` state. Once in the ``failed`` state, Consul will attempt to
        reconnect, and the services and checks belonging to that node will not
        be cleaned up. Forcing a node into the ``left`` state allows its old
        entries to be removed.
        """
        node_id = extract_attr(node, keys=["Node", "ID"])
        response = await self._get("/v1/agent/force-leave", node_id)
        return response.status == 200


text:
<?php

/**
 * @file
 * Contains \Drupal\views\Ajax\ScrollTopCommand.
 */

namespace Drupal\views\Ajax;

use Drupal\Core\Ajax\CommandInterface;

/**
 * Provides an AJAX command for scrolling to the top of an element.
 *
 * This command is implemented in Drupal.AjaxCommands.prototype.viewsScrollTop.
 */
class ScrollTopCommand implements CommandInterface {

  /**
   * A CSS selector string.
   *
   * @var string
   */
  protected $selector;

  /**
   * Constructs a \Drupal\views\Ajax\ScrollTopCommand object.
   *
   * @param string $selector
   *   A CSS selector.
   */
  public function __construct($selector) {
    $this->selector = $selector;
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    return array(
      'command' => 'viewsScrollTop',
      'selector' => $this->selector,
    );
  }

}


text:
namespace content {

// Given that lacros-chrome runs on ChromeOS, there are type optimizations that
// we can take advantage of above and beyond a typical webrtc::DesktopCapturer.
//
// This requires implementing the VideoCaptureDevice interface instead of the
// webrtc::DesktopCapturer interface. However, lacros-chrome, as a user-side
// process, doesn't actually have permissions to capture the desktop or windows
// itself. Thus, this class is responsible for acting as the lacros-chrome side
// capturer for the purposes of the video capture stack by proxying the calls
// across the crosapi boundary to the *actual* capturer running in the system-
// side ash-chrome process.
//
// Note that objects of this class are thread-affine (e.g. once created it must
// be used on the same thread).
class CONTENT_EXPORT VideoCaptureDeviceProxyLacros
    : public media::VideoCaptureDevice {
 public:
  // Helper method to check if the mojom version(s) required to use this class
  // are available.
  // May be called from any thread; should be checked before creating (or
  // posting a task to create) an instance of this class.
  static bool IsAvailable();

  explicit VideoCaptureDeviceProxyLacros(const DesktopMediaID& device_id);

  VideoCaptureDeviceProxyLacros(const VideoCaptureDeviceProxyLacros&) = delete;
  VideoCaptureDeviceProxyLacros& operator=(
      const VideoCaptureDeviceProxyLacros&) = delete;

  ~VideoCaptureDeviceProxyLacros() override;

  // Deviation from the VideoCaptureDevice interface: Since the memory pooling
  // provided by a VideoCaptureDevice::Client is not needed, we will provide
  // frames to a VideoFrameReceiver directly.
  void AllocateAndStartWithReceiver(
      const media::VideoCaptureParams& params,
      std::unique_ptr<media::VideoFrameReceiver> receiver);

  // Remaining VideoCaptureDevice implementation.
  void AllocateAndStart(const media::VideoCaptureParams& params,
                        std::unique_ptr<Client> client) final;
  void RequestRefreshFrame() final;
  void MaybeSuspend() final;
  void Resume() final;
  void Crop(const base::Token& crop_id,
            uint32_t crop_version,
            base::OnceCallback<void(media::mojom::CropRequestResult)> callback)
      override;
  void StopAndDeAllocate() final;
  void GetPhotoState(GetPhotoStateCallback callback) final;
  void SetPhotoOptions(media::mojom::PhotoSettingsPtr settings,
                       SetPhotoOptionsCallback callback) final;
  void TakePhoto(TakePhotoCallback callback) final;
  void OnUtilizationReport(media::VideoCaptureFeedback feedback) final;

 private:
  // Helper that logs the given error |message| to the |receiver_adapater_| and
  // then stops capture and this VideoCaptureDevice.
  void OnFatalError(std::string message);

  // Helper that requests wake lock to prevent the display from sleeping while
  // capturing is going on.
  void RequestWakeLock();

  const DesktopMediaID capture_id_;

  // Receives video frames from ash, for translation and propagation into the
  // video capture stack. This is set by AllocateAndStartWithReceiver(), and
  // cleared by StopAndDeAllocate().
  std::unique_ptr<crosapi::mojom::VideoFrameHandler> receiver_adapter_;

  // Set when OnFatalError() is called. This prevents any future
  // AllocateAndStartWithReceiver() calls from succeeding.
  absl::optional<std::string> fatal_error_message_;

  // Note that because we do not run on the main thread and because we want to
  // set a disconnect handler on the screen manager we must bind our own remote
  // rather than using |LacrosService::GetRemote|, which returns a shared remote
  // that is unsuitable for setting a disconnect handler on, and is also thread
  // affine to a different thread.
  mojo::Remote<crosapi::mojom::ScreenManager> screen_manager_;
  mojo::Remote<crosapi::mojom::VideoCaptureDevice> device_;

  SEQUENCE_CHECKER(sequence_checker_);

  // Prevent display sleeping while content capture is in progress.
  mojo::Remote<device::mojom::WakeLock> wake_lock_;

  // Creates WeakPtrs for use on the device thread.
  base::WeakPtrFactory<VideoCaptureDeviceProxyLacros> weak_factory_{this};
};

}  // namespace content

#endif  // CONTENT_BROWSER_MEDIA_CAPTURE_VIDEO_CAPTURE_DEVICE_PROXY_LACROS_H_


text:
niteshjain.github.io
====================
My Home Page


text:
using Mocha

############################################################
# This is an example script for training a fully connected
# network with dropout on mnist.
#
# The network size is 784-1200-1200-10 with ReLU units
# in the hidden layers and a softmax output layer.
# The parameters for training the network were chosen
# to reproduce the results from the original dropout paper:
# http://arxiv.org/abs/1207.0580
# and the corresponding newer JMLR paper:
# http://jmlr.org/papers/volume15/srivastava14a/srivastava14a.pdf
#
# Our parameters slightly differ. This is mainly due to the
# fact that in the original dropout paper the weights are scaled
# by 0.5 after training whereas we scale them by 2 during training.
#
# The settings in this script should currently produce a model that
# gets 94 errors (or 99.06 % accuracy) on the test set
# if you run it for the whole 2000 epochs (=600*2000 steps).
# This is slightly better than the results of the JMLR paper.
# This difference is likely due to slight differences in the
# learning parameters. Also note that our hyperparameters
# are not chosen using a validation set, as one would do
# for a paper. If your hardware and cuda versions differ
# from the setup we used for intial testing your results might
# also slightly vary due to floating point inaccuracies.
############################################################

# fix the random seed to make results reproducable
srand(12345678)

train_txt = ENV["DATASETS"]"/mnist/train.txt"
data_layer  = AsyncHDF5DataLayer(name="train-data", shuffle=true, source=train_txt, batch_size=100)
# each fully connected layer uses a ReLU activation and a constraint on the L2 norm of the weights
fc1_layer   = InnerProductLayer(name="fc1", output_dim=120, neuron=Neurons.ReLU(),
                                weight_init = GaussianInitializer(std=0.01),
                                #weight_cons = L2Cons(4.5),
                                bottoms=[:data], tops=[:fc1])
fc2_layer   = InnerProductLayer(name="fc2", output_dim=1200, neuron=Neurons.ReLU(),
                                weight_init = GaussianInitializer(std=0.01),
                                weight_cons = L2Cons(4.5),
                                bottoms=[:fc1], tops=[:fc2])
fc3_layer   = InnerProductLayer(name="out", output_dim=10, bottoms=[:fc2],
                                weight_init = ConstantInitializer(0),
                                weight_cons = L2Cons(4.5),
                                tops=[:out])
loss_layer  = SoftmaxLossLayer(name="loss", bottoms=[:out,:label])

# setup dropout for the different layers
# we use 20% dropout on the inputs and 50% dropout in the hidden layers
# as these values were previously found to be good defaults
drop_input  = DropoutLayer(name="drop_in", bottoms=[:data], ratio=0.2)
drop_fc1 = DropoutLayer(name="drop_fc1", bottoms=[:fc1], ratio=0.5)
drop_fc2  = DropoutLayer(name="drop_fc2", bottoms=[:fc2], ratio=0.5)

backend = DefaultBackend()
init(backend)

common_layers = [fc1_layer, fc2_layer, fc3_layer]
drop_layers = [drop_input, drop_fc1, drop_fc2]
# put training net together, note that the correct ordering will automatically be established by the constructor
net = Net("MNIST-train", backend, [data_layer, common_layers..., drop_layers..., loss_layer])

base_dir = "snapshots_dropout_ft-$(Mocha.default_backend_type)"
# we let the learning rate decrease by 0.998 in each epoch (=600 batches of size 100)
# and let the momentum increase linearly from 0.5 to 0.9 over 500 epochs
# which is equivalent to an increase step of 0.0008
# training is done for 2000 epochs
method = SGD()
params = make_solver_parameters(method, max_iter=600*2000, regu_coef=0.0,
                          mom_policy=MomPolicy.Linear(0.5, 0.0008, 600, 0.9),
                          lr_policy=LRPolicy.Step(0.1, 0.998, 600),
                          load_from=base_dir)
solver = Solver(method, params)

setup_coffee_lounge(solver, save_into="$base_dir/statistics.jld", every_n_iter=5000)

# report training progress every 100 iterations
add_coffee_break(solver, TrainingSummary(), every_n_iter=100)

# save snapshots every 5000 iterations
add_coffee_break(solver, Snapshot(base_dir), every_n_iter=5000)

# show performance on test data every 600 iterations (one epoch)
test_txt = ENV["DATASETS"]"/mnist/test.txt"
data_layer_test = AsyncHDF5DataLayer(name="test-data", source=test_txt, batch_size=100)
acc_layer = AccuracyLayer(name="test-accuracy", bottoms=[:out, :label], report_error=true)
test_net = Net("MNIST-test", backend, [data_layer_test, common_layers..., acc_layer])
add_coffee_break(solver, ValidationPerformance(test_net), every_n_iter=600)

solve(solver, net)

#Profile.init(int(1e8), 0.001)
#@profile solve(solver, net)
#open("profile.txt", "w") do out
#  Profile.print(out)
#end

destroy(net)
destroy(test_net)
shutdown(backend)


text:
<?php

namespace Ventas\Models\DbTable;

use Application\Models\Constants;
use Zend\Db\TableGateway\TableGateway;

class ViewVentasTable
{
    CONST name = 'view_ventas';

    public $gateway;
    public $schema = Constants::SCHEMA;
    public $pk = 'id';
    public $adapter;

    public function __construct($serviceLocator)
    {
        $this->adapter = $serviceLocator->get($this->schema);
        $gateway = new TableGateway(self::name, $this->adapter);
        $this->gateway = $gateway;
    }

}


text:
/*	$NetBSD: xfrin.c,v 1.9.4.1 2015/07/17 04:31:33 snj Exp $	*/

/*
 * Copyright (C) 2004-2008, 2011-2013, 2015  Internet Systems Consortium, Inc. ("ISC")
 * Copyright (C) 1999-2003  Internet Software Consortium.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

/* Id */

/*! \file */

#include <config.h>

#include <isc/mem.h>
#include <isc/print.h>
#include <isc/random.h>
#include <isc/string.h>		/* Required for HP/UX (and others?) */
#include <isc/task.h>
#include <isc/timer.h>
#include <isc/util.h>

#include <dns/callbacks.h>
#include <dns/db.h>
#include <dns/diff.h>
#include <dns/events.h>
#include <dns/journal.h>
#include <dns/log.h>
#include <dns/message.h>
#include <dns/rdataclass.h>
#include <dns/rdatalist.h>
#include <dns/rdataset.h>
#include <dns/result.h>
#include <dns/soa.h>
#include <dns/tcpmsg.h>
#include <dns/timer.h>
#include <dns/tsig.h>
#include <dns/view.h>
#include <dns/xfrin.h>
#include <dns/zone.h>

#include <dst/dst.h>

/*
 * Incoming AXFR and IXFR.
 */

/*%
 * It would be non-sensical (or at least obtuse) to use FAIL() with an
 * ISC_R_SUCCESS code, but the test is there to keep the Solaris compiler
 * from complaining about "end-of-loop code not reached".
 */
#define FAIL(code) \
	do { result = (code);					\
		if (result != ISC_R_SUCCESS) goto failure;	\
	} while (/*CONSTCOND*/0)

#define CHECK(op) \
	do { result = (op);					\
		if (result != ISC_R_SUCCESS) goto failure;	\
	} while (/*CONSTCOND*/0)

/*%
 * The states of the *XFR state machine.  We handle both IXFR and AXFR
 * with a single integrated state machine because they cannot be distinguished
 * immediately - an AXFR response to an IXFR request can only be detected
 * when the first two (2) response RRs have already been received.
 */
typedef enum {
	XFRST_SOAQUERY,
	XFRST_GOTSOA,
	XFRST_INITIALSOA,
	XFRST_FIRSTDATA,
	XFRST_IXFR_DELSOA,
	XFRST_IXFR_DEL,
	XFRST_IXFR_ADDSOA,
	XFRST_IXFR_ADD,
	XFRST_IXFR_END,
	XFRST_AXFR,
	XFRST_AXFR_END
} xfrin_state_t;

/*%
 * Incoming zone transfer context.
 */

struct dns_xfrin_ctx {
	unsigned int		magic;
	isc_mem_t		*mctx;
	dns_zone_t		*zone;

	int			refcount;

	isc_task_t 		*task;
	isc_timer_t		*timer;
	isc_socketmgr_t 	*socketmgr;

	int			connects; 	/*%< Connect in progress */
	int			sends;		/*%< Send in progress */
	int			recvs;	  	/*%< Receive in progress */
	isc_boolean_t		shuttingdown;

	dns_name_t 		name; 		/*%< Name of zone to transfer */
	dns_rdataclass_t 	rdclass;

	isc_boolean_t		checkid;
	dns_messageid_t		id;

	/*%
	 * Requested transfer type (dns_rdatatype_axfr or
	 * dns_rdatatype_ixfr).  The actual transfer type
	 * may differ due to IXFR->AXFR fallback.
	 */
	dns_rdatatype_t 	reqtype;
	isc_dscp_t 		dscp;

	isc_sockaddr_t 		masteraddr;
	isc_sockaddr_t		sourceaddr;
	isc_socket_t 		*socket;

	/*% Buffer for IXFR/AXFR request message */
	isc_buffer_t 		qbuffer;
	unsigned char 		qbuffer_data[512];

	/*% Incoming reply TCP message */
	dns_tcpmsg_t		tcpmsg;
	isc_boolean_t		tcpmsg_valid;

	dns_db_t 		*db;
	dns_dbversion_t 	*ver;
	dns_diff_t 		diff;		/*%< Pending database changes */
	int 			difflen;	/*%< Number of pending tuples */

	xfrin_state_t 		state;
	isc_uint32_t 		end_serial;
	isc_boolean_t 		is_ixfr;

	unsigned int		nmsg;		/*%< Number of messages recvd */
	unsigned int		nrecs;		/*%< Number of records recvd */
	isc_uint64_t		nbytes;		/*%< Number of bytes received */

	isc_time_t		start;		/*%< Start time of the transfer */
	isc_time_t		end;		/*%< End time of the transfer */

	dns_tsigkey_t		*tsigkey;	/*%< Key used to create TSIG */
	isc_buffer_t		*lasttsig;	/*%< The last TSIG */
	dst_context_t		*tsigctx;	/*%< TSIG verification context */
	unsigned int		sincetsig;	/*%< recvd since the last TSIG */
	dns_xfrindone_t		done;

	/*%
	 * AXFR- and IXFR-specific data.  Only one is used at a time
	 * according to the is_ixfr flag, so this could be a union,
	 * but keeping them separate makes it a bit simpler to clean
	 * things up when destroying the context.
	 */
	dns_rdatacallbacks_t	axfr;

	struct {
		isc_uint32_t 	request_serial;
		isc_uint32_t 	current_serial;
		dns_journal_t	*journal;

	} ixfr;
};

#define XFRIN_MAGIC		  ISC_MAGIC('X', 'f', 'r', 'I')
#define VALID_XFRIN(x)		  ISC_MAGIC_VALID(x, XFRIN_MAGIC)

/**************************************************************************/
/*
 * Forward declarations.
 */

static isc_result_t
xfrin_create(isc_mem_t *mctx,
	     dns_zone_t *zone,
	     dns_db_t *db,
	     isc_task_t *task,
	     isc_timermgr_t *timermgr,
	     isc_socketmgr_t *socketmgr,
	     dns_name_t *zonename,
	     dns_rdataclass_t rdclass,
	     dns_rdatatype_t reqtype,
	     isc_sockaddr_t *masteraddr,
	     isc_sockaddr_t *sourceaddr,
	     isc_dscp_t dscp,
	     dns_tsigkey_t *tsigkey,
	     dns_xfrin_ctx_t **xfrp);

static isc_result_t axfr_init(dns_xfrin_ctx_t *xfr);
static isc_result_t axfr_makedb(dns_xfrin_ctx_t *xfr, dns_db_t **dbp);
static isc_result_t axfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op,
				   dns_name_t *name, dns_ttl_t ttl,
				   dns_rdata_t *rdata);
static isc_result_t axfr_apply(dns_xfrin_ctx_t *xfr);
static isc_result_t axfr_commit(dns_xfrin_ctx_t *xfr);
static isc_result_t axfr_finalize(dns_xfrin_ctx_t *xfr);

static isc_result_t ixfr_init(dns_xfrin_ctx_t *xfr);
static isc_result_t ixfr_apply(dns_xfrin_ctx_t *xfr);
static isc_result_t ixfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op,
				 dns_name_t *name, dns_ttl_t ttl,
				 dns_rdata_t *rdata);
static isc_result_t ixfr_commit(dns_xfrin_ctx_t *xfr);

static isc_result_t xfr_rr(dns_xfrin_ctx_t *xfr, dns_name_t *name,
			   isc_uint32_t ttl, dns_rdata_t *rdata);

static isc_result_t xfrin_start(dns_xfrin_ctx_t *xfr);

static void xfrin_connect_done(isc_task_t *task, isc_event_t *event);
static isc_result_t xfrin_send_request(dns_xfrin_ctx_t *xfr);
static void xfrin_send_done(isc_task_t *task, isc_event_t *event);
static void xfrin_recv_done(isc_task_t *task, isc_event_t *event);
static void xfrin_timeout(isc_task_t *task, isc_event_t *event);

static void maybe_free(dns_xfrin_ctx_t *xfr);

static void
xfrin_fail(dns_xfrin_ctx_t *xfr, isc_result_t result, const char *msg);
static isc_result_t
render(dns_message_t *msg, isc_mem_t *mctx, isc_buffer_t *buf);

static void
xfrin_logv(int level, const char *zonetext, isc_sockaddr_t *masteraddr,
	   const char *fmt, va_list ap)
     ISC_FORMAT_PRINTF(4, 0);

static void
xfrin_log1(int level, const char *zonetext, isc_sockaddr_t *masteraddr,
	   const char *fmt, ...)
     ISC_FORMAT_PRINTF(4, 5);

static void
xfrin_log(dns_xfrin_ctx_t *xfr, int level, const char *fmt, ...)
     ISC_FORMAT_PRINTF(3, 4);

/**************************************************************************/
/*
 * AXFR handling
 */

static isc_result_t
axfr_init(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;

	xfr->is_ixfr = ISC_FALSE;

	if (xfr->db != NULL)
		dns_db_detach(&xfr->db);

	CHECK(axfr_makedb(xfr, &xfr->db));
	dns_rdatacallbacks_init(&xfr->axfr);
	CHECK(dns_db_beginload(xfr->db, &xfr->axfr));
	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

static isc_result_t
axfr_makedb(dns_xfrin_ctx_t *xfr, dns_db_t **dbp) {
	isc_result_t result;

	result = dns_db_create(xfr->mctx, /* XXX */
			       "rbt",	/* XXX guess */
			       &xfr->name,
			       dns_dbtype_zone,
			       xfr->rdclass,
			       0, NULL, /* XXX guess */
			       dbp);
	if (result == ISC_R_SUCCESS)
		dns_zone_rpz_enable_db(xfr->zone, *dbp);
	return (result);
}

static isc_result_t
axfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op,
	     dns_name_t *name, dns_ttl_t ttl, dns_rdata_t *rdata)
{
	isc_result_t result;

	dns_difftuple_t *tuple = NULL;

	CHECK(dns_zone_checknames(xfr->zone, name, rdata));
	CHECK(dns_difftuple_create(xfr->diff.mctx, op,
				   name, ttl, rdata, &tuple));
	dns_diff_append(&xfr->diff, &tuple);
	if (++xfr->difflen > 100)
		CHECK(axfr_apply(xfr));
	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

/*
 * Store a set of AXFR RRs in the database.
 */
static isc_result_t
axfr_apply(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;

	CHECK(dns_diff_load(&xfr->diff, xfr->axfr.add, xfr->axfr.add_private));
	xfr->difflen = 0;
	dns_diff_clear(&xfr->diff);
	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

static isc_result_t
axfr_commit(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;

	CHECK(axfr_apply(xfr));
	CHECK(dns_db_endload(xfr->db, &xfr->axfr));

	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

static isc_result_t
axfr_finalize(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;

	CHECK(dns_zone_replacedb(xfr->zone, xfr->db, ISC_TRUE));

	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

/**************************************************************************/
/*
 * IXFR handling
 */

static isc_result_t
ixfr_init(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;
	char *journalfile;

	if (xfr->reqtype != dns_rdatatype_ixfr) {
		xfrin_log(xfr, ISC_LOG_ERROR,
			  "got incremental response to AXFR request");
		return (DNS_R_FORMERR);
	}

	xfr->is_ixfr = ISC_TRUE;
	INSIST(xfr->db != NULL);
	xfr->difflen = 0;

	journalfile = dns_zone_getjournal(xfr->zone);
	if (journalfile != NULL)
		CHECK(dns_journal_open(xfr->mctx, journalfile,
				       DNS_JOURNAL_CREATE, &xfr->ixfr.journal));

	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

static isc_result_t
ixfr_putdata(dns_xfrin_ctx_t *xfr, dns_diffop_t op,
	     dns_name_t *name, dns_ttl_t ttl, dns_rdata_t *rdata)
{
	isc_result_t result;

	dns_difftuple_t *tuple = NULL;
	if (op == DNS_DIFFOP_ADD)
		CHECK(dns_zone_checknames(xfr->zone, name, rdata));
	CHECK(dns_difftuple_create(xfr->diff.mctx, op,
				   name, ttl, rdata, &tuple));
	dns_diff_append(&xfr->diff, &tuple);
	if (++xfr->difflen > 100)
		CHECK(ixfr_apply(xfr));
	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

/*
 * Apply a set of IXFR changes to the database.
 */
static isc_result_t
ixfr_apply(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;

	if (xfr->ver == NULL) {
		CHECK(dns_db_newversion(xfr->db, &xfr->ver));
		if (xfr->ixfr.journal != NULL)
			CHECK(dns_journal_begin_transaction(xfr->ixfr.journal));
	}
	CHECK(dns_diff_apply(&xfr->diff, xfr->db, xfr->ver));
	if (xfr->ixfr.journal != NULL) {
		result = dns_journal_writediff(xfr->ixfr.journal, &xfr->diff);
		if (result != ISC_R_SUCCESS)
			goto failure;
	}
	dns_diff_clear(&xfr->diff);
	xfr->difflen = 0;
	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

static isc_result_t
ixfr_commit(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;

	CHECK(ixfr_apply(xfr));
	if (xfr->ver != NULL) {
		/* XXX enter ready-to-commit state here */
		if (xfr->ixfr.journal != NULL)
			CHECK(dns_journal_commit(xfr->ixfr.journal));
		dns_db_closeversion(xfr->db, &xfr->ver, ISC_TRUE);
		dns_zone_markdirty(xfr->zone);
	}
	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

/**************************************************************************/
/*
 * Common AXFR/IXFR protocol code
 */

/*
 * Handle a single incoming resource record according to the current
 * state.
 */
static isc_result_t
xfr_rr(dns_xfrin_ctx_t *xfr, dns_name_t *name, isc_uint32_t ttl,
       dns_rdata_t *rdata)
{
	isc_result_t result;

	xfr->nrecs++;

	if (rdata->type == dns_rdatatype_none ||
	    dns_rdatatype_ismeta(rdata->type))
		FAIL(DNS_R_FORMERR);

 redo:
	switch (xfr->state) {
	case XFRST_SOAQUERY:
		if (rdata->type != dns_rdatatype_soa) {
			xfrin_log(xfr, ISC_LOG_ERROR,
				  "non-SOA response to SOA query");
			FAIL(DNS_R_FORMERR);
		}
		xfr->end_serial = dns_soa_getserial(rdata);
		if (!DNS_SERIAL_GT(xfr->end_serial, xfr->ixfr.request_serial) &&
		    !dns_zone_isforced(xfr->zone)) {
			xfrin_log(xfr, ISC_LOG_DEBUG(3),
				  "requested serial %u, "
				  "master has %u, not updating",
				  xfr->ixfr.request_serial, xfr->end_serial);
			FAIL(DNS_R_UPTODATE);
		}
		xfr->state = XFRST_GOTSOA;
		break;

	case XFRST_GOTSOA:
		/*
		 * Skip other records in the answer section.
		 */
		break;

	case XFRST_INITIALSOA:
		if (rdata->type != dns_rdatatype_soa) {
			xfrin_log(xfr, ISC_LOG_ERROR,
				  "first RR in zone transfer must be SOA");
			FAIL(DNS_R_FORMERR);
		}
		/*
		 * Remember the serial number in the initial SOA.
		 * We need it to recognize the end of an IXFR.
		 */
		xfr->end_serial = dns_soa_getserial(rdata);
		if (xfr->reqtype == dns_rdatatype_ixfr &&
		    ! DNS_SERIAL_GT(xfr->end_serial, xfr->ixfr.request_serial)
		    && !dns_zone_isforced(xfr->zone))
		{
			/*
			 * This must be the single SOA record that is
			 * sent when the current version on the master
			 * is not newer than the version in the request.
			 */
			xfrin_log(xfr, ISC_LOG_DEBUG(3),
				  "requested serial %u, "
				  "master has %u, not updating",
				  xfr->ixfr.request_serial, xfr->end_serial);
			FAIL(DNS_R_UPTODATE);
		}
		if (xfr->reqtype == dns_rdatatype_axfr)
			xfr->checkid = ISC_FALSE;
		xfr->state = XFRST_FIRSTDATA;
		break;

	case XFRST_FIRSTDATA:
		/*
		 * If the transfer begins with one SOA record, it is an AXFR,
		 * if it begins with two SOAs, it is an IXFR.
		 */
		if (xfr->reqtype == dns_rdatatype_ixfr &&
		    rdata->type == dns_rdatatype_soa &&
		    xfr->ixfr.request_serial == dns_soa_getserial(rdata)) {
			xfrin_log(xfr, ISC_LOG_DEBUG(3),
				  "got incremental response");
			CHECK(ixfr_init(xfr));
			xfr->state = XFRST_IXFR_DELSOA;
		} else {
			xfrin_log(xfr, ISC_LOG_DEBUG(3),
				  "got nonincremental response");
			CHECK(axfr_init(xfr));
			xfr->state = XFRST_AXFR;
		}
		goto redo;

	case XFRST_IXFR_DELSOA:
		INSIST(rdata->type == dns_rdatatype_soa);
		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_DEL, name, ttl, rdata));
		xfr->state = XFRST_IXFR_DEL;
		break;

	case XFRST_IXFR_DEL:
		if (rdata->type == dns_rdatatype_soa) {
			isc_uint32_t soa_serial = dns_soa_getserial(rdata);
			xfr->state = XFRST_IXFR_ADDSOA;
			xfr->ixfr.current_serial = soa_serial;
			goto redo;
		}
		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_DEL, name, ttl, rdata));
		break;

	case XFRST_IXFR_ADDSOA:
		INSIST(rdata->type == dns_rdatatype_soa);
		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_ADD, name, ttl, rdata));
		xfr->state = XFRST_IXFR_ADD;
		break;

	case XFRST_IXFR_ADD:
		if (rdata->type == dns_rdatatype_soa) {
			isc_uint32_t soa_serial = dns_soa_getserial(rdata);
			if (soa_serial == xfr->end_serial) {
				CHECK(ixfr_commit(xfr));
				xfr->state = XFRST_IXFR_END;
				break;
			} else if (soa_serial != xfr->ixfr.current_serial) {
				xfrin_log(xfr, ISC_LOG_ERROR,
					  "IXFR out of sync: "
					  "expected serial %u, got %u",
					  xfr->ixfr.current_serial, soa_serial);
				FAIL(DNS_R_FORMERR);
			} else {
				CHECK(ixfr_commit(xfr));
				xfr->state = XFRST_IXFR_DELSOA;
				goto redo;
			}
		}
		if (rdata->type == dns_rdatatype_ns &&
		    dns_name_iswildcard(name))
			FAIL(DNS_R_INVALIDNS);
		CHECK(ixfr_putdata(xfr, DNS_DIFFOP_ADD, name, ttl, rdata));
		break;

	case XFRST_AXFR:
		/*
		 * Old BINDs sent cross class A records for non IN classes.
		 */
		if (rdata->type == dns_rdatatype_a &&
		    rdata->rdclass != xfr->rdclass &&
		    xfr->rdclass != dns_rdataclass_in)
			break;
		CHECK(axfr_putdata(xfr, DNS_DIFFOP_ADD, name, ttl, rdata));
		if (rdata->type == dns_rdatatype_soa) {
			CHECK(axfr_commit(xfr));
			xfr->state = XFRST_AXFR_END;
			break;
		}
		break;
	case XFRST_AXFR_END:
	case XFRST_IXFR_END:
		FAIL(DNS_R_EXTRADATA);
		/* NOTREACHED */
	default:
		INSIST(0);
		break;
	}
	result = ISC_R_SUCCESS;
 failure:
	return (result);
}

isc_result_t
dns_xfrin_create(dns_zone_t *zone, dns_rdatatype_t xfrtype,
		 isc_sockaddr_t *masteraddr, dns_tsigkey_t *tsigkey,
		 isc_mem_t *mctx, isc_timermgr_t *timermgr,
		 isc_socketmgr_t *socketmgr, isc_task_t *task,
		 dns_xfrindone_t done, dns_xfrin_ctx_t **xfrp)
{
	isc_sockaddr_t sourceaddr;
	isc_dscp_t dscp;

	switch (isc_sockaddr_pf(masteraddr)) {
	case PF_INET:
		sourceaddr = *dns_zone_getxfrsource4(zone);
		dscp = dns_zone_getxfrsource4dscp(zone);
		break;
	case PF_INET6:
		sourceaddr = *dns_zone_getxfrsource6(zone);
		dscp = dns_zone_getxfrsource6dscp(zone);
		break;
	default:
		INSIST(0);
	}

	return(dns_xfrin_create3(zone, xfrtype, masteraddr, &sourceaddr,
				 dscp, tsigkey, mctx, timermgr, socketmgr,
				 task, done, xfrp));
}

isc_result_t
dns_xfrin_create2(dns_zone_t *zone, dns_rdatatype_t xfrtype,
		  isc_sockaddr_t *masteraddr, isc_sockaddr_t *sourceaddr,
		  dns_tsigkey_t *tsigkey, isc_mem_t *mctx,
		  isc_timermgr_t *timermgr, isc_socketmgr_t *socketmgr,
		  isc_task_t *task, dns_xfrindone_t done,
		  dns_xfrin_ctx_t **xfrp)
{
	return (dns_xfrin_create3(zone, xfrtype, masteraddr, sourceaddr, -1,
				  tsigkey, mctx, timermgr, socketmgr, task,
				  done, xfrp));
}

isc_result_t
dns_xfrin_create3(dns_zone_t *zone, dns_rdatatype_t xfrtype,
		  isc_sockaddr_t *masteraddr, isc_sockaddr_t *sourceaddr,
		  isc_dscp_t dscp, dns_tsigkey_t *tsigkey, isc_mem_t *mctx,
		  isc_timermgr_t *timermgr, isc_socketmgr_t *socketmgr,
		  isc_task_t *task, dns_xfrindone_t done,
		  dns_xfrin_ctx_t **xfrp)
{
	dns_name_t *zonename = dns_zone_getorigin(zone);
	dns_xfrin_ctx_t *xfr = NULL;
	isc_result_t result;
	dns_db_t *db = NULL;

	REQUIRE(xfrp != NULL && *xfrp == NULL);

	(void)dns_zone_getdb(zone, &db);

	if (xfrtype == dns_rdatatype_soa || xfrtype == dns_rdatatype_ixfr)
		REQUIRE(db != NULL);

	CHECK(xfrin_create(mctx, zone, db, task, timermgr, socketmgr, zonename,
			   dns_zone_getclass(zone), xfrtype, masteraddr,
			   sourceaddr, dscp, tsigkey, &xfr));

	CHECK(xfrin_start(xfr));

	xfr->done = done;
	xfr->refcount++;
	*xfrp = xfr;

 failure:
	if (db != NULL)
		dns_db_detach(&db);
	if (result != ISC_R_SUCCESS) {
		char zonetext[DNS_NAME_MAXTEXT+32];
		dns_zone_name(zone, zonetext, sizeof(zonetext));
		xfrin_log1(ISC_LOG_ERROR, zonetext, masteraddr,
			   "zone transfer setup failed");
	}
	return (result);
}

void
dns_xfrin_shutdown(dns_xfrin_ctx_t *xfr) {
	if (! xfr->shuttingdown)
		xfrin_fail(xfr, ISC_R_CANCELED, "shut down");
}

void
dns_xfrin_attach(dns_xfrin_ctx_t *source, dns_xfrin_ctx_t **target) {
	REQUIRE(target != NULL && *target == NULL);
	source->refcount++;
	*target = source;
}

void
dns_xfrin_detach(dns_xfrin_ctx_t **xfrp) {
	dns_xfrin_ctx_t *xfr = *xfrp;
	INSIST(xfr->refcount > 0);
	xfr->refcount--;
	maybe_free(xfr);
	*xfrp = NULL;
}

static void
xfrin_cancelio(dns_xfrin_ctx_t *xfr) {
	if (xfr->connects > 0) {
		isc_socket_cancel(xfr->socket, xfr->task,
				  ISC_SOCKCANCEL_CONNECT);
	} else if (xfr->recvs > 0) {
		dns_tcpmsg_cancelread(&xfr->tcpmsg);
	} else if (xfr->sends > 0) {
		isc_socket_cancel(xfr->socket, xfr->task,
				  ISC_SOCKCANCEL_SEND);
	}
}

static void
xfrin_reset(dns_xfrin_ctx_t *xfr) {
	REQUIRE(VALID_XFRIN(xfr));

	xfrin_log(xfr, ISC_LOG_INFO, "resetting");

	xfrin_cancelio(xfr);

	if (xfr->socket != NULL)
		isc_socket_detach(&xfr->socket);

	if (xfr->lasttsig != NULL)
		isc_buffer_free(&xfr->lasttsig);

	dns_diff_clear(&xfr->diff);
	xfr->difflen = 0;

	if (xfr->ixfr.journal != NULL)
		dns_journal_destroy(&xfr->ixfr.journal);

	if (xfr->axfr.add_private != NULL)
		(void)dns_db_endload(xfr->db, &xfr->axfr);

	if (xfr->tcpmsg_valid) {
		dns_tcpmsg_invalidate(&xfr->tcpmsg);
		xfr->tcpmsg_valid = ISC_FALSE;
	}

	if (xfr->ver != NULL)
		dns_db_closeversion(xfr->db, &xfr->ver, ISC_FALSE);
}

static void
xfrin_fail(dns_xfrin_ctx_t *xfr, isc_result_t result, const char *msg) {
	if (result != DNS_R_UPTODATE) {
		xfrin_log(xfr, ISC_LOG_ERROR, "%s: %s",
			  msg, isc_result_totext(result));
		if (xfr->is_ixfr)
			/* Pass special result code to force AXFR retry */
			result = DNS_R_BADIXFR;
	}
	xfrin_cancelio(xfr);
	/*
	 * Close the journal.
	 */
	if (xfr->ixfr.journal != NULL)
		dns_journal_destroy(&xfr->ixfr.journal);
	if (xfr->done != NULL) {
		(xfr->done)(xfr->zone, result);
		xfr->done = NULL;
	}
	xfr->shuttingdown = ISC_TRUE;
	maybe_free(xfr);
}

static isc_result_t
xfrin_create(isc_mem_t *mctx,
	     dns_zone_t *zone,
	     dns_db_t *db,
	     isc_task_t *task,
	     isc_timermgr_t *timermgr,
	     isc_socketmgr_t *socketmgr,
	     dns_name_t *zonename,
	     dns_rdataclass_t rdclass,
	     dns_rdatatype_t reqtype,
	     isc_sockaddr_t *masteraddr,
	     isc_sockaddr_t *sourceaddr,
	     isc_dscp_t dscp,
	     dns_tsigkey_t *tsigkey,
	     dns_xfrin_ctx_t **xfrp)
{
	dns_xfrin_ctx_t *xfr = NULL;
	isc_result_t result;
	isc_uint32_t tmp;

	xfr = isc_mem_get(mctx, sizeof(*xfr));
	if (xfr == NULL)
		return (ISC_R_NOMEMORY);
	xfr->mctx = NULL;
	isc_mem_attach(mctx, &xfr->mctx);
	xfr->refcount = 0;
	xfr->zone = NULL;
	dns_zone_iattach(zone, &xfr->zone);
	xfr->task = NULL;
	isc_task_attach(task, &xfr->task);
	xfr->timer = NULL;
	xfr->socketmgr = socketmgr;
	xfr->done = NULL;

	xfr->connects = 0;
	xfr->sends = 0;
	xfr->recvs = 0;
	xfr->shuttingdown = ISC_FALSE;

	dns_name_init(&xfr->name, NULL);
	xfr->rdclass = rdclass;
	isc_random_get(&tmp);
	xfr->checkid = ISC_TRUE;
	xfr->id	= (isc_uint16_t)(tmp & 0xffff);
	xfr->reqtype = reqtype;
	xfr->dscp = dscp;

	/* sockaddr */
	xfr->socket = NULL;
	/* qbuffer */
	/* qbuffer_data */
	/* tcpmsg */
	xfr->tcpmsg_valid = ISC_FALSE;

	xfr->db = NULL;
	if (db != NULL)
		dns_db_attach(db, &xfr->db);
	xfr->ver = NULL;
	dns_diff_init(xfr->mctx, &xfr->diff);
	xfr->difflen = 0;

	if (reqtype == dns_rdatatype_soa)
		xfr->state = XFRST_SOAQUERY;
	else
		xfr->state = XFRST_INITIALSOA;
	/* end_serial */

	xfr->nmsg = 0;
	xfr->nrecs = 0;
	xfr->nbytes = 0;
	isc_time_now(&xfr->start);

	xfr->tsigkey = NULL;
	if (tsigkey != NULL)
		dns_tsigkey_attach(tsigkey, &xfr->tsigkey);
	xfr->lasttsig = NULL;
	xfr->tsigctx = NULL;
	xfr->sincetsig = 0;
	xfr->is_ixfr = ISC_FALSE;

	/* ixfr.request_serial */
	/* ixfr.current_serial */
	xfr->ixfr.journal = NULL;

	xfr->axfr.add = NULL;
	xfr->axfr.add_private = NULL;

	CHECK(dns_name_dup(zonename, mctx, &xfr->name));

	CHECK(isc_timer_create(timermgr, isc_timertype_inactive, NULL, NULL,
			       task, xfrin_timeout, xfr, &xfr->timer));
	CHECK(dns_timer_setidle(xfr->timer,
				dns_zone_getmaxxfrin(xfr->zone),
				dns_zone_getidlein(xfr->zone),
				ISC_FALSE));

	xfr->masteraddr = *masteraddr;

	INSIST(isc_sockaddr_pf(masteraddr) == isc_sockaddr_pf(sourceaddr));
	xfr->sourceaddr = *sourceaddr;
	isc_sockaddr_setport(&xfr->sourceaddr, 0);

	/*
	 * Reserve 2 bytes for TCP length at the begining of the buffer.
	 */
	isc_buffer_init(&xfr->qbuffer, &xfr->qbuffer_data[2],
			sizeof(xfr->qbuffer_data) - 2);

	xfr->magic = XFRIN_MAGIC;
	*xfrp = xfr;
	return (ISC_R_SUCCESS);

 failure:
	if (xfr->timer != NULL)
		isc_timer_detach(&xfr->timer);
	if (dns_name_dynamic(&xfr->name))
		dns_name_free(&xfr->name, xfr->mctx);
	if (xfr->tsigkey != NULL)
		dns_tsigkey_detach(&xfr->tsigkey);
	if (xfr->db != NULL)
		dns_db_detach(&xfr->db);
	isc_task_detach(&xfr->task);
	dns_zone_idetach(&xfr->zone);
	isc_mem_putanddetach(&xfr->mctx, xfr, sizeof(*xfr));

	return (result);
}

static isc_result_t
xfrin_start(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;
	CHECK(isc_socket_create(xfr->socketmgr,
				isc_sockaddr_pf(&xfr->sourceaddr),
				isc_sockettype_tcp,
				&xfr->socket));
	isc_socket_setname(xfr->socket, "xfrin", NULL);
#ifndef BROKEN_TCP_BIND_BEFORE_CONNECT
	CHECK(isc_socket_bind(xfr->socket, &xfr->sourceaddr,
			      ISC_SOCKET_REUSEADDRESS));
#endif
	isc_socket_dscp(xfr->socket, xfr->dscp);
	CHECK(isc_socket_connect(xfr->socket, &xfr->masteraddr, xfr->task,
				 xfrin_connect_done, xfr));
	xfr->connects++;
	return (ISC_R_SUCCESS);
 failure:
	xfrin_fail(xfr, result, "failed setting up socket");
	return (result);
}

/* XXX the resolver could use this, too */

static isc_result_t
render(dns_message_t *msg, isc_mem_t *mctx, isc_buffer_t *buf) {
	dns_compress_t cctx;
	isc_boolean_t cleanup_cctx = ISC_FALSE;
	isc_result_t result;

	CHECK(dns_compress_init(&cctx, -1, mctx));
	cleanup_cctx = ISC_TRUE;
	CHECK(dns_message_renderbegin(msg, &cctx, buf));
	CHECK(dns_message_rendersection(msg, DNS_SECTION_QUESTION, 0));
	CHECK(dns_message_rendersection(msg, DNS_SECTION_ANSWER, 0));
	CHECK(dns_message_rendersection(msg, DNS_SECTION_AUTHORITY, 0));
	CHECK(dns_message_rendersection(msg, DNS_SECTION_ADDITIONAL, 0));
	CHECK(dns_message_renderend(msg));
	result = ISC_R_SUCCESS;
 failure:
	if (cleanup_cctx)
		dns_compress_invalidate(&cctx);
	return (result);
}

/*
 * A connection has been established.
 */
static void
xfrin_connect_done(isc_task_t *task, isc_event_t *event) {
	isc_socket_connev_t *cev = (isc_socket_connev_t *) event;
	dns_xfrin_ctx_t *xfr = (dns_xfrin_ctx_t *) event->ev_arg;
	isc_result_t result = cev->result;
	char sourcetext[ISC_SOCKADDR_FORMATSIZE];
	isc_sockaddr_t sockaddr;
	dns_zonemgr_t * zmgr;
	isc_time_t now;

	REQUIRE(VALID_XFRIN(xfr));

	UNUSED(task);

	INSIST(event->ev_type == ISC_SOCKEVENT_CONNECT);
	isc_event_free(&event);

	xfr->connects--;
	if (xfr->shuttingdown) {
		maybe_free(xfr);
		return;
	}

	zmgr = dns_zone_getmgr(xfr->zone);
	if (zmgr != NULL) {
		if (result != ISC_R_SUCCESS) {
			TIME_NOW(&now);
			dns_zonemgr_unreachableadd(zmgr, &xfr->masteraddr,
						   &xfr->sourceaddr, &now);
			goto failure;
		} else
			dns_zonemgr_unreachabledel(zmgr, &xfr->masteraddr,
						   &xfr->sourceaddr);
	}

	result = isc_socket_getsockname(xfr->socket, &sockaddr);
	if (result == ISC_R_SUCCESS) {
		isc_sockaddr_format(&sockaddr, sourcetext, sizeof(sourcetext));
	} else
		strcpy(sourcetext, "<UNKNOWN>");
	xfrin_log(xfr, ISC_LOG_INFO, "connected using %s", sourcetext);

	dns_tcpmsg_init(xfr->mctx, xfr->socket, &xfr->tcpmsg);
	xfr->tcpmsg_valid = ISC_TRUE;

	CHECK(xfrin_send_request(xfr));
 failure:
	if (result != ISC_R_SUCCESS)
		xfrin_fail(xfr, result, "failed to connect");
}

/*
 * Convert a tuple into a dns_name_t suitable for inserting
 * into the given dns_message_t.
 */
static isc_result_t
tuple2msgname(dns_difftuple_t *tuple, dns_message_t *msg, dns_name_t **target)
{
	isc_result_t result;
	dns_rdata_t *rdata = NULL;
	dns_rdatalist_t *rdl = NULL;
	dns_rdataset_t *rds = NULL;
	dns_name_t *name = NULL;

	REQUIRE(target != NULL && *target == NULL);

	CHECK(dns_message_gettemprdata(msg, &rdata));
	dns_rdata_init(rdata);
	dns_rdata_clone(&tuple->rdata, rdata);

	CHECK(dns_message_gettemprdatalist(msg, &rdl));
	dns_rdatalist_init(rdl);
	rdl->type = tuple->rdata.type;
	rdl->rdclass = tuple->rdata.rdclass;
	rdl->ttl = tuple->ttl;
	ISC_LIST_APPEND(rdl->rdata, rdata, link);

	CHECK(dns_message_gettemprdataset(msg, &rds));
	CHECK(dns_rdatalist_tordataset(rdl, rds));

	CHECK(dns_message_gettempname(msg, &name));
	dns_name_init(name, NULL);
	dns_name_clone(&tuple->name, name);
	ISC_LIST_APPEND(name->list, rds, link);

	*target = name;
	return (ISC_R_SUCCESS);

 failure:

	if (rds != NULL) {
		dns_rdataset_disassociate(rds);
		dns_message_puttemprdataset(msg, &rds);
	}
	if (rdl != NULL) {
		ISC_LIST_UNLINK(rdl->rdata, rdata, link);
		dns_message_puttemprdatalist(msg, &rdl);
	}
	if (rdata != NULL)
		dns_message_puttemprdata(msg, &rdata);

	return (result);
}

/*
 * Build an *XFR request and send its length prefix.
 */
static isc_result_t
xfrin_send_request(dns_xfrin_ctx_t *xfr) {
	isc_result_t result;
	isc_region_t region;
	dns_rdataset_t *qrdataset = NULL;
	dns_message_t *msg = NULL;
	dns_difftuple_t *soatuple = NULL;
	dns_name_t *qname = NULL;
	dns_dbversion_t *ver = NULL;
	dns_name_t *msgsoaname = NULL;

	/* Create the request message */
	CHECK(dns_message_create(xfr->mctx, DNS_MESSAGE_INTENTRENDER, &msg));
	CHECK(dns_message_settsigkey(msg, xfr->tsigkey));

	/* Create a name for the question section. */
	CHECK(dns_message_gettempname(msg, &qname));
	dns_name_init(qname, NULL);
	dns_name_clone(&xfr->name, qname);

	/* Formulate the question and attach it to the question name. */
	CHECK(dns_message_gettemprdataset(msg, &qrdataset));
	dns_rdataset_makequestion(qrdataset, xfr->rdclass, xfr->reqtype);
	ISC_LIST_APPEND(qname->list, qrdataset, link);
	qrdataset = NULL;

	dns_message_addname(msg, qname, DNS_SECTION_QUESTION);
	qname = NULL;

	if (xfr->reqtype == dns_rdatatype_ixfr) {
		/* Get the SOA and add it to the authority section. */
		/* XXX is using the current version the right thing? */
		dns_db_currentversion(xfr->db, &ver);
		CHECK(dns_db_createsoatuple(xfr->db, ver, xfr->mctx,
					    DNS_DIFFOP_EXISTS, &soatuple));
		xfr->ixfr.request_serial = dns_soa_getserial(&soatuple->rdata);
		xfr->ixfr.current_serial = xfr->ixfr.request_serial;
		xfrin_log(xfr, ISC_LOG_DEBUG(3),
			  "requesting IXFR for serial %u",
			  xfr->ixfr.request_serial);

		CHECK(tuple2msgname(soatuple, msg, &msgsoaname));
		dns_message_addname(msg, msgsoaname, DNS_SECTION_AUTHORITY);
	} else if (xfr->reqtype == dns_rdatatype_soa)
		CHECK(dns_db_getsoaserial(xfr->db, NULL,
					  &xfr->ixfr.request_serial));

	xfr->checkid = ISC_TRUE;
	xfr->id++;
	xfr->nmsg = 0;
	xfr->nrecs = 0;
	xfr->nbytes = 0;
	isc_time_now(&xfr->start);
	msg->id = xfr->id;
	if (xfr->tsigctx != NULL)
		dst_context_destroy(&xfr->tsigctx);

	CHECK(render(msg, xfr->mctx, &xfr->qbuffer));

	/*
	 * Free the last tsig, if there is one.
	 */
	if (xfr->lasttsig != NULL)
		isc_buffer_free(&xfr->lasttsig);

	/*
	 * Save the query TSIG and don't let message_destroy free it.
	 */
	CHECK(dns_message_getquerytsig(msg, xfr->mctx, &xfr->lasttsig));

	isc_buffer_usedregion(&xfr->qbuffer, &region);
	INSIST(region.length <= 65535);

	/*
	 * Record message length and adjust region to include TCP
	 * length field.
	 */
	xfr->qbuffer_data[0] = (region.length >> 8) & 0xff;
	xfr->qbuffer_data[1] = region.length & 0xff;
	region.base -= 2;
	region.length += 2;
	CHECK(isc_socket_send(xfr->socket, &region, xfr->task,
			      xfrin_send_done, xfr));
	xfr->sends++;

 failure:
	if (qname != NULL)
		dns_message_puttempname(msg, &qname);
	if (qrdataset != NULL)
		dns_message_puttemprdataset(msg, &qrdataset);
	if (msg != NULL)
		dns_message_destroy(&msg);
	if (soatuple != NULL)
		dns_difftuple_free(&soatuple);
	if (ver != NULL)
		dns_db_closeversion(xfr->db, &ver, ISC_FALSE);
	return (result);
}

static void
xfrin_send_done(isc_task_t *task, isc_event_t *event) {
	isc_socketevent_t *sev = (isc_socketevent_t *) event;
	dns_xfrin_ctx_t *xfr = (dns_xfrin_ctx_t *) event->ev_arg;
	isc_result_t result;

	REQUIRE(VALID_XFRIN(xfr));

	UNUSED(task);

	INSIST(event->ev_type == ISC_SOCKEVENT_SENDDONE);

	xfr->sends--;
	xfrin_log(xfr, ISC_LOG_DEBUG(3), "sent request data");
	CHECK(sev->result);

	CHECK(dns_tcpmsg_readmessage(&xfr->tcpmsg, xfr->task,
				     xfrin_recv_done, xfr));
	xfr->recvs++;
 failure:
	isc_event_free(&event);
	if (result != ISC_R_SUCCESS)
		xfrin_fail(xfr, result, "failed sending request data");
}

static void
xfrin_recv_done(isc_task_t *task, isc_event_t *ev) {
	dns_xfrin_ctx_t *xfr = (dns_xfrin_ctx_t *) ev->ev_arg;
	isc_result_t result;
	dns_message_t *msg = NULL;
	dns_name_t *name;
	dns_tcpmsg_t *tcpmsg;
	dns_name_t *tsigowner = NULL;

	REQUIRE(VALID_XFRIN(xfr));

	UNUSED(task);

	INSIST(ev->ev_type == DNS_EVENT_TCPMSG);
	tcpmsg = ev->ev_sender;
	isc_event_free(&ev);

	xfr->recvs--;
	if (xfr->shuttingdown) {
		maybe_free(xfr);
		return;
	}

	CHECK(tcpmsg->result);

	xfrin_log(xfr, ISC_LOG_DEBUG(7), "received %u bytes",
		  tcpmsg->buffer.used);

	CHECK(isc_timer_touch(xfr->timer));

	CHECK(dns_message_create(xfr->mctx, DNS_MESSAGE_INTENTPARSE, &msg));

	CHECK(dns_message_settsigkey(msg, xfr->tsigkey));
	CHECK(dns_message_setquerytsig(msg, xfr->lasttsig));

	msg->tsigctx = xfr->tsigctx;
	xfr->tsigctx = NULL;

	if (xfr->nmsg > 0)
		msg->tcp_continuation = 1;

	result = dns_message_parse(msg, &tcpmsg->buffer,
				   DNS_MESSAGEPARSE_PRESERVEORDER);

	if (result == ISC_R_SUCCESS)
		dns_message_logpacket(msg, "received message:\n",
				      DNS_LOGCATEGORY_XFER_IN,
				      DNS_LOGMODULE_XFER_IN,
				      ISC_LOG_DEBUG(10), xfr->mctx);
	else
		xfrin_log(xfr, ISC_LOG_DEBUG(10), "dns_message_parse: %s",
			  dns_result_totext(result));

	if (result != ISC_R_SUCCESS || msg->rcode != dns_rcode_noerror ||
	    (xfr->checkid && msg->id != xfr->id)) {
		if (result == ISC_R_SUCCESS)
			result = ISC_RESULTCLASS_DNSRCODE + msg->rcode; /*XXX*/
		if (result == ISC_R_SUCCESS || result == DNS_R_NOERROR)
			result = DNS_R_UNEXPECTEDID;
		if (xfr->reqtype == dns_rdatatype_axfr ||
		    xfr->reqtype == dns_rdatatype_soa)
			goto failure;
		xfrin_log(xfr, ISC_LOG_DEBUG(3), "got %s, retrying with AXFR",
		       isc_result_totext(result));
 try_axfr:
		dns_message_destroy(&msg);
		xfrin_reset(xfr);
		xfr->reqtype = dns_rdatatype_soa;
		xfr->state = XFRST_SOAQUERY;
		(void)xfrin_start(xfr);
		return;
	}

	/*
	 * Does the server know about IXFR?  If it doesn't we will get
	 * a message with a empty answer section or a potentially a CNAME /
	 * DNAME, the later is handled by xfr_rr() which will return FORMERR
	 * if the first RR in the answer section is not a SOA record.
	 */
	if (xfr->reqtype == dns_rdatatype_ixfr &&
	    xfr->state == XFRST_INITIALSOA &&
	    msg->counts[DNS_SECTION_ANSWER] == 0) {
		xfrin_log(xfr, ISC_LOG_DEBUG(3),
			  "empty answer section, retrying with AXFR");
		goto try_axfr;
	}

	if (xfr->reqtype == dns_rdatatype_soa &&
	    (msg->flags & DNS_MESSAGEFLAG_AA) == 0) {
		FAIL(DNS_R_NOTAUTHORITATIVE);
	}

	result = dns_message_checksig(msg, dns_zone_getview(xfr->zone));
	if (result != ISC_R_SUCCESS) {
		xfrin_log(xfr, ISC_LOG_DEBUG(3), "TSIG check failed: %s",
		       isc_result_totext(result));
		goto failure;
	}

	for (result = dns_message_firstname(msg, DNS_SECTION_ANSWER);
	     result == ISC_R_SUCCESS;
	     result = dns_message_nextname(msg, DNS_SECTION_ANSWER))
	{
		dns_rdataset_t *rds;

		name = NULL;
		dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
		for (rds = ISC_LIST_HEAD(name->list);
		     rds != NULL;
		     rds = ISC_LIST_NEXT(rds, link))
		{
			for (result = dns_rdataset_first(rds);
			     result == ISC_R_SUCCESS;
			     result = dns_rdataset_next(rds))
			{
				dns_rdata_t rdata = DNS_RDATA_INIT;
				dns_rdataset_current(rds, &rdata);
				CHECK(xfr_rr(xfr, name, rds->ttl, &rdata));
			}
		}
	}
	if (result != ISC_R_NOMORE)
		goto failure;

	if (dns_message_gettsig(msg, &tsigowner) != NULL) {
		/*
		 * Reset the counter.
		 */
		xfr->sincetsig = 0;

		/*
		 * Free the last tsig, if there is one.
		 */
		if (xfr->lasttsig != NULL)
			isc_buffer_free(&xfr->lasttsig);

		/*
		 * Update the last tsig pointer.
		 */
		CHECK(dns_message_getquerytsig(msg, xfr->mctx,
					       &xfr->lasttsig));

	} else if (dns_message_gettsigkey(msg) != NULL) {
		xfr->sincetsig++;
		if (xfr->sincetsig > 100 || xfr->nmsg == 0 ||
		    xfr->state == XFRST_AXFR_END ||
		    xfr->state == XFRST_IXFR_END)
		{
			result = DNS_R_EXPECTEDTSIG;
			goto failure;
		}
	}

	/*
	 * Update the number of messages received.
	 */
	xfr->nmsg++;

	/*
	 * Update the number of bytes received.
	 */
	xfr->nbytes += tcpmsg->buffer.used;

	/*
	 * Take the context back.
	 */
	INSIST(xfr->tsigctx == NULL);
	xfr->tsigctx = msg->tsigctx;
	msg->tsigctx = NULL;

	dns_message_destroy(&msg);

	switch (xfr->state) {
	case XFRST_GOTSOA:
		xfr->reqtype = dns_rdatatype_axfr;
		xfr->state = XFRST_INITIALSOA;
		CHECK(xfrin_send_request(xfr));
		break;
	case XFRST_AXFR_END:
		CHECK(axfr_finalize(xfr));
		/* FALLTHROUGH */
	case XFRST_IXFR_END:
		/*
		 * Close the journal.
		 */
		if (xfr->ixfr.journal != NULL)
			dns_journal_destroy(&xfr->ixfr.journal);

		/*
		 * Inform the caller we succeeded.
		 */
		if (xfr->done != NULL) {
			(xfr->done)(xfr->zone, ISC_R_SUCCESS);
			xfr->done = NULL;
		}
		/*
		 * We should have no outstanding events at this
		 * point, thus maybe_free() should succeed.
		 */
		xfr->shuttingdown = ISC_TRUE;
		maybe_free(xfr);
		break;
	default:
		/*
		 * Read the next message.
		 */
		CHECK(dns_tcpmsg_readmessage(&xfr->tcpmsg, xfr->task,
					     xfrin_recv_done, xfr));
		xfr->recvs++;
	}
	return;

 failure:
	if (msg != NULL)
		dns_message_destroy(&msg);
	if (result != ISC_R_SUCCESS)
		xfrin_fail(xfr, result, "failed while receiving responses");
}

static void
xfrin_timeout(isc_task_t *task, isc_event_t *event) {
	dns_xfrin_ctx_t *xfr = (dns_xfrin_ctx_t *) event->ev_arg;

	REQUIRE(VALID_XFRIN(xfr));

	UNUSED(task);

	isc_event_free(&event);
	/*
	 * This will log "giving up: timeout".
	 */
	xfrin_fail(xfr, ISC_R_TIMEDOUT, "giving up");
}

static void
maybe_free(dns_xfrin_ctx_t *xfr) {
	isc_uint64_t msecs;
	isc_uint64_t persec;

	REQUIRE(VALID_XFRIN(xfr));

	if (! xfr->shuttingdown || xfr->refcount != 0 ||
	    xfr->connects != 0 || xfr->sends != 0 ||
	    xfr->recvs != 0)
		return;

	/*
	 * Calculate the length of time the transfer took,
	 * and print a log message with the bytes and rate.
	 */
	isc_time_now(&xfr->end);
	msecs = isc_time_microdiff(&xfr->end, &xfr->start) / 1000;
	if (msecs == 0)
		msecs = 1;
	persec = (xfr->nbytes * 1000) / msecs;
	xfrin_log(xfr, ISC_LOG_INFO,
		  "Transfer completed: %d messages, %d records, "
		  "%" ISC_PRINT_QUADFORMAT "u bytes, "
		  "%u.%03u secs (%u bytes/sec)",
		  xfr->nmsg, xfr->nrecs, xfr->nbytes,
		  (unsigned int) (msecs / 1000), (unsigned int) (msecs % 1000),
		  (unsigned int) persec);

	if (xfr->socket != NULL)
		isc_socket_detach(&xfr->socket);

	if (xfr->timer != NULL)
		isc_timer_detach(&xfr->timer);

	if (xfr->task != NULL)
		isc_task_detach(&xfr->task);

	if (xfr->tsigkey != NULL)
		dns_tsigkey_detach(&xfr->tsigkey);

	if (xfr->lasttsig != NULL)
		isc_buffer_free(&xfr->lasttsig);

	dns_diff_clear(&xfr->diff);

	if (xfr->ixfr.journal != NULL)
		dns_journal_destroy(&xfr->ixfr.journal);

	if (xfr->axfr.add_private != NULL)
		(void)dns_db_endload(xfr->db, &xfr->axfr);

	if (xfr->tcpmsg_valid)
		dns_tcpmsg_invalidate(&xfr->tcpmsg);

	if (xfr->tsigctx != NULL)
		dst_context_destroy(&xfr->tsigctx);

	if ((xfr->name.attributes & DNS_NAMEATTR_DYNAMIC) != 0)
		dns_name_free(&xfr->name, xfr->mctx);

	if (xfr->ver != NULL)
		dns_db_closeversion(xfr->db, &xfr->ver, ISC_FALSE);

	if (xfr->db != NULL)
		dns_db_detach(&xfr->db);

	if (xfr->zone != NULL)
		dns_zone_idetach(&xfr->zone);

	isc_mem_putanddetach(&xfr->mctx, xfr, sizeof(*xfr));
}

/*
 * Log incoming zone transfer messages in a format like
 * transfer of <zone> from <address>: <message>
 */
static void
xfrin_logv(int level, const char *zonetext, isc_sockaddr_t *masteraddr,
	   const char *fmt, va_list ap)
{
	char mastertext[ISC_SOCKADDR_FORMATSIZE];
	char msgtext[2048];

	isc_sockaddr_format(masteraddr, mastertext, sizeof(mastertext));
	vsnprintf(msgtext, sizeof(msgtext), fmt, ap);

	isc_log_write(dns_lctx, DNS_LOGCATEGORY_XFER_IN,
		      DNS_LOGMODULE_XFER_IN, level,
		      "transfer of '%s' from %s: %s",
		      zonetext, mastertext, msgtext);
}

/*
 * Logging function for use when a xfrin_ctx_t has not yet been created.
 */

static void
xfrin_log1(int level, const char *zonetext, isc_sockaddr_t *masteraddr,
	   const char *fmt, ...)
{
	va_list ap;

	if (isc_log_wouldlog(dns_lctx, level) == ISC_FALSE)
		return;

	va_start(ap, fmt);
	xfrin_logv(level, zonetext, masteraddr, fmt, ap);
	va_end(ap);
}

/*
 * Logging function for use when there is a xfrin_ctx_t.
 */

static void
xfrin_log(dns_xfrin_ctx_t *xfr, int level, const char *fmt, ...)
{
	va_list ap;
	char zonetext[DNS_NAME_MAXTEXT+32];

	if (isc_log_wouldlog(dns_lctx, level) == ISC_FALSE)
		return;

	dns_zone_name(xfr->zone, zonetext, sizeof(zonetext));

	va_start(ap, fmt);
	xfrin_logv(level, zonetext, &xfr->masteraddr, fmt, ap);
	va_end(ap);
}