text:
require 'metaheuristic_interface'
require 'metaheuristics/search_results'

class AlpsGa < MetaheuristicInterface

	# From Hornby 2006 ALPS
	DEFAULTS = {
		:layer_size                  => 100,
		:max_layer_count             => 10,
		:tournament_size             => 7,
		:age_gap                     => 10,
		:aging_scheme                => :polynomial,
		:layer_elitism               => 3,
		:overall_elitism             => 0,
		:parents_from_previous_layer => true
	}

	attr_reader :results

	class Individual
		include Comparable

		attr_reader :age, :solution, :fitness

		# ctor
		def initialize(solution, age = 0)
			@solution = solution
			@age      = age
			@used     = false
			@fitness  = nil
		end

		# tag as used
		def tag_as_used
			@used = true
		end

		# age
		def age!
			if @used
				@used = false
				@age += 1
			end
		end

		# evaluate, return fitness
		def evaluate(evaluator)
			@fitness = evaluator.call(solution)
		end

		# <=>
		def <=>(individual)
			self.fitness <=> individual.fitness
		end
	end # Individual

	# ctor
	def initialize(options)
		@layer_size                  = options[:layer_size                 ] || DEFAULTS[:layer_size                 ]
		@max_layer_count             = options[:max_layer_count            ] || DEFAULTS[:max_layer_count            ]
		@tournament_size             = options[:tournament_size            ] || DEFAULTS[:tournament_size            ]
		@age_gap                     = options[:age_gap                    ] || DEFAULTS[:age_gap                    ]
		@aging_scheme                = options[:aging_scheme               ] || DEFAULTS[:aging_scheme               ]
		@layer_elitism               = options[:layer_elitism              ] || DEFAULTS[:layer_elitism              ]
		@overall_elitism             = options[:overall_elitism            ] || DEFAULTS[:overall_elitism            ]
		@parents_from_previous_layer = options[:parents_from_previous_layer] || DEFAULTS[:parents_from_previous_layer]

		@evaluator       = options[:evaluator      ] || (raise ArgumentError)
		@mutation_rate   = options[:mutation_rate  ] || (raise ArgumentError)
		@genome_init     = options[:genome_init    ] || (raise ArgumentError)

		raise ArgumentError unless [:linear, :fibonacci, :polynomial, :exponential].include?(@aging_scheme)

		@results = SearchResults.new
		@layers  = []
	end

	# run once
	def run_once
		generation = @results.generation
		if generation == 0
			@layers[0] = Array.new(@layer_size){ Individual.new(@genome_init.call) }
			evaluate_layer(0)
		else
			# all but bottom layer
			(@layers.size - 1).downto(1) do |i|
				generate_new_population_layer(i)
				evaluate_layer(i)
			end

			# bottom layer
			if generation % @age_gap == 0
				move_to_layer(@layers[0], 1)
				@layers[0] = Array.new(@layer_size){ Individual.new(@genome_init.call) }
			else
				generate_new_population_layer(0)
			end
			evaluate_layer(0)
		end

		# age population
		@layers.each do |l|
			l.each do |individual|
				individual.age!
			end
		end

		# promote individuals
		promote_individuals

		@results.increment_generation

		@layers.each.with_index do |l, idx|
			l.sort!.reverse!
			$stderr << "= layer #{idx} : max age #{max_layer_age(idx)} ---------------------------------------------------------------\n"
			l.each do |i|
#				$stderr << " - #{i.solution.__id__.to_s.rjust(7)}, fitness #{i.fitness.to_i.to_s.rjust(6)}, age #{i.age.to_s.rjust(4)}\n"
				$stderr << " - #{i.solution.__id__.to_s.rjust(7)}, fitness #{('%.4f' % i.fitness).rjust(7)}, age #{i.age.to_s.rjust(4)}\n"
			end
		end
		$stderr << "\n"
	end

private

	# max age for layer +n+
	def max_layer_age(n)
		case(@aging_scheme)
		when :linear     ; n + 1
		when :fibonacci  ; fibonacci(n + 1)
		when :polynomial ; n < 2 ? n + 1 : n ** 2
		when :exponential; 2 ** n
		else raise ArgumentError
		end * @age_gap
	end

	# fibonacci
	def fibonacci(n)
		if n == 0 || n == 1
			1
		else
			fibonacci(n - 1) + fibonacci(n - 2)
		end
	end

	# evaluate layer
	def evaluate_layer(n)
		@layers[n].each do |individual|
			fitness = individual.evaluate(@evaluator)
			@results.add_solution(individual.solution, fitness)
		end
	end

	# generate new population layer
	def generate_new_population_layer(n)
		current_layer = @layers[n]

		parent_population = ((n == 0 || !@parents_from_previous_layer) ? current_layer : (@layers[n - 1] + current_layer)).sort

		new_population = []

		# elitism
		elitism = @layer_elitism
		elitism = @overall_elitism if n == (@layers.size - 1) && @overall_elitism > elitism

		if elitism > 0
			current_layer.sort.reverse[0, [elitism, current_layer.size].min].each do |i|
				new_population << i
			end
		end

		(@layer_size - new_population.size).times do
			parent1_index = Array.new(@tournament_size){ rand(parent_population.size) }.max
			parent2_index = Array.new(@tournament_size){ rand(parent_population.size) }.reject{ |v| v == parent1_index }.max
			while parent2_index == nil || parent2_index == parent1_index
				parent2_index = rand(parent_population.size)
			end

			parent1 = parent_population[parent1_index]
			parent2 = parent_population[parent2_index]

			parent1.tag_as_used
			parent2.tag_as_used
			new_solution = parent1.solution.crossover(parent2.solution).mutate!(@mutation_rate)
			new_population << Individual.new(new_solution, [parent1.age, parent2.age].max + 1)
		end

		@layers[n] = new_population
	end

	# promote individuals
	def promote_individuals
		layer_count = @layers.size

		((layer_count == @max_layer_count) ? (layer_count - 2) : (layer_count -  1)).downto(0) do |n|
			layer = @layers[n]
			# take old ones from current layer
			max_age = max_layer_age(n)
			oldies = layer.select{ |i| i.age >= max_age }
			if !oldies.empty?
				layer.delete_if{     |i| i.age >= max_age }
				move_to_layer(oldies, n + 1) # try to fit them in with the layer above
			end
		end
	end

	# try to fit individual within layer
	def move_to_layer(individuals, n)
		# add layer
		if n > (@layers.size - 1)
			raise RuntimeError unless n <  @max_layer_count
			raise RuntimeError unless n == @layers.size
			@layers[n] = []
		end

		# add oldies in layer
		a = (@layers[n] + individuals).sort do |a, b|
			cmp_fitness = a.fitness <=> b.fitness
			if cmp_fitness == 0
				a.age <=> b.age
			else
				cmp_fitness
			end
		end.reverse

		@layers[n] = a[0, [a.size, @layer_size].min]
	end
end # AlpsGa


text:
using SAPFEWSELib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SAPAutomation
{
    public static partial class SAPFEExtension
    {

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiFrameWindow FrameWindow, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, FrameWindow.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiMainWindow MainWindow, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, MainWindow.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiModalWindow ModalWindow, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, ModalWindow.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiVContainer VContainer, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, VContainer.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiContextMenu ContextMenu, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, ContextMenu.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiUserArea UserArea, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, UserArea.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiSplitterContainer SplitterContainer, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, SplitterContainer.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiShell Shell, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Shell.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiContainerShell ContainerShell, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, ContainerShell.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiTab Tab, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Tab.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiTabStrip TabStrip, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, TabStrip.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiCustomControl CustomControl, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, CustomControl.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiToolbar Toolbar, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Toolbar.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiMenubar Menubar, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Menubar.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiMenu Menu, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Menu.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiSimpleContainer SimpleContainer, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, SimpleContainer.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiScrollContainer ScrollContainer, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, ScrollContainer.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiStatusbar Statusbar, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Statusbar.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiTableControl TableControl, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, TableControl.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiTitlebar Titlebar, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Titlebar.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiGOSShell GOSShell, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, GOSShell.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiDialogShell DialogShell, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, DialogShell.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiGridView GridView, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, GridView.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiTree Tree, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Tree.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiSplit Split, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Split.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiPicture Picture, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Picture.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiToolbarControl ToolbarControl, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, ToolbarControl.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiTextedit Textedit, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Textedit.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiOfficeIntegration OfficeIntegration, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, OfficeIntegration.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiHTMLViewer HTMLViewer, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, HTMLViewer.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiCalendar Calendar, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Calendar.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiBarChart BarChart, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, BarChart.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiNetChart NetChart, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, NetChart.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiColorSelector ColorSelector, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, ColorSelector.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiSapChart SapChart, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, SapChart.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiChart Chart, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Chart.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiMap Map, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Map.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiStage Stage, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, Stage.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiGraphAdapt GraphAdapt, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, GraphAdapt.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiEAIViewer2D EAIViewer2D, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, EAIViewer2D.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiEAIViewer3D EAIViewer3D, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, EAIViewer3D.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiApoGrid ApoGrid, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, ApoGrid.FindAllByNameEx);
        }

        public static IEnumerable<T> FindAllByNameEx<T>(this GuiAbapEditor AbapEditor, string Name, int TypeId)
            where T : class
        {
            return findAllByNameExTemplate<T>(Name, TypeId, AbapEditor.FindAllByNameEx);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using AldursLab.Testing;
using NUnit.Framework;

namespace AldursLab.Persistence.Simple.Tests.Fixtures
{
    public abstract class TestsBase
    {
        DirectoryHandle dir;
        SqLiteDataStorage sqLiteDataStorage;

        [SetUp]
        public void Setup()
        {

            dir = TempDirectoriesFactory.CreateEmpty();
            sqLiteDataStorage = new SqLiteDataStorage(dir.FullName);
        }

        [TearDown]
        public void Teardown()
        {
            TeardownHelper.DisposeAll(sqLiteDataStorage, dir);
        }

        protected SampleContext CreateContext()
        {
            return new SampleContext(new DefaultJsonSerializer(), sqLiteDataStorage);
        }
    }
}


text:
package cn.edu.nuc.acmicpc.form.dto.problem;

import com.google.common.base.Preconditions;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import cn.edu.nuc.acmicpc.dto.ProblemDto;
import javax.validation.constraints.NotNull;

/**
 * Created with IDEA
 * User: chuninsane
 * Date: 16/4/14
 * Problem edit dto.
 */
public class ProblemEditDto {

    private String action;
    private Long problemId;
    private String description;
    @NotNull(message = "Please enter a validate title.")
    @Length(min = 1, max = 50, message = "Please enter a validate title.")
    private String title;
    @NotNull(message = "Time limit should between 0 and 60000")
    @Range(min = 0, max = 60000, message = "Time limit should between 0 and 60000")
    private Integer timeLimit;
    @NotNull(message = "Time limit should between 0 and 60000")
    @Range(min = 0, max = 60000, message = "Time limit should between 0 and 60000")
    private Integer javaTimeLimit;
    @NotNull(message = "Memory limit should between 0 and 262144")
    @Range(min = 0, max = 262144, message = "Memory limit should between 0 and 262144")
    private Integer memoryLimit;
    @NotNull(message = "Memory limit should between 0 and 262144")
    @Range(min = 0, max = 262144, message = "Memory limit should between 0 and 262144")
    private Integer javaMemoryLimit;
    @NotNull(message = "Output limit should between 0 and 262144")
    @Range(min = 0, max = 262144, message = "Output limit should between 0 and 262144")
    private Integer outputLimit;
    private Boolean isSpj;
    private Boolean isVisible;
    private String input;
    private String output;
    private String sampleInput;
    private String sampleOutput;
    private String hint;
    private String source;

    @Override
    public String toString() {
        return "ProblemEditDto{" +
                "action='" + action + '\'' +
                ", problemId=" + problemId +
                ", description='" + description + '\'' +
                ", title='" + title + '\'' +
                ", isSpj=" + isSpj +
                ", timeLimit=" + timeLimit +
                ", javaTimeLimit=" + javaTimeLimit +
                ", memoryLimit=" + memoryLimit +
                ", javaMemoryLimit=" + javaMemoryLimit +
                ", outputLimit=" + outputLimit +
                ", isVisible=" + isVisible +
                ", input='" + input + '\'' +
                ", output='" + output + '\'' +
                ", sampleInput='" + sampleInput + '\'' +
                ", sampleOutput='" + sampleOutput + '\'' +
                ", hint='" + hint + '\'' +
                ", source='" + source + '\'' +
                '}';
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public Long getProblemId() {
        return problemId;
    }

    public void setProblemId(Long problemId) {
        this.problemId = problemId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Boolean getIsSpj() {
        return isSpj;
    }

    public void setIsSpj(Boolean isSpj) {
        this.isSpj = isSpj;
    }

    public Integer getTimeLimit() {
        return timeLimit;
    }

    public void setTimeLimit(Integer timeLimit) {
        this.timeLimit = timeLimit;
    }

    public Integer getJavaTimeLimit() {
        return javaTimeLimit;
    }

    public void setJavaTimeLimit(Integer javaTimeLimit) {
        this.javaTimeLimit = javaTimeLimit;
    }

    public Integer getMemoryLimit() {
        return memoryLimit;
    }

    public void setMemoryLimit(Integer memoryLimit) {
        this.memoryLimit = memoryLimit;
    }

    public Integer getJavaMemoryLimit() {
        return javaMemoryLimit;
    }

    public void setJavaMemoryLimit(Integer javaMemoryLimit) {
        this.javaMemoryLimit = javaMemoryLimit;
    }

    public Integer getOutputLimit() {
        return outputLimit;
    }

    public void setOutputLimit(Integer outputLimit) {
        this.outputLimit = outputLimit;
    }

    public Boolean getIsVisible() {
        return isVisible;
    }

    public void setIsVisible(Boolean isVisible) {
        this.isVisible = isVisible;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getOutput() {
        return output;
    }

    public void setOutput(String output) {
        this.output = output;
    }

    public String getSampleInput() {
        return sampleInput;
    }

    public void setSampleInput(String sampleInput) {
        this.sampleInput = sampleInput;
    }

    public String getSampleOutput() {
        return sampleOutput;
    }

    public void setSampleOutput(String sampleOutput) {
        this.sampleOutput = sampleOutput;
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public ProblemDto toProblemDto(ProblemDto problemDto) {
        Preconditions.checkNotNull(problemDto);
        problemDto.setTitle(title);
        problemDto.setDescription(description);
        problemDto.setInput(input);
        problemDto.setOutput(output);
        problemDto.setSampleInput(sampleInput);
        problemDto.setSampleOutput(sampleOutput);
        problemDto.setHint(hint);
        problemDto.setSource(source);
        problemDto.setTimeLimit(timeLimit);
        problemDto.setJavaTimeLimit(javaTimeLimit);
        problemDto.setMemoryLimit(memoryLimit);
        problemDto.setJavaMemoryLimit(javaMemoryLimit);
        problemDto.setOutputLimit(outputLimit);
        problemDto.setIsSpj(isSpj);
        problemDto.setIsVisible(isVisible);
        return problemDto;
    }
}


text:
Tensorflow templates

python 3.6.2 compatible

## Structure

- hyperparameters.py
- train.py
- eval.py
- models.py
- losses.py
- test.py
- utils.py
- readers.py
- summary_writers.py


text:
package wlml.ml

class GradientDescent {

}


text:
from twilio.twiml.voice_response import Dial, VoiceResponse, Sip

response = VoiceResponse()
dial = Dial()
dial.sip('sip:jack@example.com;transport=tcp')
response.append(dial)

print(response)


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

package google.registry.model.domain.token;

import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.persistResource;
import static org.junit.jupiter.api.Assertions.assertThrows;

import google.registry.model.EntityTestCase;
import google.registry.model.billing.BillingEvent.RenewalPriceBehavior;
import google.registry.model.domain.token.AllocationToken.TokenType;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.testcontainers.shaded.com.google.common.collect.ImmutableSet;

/** Unit tests for {@link PackagePromotion}. */
public class PackagePromotionTest extends EntityTestCase {

  public PackagePromotionTest() {
    super(JpaEntityCoverageCheck.ENABLED);
  }

  @BeforeEach
  void beforeEach() {
    createTld("foo");
  }

  @Test
  void testPersistence() {
    AllocationToken token =
        persistResource(
            new AllocationToken.Builder()
                .setToken("abc123")
                .setTokenType(TokenType.PACKAGE)
                .setCreationTimeForTest(DateTime.parse("2010-11-12T05:00:00Z"))
                .setAllowedTlds(ImmutableSet.of("foo"))
                .setAllowedRegistrarIds(ImmutableSet.of("TheRegistrar"))
                .setRenewalPriceBehavior(RenewalPriceBehavior.SPECIFIED)
                .setDiscountFraction(1)
                .build());

    PackagePromotion packagePromotion =
        new PackagePromotion.Builder()
            .setToken(token)
            .setPackagePrice(Money.of(CurrencyUnit.USD, 10000))
            .setMaxCreates(40)
            .setMaxDomains(10)
            .setNextBillingDate(DateTime.parse("2011-11-12T05:00:00Z"))
            .build();

    jpaTm().transact(() -> jpaTm().put(packagePromotion));
    assertAboutImmutableObjects()
        .that(jpaTm().transact(() -> PackagePromotion.loadByTokenString("abc123")).get())
        .isEqualExceptFields(packagePromotion, "packagePromotionId");
  }

  @Test
  void testFail_tokenIsNotPackage() {
    AllocationToken token =
        persistResource(
            new AllocationToken.Builder()
                .setToken("abc123")
                .setTokenType(TokenType.SINGLE_USE)
                .setCreationTimeForTest(DateTime.parse("2010-11-12T05:00:00Z"))
                .setAllowedTlds(ImmutableSet.of("foo"))
                .setAllowedRegistrarIds(ImmutableSet.of("TheRegistrar"))
                .setDiscountFraction(1)
                .build());

    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () ->
                persistResource(
                    new PackagePromotion.Builder()
                        .setToken(token)
                        .setPackagePrice(Money.of(CurrencyUnit.USD, 10000))
                        .setMaxCreates(40)
                        .setMaxDomains(10)
                        .setNextBillingDate(DateTime.parse("2011-11-12T05:00:00Z"))
                        .build()));

    assertThat(thrown).hasMessageThat().isEqualTo("Allocation token must be a PACKAGE type");
  }
}


text:
from ez_setup import use_setuptools
use_setuptools()

from setuptools import setup, find_packages

import clustermodel
# Run 2to3 builder if we're on Python 3.x, from
#   http://wiki.python.org/moin/PortingPythonToPy3k
try:
    from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
    # 2.x
    from distutils.command.build_py import build_py
command_classes = {'build_py': build_py}

setup(name='clustermodel',
      version=clustermodel.__version__,
      description="statistical models on clusters of correlated genomic data",
      packages=find_packages(),
      url="https://github.com/brentp/cluster-corr/",
      long_description=open('README.md').read(),
      platforms='any',
      classifiers=[
        'Topic :: Scientific/Engineering :: Bio-Informatics',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
          ],
      keywords='bioinformatics methylation correlation',
      author='brentp',
      author_email='bpederse@gmail.com',
      license='BSD 3-clause',
      include_package_data=True,
      #package_data = {"": ['*.R']}
      tests_require=['nose'],
      test_suite='nose.collector',
      zip_safe=False,
      install_requires=['numpy', 'pandas', 'aclust', 'toolshed'],
      #scripts=[],
      entry_points={
      },
      cmdclass=command_classes,
  )


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _lines = require('../utils/lines');

var _ElementAssert = require('./ElementAssert');

var _ElementAssert2 = _interopRequireDefault(_ElementAssert);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Base class for Node, Token and Fragment.
 *
 * @name Element
 * @class
 * @abstract
 */
var Element = function () {
    /**
     * @param {String} type
     * @param {Element[]} children
     */
    function Element(type, children) {
        (0, _classCallCheck3.default)(this, Element);

        this.type = type;

        this.firstChild = null;
        this.lastChild = null;
        this.parentElement = null;
        this.nextSibling = null;
        this.previousSibling = null;
        this.childElements = [];

        if (children) {
            for (var i = 0; i < children.length; i++) {
                if (children[i].parentElement) {
                    throw new Error('Cannot add element to several parents');
                }
            }
            this._setChildren(children);
        }

        this.isToken = false;
        this.isWhitespace = false;
        this.isCode = true;
        this.isComment = false;
        this.isNonCodeToken = this.isComment || this.isWhitespace;
        this.isNode = false;
        this.isStatement = false;
        this.isPattern = false;
        this.isAssignable = false;
        this.isFragment = false;
    }

    (0, _createClass3.default)(Element, [{
        key: 'getOwnerProgram',

        // ==== Traversing =================================================================================================

        /**
         * Owner Program for this element or null if element does not have Program in its parent hierarchy.
         *
         * @returns {Program}
         */
        value: function getOwnerProgram() {
            var element = this;
            while (element && !element._isProgram) {
                element = element.parentElement;
            }
            return element;
        }
    }, {
        key: 'getNextToken',
        value: function getNextToken() {
            var element = this;
            while (element) {
                if (element.nextSibling) {
                    return element.nextSibling.getFirstToken();
                }

                element = element.parentElement;
            }

            return null;
        }
    }, {
        key: 'getPreviousToken',
        value: function getPreviousToken() {
            var element = this;
            while (element) {
                if (element.previousSibling) {
                    return element.previousSibling.getLastToken();
                }

                element = element.parentElement;
            }

            return null;
        }

        /**
         * Next token (non-whitespace and non-comment). Null if token was not found.
         *
         * @returns {Element|null}
         */

    }, {
        key: 'getNextCodeToken',
        value: function getNextCodeToken() {
            var token = this.getNextToken();
            while (token && !token.isCode) {
                token = token.getNextToken();
            }
            return token;
        }

        /**
         * Previous token (non-whitespace and non-comment). Null if token was not found.
         *
         * @returns {Element|null}
         */

    }, {
        key: 'getPreviousCodeToken',
        value: function getPreviousCodeToken() {
            var token = this.getPreviousToken();
            while (token && !token.isCode) {
                token = token.getPreviousToken();
            }
            return token;
        }

        /**
         * Next non-whitespace token. Null if token was not found.
         *
         * @returns {Element|null}
         */

    }, {
        key: 'getNextNonWhitespaceToken',
        value: function getNextNonWhitespaceToken() {
            var token = this.getNextToken();
            while (token && token.isWhitespace) {
                token = token.getNextToken();
            }
            return token;
        }

        /**
         * Previous non-whitespace token. Null if token was not found.
         *
         * @returns {Element|null}
         */

    }, {
        key: 'getPreviousNonWhitespaceToken',
        value: function getPreviousNonWhitespaceToken() {
            var token = this.getPreviousToken();
            while (token && token.isWhitespace) {
                token = token.getPreviousToken();
            }
            return token;
        }

        /**
         * First token inside element child tree.
         *
         * @returns {Element|null}
         */

    }, {
        key: 'getFirstToken',
        value: function getFirstToken() {
            var element = this.firstChild;
            while (element && !element.isToken) {
                element = element.firstChild;
            }
            return element;
        }

        /**
         * Last token inside element child tree.
         *
         * @returns {Element|null}
         */

    }, {
        key: 'getLastToken',
        value: function getLastToken() {
            var element = this.lastChild;
            while (element && !element.isToken) {
                element = element.lastChild;
            }
            return element;
        }

        /**
         * Calculates and returns Element range.
         *
         * @returns {Number[]}
         */

    }, {
        key: 'getRange',
        value: function getRange() {
            var counter = 0;

            var previous = this.getPreviousToken();
            while (previous) {
                counter += previous._sourceCodeLength;
                previous = previous.getPreviousToken();
            }

            return [counter, counter + this.getSourceCodeLength()];
        }

        /**
         * Calculates and returns Element loc.
         *
         * @returns {Object}
         */

    }, {
        key: 'getLoc',
        value: function getLoc() {
            var prevToken = this.getPreviousToken();
            var startColumn = 0;
            var startLine = 1;
            while (prevToken) {
                var lines = prevToken._sourceCodeLines;
                startColumn += lines[lines.length - 1].length;
                if (lines.length > 1) {
                    while (prevToken) {
                        startLine += prevToken.getNewlineCount();
                        prevToken = prevToken.getPreviousToken();
                    }
                    break;
                }
                prevToken = prevToken.getPreviousToken();
            }

            var elementLines = this.getSourceCodeLines();
            var endLine = startLine + elementLines.length - 1;
            var endColumn = elementLines[elementLines.length - 1].length;

            if (startLine === endLine) {
                endColumn += startColumn;
            }

            return {
                start: {
                    line: startLine,
                    column: startColumn
                },
                end: {
                    line: endLine,
                    column: endColumn
                }
            };
        }

        // ==== Source Code ================================================================================================

        /**
         * Generated source code length.
         *
         * @returns {Number}
         */

    }, {
        key: 'getSourceCodeLength',
        value: function getSourceCodeLength() {
            var length = 0;
            var child = this.firstChild;
            while (child) {
                length += child.getSourceCodeLength();
                child = child.nextSibling;
            }
            return length;
        }

        /**
         * Generated source code.
         *
         * @returns {String}
         */

    }, {
        key: 'getSourceCode',
        value: function getSourceCode() {
            var code = '';
            var child = this.firstChild;

            while (child) {
                code += child.getSourceCode();
                child = child.nextSibling;
            }
            return code;
        }

        /**
         * Generated source code lines.
         *
         * @returns {String[]}
         */

    }, {
        key: 'getSourceCodeLines',
        value: function getSourceCodeLines() {
            return (0, _lines.getLines)(this.getSourceCode());
        }

        /**
         * Generated source code line break count.
         *
         * @returns {Number}
         */

    }, {
        key: 'getNewlineCount',
        value: function getNewlineCount() {
            var count = 0;
            var child = this.firstChild;
            while (child) {
                count += child.getNewlineCount();
                child = child.nextSibling;
            }
            return count;
        }

        // ==== Child Element Manipulation =================================================================================

        /**
         * Removes specified element from the element child list.
         *
         * @param {Element} element
         *
         * @returns {Element}
         */

    }, {
        key: 'removeChild',
        value: function removeChild(element) {
            if (element.parentElement !== this) {
                throw new Error('The element to be removed is not a child of this element.');
            }

            var children = this.childElements.concat();
            var elementIndex = children.indexOf(element);
            children.splice(elementIndex, 1);

            this._setChildren(children);

            var ownerProgram = this.getOwnerProgram();
            if (ownerProgram) {
                ownerProgram._removeElementsFromProgram([element]);
            }

            setParentElement(element, null);

            return element;
        }

        /**
         * Removes element.
         */

    }, {
        key: 'remove',
        value: function remove() {
            if (!this.parentElement) {
                return;
            }

            this.parentElement.removeChild(this);
        }

        /**
         * Appends specified element to the end of the child list.
         * Accepts multiple nodes using `Fragment`.
         *
         * @param {Element} newElement
         */

    }, {
        key: 'appendChild',
        value: function appendChild(newElement) {
            var children = void 0;
            var newElements = void 0;
            if (newElement.isFragment) {
                this._ensureCanAdoptFragment(newElement);
                newElements = newElement.childElements;
                children = this.childElements.concat(newElement.childElements);
            } else {
                if (newElement.parentElement) {
                    throw new Error('Remove element before adding again');
                }
                this._ensureCanAdopt(newElement);
                newElements = [newElement];
                children = this.childElements.concat(newElement);
            }

            this._setChildren(children);

            if (newElements) {
                var ownerProgram = this.getOwnerProgram();
                if (ownerProgram) {
                    ownerProgram._addElementsToProgram(newElements);
                }
            }
        }

        /**
         * Prepends specified element to the beginning of the child list.
         * Accepts multiple nodes using `Fragment`.
         *
         * @param {Element} newElement
         */

    }, {
        key: 'prependChild',
        value: function prependChild(newElement) {
            var children = void 0;
            var newElements = void 0;
            if (newElement.isFragment) {
                this._ensureCanAdoptFragment(newElement);
                newElements = newElement.childElements;
                children = newElement.childElements.concat(this.childElements);
            } else {
                if (newElement.parentElement) {
                    throw new Error('Remove element before adding again');
                }
                this._ensureCanAdopt(newElement);
                newElements = [newElement];
                children = [newElement].concat(this.childElements);
            }

            this._setChildren(children);

            if (newElements) {
                var ownerProgram = this.getOwnerProgram();
                if (ownerProgram) {
                    ownerProgram._prependElementsToProgram(newElements);
                }
            }
        }

        /**
         * Inserts specified element before specified reference child.
         * Accepts multiple nodes using `Fragment`.
         *
         * @param {Element} newElement
         * @param {Element} referenceChild
         */

    }, {
        key: 'insertChildBefore',
        value: function insertChildBefore(newElement, referenceChild) {
            if (referenceChild.parentElement !== this) {
                throw new Error('Invalid reference child');
            }

            var index = this.childElements.indexOf(referenceChild);
            var childrenBefore = this.childElements.slice(0, index);
            var childrenAfter = this.childElements.slice(index);

            var children = void 0;
            var newElements = void 0;
            if (newElement.isFragment) {
                this._ensureCanAdoptFragment(newElement);
                newElements = newElement.childElements;
                children = childrenBefore.concat(newElement.childElements, childrenAfter);
            } else {
                if (newElement.parentElement) {
                    throw new Error('Remove element before adding again');
                }

                this._ensureCanAdopt(newElement);
                children = childrenBefore.concat(newElement, childrenAfter);
                newElements = [newElement];
            }

            this._setChildren(children);

            if (newElements) {
                var ownerProgram = this.getOwnerProgram();
                if (ownerProgram) {
                    ownerProgram._addElementsToProgram(newElements);
                }
            }
        }

        /**
         * Replaces children from `firstRefChild` to `lastRefChild` with specified element.
         * Accepts multiple replacement nodes using `Fragment`.
         *
         * @param {Element} newElement
         * @param {Element} firstRefChild
         * @param {Element} lastRefChild
         */

    }, {
        key: 'replaceChildren',
        value: function replaceChildren(newElement, firstRefChild, lastRefChild) {
            if (!firstRefChild || firstRefChild.parentElement !== this) {
                throw new Error('Invalid first reference child');
            }

            if (!lastRefChild || lastRefChild.parentElement !== this) {
                throw new Error('Invalid last reference child');
            }

            var firstIndex = this.childElements.indexOf(firstRefChild);
            var lastIndex = this.childElements.indexOf(lastRefChild);

            if (firstIndex > lastIndex) {
                throw new Error('Invalid reference children order');
            }

            var childrenBefore = this.childElements.slice(0, firstIndex);
            var childrenAfter = this.childElements.slice(lastIndex + 1);
            var replacedChildren = this.childElements.slice(firstIndex, lastIndex + 1);

            var children = void 0;
            var newElements = void 0;
            if (newElement.isFragment) {
                this._ensureCanAdoptFragment(newElement);
                children = childrenBefore.concat(newElement.childElements, childrenAfter);
                newElements = newElement.childElements;
            } else {
                if (newElement.parentElement) {
                    throw new Error('Remove element before adding again');
                }

                this._ensureCanAdopt(newElement);
                children = childrenBefore.concat(newElement, childrenAfter);
                newElements = [newElement];
            }

            this._setChildren(children);

            var ownerProgram = this.getOwnerProgram();

            if (ownerProgram) {
                ownerProgram._removeElementsFromProgram(replacedChildren);
            }

            for (var i = 0; i < replacedChildren.length; i++) {
                var replacedChild = replacedChildren[i];
                replacedChild.previousSibling = null;
                replacedChild.nextSibling = null;
                setParentElement(replacedChild, null);
            }

            if (ownerProgram && newElements) {
                ownerProgram._addElementsToProgram(newElements);
            }
        }

        /**
         * Removes children from `firstRefChild` to `lastRefChild` with specified element.
         *
         * @param {Element} firstRefChild
         * @param {Element} lastRefChild
         */

    }, {
        key: 'removeChildren',
        value: function removeChildren(firstRefChild, lastRefChild) {
            if (!firstRefChild || firstRefChild.parentElement !== this) {
                throw new Error('Invalid first reference child');
            }

            if (!lastRefChild || lastRefChild.parentElement !== this) {
                throw new Error('Invalid last reference child');
            }

            var firstIndex = this.childElements.indexOf(firstRefChild);
            var lastIndex = this.childElements.indexOf(lastRefChild);

            if (firstIndex > lastIndex) {
                throw new Error('Invalid reference children order');
            }

            var children = this.childElements.slice(0, firstIndex).concat(this.childElements.slice(lastIndex + 1));
            var removedChildren = this.childElements.slice(firstIndex, lastIndex + 1);

            this._setChildren(children);

            var ownerProgram = this.getOwnerProgram();

            if (ownerProgram) {
                ownerProgram._removeElementsFromProgram(removedChildren);
            }

            for (var i = 0; i < removedChildren.length; i++) {
                var removedChild = removedChildren[i];
                removedChild.previousSibling = null;
                removedChild.nextSibling = null;
                setParentElement(removedChild, null);
            }
        }

        /**
         * Replaces child with specified element.
         * Accepts multiple replacement nodes using `Fragment`.
         *
         * @param {Element} newElement
         * @param {Element} oldElement
         */

    }, {
        key: 'replaceChild',
        value: function replaceChild(newElement, oldElement) {
            this.replaceChildren(newElement, oldElement, oldElement);
        }

        /**
         * Returns array of child element from firstRefChild to lastRefChild (including reference children).
         *
         * @param {Element} firstRefChild
         * @param {Element} lastRefChild
         * @returns {Array}
         */

    }, {
        key: 'getChildrenBetween',
        value: function getChildrenBetween(firstRefChild, lastRefChild) {
            if (!firstRefChild || firstRefChild.parentElement !== this) {
                throw new Error('Invalid first reference child');
            }

            if (!lastRefChild || lastRefChild.parentElement !== this) {
                throw new Error('Invalid last reference child');
            }

            var firstIndex = this.childElements.indexOf(firstRefChild);
            var lastIndex = this.childElements.indexOf(lastRefChild);

            if (firstIndex > lastIndex) {
                throw new Error('Invalid reference children order');
            }

            return this.childElements.slice(firstIndex, lastIndex + 1);
        }

        /**
         * Makes sure specified child is not already one of the parents of this element.
         * Throws error on failure.
         *
         * @param {Element} child
         * @private
         */

    }, {
        key: '_ensureCanAdopt',
        value: function _ensureCanAdopt(child) {
            var element = this;
            while (element) {
                if (element === child) {
                    throw new Error('The new child element contains the parent.');
                }
                element = element.parentElement;
            }
        }

        /**
         * Calls _ensureCanAdopt for each fragment element.
         *
         * @param {Element} fragment
         * @private
         */

    }, {
        key: '_ensureCanAdoptFragment',
        value: function _ensureCanAdoptFragment(fragment) {
            var fragmentChild = fragment.firstChild;
            while (fragmentChild) {
                this._ensureCanAdopt(fragmentChild);
                fragmentChild = fragmentChild.nextSibling;
            }
        }

        /**
         * Assigns new children. Runs element syntax assertions.
         *
         * @param {Element[]} newChildren
         * @private
         */

    }, {
        key: '_setChildren',
        value: function _setChildren(newChildren) {
            this._acceptChildren(new _ElementAssert2.default(newChildren));

            if (newChildren.length > 0) {
                var previousChild = newChildren[0];
                this.firstChild = previousChild;
                previousChild.previousSibling = null;
                setParentElement(previousChild, this);
                if (newChildren.length > 1) {
                    // TODO(flow): error with only `let child;`
                    var child = newChildren[1];
                    for (var i = 1; i < newChildren.length; i++) {
                        child = newChildren[i];
                        child.previousSibling = previousChild;
                        setParentElement(child, this);
                        previousChild.nextSibling = child;
                        previousChild = child;
                    }
                    child.nextSibling = null;
                    this.lastChild = child;
                } else {
                    previousChild.nextSibling = null;
                    this.lastChild = previousChild;
                }
            } else {
                this.firstChild = this.lastChild = null;
            }

            this.childElements = newChildren;
        }

        /**
         * Runs element syntax assertions. Should be implemented for every Node.
         *
         * @param {Object} children
         * @abstract
         */

    }, {
        key: '_acceptChildren',
        value: function _acceptChildren(children) {}
        // Override

        /**
         * Clones current Element structure.
         *
         * @returns {Element}
         */

    }, {
        key: 'cloneElement',
        value: function cloneElement() {
            var clonedChildren = new Array(this.childElements.length);
            for (var i = 0; i < clonedChildren.length; i++) {
                clonedChildren[i] = this.childElements[i].cloneElement();
            }
            var objectToClone = this;
            return new objectToClone.constructor(clonedChildren);
        }
    }]);
    return Element;
}();

/**
 * Artificial class for correct flow behaviour.
 */

exports.default = Element;

var ConcreteElement = function (_Element) {
    (0, _inherits3.default)(ConcreteElement, _Element);

    function ConcreteElement(children) {
        (0, _classCallCheck3.default)(this, ConcreteElement);
        return (0, _possibleConstructorReturn3.default)(this, (ConcreteElement.__proto__ || (0, _getPrototypeOf2.default)(ConcreteElement)).call(this, 'ConcreteElement', children));
    }

    return ConcreteElement;
}(Element);

function setParentElement(element, parentElement) {
    element.parentElement = parentElement;
    if (element._onSetParentElement) {
        element._onSetParentElement(parentElement);
    }
}
//# sourceMappingURL=Element.js.map


text:
require "picktastic/version"
require "picktastic/engine"

module Picktastic
end


text:
#import <Foundation/Foundation.h>
#import "S3Request.h"
#import "S3Constants.h"

/** Request Object for Listing the Objects in the specified bucket.
 *
 */
@interface S3ListObjectsRequest:S3Request {
}

/** Limits the response to keys that begin with the specified prefix.
 *  You can use prefixes to separate a bucket into different groupings of keys.
 */
@property (nonatomic, retain) NSString *prefix;

/** Specifies the key to start with when listing objects in a bucket. Amazon
 *  S3 lists objects in alphabetical order.
 */
@property (nonatomic, retain) NSString *marker;

/**  A delimiter is a character you use to group keys. All keys that contain
 *   the same string between the prefix and the first occurrence of the
 *   delimiter are grouped under a single result element.
 */
@property (nonatomic, retain) NSString *delimiter;

/** Sets the maximum number of keys returned in the response body. The
 *  response might contain fewer keys but will never contain more.
 */
@property (nonatomic) int32_t maxKeys;

-(id)initWithName:(NSString *)theBucketName;

@end


text:
class ComponentLoop(object):

    def __init__(self, heppyResult, reader):
        self.reader = reader
        self.heppyResult = heppyResult
    def __call__(self):
        self.reader.begin()
        for component in self.heppyResult.components():
            self.reader.read(component)
        return self.reader.end()

##__________________________________________________________________||


text:
package com.regulus.tool.api.test.domain.repository.suites;

import com.regulus.tool.api.test.domain.model.TestSuite;
import com.regulus.tool.api.test.domain.repository.entity.TestSuiteEntity;
import com.regulus.tool.api.test.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static com.regulus.tool.api.test.util.Constants.JSON_FILE_SUFFIX;
import static java.util.stream.Collectors.toList;

@Repository("testSuitesRepository")
public class DefaultTestSuitesRepository implements TestSuitesRepository {

	@Value("${user.dir}/suites")
	private String testSuitesFolder;

	@Override
	public void saveTestSuite(TestSuite testSuite) {
		FileUtil.createOrSaveFile(Paths.get(testSuitesFolder, testSuite.getName() + JSON_FILE_SUFFIX), new TestSuiteEntity(testSuite));
	}

	@Override
	public void deleteTestSuite(String suiteName) {
		FileUtil.deleteFileIfExist(Paths.get(testSuitesFolder, suiteName + JSON_FILE_SUFFIX));
	}

	@Override
	public void renameTestSuite(String oldName, String newName) {
		FileUtil.renameFile(
				Paths.get(testSuitesFolder, oldName + JSON_FILE_SUFFIX),
				Paths.get(testSuitesFolder, newName + JSON_FILE_SUFFIX)
		);
	}

	@Override
	public List<String> loadAllTestSuiteNames() {
		return FileUtil.listJsonFilesUnder(testSuitesFolder)
				.map(FileUtil:: getJsonFileNameWithoutSuffix)
				.sorted()
				.collect(toList());
	}

	@Override
	public TestSuite loadTestSuite(String suiteName) {
		Path filePath = Paths.get(testSuitesFolder, suiteName + JSON_FILE_SUFFIX);
		TestSuiteEntity testSuiteEntity = FileUtil.readFile(filePath, TestSuiteEntity.class);
		return new TestSuite(testSuiteEntity, suiteName);
	}

	@Override
	public boolean isTestSuiteExist(String suiteName) {
		return Paths.get(testSuitesFolder, suiteName + JSON_FILE_SUFFIX).toFile().exists();
	}
}


text:
package goexperiment

const HeapMinimum512KiB = false
const HeapMinimum512KiBInt = 0


text:
var inherit = require('./inherit');

/**
 * High performance clock, based on mrdoob's
 * [Three.js clock](https://github.com/mrdoob/three.js/blob/master/src/core/Clock.js),
 * but with tweaks.
 *
 * @class Clock
 * @extends Object
 * @constructor
 */
var Clock = function() {
    this.startTime = 0;
    this.oldTime = 0;
    this.elapsedTime = 0;

    this.running = false;

    this.timer = window.performance && window.performance.now ? window.performance : Date;
};

inherit(Clock, Object, {
    /**
     * Gets the current time from the underlying timer
     *
     * @method now
     * @return {Number} The current timestamp
     * @example
     *      clock.now();
     */
    now: function() {
        return this.timer.now();
    },
    /**
     * Starts the timer
     *
     * @method start
     * @return {Clock} Returns itself.
     * @chainable
     * @example
     *      clock.start();
     */
    start: function() {
        this.startTime = this.oldTime = this.now();
        this.running = true;

        return this;
    },
    /**
     * Stops the timer
     *
     * @method stop
     * @return {Clock} Returns itself.
     * @chainable
     * @example
     *      clock.stop();
     */
    stop: function() {
        this.getElapsedTime();
        this.running = false;

        return this;
    },
    /**
     * Resets the timer
     *
     * @method reset
     * @return {Clock} Returns itself.
     * @chainable
     * @example
     *      clock.reset();
     */
    reset: function() {
        this.elapsedTime = 0;
        this.startTime = this.oldTime = this.now();

        return this;
    },
    /**
     * Gets the total time that the timer has been running
     *
     * @method getElapsedTime
     * @return {Number} Total ellapsed time in ms
     * @example
     *      clock.getElapsedTime();
     */
    getElapsedTime: function() {
        this.getDelta();

        return this.elapsedTime;
    },
    /**
     * Gets the difference in time since getDelta() was called last
     *
     * @method getDelta
     * @return {Number} Ellapsed time since last call in seconds
     * @example
     *      clock.getDelta();
     */
    getDelta: function() {
        var diff = 0;

        if(this.running) {
            var newTime = this.now();

            diff = 0.001 * (newTime - this.oldTime);
            this.oldTime = newTime;

            this.elapsedTime += diff;
        }

        return diff;
    }
});

module.exports = Clock;


text:
var Q = require('q'),
    Squad = require('../lib/node-squad.js');

//copyright nobody
var dataSet = ['This','is','how','we','reject','it'];
var config = {
    squadSize:3,
    disableLogs: false,
    stopOnReject:true
};

var job = function (item){
    var jobDeferred = Q.defer();

    //waiting randomly
    var randomWait = Math.floor(Math.random() * 1000) + 1;
    setTimeout(function(){
            jobDeferred.reject("sorry buddy");
        },
        randomWait);

    return jobDeferred.promise;
};

Squad.run(dataSet,job,config)
    .then(function(lyrics){
    console.log('Finished processing all the data.');
}).then(function(results){
       console.log("This 'then' should not be called!!!!!!!");
}).catch(function(error){
    config.stopOnReject = false;
    return Squad.run(dataSet,job,config).then(function(results){
        console.log("Here are the results : ");
        console.log(results);
    }).catch(function(){
        console.log("This 'catch' should not be called!!!!!!!");
    });
});


text:
[![travis build](https://img.shields.io/travis/mapcraftlabs/mapcraftjs.svg?style=flat-square)](https://travis-ci.org/mapcraftlabs/mapcraftjs)
[![codecov coverage](https://img.shields.io/codecov/c/github/mapcraftlabs/mapcraftjs.svg?style=flat-square)](https://codecov.io/github/mapcraftlabs/mapcraftjs)

## Themes

The first module we've added is a theming module, designed to take a vector of values and turn it into Leaflet styling objects for each element in the vector.

The API is pretty simple.  Just run

`var theme = new Theme(config, data);`

to create the theme (where config is a javascript object and data is a vector of values) and then

`var style = theme.getStyle(val);`

to get a Leaflet theme JSON object suitable for calling [layer.getStyle(style)](http://leafletjs.com/reference.html#path-setstyle).  You can also call

`var scaledVal = theme.getScaledVal(val);`

to get the actual scaled value if you don't want a style object.

#### Linear theming

All the challenge is in the config object for the theme.  Here is a simple example that maps the min/max values in the `data` array to a linear scale between two colors (using d3).

`opacity` sets the opacity of the shapes, `weight` is the thickness of the outside borders of the shapes, and `outlineColor` is the color of the border.  These other attributes can be added to all themes, although they are often omitted on this page for brevity.

```javascript
{
    opacity: .9,
    weight: 0,
    outlineColor: '#000000',
    scaleType: 'linear',
    interpolate: ['#fff5eb', '#7f2704']
}
```

You can use `interpolate: [500, 5000]` instead of using colors if you want the outcome to be integers instead of colors.  This can be used, e.g. to determine the radius of circles in the map.  *The resulting style objects will not work in Leaflet - just use `getScaledVal`*.

NaN values and undefined values will be themed as transparent.

You can also do a 3-way interpolation, for instance so that the number zero is always set to a certain color, with the middleValue attribute.

```javascript
{
    scaleType: 'linear',
    middleValue: 0,
    interpolate: ['#fff5eb', '#ffffff', '#7f2704']
}
```

You can also do a linear (continuous) interpolation with a color scheme, which uses the first and last colors from the colorbrewer color scheme to interpolate between.

```javascript
{
    scaleType: 'linear',
    colorScheme: 'YlGn'
}
```

#### Manual breaks

Manual breaks allows the user to specify the breakpoints.  In this case you don't have to pass `data` into the theme as the user has full control of the theme.  The color scheme is again from color brewer and the number of bins (colors) will be one greater than the number of breaks.  Note that most colorbrewer color schemes have versions for about 3 to 9 colors, so the number of breaks should generally be between 2 and 8 (whatever colorbrewer has specified for a given color scheme should work).

```javascript
{
    scaleType: 'manual',
    breaks: [4, 8, 20, 40],
    colorScheme: 'YlGn'
}
```

#### Categorical theming

Categorical theming can be used instead of the interpolate attribute by using the categorical theming instead.  In this case, values can be non-numeric, and are mapped to colors by the configuration.  A defaultColor attribute can be added and will be applied to any values which don't exist in the theme.  A full spec might look like this.

```javascript
{
    scaleType: 'categorical',
    defaultColor: '#ABCDEF',
    categories: {
        'Office': '#ff9999',
        'Hotel': '#ff9933',
        'Retail': '#FF0000',
        'Residential': '#FFFF00',
        'Industrial': '#A020F0',
        'School': '#0000FF',
        'Vacant': '#FFFFFF',
        'Parking': '#666666'
    }
}
```

#### Auto-categorical theming

Similar to categorical theming, but maps unique values to the random d3 color scheme (d3.category20).  This is an easy way to map all possible values that actually occur in the data to discrete color.

```javascript
{
    scaleType: 'autocategorical'
}
```

#### Quantile theming

Quantile themed maps map each quantile of the input array to a color scheme from [colorbrewer](http://colorbrewer2.org/).  You need to specify both the name of the color scheme (`colorScheme`) and the number of bins (`numBins`) to use.  For quantile theming, the number of bins is equal to the number of quantiles that will be given separate colors.

```javascript
{
    scaleType: 'quantile',
    colorScheme: 'YlGn',
    numBins: 7
}
```

#### Jenks

For natural clustering you can use jenks. This actually uses the simple-statistics method ckmeans, but I figure most people looking for it will look for jenks.

```javascript
{
    scaleType: 'jenks',
    numBins: 5,
    colorScheme: 'YlGn'
}
```


text: A web application to read web comics keeping last page


text:
// ReSharper disable All

namespace OpenTl.Schema.Messages
{
	using System;
	using System.Collections;
	using System.Text;

	using OpenTl.Schema;
	using OpenTl.Schema.Serialization.Attributes;

	[Serialize(0xedfd405f)]
	public sealed class TAllStickers : IAllStickers
	{
       [SerializationOrder(0)]
       public int Hash {get; set;}

       [SerializationOrder(1)]
       public OpenTl.Schema.TVector<OpenTl.Schema.IStickerSet> Sets {get; set;}

	}
}


text:
package org.atrzaska.rsi2.mashup.string;

public class RemoveExtraSpacesTransform implements IStringTransform {
    public String applyTransform(String input) {
        String output = input;

        output = output.replace("          ", " ");
        output = output.replace("         ", " ");
        output = output.replace("        ", " ");
        output = output.replace("       ", " ");
        output = output.replace("      ", " ");
        output = output.replace("     ", " ");
        output = output.replace("    ", " ");
        output = output.replace("   ", " ");
        output = output.replace("  ", " ");

        output = output.replace(" \r\n", " ");
        output = output.replace(" \n", " ");

        // check for extra space at the beginning
        if(output.startsWith(" ")) {
            output = output.substring(1);
        }

        // check for extra space at the end
        if(output.endsWith(" ")) {
            output = output.substring(0, output.length()- 1);
        }

        return output;
    }

}


text:
<?php namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class SpawnSeederCommand extends GeneratorCommand {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'spawn:seeder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new seeder class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Spawn';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return base_path().'/resources/stubs/seeder.stub';
    }

    /**
     * Get the destination class path.
     *
     * @param  string  $name
     * @return string
     */
    protected function getPath($name)
    {
        return base_path().'/database/seeds/'.$name.'TableSeeder.php';
    }

    /**
     * Parse the name and format according to the root namespace.
     *
     * @param  string  $name
     * @return string
     */
    protected function parseName($name)
    {
        return $name;
    }

}


text:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Nardax.Serialization
{
    public class BinarySerializer<T> : ISerializer<T, byte[]>
    {
        //Serialiserar ett värde med valfri typ
        public byte[] Serialize(T value)
        {
            using (var stream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(stream, value);
                return stream.ToArray();
            }
        }

        public T Deserialize(byte[] bytes)
        {
            using (var memoryStream = new MemoryStream(bytes))
            {
                var binaryFormatter = new BinaryFormatter();
                memoryStream.Position = 0;
                return (T)binaryFormatter.Deserialize(memoryStream);
            }
        }
    }
}


text:
// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <consensus/consensus.h>
#include <policy/policy.h> // ELEMENTS: for policyAsset
#include <wallet/receive.h>
#include <wallet/transaction.h>
#include <wallet/wallet.h>

isminetype CWallet::IsMine(const CTxIn& txin) const
{
    AssertLockHeld(cs_wallet);
    return IsMine(txin.prevout);
}

isminetype CWallet::IsMine(const COutPoint &outpoint) const
{
    AssertLockHeld(cs_wallet);
    std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(outpoint.hash);
    if (mi != mapWallet.end())
    {
        const CWalletTx& prev = (*mi).second;
        if (outpoint.n < prev.tx->vout.size())
            return IsMine(prev.tx->vout[outpoint.n]);
    }
    return ISMINE_NO;
}

bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
{
    LOCK(cs_wallet);

    for (const CTxIn& txin : tx.vin)
    {
        auto mi = mapWallet.find(txin.prevout.hash);
        if (mi == mapWallet.end())
            return false; // any unknown inputs can't be from us

        const CWalletTx& prev = (*mi).second;

        if (txin.prevout.n >= prev.tx->vout.size())
            return false; // invalid input!

        if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
            return false;
    }
    return true;
}

CAmountMap CWallet::GetCredit(const CWalletTx& wtx, const isminefilter& filter) const {
    CAmountMap nCredit;
    for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
        if (IsMine(wtx.tx->vout[i]) & filter) {
            CAmount credit = std::max<CAmount>(0, wtx.GetOutputValueOut(i));
            if (!MoneyRange(credit))
                throw std::runtime_error(std::string(__func__) + ": value out of range");

            nCredit[wtx.GetOutputAsset(i)] += credit;
            if (!MoneyRange(nCredit))
                throw std::runtime_error(std::string(__func__) + ": value out of range");
        }
    }
    return nCredit;
}

CAmountMap CWallet::GetChange(const CWalletTx& wtx) const {
    CAmountMap nChange;
    for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
        if (IsChange(wtx.tx->vout[i])) {
            CAmount change = wtx.GetOutputValueOut(i);
            if (change < 0) {
                continue;
            }

            if (!MoneyRange(change))
                throw std::runtime_error(std::string(__func__) + ": value out of range");

            nChange[wtx.GetOutputAsset(i)] += change;
            if (!MoneyRange(nChange))
                throw std::runtime_error(std::string(__func__) + ": value out of range");
        }
    }
    return nChange;
}

CAmountMap CWallet::GetChange(const CTransaction& tx) const
{
    LOCK(cs_wallet);
    CAmountMap nChange;
    for (const CTxOut& txout : tx.vout)
    {
        nChange += GetChange(txout);
        if (!MoneyRange(nChange))
            throw std::runtime_error(std::string(__func__) + ": value out of range");
    }
    return nChange;
}

bool CWallet::IsChange(const CTxOut& txout) const
{
    return IsChange(txout.scriptPubKey);
}

bool CWallet::IsChange(const CScript& script) const
{
    // TODO: fix handling of 'change' outputs. The assumption is that any
    // payment to a script that is ours, but is not in the address book
    // is change. That assumption is likely to break when we implement multisignature
    // wallets that return change back into a multi-signature-protected address;
    // a better way of identifying which outputs are 'the send' and which are
    // 'the change' will need to be implemented (maybe extend CWalletTx to remember
    // which output, if any, was change).
    AssertLockHeld(cs_wallet);
    if (IsMine(script))
    {
        CTxDestination address;
        if (!ExtractDestination(script, address))
            return true;
        if (!FindAddressBookEntry(address)) {
            return true;
        }
    }
    return false;
}

CAmountMap CWallet::GetChange(const CTxOut& txout) const
{
    AssertLockHeld(cs_wallet);

    CAmountMap change;
    change[txout.nAsset.GetAsset()] = txout.nValue.GetAmount();
    if (!MoneyRange(change))
        throw std::runtime_error(std::string(__func__) + ": value out of range");
    return (IsChange(txout) ? change : CAmountMap());
}

CAmountMap CWalletTx::GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate) const
{
    auto& amount = m_amounts[type];
    if (recalculate || !amount.m_cached[filter]) {
        amount.Set(filter, type == DEBIT ? pwallet->GetDebit(*tx, filter) : pwallet->GetCredit(*this, filter));
        m_is_cache_empty = false;
    }
    return amount.m_value[filter];
}

CAmountMap CWalletTx::GetCredit(const isminefilter& filter) const
{
    // Must wait until coinbase is safely deep enough in the chain before valuing it
    if (IsImmatureCoinBase())
        return CAmountMap();

    CAmountMap credit;
    if (filter & ISMINE_SPENDABLE) {
        // GetBalance can assume transactions in mapWallet won't change
        credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE);
    }
    if (filter & ISMINE_WATCH_ONLY) {
        credit += GetCachableAmount(CREDIT, ISMINE_WATCH_ONLY);
    }
    return credit;
}

CAmountMap CWallet::GetCredit(const CTransaction& tx, const size_t out_index, const isminefilter& filter) const
{
    {
        LOCK(cs_wallet);
        std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(tx.GetHash());
        if (mi != mapWallet.end())
        {
            const CWalletTx& wtx = (*mi).second;
            if (out_index < wtx.tx->vout.size() && IsMine(wtx.tx->vout[out_index]) & filter) {
                CAmountMap amounts;
                amounts[wtx.GetOutputAsset(out_index)] = std::max<CAmount>(0, wtx.GetOutputValueOut(out_index));
                return amounts;
            }
        }
    }
    return CAmountMap();
}

CAmountMap CWalletTx::GetDebit(const isminefilter& filter) const
{
    if (tx->vin.empty())
        return CAmountMap();

    CAmountMap debit;
    if (filter & ISMINE_SPENDABLE) {
        debit += GetCachableAmount(DEBIT, ISMINE_SPENDABLE);
    }
    if (filter & ISMINE_WATCH_ONLY) {
        debit += GetCachableAmount(DEBIT, ISMINE_WATCH_ONLY);
    }
    return debit;
}

CAmountMap CWalletTx::GetChange() const
{
    if (fChangeCached)
        return nChangeCached;
    nChangeCached = pwallet->GetChange(*this);
    fChangeCached = true;
    return nChangeCached;
}

CAmountMap CWalletTx::GetImmatureCredit(bool fUseCache) const
{
    if (IsImmatureCoinBase() && IsInMainChain()) {
        return GetCachableAmount(IMMATURE_CREDIT, ISMINE_SPENDABLE, !fUseCache);
    }

    return CAmountMap();
}

CAmountMap CWalletTx::GetImmatureWatchOnlyCredit(const bool fUseCache) const
{
    if (IsImmatureCoinBase() && IsInMainChain()) {
        return GetCachableAmount(IMMATURE_CREDIT, ISMINE_WATCH_ONLY, !fUseCache);
    }

    return CAmountMap();
}

CAmountMap CWalletTx::GetAvailableCredit(bool fUseCache, const isminefilter& filter) const
{
    if (pwallet == nullptr)
        return CAmountMap();

    // Avoid caching ismine for NO or ALL cases (could remove this check and simplify in the future).
    bool allow_cache = (filter & ISMINE_ALL) && (filter & ISMINE_ALL) != ISMINE_ALL;

    // Must wait until coinbase is safely deep enough in the chain before valuing it
    if (IsImmatureCoinBase())
        return CAmountMap();

    if (fUseCache && allow_cache && m_amounts[AVAILABLE_CREDIT].m_cached[filter]) {
        return m_amounts[AVAILABLE_CREDIT].m_value[filter];
    }

    bool allow_used_addresses = (filter & ISMINE_USED) || !pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE);
    CAmountMap nCredit;
    uint256 hashTx = GetHash();
    for (unsigned int i = 0; i < tx->vout.size(); i++)
    {
        if (!pwallet->IsSpent(hashTx, i) && (allow_used_addresses || !pwallet->IsSpentKey(hashTx, i))) {
            if (pwallet->IsMine(tx->vout[i]) & filter) {
                CAmount credit = std::max<CAmount>(0, GetOutputValueOut(i));
                if (!MoneyRange(credit))
                    throw std::runtime_error(std::string(__func__) + ": value out of range");

                nCredit[GetOutputAsset(i)] += std::max<CAmount>(0, GetOutputValueOut(i));
                if (!MoneyRange(nCredit))
                    throw std::runtime_error(std::string(__func__) + ": value out of range");
            }
        }
    }

    if (allow_cache) {
        m_amounts[AVAILABLE_CREDIT].Set(filter, nCredit);
        m_is_cache_empty = false;
    }

    return nCredit;
}

void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
                           std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const
{
    nFee = 0;
    listReceived.clear();
    listSent.clear();

    // Compute fee:
    CAmountMap mapDebit = GetDebit(filter);
    if (mapDebit > CAmountMap()) // debit>0 means we signed/sent this transaction
    {
        nFee = -GetFeeMap(*tx)[::policyAsset];
    }

    LOCK(pwallet->cs_wallet);
    // Sent/received.
    for (unsigned int i = 0; i < tx->vout.size(); ++i)
    {
        const CTxOut& txout = tx->vout[i];
        CAmount output_value = GetOutputValueOut(i);
        // Don't list unknown assets
        isminetype fIsMine = output_value != -1 ?  pwallet->IsMine(txout) : ISMINE_NO;
        // Only need to handle txouts if AT LEAST one of these is true:
        //   1) they debit from us (sent)
        //   2) the output is to us (received)
        if (mapDebit > CAmountMap())
        {
            // Don't report 'change' txouts
            if (pwallet->IsChange(txout))
                continue;
        }
        else if (!(fIsMine & filter))
            continue;

        // In either case, we need to get the destination address
        CTxDestination address;

        if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
        {
            pwallet->WalletLogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
                                    this->GetHash().ToString());
            address = CNoDestination();
        }

        COutputEntry output = {address, output_value, (int)i, GetOutputAsset(i), GetOutputAmountBlindingFactor(i), GetOutputAssetBlindingFactor(i)};

        // If we are debited by the transaction, add the output as a "sent" entry
        if (mapDebit > CAmountMap() && !txout.IsFee())
            listSent.push_back(output);

        // If we are receiving the output, add it as a "received" entry
        if (fIsMine & filter)
            listReceived.push_back(output);
    }

}

bool CWallet::IsTrusted(const CWalletTx& wtx, std::set<uint256>& trusted_parents) const
{
    AssertLockHeld(cs_wallet);
    // Quick answer in most cases
    if (!chain().checkFinalTx(*wtx.tx)) return false;
    int nDepth = wtx.GetDepthInMainChain();
    if (nDepth >= 1) return true;
    if (nDepth < 0) return false;
    // using wtx's cached debit
    if (!m_spend_zero_conf_change || !wtx.IsFromMe(ISMINE_ALL)) return false;

    // Don't trust unconfirmed transactions from us unless they are in the mempool.
    if (!wtx.InMempool()) return false;

    // Trusted if all inputs are from us and are in the mempool:
    for (const CTxIn& txin : wtx.tx->vin)
    {
        // Transactions not sent by us: not trusted
        const CWalletTx* parent = GetWalletTx(txin.prevout.hash);
        if (parent == nullptr) return false;
        const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
        // Check that this specific input being spent is trusted
        if (IsMine(parentOut) != ISMINE_SPENDABLE) return false;
        // If we've already trusted this parent, continue
        if (trusted_parents.count(parent->GetHash())) continue;
        // Recurse to check that the parent is also trusted
        if (!IsTrusted(*parent, trusted_parents)) return false;
        trusted_parents.insert(parent->GetHash());
    }
    return true;
}

bool CWalletTx::IsTrusted() const
{
    std::set<uint256> trusted_parents;
    LOCK(pwallet->cs_wallet);
    return pwallet->IsTrusted(*this, trusted_parents);
}

CWallet::Balance CWallet::GetBalance(const int min_depth, bool avoid_reuse) const
{
    Balance ret;
    isminefilter reuse_filter = avoid_reuse ? ISMINE_NO : ISMINE_USED;
    {
        LOCK(cs_wallet);
        std::set<uint256> trusted_parents;
        for (const auto& entry : mapWallet)
        {
            const CWalletTx& wtx = entry.second;
            const bool is_trusted{IsTrusted(wtx, trusted_parents)};
            const int tx_depth{wtx.GetDepthInMainChain()};
            const CAmountMap tx_credit_mine{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_SPENDABLE | reuse_filter)};
            const CAmountMap tx_credit_watchonly{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_WATCH_ONLY | reuse_filter)};
            if (is_trusted && tx_depth >= min_depth) {
                ret.m_mine_trusted += tx_credit_mine;
                ret.m_watchonly_trusted += tx_credit_watchonly;
            }
            if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
                ret.m_mine_untrusted_pending += tx_credit_mine;
                ret.m_watchonly_untrusted_pending += tx_credit_watchonly;
            }
            ret.m_mine_immature += wtx.GetImmatureCredit();
            ret.m_watchonly_immature += wtx.GetImmatureWatchOnlyCredit();
        }
    }
    return ret;
}

std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() const
{
    std::map<CTxDestination, CAmount> balances;

    {
        LOCK(cs_wallet);
        std::set<uint256> trusted_parents;
        for (const auto& walletEntry : mapWallet)
        {
            const CWalletTx& wtx = walletEntry.second;

            if (!IsTrusted(wtx, trusted_parents))
                continue;

            if (wtx.IsImmatureCoinBase())
                continue;

            int nDepth = wtx.GetDepthInMainChain();
            if (nDepth < (wtx.IsFromMe(ISMINE_ALL) ? 0 : 1))
                continue;

            for (unsigned int i = 0; i < wtx.tx->vout.size(); i++)
            {
                CTxDestination addr;
                if (!IsMine(wtx.tx->vout[i]))
                    continue;
                if(!ExtractDestination(wtx.tx->vout[i].scriptPubKey, addr))
                    continue;

                CAmount n = IsSpent(walletEntry.first, i) ? 0 : wtx.GetOutputValueOut(i);
                if (n < 0) {
                    continue;
                }
                balances[addr] += n;
            }
        }
    }

    return balances;
}

std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings() const
{
    AssertLockHeld(cs_wallet);
    std::set< std::set<CTxDestination> > groupings;
    std::set<CTxDestination> grouping;

    for (const auto& walletEntry : mapWallet)
    {
        const CWalletTx& wtx = walletEntry.second;

        if (wtx.tx->vin.size() > 0)
        {
            bool any_mine = false;
            // group all input addresses with each other
            for (const CTxIn& txin : wtx.tx->vin)
            {
                CTxDestination address;
                if(!IsMine(txin)) /* If this input isn't mine, ignore it */
                    continue;
                if(!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
                    continue;
                grouping.insert(address);
                any_mine = true;
            }

            // group change with input addresses
            if (any_mine)
            {
               for (const CTxOut& txout : wtx.tx->vout)
                   if (IsChange(txout))
                   {
                       CTxDestination txoutAddr;
                       if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
                           continue;
                       grouping.insert(txoutAddr);
                   }
            }
            if (grouping.size() > 0)
            {
                groupings.insert(grouping);
                grouping.clear();
            }
        }

        // group lone addrs by themselves
        for (const auto& txout : wtx.tx->vout)
            if (IsMine(txout))
            {
                CTxDestination address;
                if(!ExtractDestination(txout.scriptPubKey, address))
                    continue;
                grouping.insert(address);
                groupings.insert(grouping);
                grouping.clear();
            }
    }

    std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
    std::map< CTxDestination, std::set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
    for (std::set<CTxDestination> _grouping : groupings)
    {
        // make a set of all the groups hit by this new group
        std::set< std::set<CTxDestination>* > hits;
        std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
        for (const CTxDestination& address : _grouping)
            if ((it = setmap.find(address)) != setmap.end())
                hits.insert((*it).second);

        // merge all hit groups into a new single group and delete old groups
        std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
        for (std::set<CTxDestination>* hit : hits)
        {
            merged->insert(hit->begin(), hit->end());
            uniqueGroupings.erase(hit);
            delete hit;
        }
        uniqueGroupings.insert(merged);

        // update setmap
        for (const CTxDestination& element : *merged)
            setmap[element] = merged;
    }

    std::set< std::set<CTxDestination> > ret;
    for (const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
    {
        ret.insert(*uniqueGrouping);
        delete uniqueGrouping;
    }

    return ret;
}

// ELEMENTS
CAmountMap CWalletTx::GetIssuanceAssets(unsigned int input_index) const {
    CAmountMap ret;
    CAsset asset, token;
    GetIssuanceAssets(input_index, &asset, &token);
    if (!asset.IsNull()) {
        ret[asset] = GetIssuanceAmount(input_index, false);
    }
    if (!token.IsNull()) {
        ret[token] = GetIssuanceAmount(input_index, true);
    }
    return ret;
}
// end ELEMENTS


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractSyntax.Expression
{
    [Serializable]
    public class ElementList<ELEMENT> : Element, IReadOnlyList<ELEMENT> where ELEMENT : Element
    {
        public ElementList()
        {

        }

        public ElementList(TextPosition tp, IReadOnlyList<Element> child)
            :base(tp)
        {
            AppendChild(child);
        }

        public new ELEMENT this[int index]
        {
            get { return (ELEMENT)base[index]; }
        }

        public new IEnumerator<ELEMENT> GetEnumerator()
        {
            for (var i = 0; i < Count; ++i)
            {
                yield return this[i];
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Ploeh.AutoFixture.Kernel;
using Ploeh.TestTypeFoundation;
using Xunit;
using Xunit.Extensions;

namespace Ploeh.AutoFixtureUnitTest.Kernel
{
    public class SortedSetSpecificationTest
    {
        [Fact]
        public void SutIsRequestSpecification()
        {
            // Fixture setup
            // Exercise system
            var sut = new SortedSetSpecification();
            // Verify outcome
            Assert.IsAssignableFrom<IRequestSpecification>(sut);
            // Teardown
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData(1)]
        [InlineData(typeof(object))]
        [InlineData(typeof(string))]
        [InlineData(typeof(int))]
        [InlineData(typeof(Version))]
        [InlineData(typeof(int?))]
        [InlineData(typeof(EmptyEnum?))]
        [InlineData(typeof(object[]))]
        [InlineData(typeof(string[]))]
        [InlineData(typeof(int[]))]
        [InlineData(typeof(Version[]))]
        [InlineData(typeof(int?[]))]
        [InlineData(typeof(EmptyEnum?[]))]
        public void IsSatisfiedByNonSortedSetRequestReturnsCorrectResult(object request)
        {
            // Fixture setup.
            var sut = new SortedSetSpecification();
            // Exercise system
            var result = sut.IsSatisfiedBy(request);
            // Verify outcome
            Assert.False(result);
            // Teardown
        }

        [Theory]
        [InlineData(typeof(SortedSet<string>))]
        [InlineData(typeof(SortedSet<int>))]
        [InlineData(typeof(SortedSet<object>))]
        [InlineData(typeof(SortedSet<Version>))]
        [InlineData(typeof(SortedSet<int?>))]
        [InlineData(typeof(SortedSet<EmptyEnum?>))]
        [InlineData(typeof(SortedSet<string[]>))]
        [InlineData(typeof(SortedSet<int[]>))]
        [InlineData(typeof(SortedSet<object[]>))]
        [InlineData(typeof(SortedSet<Version[]>))]
        [InlineData(typeof(SortedSet<int?[]>))]
        [InlineData(typeof(SortedSet<EmptyEnum?[]>))]
        public void IsSatisfiedBySortedSetRequestReturnsCorrectResult(object request)
        {
            // Fixture setup
            var sut = new SortedSetSpecification();
            // Exercise system
            var result = sut.IsSatisfiedBy(request);
            // Verify outcome
            Assert.True(result);
            // Teardown
        }
    }
}