text:
module Doxyparser

	# A plain old OOP Class
  class Struct < Compound

  	# @return [bool] true if any of its methods is 'pure virtual'
    def abstract?
    	@is_abstract ||= methods(:all).any? { |m| m.virt == 'pure-virtual'}
    end

    # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @return [Array<Function>] declared constructors
    def constructors(access = :public)
    	return case access
    	when :public
      	@public_constructors ||= methods(:public, nil, [@basename])
    	when :protected
      	@protected_constructors ||= methods(:protected, nil, [@basename])
    	when :private
      	@private_constructors ||= methods(:private, nil, [@basename])
    	when :all
    		constructors(:public) + constructors(:protected) + constructors(:private)
   		end
    end

    # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @return [Array<Function>] declared destructors
    def destructors(access = :public)
    	return case access
    	when :public
      	@public_destructors ||= methods(:public, nil, [/^~/])
    	when :protected
      	@protected_destructors ||= methods(:protected, nil, [/^~/])
    	when :private
      	@private_destructors ||= methods(:private, nil, [/^~/])
    	when :all
    		destructors(:public) + destructors(:protected) + destructors(:private)
   		end
    end

    # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @param static If nil are static members excluded. If not nil only static members are returned
    # @param filter [Array<String>] list of Regex. Members whose name does not match any of the regexes will be excluded
    # @return [Array<Function>] declared methods
    def methods(access = :public, static = nil, filter = nil)
    	if access == :all
    		return methods(:public, static, filter) + methods(:protected, static, filter) + methods(:private, static, filter)
    	end
    	if access == :public && filter.nil? # Caches public methods
    	 	if static.nil?
    			@public_methods ||= _methods(:public, nil, nil)
    			return @public_methods
    		end
    		@public_static_methods ||= _methods(:public, true, nil)
    		return @public_static_methods
    	end
      _methods(access, static, filter)
    end

		# @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @param static If nil are static members excluded. If not nil only static members are returned
    # @param filter [Array<String>] list of Regex. Members whose name does not match any of the regexes will be excluded
    # @return [Array<Variable>] declared attributes
    def attributes(access = :public, static = nil, filter = nil)
    	if access == :all
    		return attributes(:public, static, filter) + attributes(:protected, static, filter) + attributes(:private, static, filter)
    	end
    	if access == :public && filter.nil? # Caches public attributes
    	 	if static.nil?
    			@public_attributes ||= _attributes(:public, nil, nil)
    			return @public_attributes
    		end
  			@public_static_attributes ||= _attributes(:public, true, nil)
   			return @public_static_attributes
    	end
	    _attributes(access, static, filter)
    end

    # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @param filter [Array<String>] list of Regex. Members whose name does not match any of the regexes will be excluded
    # @return [Array<Struct>] declared inner-classes and inner-structs
    def innerclasses(access = :public, filter = nil)
  		if filter.nil?
	    	if access == :all
    			@all_innerclasses ||= innerclasses(:public) + innerclasses(:protected) + innerclasses(:private)
    			return @all_innerclasses
    		end
	    	if access == :public
  	  		@public_innerclasses ||= only_innerclasses(:public) + only_innerstructs(:public)
    			return @public_innerclasses
    		end
    	end
    	if access == :all
   			return innerclasses(:public, filter) + innerclasses(:protected, filter) + innerclasses(:private, filter)
   		end
    	only_innerclasses(access, filter) + only_innerstructs(access, filter)
    end

		# @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @param filter [Array<String>] list of Regex. Members whose name does not match any of the regexes will be excluded
    # @return [Array<Struct>] declared inner-classes (inner-structs are excluded)
    def only_innerclasses(access = :public, filter = nil)
    	if access == :all
    		return innerclasses(:public, filter) + innerclasses(:protected, filter) + innerclasses(:private, filter)
    	end
      lst = doc.xpath(%Q{/doxygen/compounddef/innerclass[@prot="#{access}"]})
      lst = lst.select { |c| c["refid"].start_with?("class") }
      do_filter(filter, lst, Doxyparser::Class) { |node|
        del_prefix(node.child.content)
      }
    end

	  # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @param filter [Array<String>] list of Regex. Members whose name does not match any of the regexes will be excluded
    # @return [Array<Struct>] declared inner-structs (inner-classes are excluded)
    def only_innerstructs(access = :public, filter = nil)
    	if access == :all
    		return innerstructs(:public, filter) + innerstructs(:protected, filter) + innerstructs(:private, filter)
    	end
      lst = doc.xpath(%Q{/doxygen/compounddef/innerclass[@prot="#{access}"]})
      lst = lst.select { |c| c["refid"].start_with?("struct") }
      do_filter(filter, lst, Doxyparser::Struct) { |node|
        del_prefix(node.child.content)
      }
    end

    # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @return [Array<Type>] declared super-types for this struct/class
    def parent_types(access = :public)
    	if access == :public
    		@public_parent_types ||= _parent_types(:public)
    		return @public_parent_types
    	end
    	if access == :all
    			@all_parent_types ||= parent_types(:public) + parent_types(:protected) + parent_types(:private)
    			return @all_parent_types
    	end
      _parent_types(access)
    end

    # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @param filter [Array<String>] list of Regex. Members whose name does not match any of the regexes will be excluded
    # @return [Array<Enum>] declared enums
    def enums(access = :public, filter = nil)
    	if access == :public && filter.nil?
    		@public_enums ||= _enums(:public)
    		return @public_enums
    	end
    	if access == :all && filter.nil?
    		@all_enums ||= enums(:public) + enums(:protected) + enums(:private)
    		return @all_enums
    	end
      _enums(access, filter)
    end

	  # @param access [Symbol] access modifier (:public, :protected, :private, :all)
    # @param filter [Array<String>] list of Regex. Members whose name does not match any of the regexes will be excluded
    # @return [Array<Typedef>] declared typedefs
    def typedefs(access = :public, filter = nil)
    	if access == :public && filter.nil?
    		@public_typedefs ||= _typedefs(:public)
    		return @public_typedefs
    	end
    	if access == :all && filter.nil?
    		@all_typedefs ||= typedefs(:public) + typedefs(:protected) + typedefs(:private)
    		return @all_typedefs
    	end
      _typedefs(access, filter)
    end

   	attr_reader :file
  	attr_reader :friends
  	attr_reader :template_params

    private

    def _methods(access = :public, static = nil, filter = nil)
    	if static.nil?
        static = "-"
      else
        static = "-static-"
      end
      sectiondef = %Q{#{access}#{static}func}
      lst = doc.xpath(%Q{/doxygen/compounddef/sectiondef[@kind="#{sectiondef}"]/memberdef[@kind="function"][@prot="#{access}"]})
      do_filter(filter, lst, Doxyparser::Function) { |node|
        node.xpath("name")[0].child.content
      }
    end

    def _attributes(access = :public, static = nil, filter = nil)
    	if static.nil?
        static = "-"
      else
        static = "-static-"
      end
      sectiondef = %Q{#{access}#{static}attrib}
      lst = doc.xpath(%Q{/doxygen/compounddef/sectiondef[@kind="#{sectiondef}"]/memberdef[@kind="variable"][@prot="#{access}"]})
      do_filter(filter, lst, Doxyparser::Variable) { |node|
        node.xpath("name")[0].child.content
      }
    end

    def compute_path
      aux = escape_class_name(@name)
      @xml_path = %Q{#{@dir}/struct#{aux}.xml}
    end

    def _typedefs(access, filter=nil)
    	sectiondef = %Q{#{access}-type}
      lst = doc.xpath(%Q{/doxygen/compounddef/sectiondef[@kind="#{sectiondef}"]/memberdef[@kind="typedef"][@prot="#{access}"]})
      do_filter(filter, lst, Doxyparser::Typedef) { |node|
      	del_spaces node.xpath("name")[0].child.content
      }
    end

    def _enums(access, filter=nil)
    	sectiondef = %Q{#{access}-type}
      lst = doc.xpath(%Q{/doxygen/compounddef/sectiondef[@kind="#{sectiondef}"]/memberdef[@kind="enum"][@prot="#{access}"]})
      filter.map!{ |exp| exp =~ /^#{@basename}_Enum/ ? /@\d*/ : exp} unless filter.nil?
      do_filter(filter, lst, Doxyparser::Enum) { |node|
        node.xpath("name")[0].child.content
      }
    end

    def _parent_types(access)
    	doc.xpath(%Q{/doxygen/compounddef/basecompoundref[@prot="#{access}"]}).map { |t| 	Doxyparser::Type.new(name: t.child.content, dir: @dir) }
    end

    def init_attributes
  		super
  		@file = init_file
  		@friends = init_friends
  		@template_params = init_template_params
  	end

    def init_file
      n = doc.xpath("/doxygen/compounddef/includes")[0]
      return n ? HFile.new(dir: @dir, node: n) : nil
    end

    def init_friends
      lst=doc.xpath(%Q{/doxygen/compounddef/sectiondef[@kind="friend"]/memberdef[@kind="friend"]})
      lst.map { |node|
        Doxyparser::Friend.new(parent: self, node: node)
      }
    end

    def init_template_params
      params=doc.xpath(%Q{/doxygen/compounddef/templateparamlist/param})
      params.map { |param|
        Doxyparser::Param.new(parent: self, node: param)
      }
    end
  end
end


text:
class Society < ActiveRecord::Base
  has_many :joins
  has_many :events
  has_many :bearers
  has_many :members, through: :joins
  has_and_belongs_to_many :groups

  accepts_nested_attributes_for :joins, allow_destroy: true,
                      reject_if: proc { |attributes| attributes['role'].blank? }

  has_attached_file :logo, styles: { medium: "200x200>", small: "150x150>" },
                  default_url: "/images/missing_:style.png",
                  preserve_files: true

  validates_attachment_content_type :logo, content_type: ['image/jpeg', 'image/jpg', 'image/png']
  validates_attachment_size :logo, :less_than => 4.megabytes

  validates :name, length: { maximum: 30 }, presence: true, uniqueness: { case_sensitive: false }
  validates :register_num, length: { is: 8 }, numericality: { only_integer: true }
  validates :description, length: { maximum: 500 }
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PasswordStrength_PasswordStrength : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {
    }
}


text:
%
% Usage: [W [optim]]=mexFistaGraph(Y,X,W0,graph,param);
%
% Name: mexFistaGraph
%
% Description: mexFistaGraph solves sparse regularized problems.
%         X is a design matrix of size m x p
%         X=[x^1,...,x^n]', where the x_i's are the rows of X
%         Y=[y^1,...,y^n] is a matrix of size m x n
%         It implements the algorithms FISTA, ISTA and subgradient descent.
%
%         It implements the algorithms FISTA, ISTA and subgradient descent for solving
%
%           min_W  loss(W) + lambda psi(W)
%
%         The function psi are those used by mexProximalGraph (see documentation)
%         for the loss functions, see the documentation of mexFistaFlat
%
%         This function can also handle intercepts (last row of W is not regularized),
%         and/or non-negativity constraints on W.
%
% Inputs: Y:  double dense m x n matrix
%         X:  double dense or sparse m x p matrix
%         W0:  double dense p x n matrix or p x Nn matrix (for multi-logistic loss)
%              initial guess
%         graph: struct (see documentation of mexProximalGraph)
%         param: struct
%            param.loss (choice of loss, see above)
%            param.regul (choice of regularization, see function mexProximalFlat)
%            param.lambda (regularization parameter)
%            param.lambda2 (optional, regularization parameter, 0 by default)
%            param.lambda3 (optional, regularization parameter, 0 by default)
%            param.verbose (optional, verbosity level, false by default)
%            param.pos (optional, adds positivity constraints on the
%                coefficients, false by default)
%            param.numThreads (optional, number of threads for exploiting
%                multi-core / multi-cpus. By default, it takes the value -1,
%                which automatically selects all the available CPUs/cores).
%            param.max_it (optional, maximum number of iterations, 100 by default)
%            param.it0 (optional, frequency for computing duality gap, every 10 iterations by default)
%            param.tol (optional, tolerance for stopping criteration, which is a relative duality gap
%                if it is available, or a relative change of parameters).
%            param.gamma (optional, multiplier for increasing the parameter L in fista, 1.5 by default)
%            param.L0 (optional, initial parameter L in fista, 0.1 by default, should be small enough)
%            param.fixed_step (deactive the line search for L in fista and use param.L0 instead)
%            param.compute_gram (optional, pre-compute X^TX, false by default).
%            param.intercept (optional, do not regularize last row of W, false by default).
%            param.ista (optional, use ista instead of fista, false by default).
%            param.subgrad (optional, if not param.ista, use subradient descent instead of fista, false by default).
%            param.a, param.b (optional, if param.subgrad, the gradient step is a/(t+b)
%            also similar options as mexProximalTree
%
%            the function also implements the ADMM algorithm via an option param.admm=true. It is not documented
%            and you need to look at the source code to use it.
%
%
% Output:  W:  double dense p x n matrix or p x Nn matrix (for multi-logistic loss)
%          optim: optional, double dense 4 x n matrix.
%              first row: values of the objective functions.
%              third row: values of the relative duality gap (if available)
%              fourth row: number of iterations
%
% Author: Julien Mairal, 2010


text:
package exprest.test.unit.resource;

import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;

import test.exprest.module.system.resources.SystemResource;
import exprest.test.core.TestResourceFactory;

public class SystemResourceTest {

   @Test
   public void testUser() {
//      SystemResource r = TestResourceFactory.getResource(SystemResource.class);
//      Assert.assertEquals(r.user().getName(), "joel");
//
//      Reporter.log("The logged in user is " + r.user().getName());
   }

   @Test
   public void testAuthorities() {
//      SystemResource r = TestResourceFactory.getResource(SystemResource.class);
//      Assert.assertEquals(r.user().getAuthorities().size(), 1);
   }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:zstack="http://zstack.org/schema/zstack"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     	 http://zstack.org/schema/zstack
         http://zstack.org/schema/zstack/plugin.xsd"
       default-init-method="init" default-destroy-method="destory">

	<bean id="VolumeSnapshotKvmSimulator" class="org.zstack.simulator.kvm.VolumeSnapshotKvmSimulator" />

	<bean id="KVMSimulatorConfig" class="org.zstack.simulator.kvm.KVMSimulatorConfig" />

	<bean id="KVMStartVmExtension" class="org.zstack.test.kvm.KVMStartVmExtension">
		<zstack:plugin>
			<zstack:extension interface="org.zstack.kvm.KVMStartVmExtensionPoint" />
		</zstack:plugin>
	</bean>

	<bean id="KVMStopVmExtension" class="org.zstack.test.kvm.KVMStopVmExtension">
		<zstack:plugin>
			<zstack:extension interface="org.zstack.kvm.KVMStopVmExtensionPoint" />
		</zstack:plugin>
	</bean>

	<bean id="KVMRebootVmExtension" class="org.zstack.test.kvm.KVMRebootVmExtension">
		<zstack:plugin>
			<zstack:extension interface="org.zstack.kvm.KVMRebootVmExtensionPoint" />
		</zstack:plugin>
	</bean>

	<bean id="KVMDestroyVmExtension" class="org.zstack.test.kvm.KVMDestroyVmExtension">
		<zstack:plugin>
			<zstack:extension interface="org.zstack.kvm.KVMDestroyVmExtensionPoint" />
		</zstack:plugin>
	</bean>
</beans>


text:
var helpers = require('./helpers'),
    path = require('path'),
    fs = require('fs'),
    shell = require('shelljs'),
    Q = require('q'),
    events = require('../src/cordova/events'),
    cordova = require('../src/cordova/cordova');

var tmpDir = helpers.tmpDir('plugin_test');
var project = path.join(tmpDir, 'project');
var pluginsDir = path.join(__dirname, 'fixtures', 'plugins');
var pluginId = 'org.apache.cordova.fakeplugin1';

describe('plugin end-to-end', function() {
    var results;

    beforeEach(function() {
        shell.rm('-rf', project);
    });
    afterEach(function() {
        process.chdir(path.join(__dirname, '..'));  // Needed to rm the dir on Windows.
        shell.rm('-rf', tmpDir);
    });

    // The flow tested is: ls, add, ls, rm, ls.
    // Plugin dependencies are not tested as that should be corvered in plugman tests.
    // TODO (kamrik): Test the 'plugin search' command.
    it('should successfully run', function(done) {
        // cp then mv because we need to copy everything, but that means it'll copy the whole directory.
        // Using /* doesn't work because of hidden files.
        shell.cp('-R', path.join(__dirname, 'fixtures', 'base'), tmpDir);
        shell.mv(path.join(tmpDir, 'base'), project);
        // Copy some platform to avoid working on a project with no platforms.
        shell.cp('-R', path.join(__dirname, 'fixtures', 'platforms', helpers.testPlatform), path.join(project, 'platforms'));
        process.chdir(project);

        events.on('results', function(res) { results = res; });

        // Check there are no plugins yet.
        cordova.raw.plugin('list').then(function() {
            expect(results).toMatch(/No plugins added/gi);
        }).then(function() {
            // Add a fake plugin from fixtures.
            return cordova.raw.plugin('add', path.join(pluginsDir, 'fake1'));
        }).then(function() {
           expect(path.join(project, 'plugins', pluginId, 'plugin.xml')).toExist();
        }).then(function() {
            return cordova.raw.plugin('ls');
        }).then(function() {
            expect(results).toContain(pluginId);
        }).then(function() {
            // And now remove it.
            return cordova.raw.plugin('rm', pluginId);
        }).then(function() {
            // The whole dir should be gone.
            expect(path.join(project, 'plugins', pluginId)).not.toExist();
        }).then(function() {
            return cordova.raw.plugin('ls');
        }).then(function() {
            expect(results).toMatch(/No plugins added/gi);
        }).fail(function(err) {
            console.log(err);
            expect(err).toBeUndefined();
        }).fin(done);
    });
});


text:
package com.navercorp.pinpoint.grpc;

/**
 * @author jaehong.kim
 */
public interface StatusError {

    boolean isSimpleError();

    String getMessage();

    Throwable getThrowable();
}


text:
//
//  SKRightSideViewController.m
//  Skim
//
//  Created by Christiaan Hofman on 3/28/10.

#import "SKRightSideViewController.h"
#import "SKMainWindowController.h"
#import "SKMainWindowController_Actions.h"
#import "SKMainWindowController_UI.h"
#import "NSMenu_SKExtensions.h"
#import "NSSegmentedControl_SKExtensions.h"
#import "SKTypeSelectHelper.h"
#import "SKNoteOutlineView.h"
#import "NSColor_SKExtensions.h"

#define COLOR_COLUMNID @"color"

@implementation SKRightSideViewController

@synthesize noteArrayController, noteOutlineView, snapshotArrayController, snapshotTableView;

- (void)dealloc {
    [snapshotTableView setDelegate:nil];
    [snapshotTableView setDataSource:nil];
    [noteOutlineView setDelegate:nil];
    [noteOutlineView setDataSource:nil];
    SKDESTROY(noteArrayController);
    SKDESTROY(snapshotArrayController);
    SKDESTROY(noteOutlineView);
    SKDESTROY(snapshotTableView);
    [super dealloc];
}

- (NSString *)nibName {
    return @"RightSideView";
}

- (void)loadView {
    [super loadView];

    [button setToolTip:NSLocalizedString(@"View Notes", @"Tool tip message") forSegment:SKNoteSidePaneState];
    [button setToolTip:NSLocalizedString(@"View Snapshots", @"Tool tip message") forSegment:SKSnapshotSidePaneState];

    NSMenu *menu = [NSMenu menu];
    [menu addItemWithTitle:NSLocalizedString(@"Ignore Case", @"Menu item title") action:@selector(toggleCaseInsensitiveNoteSearch:) target:mainController];
    [[searchField cell] setSearchMenuTemplate:menu];
    [[searchField cell] setPlaceholderString:NSLocalizedString(@"Search", @"placeholder")];

    [noteOutlineView setAutoresizesOutlineColumn: NO];

    [noteOutlineView setDelegate:mainController];
    [noteOutlineView setDataSource:mainController];
    [snapshotTableView setDelegate:mainController];
    [snapshotTableView setDataSource:mainController];
    [[noteOutlineView menu] setDelegate:mainController];
    [[snapshotTableView menu] setDelegate:mainController];

    [noteOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];

    [snapshotTableView setBackgroundColor:[NSColor mainSourceListBackgroundColor]];
}

@end


text:
#ifndef QUICKSTEP_EXPRESSIONS_STREAM_GENERATOR_GENERATE_SERIES_HANDLE_HPP_
#define QUICKSTEP_EXPRESSIONS_STREAM_GENERATOR_GENERATE_SERIES_HANDLE_HPP_

#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>

#include "expressions/stream_generator/GeneratorFunctionHandle.hpp"
#include "types/DatetimeLit.hpp"
#include "types/IntervalLit.hpp"
#include "types/Type.hpp"
#include "types/TypeID.hpp"
#include "types/TypedValue.hpp"
#include "types/containers/ColumnVector.hpp"
#include "types/containers/ColumnVectorsValueAccessor.hpp"
#include "utility/Macros.hpp"

#include "glog/logging.h"

namespace quickstep {

/** \addtogroup Expressions
 *  @{
 */

/**
 * @brief Handle for the instantiated GenerateSeries function.
 */
class GenerateSeriesHandle : public GeneratorFunctionHandle {
 public:
  int getNumberOfOutputColumns() const override {
    return 1;
  }

  const std::string getOutputColumnName(int index) const override {
    if (index > 0) {
      LOG(FATAL) << "generate_series function has only 1 output column";
    }
    // Use the function name as the column name.
    return getName();
  }

  const Type& getOutputColumnType(int index) const override {
    if (index > 0) {
      LOG(FATAL) << "generate_series function has only 1 output column";
    }
    return type_;
  }

  std::size_t getEstimatedCardinality() const override {
    switch (type_.getTypeID()) {
      case TypeID::kInt: {
        return estimateCardinality<int>();
      }
      case TypeID::kLong: {
        return estimateCardinality<std::int64_t>();
      }
      case TypeID::kFloat: {
        return estimateCardinality<float>();
      }
      case TypeID::kDouble: {
        return estimateCardinality<double>();
      }
      default:
        LOG(FATAL) << "GenerateSeries cannot handle arguments with type "
                   << type_.getName();
    }
    return 0;
  }

  void populateColumns(ColumnVectorsValueAccessor *results) const override {
    DCHECK(results != nullptr);

    // Generate the output column.
    NativeColumnVector *result_vec;
    switch (type_.getTypeID()) {
      case TypeID::kInt: {
        result_vec = generateColumn<int>();
        break;
      }
      case TypeID::kLong: {
        result_vec = generateColumn<std::int64_t>();
        break;
      }
      case TypeID::kFloat: {
        result_vec = generateColumn<float>();
        break;
      }
      case TypeID::kDouble: {
        result_vec = generateColumn<double>();
        break;
      }
      default:
        // Should not reach here -- type checking should be done inside
        // GenerateSeries::createHandle() at query compile time.
        LOG(FATAL) << "GenerateSeries cannot handle arguments with type "
                   << type_.getName();
    }
    // Add the output column into the ColumnVectorsValueAccessor container.
    results->addColumn(result_vec);
  }

  ColumnVector* generateColumn() const override {
    switch (type_.getTypeID()) {
      case TypeID::kInt:
        return generateColumn<int>();
      case TypeID::kLong:
        return generateColumn<std::int64_t>();
      case TypeID::kFloat:
        return generateColumn<float>();
      case TypeID::kDouble:
        return generateColumn<double>();
      case TypeID::kDatetime:
        return generateDatetimeColumn();
      default:
        // Should not reach here -- type checking should be done inside
        // GenerateSeries::createHandle() at query compile time.
        LOG(FATAL) << "GenerateSeries cannot handle arguments with type "
                   << type_.getName();
    }
  }

 private:
  /**
   * @brief Constructor. A GenerateSeriesHandle object should only be
   *        instantiated inside method GenerateSeries::createHandle().
   *
   * @param func_name The registered name of the GenerateSeries function.
   * @param orig_args The original constant arguments to this function
   * @param type The unified type for the arguments.
   * @param start The start value. Its type should equal unified_type.
   * @param end The end value. Its type should equal unified_type.
   * @param step The step size. Its type should equal unified_type.
   */
  GenerateSeriesHandle(const std::string &func_name,
                       const std::vector<TypedValue> &orig_args,
                       const Type &unified_type,
                       const TypedValue &start,
                       const TypedValue &end,
                       const TypedValue &step)
      : GeneratorFunctionHandle(func_name, orig_args),
        type_(unified_type),
        start_(start),
        end_(end),
        step_(step) {
  }

  template <typename T>
  NativeColumnVector* generateColumn() const {
    T start = start_.getLiteral<T>();
    T end = end_.getLiteral<T>();
    T step = step_.getLiteral<T>();

    DCHECK_NE(step, static_cast<T>(0));
    std::size_t length = static_cast<std::size_t>((end - start) / step + 1);
    DCHECK_GE(length, static_cast<std::size_t>(0));

    NativeColumnVector *result_vec = new NativeColumnVector(type_, length);
    T value = start;
    for (std::size_t i = 0; i < length; ++i) {
      result_vec->appendUntypedValue(&value);
      value += step;
    }
    return result_vec;
  }

  NativeColumnVector* generateDatetimeColumn() const {
    const std::int64_t start = start_.getLiteral<DatetimeLit>().ticks;
    const std::int64_t end = end_.getLiteral<DatetimeLit>().ticks;
    const std::int64_t step = step_.getLiteral<DatetimeIntervalLit>().interval_ticks;

    DCHECK_NE(0, step);
    std::size_t length = (end - start) / step + 1;
    DCHECK_LE(0, length);

    NativeColumnVector *result_vec = new NativeColumnVector(type_, length);
    std::int64_t value = start;
    for (std::size_t i = 0; i < length; ++i) {
      result_vec->appendUntypedValue(&value);
      value += step;
    }

    return result_vec;
  }

  template <typename T>
  std::size_t estimateCardinality() const {
    T step = step_.getLiteral<T>();
    DCHECK_NE(step, static_cast<T>(0));
    return static_cast<std::size_t>(
        (end_.getLiteral<T>() - start_.getLiteral<T>()) / step + 1);
  }

  const Type &type_;
  const TypedValue start_;
  const TypedValue end_;
  const TypedValue step_;

  friend class GenerateSeries;

  DISALLOW_COPY_AND_ASSIGN(GenerateSeriesHandle);
};

/** @} */

}  // namespace quickstep

#endif  // QUICKSTEP_EXPRESSIONS_STREAM_GENERATOR_GENERATE_SERIES_HANDLE_HPP_


text:
<xsd:schema
xmlns:cite="http://www.opengeospatial.net/cite"
xmlns:gml="http://www.opengis.net/gml/3.2"
xmlns:tows='<?php echo base_url(); ?>'
xmlns:wfs="http://www.opengis.net/wfs/2.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace='<?php echo base_url(); ?>'
>

<xsd:import namespace='http://www.opengis.net/gml'
schemaLocation='http://schemas.opengis.net/gml/3.2.1/gml.xsd'/>

<xsd:complexType name="hydro_siteType">
    <xsd:complexContent>
        <xsd:extension base="gml:AbstractFeatureType">
            <xsd:sequence>
                <xsd:element name ='site_id' type='int' nillable='false' minOccurs='1' maxOccurs='1'/>
                <xsd:element name ='name' nillable='true' minOccurs='0' maxOccurs='1'>
                    <xsd:simpleType>
                        <xsd:restriction base='string'><xsd:maxLength value='80'/></xsd:restriction>
                    </xsd:simpleType>
                </xsd:element>
                <xsd:element name ='lon' type='double' nillable='true' minOccurs='0' maxOccurs='1'/>
                <xsd:element name ='lat' type='double' nillable='true' minOccurs='0' maxOccurs='1'/>
                <xsd:element name ='waterml2url' nillable='false' minOccurs='1' maxOccurs='1'/>
                <xsd:element name ='watermlurl' nillable='false' minOccurs='1' maxOccurs='1'/>
                <xsd:element name ='graphurl' nillable='false' minOccurs='0' maxOccurs='1'/>
                <xsd:element name ='downloadurl' nillable='false' minOccurs='0' maxOccurs='1'/>
                <xsd:element name ='begindate' nillable='false' minOccurs='1' maxOccurs='1'/>
                <xsd:element name ='enddate' nillable='false' minOccurs='0' maxOccurs='1'/>
                <xsd:element name ='descriptor' nillable='false' minOccurs='0' maxOccurs='1'/>
                <xsd:element name ='source' nillable='false' minOccurs='0' maxOccurs='1'/>
                <xsd:element name ='geom' type='gml:PointPropertyType' nillable='true' minOccurs='0' maxOccurs='1'/>
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

<xsd:element name='hydro_site' type='tows:hydro_siteType' substitutionGroup='gml:AbstractFeature'/>

</xsd:schema>


text:
"""
Dataframe exchange protocol implementation.

See more in https://data-apis.org/dataframe-protocol/latest/index.html.

Notes
-----
- Interpreting a raw pointer (as in ``Buffer.ptr``) is annoying and unsafe to
  do in pure Python. It's more general but definitely less friendly than having
  ``to_arrow`` and ``to_numpy`` methods. So for the buffers which lack
  ``__dlpack__`` (e.g., because the column dtype isn't supported by DLPack),
  this is worth looking at again.
"""

import collections
from typing import Any, Dict, Optional, Iterable, Sequence
import numpy as np

from modin.core.dataframe.base.interchange.dataframe_protocol.dataframe import (
    ProtocolDataframe,
)
from modin.core.dataframe.pandas.dataframe.dataframe import PandasDataframe
from modin.utils import _inherit_docstrings
from .column import PandasProtocolColumn

@_inherit_docstrings(ProtocolDataframe)
class PandasProtocolDataframe(ProtocolDataframe):
    """
    A data frame class, with only the methods required by the interchange protocol defined.

    Instances of this (private) class are returned from ``modin.pandas.DataFrame.__dataframe__``
    as objects with the methods and attributes defined on this class.

    A "data frame" represents an ordered collection of named columns.
    A column's "name" must be a unique string. Columns may be accessed by name or by position.
    This could be a public data frame class, or an object with the methods and
    attributes defined on this DataFrame class could be returned from the
    ``__dataframe__`` method of a public data frame class in a library adhering
    to the dataframe interchange protocol specification.

    Parameters
    ----------
    df : PandasDataframe
        A ``PandasDataframe`` object.
    nan_as_null : bool, default:False
        A keyword intended for the consumer to tell the producer
        to overwrite null values in the data with ``NaN`` (or ``NaT``).
        This currently has no effect; once support for nullable extension
        dtypes is added, this value should be propagated to columns.
    allow_copy : bool, default: True
        A keyword that defines whether or not the library is allowed
        to make a copy of the data. For example, copying data would be necessary
        if a library supports strided buffers, given that this protocol
        specifies contiguous buffers. Currently, if the flag is set to ``False``
        and a copy is needed, a ``RuntimeError`` will be raised.
    """

    def __init__(
        self,
        df: PandasDataframe,
        nan_as_null: bool = False,
        allow_copy: bool = True,
    ) -> None:
        self._df = df
        self._nan_as_null = nan_as_null
        self._allow_copy = allow_copy

    def __dataframe__(self, nan_as_null: bool = False, allow_copy: bool = True):
        return PandasProtocolDataframe(
            self._df, nan_as_null=nan_as_null, allow_copy=allow_copy
        )

    @property
    def metadata(self) -> Dict[str, Any]:
        return {"modin.index": self._df.index}

    def num_columns(self) -> int:
        return len(self._df.columns)

    def num_rows(self) -> int:
        return len(self._df.index)

    def num_chunks(self) -> int:
        return self._df._partitions.shape[0]

    def column_names(self) -> Iterable[str]:
        for col in self._df.columns:
            yield col

    def get_column(self, i: int) -> PandasProtocolColumn:
        return PandasProtocolColumn(
            self._df.take_2d_labels_or_positional(
                row_positions=None, col_positions=[i]
            ),
            allow_copy=self._allow_copy,
        )

    def get_column_by_name(self, name: str) -> PandasProtocolColumn:
        return PandasProtocolColumn(
            self._df.take_2d_labels_or_positional(
                row_positions=None, col_labels=[name]
            ),
            allow_copy=self._allow_copy,
        )

    def get_columns(self) -> Iterable[PandasProtocolColumn]:
        for name in self._df.columns:
            yield PandasProtocolColumn(
                self._df.take_2d_labels_or_positional(
                    row_positions=None, col_labels=[name]
                ),
                allow_copy=self._allow_copy,
            )

    def select_columns(self, indices: Sequence[int]) -> "PandasProtocolDataframe":
        if not isinstance(indices, collections.abc.Sequence):
            raise ValueError("`indices` is not a sequence")

        return PandasProtocolDataframe(
            self._df.take_2d_labels_or_positional(
                row_positions=None, col_positions=indices
            ),
            allow_copy=self._allow_copy,
        )

    def select_columns_by_name(self, names: Sequence[str]) -> "PandasProtocolDataframe":
        if not isinstance(names, collections.abc.Sequence):
            raise ValueError("`names` is not a sequence")

        return PandasProtocolDataframe(
            self._df.take_2d_labels_or_positional(row_positions=None, col_labels=names),
            allow_copy=self._allow_copy,
        )

    def get_chunks(
        self, n_chunks: Optional[int] = None
    ) -> Iterable["PandasProtocolDataframe"]:
        cur_n_chunks = self.num_chunks()
        n_rows = self.num_rows()
        if n_chunks is None or n_chunks == cur_n_chunks:
            cum_row_lengths = np.cumsum([0] + self._df.row_lengths)
            for i in range(len(cum_row_lengths) - 1):
                yield PandasProtocolDataframe(
                    self._df.take_2d_labels_or_positional(
                        row_positions=range(cum_row_lengths[i], cum_row_lengths[i + 1]),
                        col_positions=None,
                    ),
                    allow_copy=self._allow_copy,
                )
            return
        if n_chunks % cur_n_chunks != 0:
            raise RuntimeError(
                "The passed `n_chunks` must be a multiple of `self.num_chunks()`."
            )

        if n_chunks > n_rows:
            raise RuntimeError(
                "The passed `n_chunks` value is bigger than `self.num_rows()`."
            )

        chunksize = n_rows // n_chunks
        new_lengths = [chunksize] * n_chunks
        new_lengths[-1] = n_rows % n_chunks + new_lengths[-1]

        new_partitions = self._df._partition_mgr_cls.map_axis_partitions(
            0,
            self._df._partitions,
            lambda df: df,
            keep_partitioning=False,
            lengths=new_lengths,
        )
        new_df = self._df.__constructor__(
            new_partitions,
            self._df.index,
            self._df.columns,
            new_lengths,
            self._df.column_widths,
        )
        cum_row_lengths = np.cumsum([0] + new_df.row_lengths)
        for i in range(len(cum_row_lengths) - 1):
            yield PandasProtocolDataframe(
                new_df.take_2d_labels_or_positional(
                    row_positions=range(cum_row_lengths[i], cum_row_lengths[i + 1]),
                    col_positions=None,
                ),
                allow_copy=self._allow_copy,
            )


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Just A Programmer LLC")]
[assembly: AssemblyProduct("AppDomainPowershellRunner")]
[assembly: AssemblyCopyright("Copyright © Just A Programmer LLC 2011-2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: AssemblyVersion("0.9.*")]


text:
namespace libmv {

//
// A pinhole camera model
//
// Equation of the projection of a 3D point in the camera frame:
//  s x = K [ R | t ] X
// where
//  X is the homogeneous 3D point
//  K is the calibration matrix with the intrinsic parameters.
//  R is the orientation of the camera expressed in a world coordinate frame
//  t is the position of the camera expressed in a world coordinate frame
//  x is the 2D projection (pixel) of the homogeneous point X
//    in the camera frame
//  s is a 2D scale factor
//                             [ focal_x skew_factor principal_point_x]
//  K can be decomposed in K = [    0      focal_y   principal_point_y]
//                             [    0        0              1         ]
//  where
//    focal_x and focal_y are the camera focal (in pixels) along x and y axis
//    principal_point_x and principal_point_y are the coordinate of the
//      principal point (in pixels) expressed in the camera frame
//
class PinholeCamera : public Camera {
 public:
  PinholeCamera();
  PinholeCamera(const Mat34  &P);
  PinholeCamera(const Mat3  &R, const Vec3  &t);
  PinholeCamera(const Mat3  &K, const Mat3  &R, const Vec3  &t);
  PinholeCamera(double focal, const Vec2 &principal_point);
  virtual ~PinholeCamera();

  // The function computes the projection of a 3D point
  virtual bool ProjectPointStructure(const PointStructure &point_structure,
                                     PointFeature *feature) const;
  // The function computes the projection of a 3D point
  virtual bool ProjectPointStructure(const PointStructure &point_structure,
                                     Vec2 *q) const;

  // TODO(julien) A visibility test for a structure

  // The function returns the ray direction of a pixel
  virtual Vec3 Ray(const Vec2f &pixel) {
    return Vec3(pixel.x(), pixel.y(), -focal_x_);
  }

  PinholeCamera(const PinholeCamera &camera);

  const Mat34 &projection_matrix() const  { return projection_matrix_; }
  const Mat3 &intrinsic_matrix() const    { return intrinsic_matrix_; }
  const Mat3 &orientation_matrix() const  { return orientation_matrix_; }
  const Vec3 &position() const            { return position_; }

  double focal_x() const                  { return focal_x_; }
  double focal_y() const                  { return focal_y_; }
  double skew_factor() const              { return skew_factor_; }
  const Vec2 &principal_point() const     { return principal_point_; }
  const Vec2u &image_size() const          { return image_size_; }
  uint image_width() const          { return image_size_(0); }
  uint image_height() const          { return image_size_(1); }

  void set_projection_matrix(const Mat34 & p) {
    projection_matrix_ = p;
    // scale K so that K(2,2) = 1
    KRt_From_P(projection_matrix_,
               &intrinsic_matrix_,
               &orientation_matrix_,
               &position_);
    focal_x_            = intrinsic_matrix_(0, 0);
    focal_y_            = intrinsic_matrix_(1, 1);
    skew_factor_        = intrinsic_matrix_(0, 1);
    principal_point_(0) = intrinsic_matrix_(0, 2);
    principal_point_(1) = intrinsic_matrix_(1, 2);
  }

  void set_intrinsic_matrix(const Mat3 &intrinsic_matrix) {
    intrinsic_matrix_   = intrinsic_matrix;
    focal_x_            = intrinsic_matrix_(0, 0);
    focal_y_            = intrinsic_matrix_(1, 1);
    skew_factor_        = intrinsic_matrix_(0, 1);
    principal_point_(0) = intrinsic_matrix_(0, 2);
    principal_point_(1) = intrinsic_matrix_(1, 2);

    CHECK(intrinsic_matrix_(1, 0) == 0 &&
          intrinsic_matrix_(2, 0) == 0 &&
          intrinsic_matrix_(2, 1) == 0);

    UpdateProjectionMatrix();
  }

  void set_orientation_matrix(const Mat3 &orientation_matrix) {
    orientation_matrix_ = orientation_matrix;
    UpdateProjectionMatrix();
  }
  void set_position(const Vec3 &position) {
    position_ = position;
    UpdateProjectionMatrix();
  }
  // TODO(julien) clean the code: avoid to have SetXXX and set_XXX
  void SetExtrinsicParameters(const Mat3 &orientation_matrix,
                              const Vec3 &position) {
    orientation_matrix_ = orientation_matrix;
    position_ = position;
    UpdateProjectionMatrix();
  }
  void SetIntrinsicParameters(double focal, const Vec2 &principal_point) {
    focal_x_ = focal;
    focal_y_ = focal;
    principal_point_ = principal_point;
    UpdateIntrinsicMatrix();
    UpdateProjectionMatrix();
  }
  void SetIntrinsicExtrinsicParameters(const Mat3 &intrinsic_matrix,
                                       const Mat3 &orientation_matrix,
                                       const Vec3 &position) {
    intrinsic_matrix_   = intrinsic_matrix;
    focal_x_ = intrinsic_matrix_(0, 0);
    focal_y_ = intrinsic_matrix_(1, 1);
    principal_point_ << intrinsic_matrix_(0, 2), intrinsic_matrix_(1, 2);
    orientation_matrix_ = orientation_matrix;
    position_ = position;
    UpdateProjectionMatrix();
  }
  void GetIntrinsicExtrinsicParameters(Mat3 *intrinsic_matrix,
                                       Mat3 *orientation_matrix,
                                       Vec3 *position) {
    *intrinsic_matrix   = intrinsic_matrix_;
    *orientation_matrix = orientation_matrix_;
    *position = position_;
  }
  const Mat34 GetPoseMatrix() const  {
    Mat34 P;
    P.block<3, 3>(0, 0) = orientation_matrix_;
    P.col(3) = position_;
    return P;
  }
  void SetFocal(double focal) {
    focal_x_ = focal;
    focal_y_ = focal;
    UpdateIntrinsicMatrix();
    UpdateProjectionMatrix();
  }
  void SetFocal(double focal_x, double focal_y) {
    focal_x_ = focal_x;
    focal_y_ = focal_y;
    UpdateIntrinsicMatrix();
    UpdateProjectionMatrix();
  }
  void set_principal_point(const Vec2 &principal_point) {
    principal_point_ = principal_point;
    UpdateIntrinsicMatrix();
    UpdateProjectionMatrix();
  }
  void set_skew_factor(double skew_factor) {
    skew_factor_ = skew_factor;
    UpdateIntrinsicMatrix();
    UpdateProjectionMatrix();
  }
  // Sets the image size (width, height)
  void set_image_size(const Vec2u &size) {
    image_size_ = size;
  }

 private:
  void UpdateProjectionMatrix();
  void UpdateIntrinsicMatrix();

  Mat34 projection_matrix_;
  Mat3  intrinsic_matrix_;
  Mat3  orientation_matrix_;
  Vec3  position_;

  double  focal_x_;
  double  focal_y_;
  Vec2    principal_point_;
  double  skew_factor_;
  // Contains the image size (width, height)
  Vec2u    image_size_;
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

// The class models a pinhole camera model with radial and/or tangential
// distortion.
class PinholeCameraDistortion : public PinholeCamera {
 public:
  PinholeCameraDistortion(LensDistortion *lens_distortion = NULL);
  PinholeCameraDistortion(const Mat3 &K,
                          const Mat3 &R,
                          const Vec3 &t,
                          LensDistortion *lens_distortion);
  PinholeCameraDistortion(const Mat3 &R,
                          const Vec3 &t,
                          LensDistortion *lens_distortion);

  PinholeCameraDistortion(const PinholeCameraDistortion &camera);

  // The function computes the projection of a 3D point
  virtual bool ProjectPointStructure(const PointStructure &point_structure,
                                     PointFeature *feature) const;

  // The function computes the undistorted feature using the camera distorsion
  // model
  virtual void ComputeUndistortedFeature(const Feature &feature,
                                         Feature *undistorted_feature) const;

  // The function undistort the feature using the camera distorsion model
  virtual void UndistortFeature(Feature *feature) const;

  void ComputeUndistortedCoordinates(const Vec2 &point,
                                     Vec2 *undistorted_point) const;
  void ComputeDistortedCoordinates(const Vec2 &point,
                                   Vec2 *distorted_point) const;

  const LensDistortion *lens_distortion() const {
    return lens_distortion_;
  }

  void set_lens_distortion(LensDistortion *lens_distortion) {
    lens_distortion_ = lens_distortion;
  }

 private:
  LensDistortion *lens_distortion_;
};

}  // namespace libmv

#endif  // LIBMV_CAMERA_PINHOLE_CAMERA_H_


text:
package io.xlate.edi.internal.stream.json;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.ArrayDeque;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Logger;

import io.xlate.edi.internal.stream.Configurable;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.schema.EDISimpleType.Base;
import io.xlate.edi.stream.EDIInputFactory;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamException;
import io.xlate.edi.stream.EDIStreamReader;
import io.xlate.edi.stream.EDIValidationException;

abstract class StaEDIJsonParser implements Configurable {

    private static final Logger LOGGER = Logger.getLogger(StaEDIJsonParser.class.getName());

    static final String MSG_EXCEPTION = "Exception reading the EDI stream as JSON";
    static final String MSG_UNEXPECTED = "Unexpected event reached parsing JSON: ";

    static final String KEY_TYPE = "type";
    static final String KEY_NAME = "name";
    static final String KEY_META = "meta";
    static final String KEY_DATA = "data";

    protected final EDIStreamReader ediReader;
    protected final Map<String, Object> properties;
    protected final boolean emptyElementsNull;
    protected final boolean elementsAsObject;

    final Queue<Event> eventQueue = new ArrayDeque<>();
    final Queue<String> valueQueue = new ArrayDeque<>();

    final DecimalFormat decimalParser = new DecimalFormat();
    final ParsePosition decimalPosition = new ParsePosition(0);

    Event currentEvent;
    String currentValue;
    BigDecimal currentNumber;

    enum Event {
        /**
         * @see jakarta.json.stream.JsonParser.Event#START_ARRAY
         */
        START_ARRAY,
        /**
         * @see jakarta.json.stream.JsonParser.Event#START_OBJECT
         */
        START_OBJECT,
        /**
         * @see jakarta.json.stream.JsonParser.Event#KEY_NAME
         */
        KEY_NAME,
        /**
         * @see jakarta.json.stream.JsonParser.Event#VALUE_STRING
         */
        VALUE_STRING,
        /**
         * @see jakarta.json.stream.JsonParser.Event#VALUE_NUMBER
         */
        VALUE_NUMBER,
        /**
         * @see jakarta.json.stream.JsonParser.Event#VALUE_TRUE
         */
        VALUE_TRUE,
        /**
         * @see jakarta.json.stream.JsonParser.Event#VALUE_FALSE
         */
        VALUE_FALSE,
        /**
         * @see jakarta.json.stream.JsonParser.Event#VALUE_NULL
         */
        VALUE_NULL,
        /**
         * @see jakarta.json.stream.JsonParser.Event#END_OBJECT
         */
        END_OBJECT,
        /**
         * @see jakarta.json.stream.JsonParser.Event#END_ARRAY
         */
        END_ARRAY
    }

    @FunctionalInterface
    interface EDIStreamReaderRunner<T> {
        T execute() throws EDIStreamException;
    }

    StaEDIJsonParser(EDIStreamReader ediReader, Map<String, Object> properties) {
        super();
        this.ediReader = ediReader;
        this.properties = properties;
        this.emptyElementsNull = getProperty(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, Boolean::parseBoolean, false);
        this.elementsAsObject = getProperty(EDIInputFactory.JSON_OBJECT_ELEMENTS, Boolean::parseBoolean, false);
    }

    protected abstract RuntimeException newJsonException(String message, Throwable cause);

    protected abstract RuntimeException newJsonParsingException(String message, Throwable cause);

    @Override
    public Object getProperty(String name) {
        return properties.get(name);
    }

    <T> T executeWithReader(EDIStreamReaderRunner<T> runner) {
        try {
            return runner.execute();
        } catch (EDIStreamException e) {
            if (e.getCause() instanceof IOException) {
                throw newJsonException(MSG_EXCEPTION, e);
            } else {
                throw newJsonParsingException(MSG_EXCEPTION, e);
            }
        }
    }

    void advanceEvent() {
        currentEvent = eventQueue.remove();
        currentValue = valueQueue.remove();
    }

    void parseNumber(EDISimpleType elementType, String text) {
        if (elementType.getBase() == Base.NUMERIC) {
            final Integer scale = elementType.getScale();
            final long unscaled = Long.parseLong(text);

            this.currentNumber = BigDecimal.valueOf(unscaled, scale);
        } else {
            decimalPosition.setIndex(0);
            decimalParser.setParseBigDecimal(true);

            this.currentNumber = (BigDecimal) decimalParser.parse(text, decimalPosition);
        }
    }

    void enqueue(Event event, String value) {
        eventQueue.add(event);
        valueQueue.add(value != null ? value : "");
    }

    void enqueueStructureBegin(String typeName, String structureName) {
        enqueue(Event.START_OBJECT, null);

        enqueue(Event.KEY_NAME, KEY_NAME);
        enqueue(Event.VALUE_STRING, structureName);

        enqueue(Event.KEY_NAME, KEY_TYPE);
        enqueue(Event.VALUE_STRING, typeName);

        enqueue(Event.KEY_NAME, KEY_DATA);
        enqueue(Event.START_ARRAY, null);
    }

    void enqueueDataElement() {
        EDIReference referencedType = ediReader.getSchemaTypeReference();
        EDISimpleType elementType = null;

        if (referencedType != null) {
            elementType = (EDISimpleType) referencedType.getReferencedType();
        }

        if (elementsAsObject) {
            enqueue(Event.START_OBJECT, null);
            enqueue(Event.KEY_NAME, KEY_TYPE);
            enqueue(Event.VALUE_STRING, "element");
            enqueue(Event.KEY_NAME, KEY_DATA);
        }

        final Event dataEvent;
        final String dataText = ediReader.getText();

        if (dataText.isEmpty() || elementType == null) {
            dataEvent = this.emptyElementsNull ? Event.VALUE_NULL : Event.VALUE_STRING;
        } else if (elementType.getBase() == Base.DECIMAL || elementType.getBase() == Base.NUMERIC) {
            Event numberEvent;

            try {
                parseNumber(elementType, dataText);
                numberEvent = Event.VALUE_NUMBER;
            } catch (Exception e) {
                numberEvent = Event.VALUE_STRING;
            }

            dataEvent = numberEvent;
        } else {
            dataEvent = Event.VALUE_STRING;
        }

        enqueue(dataEvent, dataText);

        if (elementsAsObject) {
            enqueue(Event.END_OBJECT, null);
        }
    }

    void enqueueEvent(EDIStreamEvent ediEvent) {
        LOGGER.finer(() -> "Enqueue EDI event: " + ediEvent);
        currentNumber = null;

        switch (ediEvent) {
        case ELEMENT_DATA:
            enqueueDataElement();
            break;
        case START_INTERCHANGE:
            enqueueStructureBegin("loop", "INTERCHANGE");
            break;
        case START_GROUP:
        case START_TRANSACTION:
        case START_LOOP:
            enqueueStructureBegin("loop", ediReader.getReferenceCode());
            break;
        case START_SEGMENT:
            enqueueStructureBegin("segment", ediReader.getText());
            break;
        case START_COMPOSITE:
            enqueueStructureBegin("composite", ediReader.getReferenceCode());
            break;

        case END_INTERCHANGE:
        case END_GROUP:
        case END_TRANSACTION:
        case END_LOOP:
        case END_SEGMENT:
        case END_COMPOSITE:
            enqueue(Event.END_ARRAY, null);
            enqueue(Event.END_OBJECT, null);
            break;

        case SEGMENT_ERROR:
        case ELEMENT_OCCURRENCE_ERROR:
        case ELEMENT_DATA_ERROR:
            Throwable cause = new EDIValidationException(ediEvent, ediReader.getErrorType(), ediReader.getLocation(), ediReader.getText());
            throw newJsonParsingException("Unhandled EDI validation error", cause);

        default:
            throw new IllegalStateException("Unknown state: " + ediEvent);
        }
    }

    Event nextEvent() {
        if (eventQueue.isEmpty()) {
            LOGGER.finer(() -> "eventQueue is empty, calling ediReader.next()");
            enqueueEvent(executeWithReader(ediReader::next));
        }

        advanceEvent();

        return currentEvent;
    }

    /**
     * @see jakarta.json.stream.JsonLocation#getLineNumber()
     */
    public long getLineNumber() {
        return ediReader.getLocation().getLineNumber();
    }

    /**
     * @see jakarta.json.stream.JsonLocation#getColumnNumber()
     */
    public long getColumnNumber() {
        return ediReader.getLocation().getColumnNumber();
    }

    /**
     * @see jakarta.json.stream.JsonLocation#getStreamOffset()
     */
    public long getStreamOffset() {
        return ediReader.getLocation().getCharacterOffset();
    }

    public void close() {
        try {
            ediReader.close();
        } catch (IOException e) {
            throw newJsonException(MSG_EXCEPTION, e);
        }
    }

    void assertEventValueNumber() {
        final Event current = this.currentEvent;

        if (current != Event.VALUE_NUMBER) {
            throw new IllegalStateException("Unable to get number value for event [" + current + ']');
        }
    }

    void assertEventValueString() {
        final Event current = this.currentEvent;

        switch (current) {
        case KEY_NAME:
        case VALUE_STRING:
        case VALUE_NUMBER:
            break;
        default:
            throw new IllegalStateException("Unable to get string value for event [" + current + ']');
        }
    }

    /**
     * @see jakarta.json.stream.JsonParser#hasNext()
     * @see javax.json.stream.JsonParser#hasNext()
     */
    public boolean hasNext() {
        return !eventQueue.isEmpty() || executeWithReader(ediReader::hasNext);
    }

    /**
     * @see jakarta.json.stream.JsonParser#getBigDecimal()
     */
    public BigDecimal getBigDecimal() {
        assertEventValueNumber();
        return currentNumber;
    }

    /**
     * @see jakarta.json.stream.JsonParser#getInt()
     */
    public int getInt() {
        return (int) getLong();
    }

    /**
     * @see jakarta.json.stream.JsonParser#getLong()
     */
    public long getLong() {
        assertEventValueNumber();
        return currentNumber.longValue();
    }

    /**
     * @see jakarta.json.stream.JsonParser#getString()
     */
    public String getString() {
        assertEventValueString();
        return this.currentValue;
    }

    /**
     * @see jakarta.json.stream.JsonParser#isIntegralNumber()
     */
    public boolean isIntegralNumber() {
        assertEventValueNumber();
        return currentNumber.scale() == 0;
    }

}


text:
package org.kie.server.services.taskassigning.planning;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;
import org.kie.server.api.model.taskassigning.TaskData;
import org.kie.server.services.taskassigning.core.model.Task;
import org.kie.server.services.taskassigning.core.model.TaskAssigningSolution;
import org.kie.server.services.taskassigning.user.system.api.User;
import org.kie.server.services.taskassigning.user.system.api.UserSystemService;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.optaplanner.core.impl.solver.ProblemFactChange;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class SolutionSynchronizerTest extends RunnableBaseTest<SolutionSynchronizer> {

    private static final Duration SYNCH_INTERVAL = Duration.ofMillis(2);
    private static final Duration USERS_SYNCH_INTERVAL = Duration.ofMillis(4000);
    private static final Duration QUERY_SHIFT = Duration.parse("PT2S");
    private static final long SYSTEM_TIME = 0;

    @Mock
    private SolverExecutor solverExecutor;

    @Mock
    private TaskAssigningRuntimeDelegate delegate;

    @Mock
    private UserSystemService userSystemService;

    @Mock
    private Consumer<SolutionSynchronizer.Result> resultConsumer;

    @Captor
    private ArgumentCaptor<TaskAssigningSolution> solutionCaptor;

    @Captor
    private ArgumentCaptor<SolutionSynchronizer.Result> resultCaptor;

    @Mock
    private TaskAssigningSolution generatedSolution;

    @Mock
    private TaskAssigningSolution emptySolution;

    @Mock
    private List<ProblemFactChange<TaskAssigningSolution>> generatedChanges;

    @Mock
    private List<ProblemFactChange<TaskAssigningSolution>> emptyChanges;

    private boolean usersSyncTime;

    private boolean unchangedPeriodTime;

    private CountDownLatch queryExecutionsCountDown;

    private CountDownLatch applyResultCountDown;

    private SolverHandlerContext context;

    @Override
    protected SolutionSynchronizer createRunnableBase() {
        context = new SolverHandlerContext(QUERY_SHIFT);
        applyResultCountDown = new CountDownLatch(1);
        return new SolutionSynchronizerMock(solverExecutor, delegate, userSystemService,
                                            SYNCH_INTERVAL, USERS_SYNCH_INTERVAL, context, resultConsumer);
    }

    @Test(timeout = TEST_TIMEOUT)
    @SuppressWarnings("unchecked")
    public void initSolverExecutor() throws Exception {
        CompletableFuture future = startRunnableBase();
        LocalDateTime firstQueryTime = LocalDateTime.now();

        List<User> userList = mockUserList();
        List<TaskAssigningRuntimeDelegate.FindTasksResult> results = mockTasksQueryExecutions(firstQueryTime);
        LocalDateTime firstSuccessfulQueryTime = results.get(results.size() - 1).getQueryTime();
        queryExecutionsCountDown = new CountDownLatch(results.size());
        prepareQueryExecutions(results);

        when(emptySolution.getTaskList()).thenReturn(Collections.emptyList());
        when(generatedSolution.getTaskList()).thenReturn(Collections.singletonList(new Task()));
        when(solverExecutor.isStopped()).thenReturn(true);
        when(userSystemService.findAllUsers()).thenReturn(userList);

        runnableBase.initSolverExecutor();

        // wait for the query executions to happen
        queryExecutionsCountDown.await();

        verify(delegate, times(results.size())).findTasks(anyList(), eq(null), anyObject());
        verify(solverExecutor).start(solutionCaptor.capture());
        assertEquals(generatedSolution, solutionCaptor.getValue());
        LocalDateTime nextQueryTime = context.shiftQueryTime(firstSuccessfulQueryTime.withNano(0));
        LocalDateTime previousQueryTime = context.shiftQueryTime(nextQueryTime);
        assertEquals(previousQueryTime, context.getPreviousQueryTime());
        assertEquals(nextQueryTime, context.getNextQueryTime());

        runnableBase.destroy();
        future.get();
        assertTrue(runnableBase.isDestroyed());
    }

    @Test(timeout = TEST_TIMEOUT)
    public void synchronizeSolution() throws Exception {
        CompletableFuture future = startRunnableBase();
        LocalDateTime startTime = LocalDateTime.now().withNano(0);
        List<TaskAssigningRuntimeDelegate.FindTasksResult> tasksQueryResults = mockTasksQueryExecutions(startTime);
        int executionsCount = tasksQueryResults.size();

        usersSyncTime = false;
        executeSynchronizeSolution(future, startTime, tasksQueryResults, Collections.emptyList(), executionsCount);

        // all tasks query executions were produced.
        verityTasksQueryExecutions(startTime, tasksQueryResults);
        // no users query executions were produced.
        verify(userSystemService, never()).findAllUsers();
        verify(resultConsumer).accept(resultCaptor.capture());
        assertTrue(resultCaptor.getValue().hasChanges());
        assertEquals(generatedChanges, resultCaptor.getValue().getChanges());
    }

    @Test(timeout = TEST_TIMEOUT)
    public void synchronizeSolutionIncludingUsersSyncWithoutUserChanges() throws Exception {
        CompletableFuture future = startRunnableBase();
        LocalDateTime startTime = LocalDateTime.now().withNano(0);
        List<TaskAssigningRuntimeDelegate.FindTasksResult> tasksQueryResults = mockTasksQueryExecutions(startTime);
        List<List<User>> userQueryResults = mockEmptyQueryExecutions(tasksQueryResults.size(), Collections::emptyList);
        int executionsCount = tasksQueryResults.size();

        usersSyncTime = true;
        executeSynchronizeSolution(future, startTime, tasksQueryResults, userQueryResults, executionsCount);

        // all tasks query executions were produced.
        verityTasksQueryExecutions(startTime, tasksQueryResults);
        // user executions were produced executionsCount-2 times since the tasks queries fails two times.
        verify(userSystemService, times(executionsCount - 2)).findAllUsers();

        assertTrue(resultCaptor.getValue().hasChanges());
        verify(resultConsumer).accept(resultCaptor.capture());
        assertEquals(generatedChanges, resultCaptor.getValue().getChanges());
    }

    @Test(timeout = TEST_TIMEOUT)
    @SuppressWarnings("unchecked")
    public void synchronizeSolutionIncludingUsersSyncWithUserChanges() throws Exception {
        CompletableFuture future = startRunnableBase();
        LocalDateTime startTime = LocalDateTime.now().withNano(0);
        List<TaskAssigningRuntimeDelegate.FindTasksResult> tasksQueryResults = mockTasksQueryExecutions(startTime);
        List<List<User>> userQueryResults = mockUsersQueryExecutions();
        int executionsCount = userQueryResults.size();

        usersSyncTime = true;
        executeSynchronizeSolution(future, startTime, tasksQueryResults, userQueryResults, executionsCount);

        // all user executions was executed, results were produced in last execution.
        verify(userSystemService, times(userQueryResults.size())).findAllUsers();

        /*
        Three task query executions were produced.
        initial setup queryTimes -> [startTime]
        execution0:
            execute query with lastModification = startTime
            execution was ok, but result0 has no results.
            nextQueryTime0 = context.shiftQueryTime(startTime)
        execution1:
            execute query with lastModification = nextQueryTime0
            execution is ok, but result1 has no values.
            nextQueryTime1 = context.shiftQueryTime(result1.getQueryTime())
        execution2:
            execute query with lastModification = nextQueryTime1
            execution is ok, but result2 has no values.
            nextQueryTime2 = context.shiftQueryTime(result2.getQueryTime())
        */

        verify(delegate, times(1)).findTasks(anyList(), eq(startTime), anyObject());
        verify(delegate, times(1)).findTasks(anyList(), eq(context.shiftQueryTime(tasksQueryResults.get(0).getQueryTime())), anyObject());
        verify(delegate, times(1)).findTasks(anyList(), eq(context.shiftQueryTime(tasksQueryResults.get(1).getQueryTime())), anyObject());

        assertEquals(context.shiftQueryTime(tasksQueryResults.get(2).getQueryTime()), context.getNextQueryTime());

        assertTrue(resultCaptor.getValue().hasChanges());
        verify(resultConsumer).accept(resultCaptor.capture());
        assertEquals(generatedChanges, resultCaptor.getValue().getChanges());
    }

    @Test
    public void synchronizeSolutionWithNoChangesTimeout() throws Exception {
        CompletableFuture future = startRunnableBase();
        LocalDateTime startTime = LocalDateTime.now().withNano(0);
        List<TaskAssigningRuntimeDelegate.FindTasksResult> tasksQueryResults = mockNoChangesTasksQueryExecutions(startTime);
        int executionsCount = tasksQueryResults.size();

        unchangedPeriodTime = true;
        executeSynchronizeSolutionWithNoChangesTimeout(future, startTime, Duration.ofMillis(100), tasksQueryResults, executionsCount);

        verify(resultConsumer).accept(resultCaptor.capture());
        assertFalse(resultCaptor.getValue().hasChanges());
        assertNull(resultCaptor.getValue().getChanges());
    }

    @Test
    public void calculateNextUsersSyncTime() {
        long expectedValue = SYSTEM_TIME + 4000;
        calculateNextUsersSyncTime(USERS_SYNCH_INTERVAL, SYSTEM_TIME, expectedValue);
    }

    @Test
    public void calculateNextUnchangedPeriodTime() {
        long expectedValue = SYSTEM_TIME + 5000;
        calculateNextUnchangedPeriodTime(Duration.ofMillis(5000), SYSTEM_TIME, expectedValue);
    }

    private void calculateNextUsersSyncTime(Duration duration, long systemTime, long expectedValue) {
        runnableBase = spy(new SolutionSynchronizer(solverExecutor, delegate, userSystemService,
                                                    SYNCH_INTERVAL, duration, context, resultConsumer));
        doReturn(systemTime).when(runnableBase).getSystemTime();
        long nextUsersSyncTime = runnableBase.calculateNextUsersSyncTime();
        assertEquals(expectedValue, nextUsersSyncTime);
    }

    private void calculateNextUnchangedPeriodTime(Duration duration, long systemTime, long expectedValue) {
        runnableBase = spy(new SolutionSynchronizer(solverExecutor, delegate, userSystemService,
                                                    SYNCH_INTERVAL, duration, context, resultConsumer));
        doReturn(systemTime).when(runnableBase).getSystemTime();
        long nextUnchangedPeriodTime = runnableBase.calculateNextUnchangedPeriodTime(duration);
        assertEquals(expectedValue, nextUnchangedPeriodTime);
    }

    private void executeSynchronizeSolution(CompletableFuture future, LocalDateTime startTime,
                                            List<TaskAssigningRuntimeDelegate.FindTasksResult> tasksQueryResults,
                                            List<List<User>> userQueryResults,
                                            int executionsCount) throws Exception {

        TaskAssigningSolution solution = new TaskAssigningSolution(1, new ArrayList<>(), new ArrayList<>());
        queryExecutionsCountDown = new CountDownLatch(executionsCount);
        prepareQueryExecutions(tasksQueryResults);
        prepareUserQueryExecutions(userQueryResults);

        when(generatedChanges.isEmpty()).thenReturn(false);
        when(emptyChanges.isEmpty()).thenReturn(true);
        when(solverExecutor.isStarted()).thenReturn(true);
        runnableBase.synchronizeSolution(solution, startTime);

        // wait for the query executions to happen
        queryExecutionsCountDown.await();
        applyResultCountDown.await();

        verify(resultConsumer).accept(resultCaptor.capture());
        assertEquals(generatedChanges, resultCaptor.getValue().getChanges());
        runnableBase.destroy();
        future.get();
        assertTrue(runnableBase.isDestroyed());
    }

    private void executeSynchronizeSolutionWithNoChangesTimeout(CompletableFuture future, LocalDateTime startTime,
                                                                Duration unchangedPeriodTimeout,
                                                                List<TaskAssigningRuntimeDelegate.FindTasksResult> tasksQueryResults,
                                                                int executionsCount) throws Exception {

        TaskAssigningSolution solution = new TaskAssigningSolution(1, new ArrayList<>(), new ArrayList<>());
        queryExecutionsCountDown = new CountDownLatch(executionsCount);
        prepareQueryExecutions(tasksQueryResults);

        when(generatedChanges.isEmpty()).thenReturn(false);
        when(emptyChanges.isEmpty()).thenReturn(true);
        when(solverExecutor.isStarted()).thenReturn(true);
        runnableBase.synchronizeSolution(solution, startTime, unchangedPeriodTimeout);

        // wait for the query executions to happen
        queryExecutionsCountDown.await();
        applyResultCountDown.await();

        verify(resultConsumer).accept(resultCaptor.capture());
        runnableBase.destroy();
        future.get();
        assertTrue(runnableBase.isDestroyed());
    }

    /**
     * Mock the results of the findTasksQuery and emulate errors in the middle by producing null.
     * Last execution produces values.
     * execution 0, no results
     * execution 1, no results
     * execution 2, no results
     * execution 3, null -> an error is produced
     * execution 4, null -> an error is produced
     * execution 5, null -> no results
     * execution 6, finally results are produced.
     */
    private List<TaskAssigningRuntimeDelegate.FindTasksResult> mockTasksQueryExecutions(LocalDateTime startTime) {
        List<TaskData> taskDataList = mockTaskDataList();
        TaskAssigningRuntimeDelegate.FindTasksResult result0 = mockFindTaskResult(startTime.plusMinutes(1), new ArrayList<>());
        TaskAssigningRuntimeDelegate.FindTasksResult result1 = mockFindTaskResult(startTime.plusMinutes(2), new ArrayList<>());
        TaskAssigningRuntimeDelegate.FindTasksResult result2 = mockFindTaskResult(startTime.plusMinutes(3), new ArrayList<>());
        TaskAssigningRuntimeDelegate.FindTasksResult resultFailure3 = null;
        TaskAssigningRuntimeDelegate.FindTasksResult resultFailure4 = null;
        TaskAssigningRuntimeDelegate.FindTasksResult result5 = mockFindTaskResult(startTime.plusMinutes(4), new ArrayList<>());
        TaskAssigningRuntimeDelegate.FindTasksResult result6 = mockFindTaskResult(startTime.plusMinutes(5), taskDataList);
        return Arrays.asList(result0, result1, result2, resultFailure3, resultFailure4, result5, result6);
    }

    private List<TaskAssigningRuntimeDelegate.FindTasksResult> mockNoChangesTasksQueryExecutions(LocalDateTime startTime) {
        return Collections.singletonList(mockFindTaskResult(startTime.plusMinutes(1), new ArrayList<>()));
    }

    /**
     * Verify that the synchronization sequence defined in mockTasksQueryExecutions was executed.
     */
    @SuppressWarnings("unchecked")
    private void verityTasksQueryExecutions(LocalDateTime startTime, List<TaskAssigningRuntimeDelegate.FindTasksResult> results) {
        /*
        initial setup queryTimes -> [startTime]
        execution0:
            execute query with lastModification = startTime
            execution was ok, but result0 has no results.
            nextQueryTime0 = context.shiftQueryTime(result0.getQueryTime())
        execution1:
            execute query with lastModification = nextQueryTime0
            execution is ok, but result1 has no values.
            nextQueryTime1 = context.shiftQueryTime(result1.getQueryTime())
        execution2:
            execute query with lastModification = nextQueryTime1
            execution is ok, but result2 has no values.
            nextQueryTime2 = context.shiftQueryTime(result2.getQueryTime())
        execution3:
            execute query with lastModification = nextQueryTime2
            execution fails.
            a retry is produced.
        execution4:
            execute query with lastModification = nextQueryTime2
            execution fails.
            a retry is produced.
        execution5:
            execute query with lastModification = nextQueryTime2
            execution is ok, but result5 has no values
            nextQueryTime5 = context.shift(result5.getQueryTime())
        execution6:
            execute query with lastModification = nextQueryTime5
            execution is ok, and result6 has values!
            nextQueryTime6 = context.shiftQueryTime(result6.getQueryTime())
            End of loop since results are produced.
        */

        verify(delegate, times(1)).findTasks(anyList(), eq(startTime), anyObject());
        verify(delegate, times(1)).findTasks(anyList(), eq(context.shiftQueryTime(results.get(0).getQueryTime())), anyObject());
        verify(delegate, times(1)).findTasks(anyList(), eq(context.shiftQueryTime(results.get(1).getQueryTime())), anyObject());
        verify(delegate, times(3)).findTasks(anyList(), eq(context.shiftQueryTime(results.get(2).getQueryTime())), anyObject());
        verify(delegate, times(results.size())).findTasks(anyList(), anyObject(), anyObject());
    }

    /**
     * Mock the results of the findAllUsers method execution and emulate errors in the middle by producing null.
     * Last execution produces values.
     * execution 0, null
     * execution 1, no results
     * execution 2, results are produced.
     */
    private List<List<User>> mockUsersQueryExecutions() {
        User user = mock(User.class);
        List<User> result0Failure = null;
        List<User> result1 = Collections.emptyList();
        List<User> result2 = Collections.singletonList(user);
        return Arrays.asList(result0Failure, result1, result2);
    }

    private <T> List<T> mockEmptyQueryExecutions(int size, Supplier<T> emptyResultSupplier) {
        List<T> result = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            result.add(emptyResultSupplier.get());
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    private void prepareQueryExecutions(List<TaskAssigningRuntimeDelegate.FindTasksResult> results) {
        doAnswer(createExecutions(results)).when(delegate).findTasks(anyList(), anyObject(), anyObject());
    }

    private void prepareUserQueryExecutions(List<List<User>> results) {
        doAnswer(createExecutions(results)).when(userSystemService).findAllUsers();
    }

    private <T> Answer createExecutions(List<T> results) {
        return new Answer() {
            private int invocations = 0;

            public Object answer(InvocationOnMock invocation) {
                T result = results.get(invocations++);
                if (result == null) {
                    throw new RuntimeException("Emulate a connection error. The synchronizer must retry.");
                }
                return result;
            }
        };
    }

    private List<TaskData> mockTaskDataList() {
        return Collections.singletonList(new TaskData());
    }

    private List<User> mockUserList() {
        return new ArrayList<>();
    }

    private TaskAssigningRuntimeDelegate.FindTasksResult mockFindTaskResult(LocalDateTime queryTime, List<TaskData> taskDataList) {
        return new TaskAssigningRuntimeDelegate.FindTasksResult(queryTime, taskDataList);
    }

    private class SolutionSynchronizerMock extends SolutionSynchronizer {

        private SolutionSynchronizerMock(SolverExecutor solverExecutor,
                                         TaskAssigningRuntimeDelegate delegate,
                                         UserSystemService userSystem,
                                         Duration syncInterval,
                                         Duration usersSyncInterval,
                                         SolverHandlerContext context,
                                         Consumer<Result> resultConsumer) {
            super(solverExecutor, delegate, userSystem, syncInterval, usersSyncInterval, context, resultConsumer);
        }

        @Override
        protected List<ProblemFactChange<TaskAssigningSolution>> buildChanges(TaskAssigningSolution solution, List<TaskData> updatedTaskDataList) {
            return updatedTaskDataList.isEmpty() ? emptyChanges : generatedChanges;
        }

        @Override
        protected List<ProblemFactChange<TaskAssigningSolution>> buildChanges(TaskAssigningSolution solution, List<TaskData> updatedTaskDataList, List<User> updatedUserList) {
            return updatedTaskDataList.isEmpty() && updatedUserList.isEmpty() ? emptyChanges : generatedChanges;
        }

        @Override
        protected TaskAssigningSolution buildSolution(List<TaskData> taskDataList, List<User> externalUsers) {
            return taskDataList.isEmpty() ? emptySolution : generatedSolution;
        }

        @Override
        protected boolean isUsersSyncTime() {
            return usersSyncTime;
        }

        @Override
        protected boolean isUnchangedPeriodTime() {
            return unchangedPeriodTime;
        }

        @Override
        Pair<Action, Result> doInitSolverExecutor() {
            Pair<Action, Result> result = super.doInitSolverExecutor();
            queryExecutionsCountDown.countDown();
            return result;
        }

        @Override
        Pair<Action, Result> doSynchronizeSolution() {
            Pair<Action, Result> result = super.doSynchronizeSolution();
            queryExecutionsCountDown.countDown();
            return result;
        }

        @Override
        protected void applyResult(Result result) {
            super.applyResult(result);
            applyResultCountDown.countDown();
        }
    }
}


text:
- find jQuery at use-time, instead of at load time

- prefer global jQuery to be compatible with `require()`-free environments


text:
package tests

import (
	"io/ioutil"
	"testing"

	"github.com/hoop33/tbdotd/app/models"
	"github.com/stretchr/testify/assert"
)

func TestInformITVideoParsesContents(t *testing.T) {
	filename := "informit_video.xml"
	contents, err := ioutil.ReadFile(filename)
	if err != nil {
		t.Fail()
	} else {
		vendor := models.Vendors["InformIT"]
		source := vendor.Sources["InformIT Video"]
		deal := source.InformITVideo(&vendor, contents)
		assert.Equal(t, "Ruby on Rails Tutorial LiveLessons, The: Learn Web Development With Rails by Michael Hartl", deal.Title)
		assert.Equal(t, "http://www.informit.com/deals/video/", deal.Url)
		assert.Equal(t, int64(1443333600), deal.ExpirationDate.Unix())
	}
}

func TestInformITVideoEmptyReturnsNoResults(t *testing.T) {
	vendor := models.Vendors["InformIT"]
	source := vendor.Sources["InformIT Video"]
	deal := source.InformITVideo(&vendor, []byte{})
	assert.Equal(t, "No Deal", deal.Title)
}


text:
package error

import (
	"errors"
	"strings"
)

// NotFound returns a new error 'not found'.
func NotFound() error {
	return errors.New(NotFoundErrorMessage)
}

// IsNotFound returns true if the error is a 'not found' error.
func IsNotFound(err error) bool {
	return strings.ToLower(err.Error()) == strings.ToLower(NotFoundErrorMessage)
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="profit">
        <note>
            Frames file for 'profit' based on sentences in financial subcorpus.
            No verbnet entry.  No comparison.
        </note>

        <roleset id="profit.01" name="make money from">
            <roles>
                <role descr="entity making money" n="0"/>
                <role descr="source" n="1"/>
            </roles>

            <example name="transitive, typical">
                <text>
                    ...protects against stocks being relentlessly beaten downward by
                    those-1 seeking *trace*-1 to profit from lower prices.
                </text>
                <arg n="0">*trace*</arg>
                <rel>profit</rel>
                <arg n="1">from lower prices</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
module Distribution.Solver.Types.ResolverPackage
    ( ResolverPackage(..)
    , resolverPackageLibDeps
    , resolverPackageExeDeps
    ) where

import Distribution.Solver.Types.InstSolverPackage
import Distribution.Solver.Types.SolverId
import Distribution.Solver.Types.SolverPackage
import qualified Distribution.Solver.Types.ComponentDeps as CD

import Distribution.Compat.Binary (Binary(..))
import Distribution.Compat.Graph (IsNode(..))
import Distribution.Package (Package(..), HasUnitId(..))
import Distribution.Simple.Utils (ordNub)
import GHC.Generics (Generic)

-- | The dependency resolver picks either pre-existing installed packages
-- or it picks source packages along with package configuration.
--
-- This is like the 'InstallPlan.PlanPackage' but with fewer cases.
--
data ResolverPackage loc = PreExisting InstSolverPackage
                         | Configured  (SolverPackage loc)
  deriving (Eq, Show, Generic)

instance Binary loc => Binary (ResolverPackage loc)

instance Package (ResolverPackage loc) where
  packageId (PreExisting ipkg)     = packageId ipkg
  packageId (Configured  spkg)     = packageId spkg

resolverPackageLibDeps :: ResolverPackage loc -> CD.ComponentDeps [SolverId]
resolverPackageLibDeps (PreExisting ipkg) = instSolverPkgLibDeps ipkg
resolverPackageLibDeps (Configured spkg) = solverPkgLibDeps spkg

resolverPackageExeDeps :: ResolverPackage loc -> CD.ComponentDeps [SolverId]
resolverPackageExeDeps (PreExisting ipkg) = instSolverPkgExeDeps ipkg
resolverPackageExeDeps (Configured spkg) = solverPkgExeDeps spkg

instance IsNode (ResolverPackage loc) where
  type Key (ResolverPackage loc) = SolverId
  nodeKey (PreExisting ipkg) = PreExistingId (packageId ipkg) (installedUnitId ipkg)
  nodeKey (Configured spkg) = PlannedId (packageId spkg)
  -- Use dependencies for ALL components
  nodeNeighbors pkg =
    ordNub $ CD.flatDeps (resolverPackageLibDeps pkg) ++
             CD.flatDeps (resolverPackageExeDeps pkg)


text:
package cmd

import (
	"fmt"
	"io"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/controller"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
	cmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util/wait"
	"github.com/spf13/cobra"
)

const (
	resize_long = `Set a new size for a Replication Controller.

Resize also allows users to specify one or more preconditions for the resize action.
If --current-replicas or --resource-version is specified, it is validated before the
resize is attempted, and it is guaranteed that the precondition holds true when the
resize is sent to the server.`
	resize_example = `// Resize replication controller named 'foo' to 3.
$ kubectl resize --replicas=3 replicationcontrollers foo

// If the replication controller named foo's current size is 2, resize foo to 3.
$ kubectl resize --current-replicas=2 --replicas=3 replicationcontrollers foo`

	retryFrequency = controller.DefaultSyncPeriod / 100
	retryTimeout   = 10 * time.Second
)

func NewCmdResize(f *cmdutil.Factory, out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "resize [--resource-version=version] [--current-replicas=count] --replicas=COUNT RESOURCE ID",
		Short:   "Set a new size for a Replication Controller.",
		Long:    resize_long,
		Example: resize_example,
		Run: func(cmd *cobra.Command, args []string) {
			err := RunResize(f, out, cmd, args)
			cmdutil.CheckErr(err)
		},
	}
	cmd.Flags().String("resource-version", "", "Precondition for resource version. Requires that the current resource version match this value in order to resize.")
	cmd.Flags().Int("current-replicas", -1, "Precondition for current size. Requires that the current size of the replication controller match this value in order to resize.")
	cmd.Flags().Int("replicas", -1, "The new desired number of replicas. Required.")
	return cmd
}

func RunResize(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
	count := cmdutil.GetFlagInt(cmd, "replicas")
	if len(args) != 2 || count < 0 {
		return cmdutil.UsageError(cmd, "--replicas=COUNT RESOURCE ID")
	}

	cmdNamespace, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	mapper, _ := f.Object()
	// TODO: use resource.Builder instead
	mapping, namespace, name, err := cmdutil.ResourceFromArgs(cmd, args, mapper, cmdNamespace)
	if err != nil {
		return err
	}

	resizer, err := f.Resizer(mapping)
	if err != nil {
		return err
	}

	resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
	currentSize := cmdutil.GetFlagInt(cmd, "current-replicas")
	precondition := &kubectl.ResizePrecondition{currentSize, resourceVersion}
	cond := kubectl.ResizeCondition(resizer, precondition, namespace, name, uint(count))

	msg := "resized"
	if err = wait.Poll(retryFrequency, retryTimeout, cond); err != nil {
		msg = fmt.Sprintf("Failed to resize controller in spite of retrying for %s", retryTimeout)
		if err != nil {
			return err
		}
	}
	fmt.Fprintf(out, "%s\n", msg)
	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FilmIndustryNetwork.Entities;
using FilmIndustryNetwork.Entities.Graph;
using FilmIndustryNetwork.Interfaces;

namespace FilmIndustryNetwork.Services
{
    public class GraphPersonService : IGraphPersonService
    {
        private readonly IPersonRepository _personRepo;

        public GraphPersonService(IPersonRepository personRepo)
        {
            _personRepo = personRepo;
        }

        public async Task<IEnumerable<MixedResult>> GetPersonGraphByNameAsync(string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException(nameof(name));
            return await _personRepo.GetGraph((Person person) => person.Name == name);
        }

        public async Task<IEnumerable<MixedResult>> GetPersonGraphByBirthYearAsync(int year)
        {
            return await _personRepo.GetGraph((Person person) => person.DateOfBirth.Year == year);
        }

        public async Task<IEnumerable<MixedResult>> GetPersonGraphByBirthDateAsync(DateTime birthDate)
        {
            return await _personRepo.GetGraph((Person person) => person.DateOfBirth == birthDate);
        }

        public async Task<List<MixedResult>> GetDegreesOfSeparationGraph(Person startingPerson, Person endingPerson)
        {
            if (startingPerson == null)
                throw new ArgumentNullException(nameof(startingPerson));
            if (endingPerson == null)
                throw new ArgumentNullException(nameof(endingPerson));

            var results = await _personRepo.GetPath(startingPerson, endingPerson);
            var r = results;
            return r;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.15"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>astro: Namespace Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

astro
    1.0.0

A simple astrodynamics library

computeAbsorptionRadiationPressure()
: astro

computeCannonballPoyntingRobertsonDragAcceleration()
: astro

computeCannonballRadiationPressureAcceleration()
: astro

computeCentralBodyAcceleration()
: astro

computeCircularVelocity()
: astro

computeEllipticalKeplerFunction()
: astro

computeFirstDerivativeEllipticalKeplerFunction()
: astro

computeJ2Acceleration()
: astro

computeKeplerMeanMotion()
: astro

computeKeplerOrbitalPeriod()
: astro

computeRadiationPressure()
: astro

convertCartesianToKeplerianElements()
: astro

convertEccentricAnomalyToMeanAnomaly()
: astro

convertEccentricAnomalyToTrueAnomaly()
: astro

convertEllipticalEccentricAnomalyToMeanAnomaly()
: astro

convertEllipticalEccentricAnomalyToTrueAnomaly()
: astro

convertEllipticalMeanAnomalyToEccentricAnomaly()
: astro

convertHyperbolicEccentricAnomalyToMeanAnomaly()
: astro

convertHyperbolicEccentricAnomalyToTrueAnomaly()
: astro

convertKeplerianToCartesianElements()
: astro

convertTrueAnomalyToEccentricAnomaly()
: astro

convertTrueAnomalyToEllipticalEccentricAnomaly()
: astro

convertTrueAnomalyToHyperbolicEccentricAnomaly()
: astro

Generated on Fri Jan 4 2019 17:35:21 for astro by

     1.8.15


text:
package sorm.mappings

import sext._, embrace._
import sorm._
import driver.DriverConnection
import core._
import jdbc.ResultSetView
import reflection._

class OptionToTableMapping
  ( val reflection : Reflection,
    val membership : Option[Membership],
    val settings : Map[Reflection, EntitySettings] )
  extends SlaveTableMapping
  {
    lazy val item = Mapping( reflection.generics(0), Membership.OptionToTableItem(this), settings )
    lazy val primaryKeyColumns = masterTableColumns
    lazy val generatedColumns = primaryKeyColumns
    lazy val mappings = item +: Stream()

    def parseResultSet(rs: ResultSetView, connection : DriverConnection)
      = rs.byNameRowsTraversable.toStream.headOption.map(item.valueFromContainerRow(_, connection))

    override def update ( value : Any, masterKey : Stream[Any], connection : DriverConnection ) {
      connection.delete(tableName, masterTableColumnNames zip masterKey)
      insert(value, masterKey, connection)
    }

    override def insert ( v : Any, masterKey : Stream[Any], connection : DriverConnection ) {
      v.asInstanceOf[Option[_]]
        .foreach{ v =>
          val pk = masterKey
          val values = item.valuesForContainerTableRow(v) ++: (primaryKeyColumnNames zip pk)
          connection.insert(tableName, values)
          item.insert(v, pk, connection)
        }
    }

    def valuesForContainerTableRow ( value : Any ) = Stream()
  }


text:
[![Build status][ci-image]][ci-status]

:exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation:

**NOTE: This fork is no longer maintained. Use [Jared's fork](https://github.com/jared-stilwell/escomplex-coffee) instead.**

:exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation: :anguished: :exclamation:

Software complexity analysis for CoffeeScript projects.
CoffeeScript-specific wrapper around [escomplex][escomplex].

[ci-image]: https://secure.travis-ci.org/philbooth/escomplex-coffee.png?branch=master
[ci-status]: http://travis-ci.org/#!/philbooth/escomplex-coffee
[escomplex]: https://github.com/philbooth/escomplex
[coffee]: https://github.com/michaelficarra/CoffeeScriptRedux
[license]: https://github.com/philbooth/escomplex-coffee/blob/master/COPYING
[node]: http://nodejs.org/
[npm]: https://npmjs.org/
[jshint]: https://github.com/jshint/node-jshint
[mocha]: http://visionmedia.github.com/mocha
[chai]: http://chaijs.com/


text:
package crate.elasticsearch.module.restore;

import crate.elasticsearch.action.restore.RestoreAction;
import crate.elasticsearch.action.restore.TransportRestoreAction;
import crate.elasticsearch.action.restore.parser.RestoreParser;
import org.elasticsearch.action.GenericAction;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.multibindings.MapBinder;

public class RestoreModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(TransportRestoreAction.class).asEagerSingleton();

        bind(RestoreParser.class).asEagerSingleton();

        MapBinder<GenericAction, TransportAction> transportActionsBinder = MapBinder.newMapBinder(binder(), GenericAction.class, TransportAction.class);
        transportActionsBinder.addBinding(RestoreAction.INSTANCE).to(TransportRestoreAction.class).asEagerSingleton();

        MapBinder<String, GenericAction> actionsBinder = MapBinder.newMapBinder(binder(), String.class, GenericAction.class);
        actionsBinder.addBinding(RestoreAction.NAME).toInstance(RestoreAction.INSTANCE);

    }

}