text:
package tfexamples

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"math"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"

	"github.com/youpy/go-wav"

	"github.com/google-research/korvapuusti/analysis/data_processing/spectrum"
	"github.com/google-research/korvapuusti/tools/carfac"
)

// Counts the number of digits in an integer.
func iterativeDigitsCount(number int64) int64 {
	count := 0
	for number != 0 {
		number /= 10
		count++
	}
	return int64(count)

}

// Extracts integer from a string (e.g., "0060.00" becomes 60)
func getNumberFromStr(inputStr string) (float32, error) {
	re := regexp.MustCompile(`[-]?\d[\d,]*[\.]?[\d{2}]*`)
	number, err := strconv.ParseFloat(re.FindString(inputStr), 32)
	if err != nil {
		return 0, err
	}
	return float32(number), nil
}

// Extracts frequencies and levels from file string
// r000001_combined_00060.00Hz_-50.00dBFS+04800.00Hz_-60.00dBFS.wav
// becomes frequencies 60, 4800 and levels -50, -60
// TODO: calculate other db level.
func extractMetadataFile(file string) ([]float32, []float32, error) {
	s := strings.Split(file, "/")
	s1 := s[len(s)-1]
	s2 := strings.Split(s1, "+")
	toneLevelProbe := strings.Split(s2[0], "_")
	toneLevelMasker := strings.Split(s2[1], "_")
	frequencyProbe, err := getNumberFromStr(toneLevelProbe[2])
	if err != nil {
		return nil, nil, err
	}
	frequencyMasker, err := getNumberFromStr(toneLevelMasker[0])
	if err != nil {
		return nil, nil, err
	}
	levelMasker, err := getNumberFromStr(toneLevelMasker[1])
	if err != nil {
		return nil, nil, err
	}
	levelProbe, err := getNumberFromStr(toneLevelProbe[3])
	if err != nil {
		return nil, nil, err
	}
	frequencies := []float32{frequencyProbe, frequencyMasker}
	levels := []float32{levelProbe, levelMasker}
	return frequencies, levels, nil
}

// Opens wave file and returns the samples in an array of max length maxSamples
func readWavfile(filePath string, maxSamples int, skipNSamples int) ([]float32, error) {
	// OpenRead the file
	f, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	reader := wav.NewReader(f)
	defer f.Close()

	var buffer []float32
	totalNSamples := 0
	for {
		samples, err := reader.ReadSamples()
		if err == io.EOF {
			break
		} else if err != nil {
			return nil, err
		}
		for _, sample := range samples {
			if totalNSamples > skipNSamples {
				buffer = append(buffer, float32(reader.FloatValue(sample, 0)))
			}
			totalNSamples++
		}
		if len(buffer) >= maxSamples {
			break
		}
	}
	return buffer, nil
}

// Calculates the CARFAC NAP features from a buffer.
func getCarfacFeatures(sampleRate int, carfacBuffer []float32) (int, []float32, error) {
	cf := carfac.New(sampleRate)
	cf.Run(carfacBuffer)
	NAP, err := cf.NAP()
	if err != nil {
		return 0, nil, err
	}
	return cf.NumChannels(), NAP, nil
}

// Calculate FFT and SNR on each CARFAC channel.
func getSignalNoiseFeaturesCarfac(sampleRate int, fftWindowSize int, numChannels int,
	carfacFeatures []float32, carfacStableIdx int) (int, []float32, []float32) {
	signalPowerFeatures := make([]float32, numChannels*(fftWindowSize/2))
	noisePowerFeatures := make([]float32, numChannels*(fftWindowSize/2))
	numBins := 0
	for channelIdx := 0; channelIdx < numChannels; channelIdx++ {
		buffer := make([]float64, fftWindowSize)
		for freqIdx := range buffer {
			buffer[freqIdx] = float64(carfacFeatures[(channelIdx + (carfacStableIdx+freqIdx)*numChannels)])
		}
		spec := spectrum.Compute(buffer, sampleRate)
		numBins = len(spec.SignalPower)
		for freqIdx := range spec.SignalPower {
			signalPowerFeatures[channelIdx*numBins+freqIdx] = float32(spec.SignalPower[freqIdx])
			noisePowerFeatures[channelIdx*numBins+freqIdx] = float32(spec.NoisePower[freqIdx])
		}
	}
	return numBins, signalPowerFeatures, noisePowerFeatures
}

// Calculate FFT and SNR on the buffer.
func getSignalNoiseFeatures(sampleRate int, fftWindowSize int, features []float32) (int, []float32, []float32, []float32, []float32) {
	signalPowerFeatures := make([]float32, fftWindowSize/2)
	noisePowerFeatures := make([]float32, fftWindowSize/2)
	fftCoefficients := make([]float32, fftWindowSize/2)
	numBins := 0
	buffer := make([]float64, fftWindowSize)
	float32buffer := make([]float32, fftWindowSize)
	for freqIdx := range buffer {
		buffer[freqIdx] = float64(features[freqIdx])
		float32buffer[freqIdx] = float32(features[freqIdx])
	}
	spec := spectrum.Compute(buffer, sampleRate)
	numBins = len(spec.SignalPower)
	for freqIdx := range spec.SignalPower {
		signalPowerFeatures[freqIdx] = float32(spec.SignalPower[freqIdx])
		noisePowerFeatures[freqIdx] = float32(spec.NoisePower[freqIdx])
		fftCoefficients[freqIdx] = float32(spec.Coefficients[freqIdx])
	}
	return numBins, signalPowerFeatures, noisePowerFeatures, fftCoefficients, float32buffer
}

type example struct {
	SampleRate           int       `json:"samplerate"`
	Frequencies          []float32 `json:"frequencies"`
	SPLs                 []float32 `json:"spls"`
	ProbeFrequency       float32   `json:"probefrequency"`
	ProbeLevel           int       `json:"probelevel"`
	ProbeLoudness        int       `json:"probeloudness"`
	ProbeMasking         float32   `json:"probemasking"`
	Channels             int       `json:"channels"`
	Bins                 int       `json:"bins"`
	SpectrumSignalCarfac []float32 `json:"spectrumsignalcarfac"`
	SpectrumNoiseCarfac  []float32 `json:"spectrumnoisecarfac"`
	SpectrumSignal       []float32 `json:"spectrumsignal"`
	SpectrumNoise        []float32 `json:"spectrumnoise"`
	Coefficients         []float32 `json:"coefficients"`
	Buffer               []float32 `json:"buffer"`
}

type ExampleId struct {
	ProbeFrequency       float32   `json:"probe_frequency"`
	ProbeLevel           int       `json:"probe_level"`
	PerceivedProbeLevels []float64 `json:"perceived_probe_levels"`
	WorkerIds            []int     `json:"worker_ids"`
	MaskerFrequency      float32   `json:"masker_frequency"`
	MaskerLevel          int       `json:"masker_level"`
	WavfileIdentifier    string    `json:"wavfile_identifier"`
}

// WriteExamplesToRecordIO writes TF examples to recordio shards.
func WriteExamplesToRecordIO(waveFileDirectory string, dataPath string, filePrefix string, shardSize int, carfacStableIdx int,
	fftWindowSize int, sampleRate int, skipSeconds float64, unityDBLevel float64, extractMetaDataFromFile bool) error {
	count := 0
	var done func()
	defer func() {
		if done != nil {
			done()
		}
	}()
	files, err := os.Open(waveFileDirectory)
	if err != nil {
		return err
	}
	readFiles, err := files.Readdir(-1)
	files.Close()
	if err != nil {
		return err
	}

	file, err := os.Open(dataPath)
	if err != nil {
		return err
	}

	defer file.Close()

	bytesData, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}

	var exampleIds []ExampleId

	error := json.Unmarshal(bytesData, &exampleIds)
	if error != nil {
		return error
	}

	// Calculate how many samples to skip.
	skipNSamples := int(float64(sampleRate) * skipSeconds)

	allData := []*example{}
	dataExamples := 0
	wroteExamples := 0

	// Loop over all files in the provided directory.
	for _, exampleID := range exampleIds {
		var foundMatch bool

		if exampleID.ProbeFrequency == 17625.0 {
			continue
		}
		perceivedProbeLevels := exampleID.PerceivedProbeLevels
		actualProbeLevel := exampleID.ProbeLevel
		sum := 0.
		maskingSum := 0.
		for _, perceivedLevel := range perceivedProbeLevels {
			sum = sum + perceivedLevel
			masking := math.Max(0., float64(actualProbeLevel)-perceivedLevel)
			maskingSum = maskingSum + masking
		}
		meanPerceivedLevel := int(math.Abs(sum / float64(len(perceivedProbeLevels))))
		meanProbeMasking := float32(math.Abs(float64(maskingSum / float64(len(perceivedProbeLevels)))))

		for fileIdx, infilePath := range readFiles {
			wavfileidentifier := ""
			if extractMetaDataFromFile {
				wavfileidentifier = exampleID.WavfileIdentifier
			} else {
				wavfileidentifierSplit := strings.Split(exampleID.WavfileIdentifier, "/")
				wavfileidentifier = wavfileidentifierSplit[len(wavfileidentifierSplit)-1]
			}
			matched, _ := filepath.Match("*"+wavfileidentifier,
				infilePath.Name())
			// Only take combined tones.
			if matched {
				foundMatch = true
				fmt.Printf("Working on file %d: %s\n", fileIdx, infilePath.Name())

				// Extract all information needed from the file.
				levels := []float32{}
				frequencies := []float32{}
				if extractMetaDataFromFile {
					frequencies, levels, err = extractMetadataFile(infilePath.Name())
					otherFrequencies := []float32{exampleID.MaskerFrequency, exampleID.ProbeFrequency}
					for idx, frequency := range frequencies {
						if math.Floor(float64(frequency)) != math.Floor(float64(otherFrequencies[idx])) && math.Ceil(float64(frequency)) != math.Ceil(float64(otherFrequencies[idx])) {
							fmt.Printf("Frequency 1: %f Frequency 2: %f", frequency, otherFrequencies[idx])
							err := errors.New("mismatch between dataFile and WavFiles")
							return err
						}
					}
				} else {
					frequencies = []float32{exampleID.MaskerFrequency, exampleID.ProbeFrequency}
				}

				if err != nil {
					return err
				}
				buffer, err := readWavfile(path.Join(waveFileDirectory, infilePath.Name()), carfacStableIdx+(fftWindowSize*10), skipNSamples)
				if err != nil {
					return err
				}

				// Get CARFAC features.
				numChannels, NAP, err := getCarfacFeatures(sampleRate, buffer)
				if err != nil {
					return err
				}
				numBins, signalPowerFeaturesCarfac, noisePowerFeaturesCarfac := getSignalNoiseFeaturesCarfac(sampleRate, fftWindowSize,
					numChannels, NAP, carfacStableIdx)
				numBinsTwo, signalPowerFeatures, noisePowerFeatures, fftCoefficients, buffer := getSignalNoiseFeatures(sampleRate, fftWindowSize, buffer)
				if numBins != numBinsTwo {
					err := errors.New("Two different number of frequency bins after FFT.")
					return err
				}
				realLevels := []float32{}
				if extractMetaDataFromFile {
					for _, level := range levels {
						realLevel := level + float32(unityDBLevel)
						realLevels = append(realLevels, realLevel)
					}
					otherLevels := []float32{float32(exampleID.MaskerLevel), float32(exampleID.ProbeLevel)}
					for idx, level := range realLevels {
						fmt.Printf("level 1: %f level 2: %f", level, otherLevels[idx])
						if level != otherLevels[idx] {
							err := errors.New("mismatch between dataFile and WavFiles")
							return err
						}
					}
				} else {
					realLevels = []float32{float32(exampleID.MaskerLevel), float32(exampleID.ProbeLevel)}
				}

				// Save to TF Example and write to file.
				example := &example{
					SampleRate:           sampleRate,
					Frequencies:          frequencies,
					SPLs:                 realLevels,
					ProbeFrequency:       exampleID.ProbeFrequency,
					ProbeLevel:           exampleID.ProbeLevel,
					ProbeLoudness:        meanPerceivedLevel,
					ProbeMasking:         meanProbeMasking,
					Channels:             numChannels,
					Bins:                 numBins,
					SpectrumSignalCarfac: signalPowerFeaturesCarfac,
					SpectrumNoiseCarfac:  noisePowerFeaturesCarfac,
					SpectrumSignal:       signalPowerFeatures,
					SpectrumNoise:        noisePowerFeatures,
					Coefficients:         fftCoefficients,
					Buffer:               buffer,
				}

				allData = append(allData, example)
				count++
				dataExamples++

				fmt.Printf("Samples total: (L) %d\n", len(buffer))
				fmt.Printf("Mean perceived level %d\n", meanPerceivedLevel)
				fmt.Printf("Mean masking %d\n", meanProbeMasking)
				fmt.Printf("CARFAC features total: (L) %d\n", len(NAP))
				fmt.Printf("Signal Carfac features total: %d\n", len(signalPowerFeaturesCarfac))
				fmt.Printf("Noise Carfac features total: %d\n", len(noisePowerFeaturesCarfac))
				fmt.Printf("Signal features total: %d\n", len(signalPowerFeatures))
				fmt.Printf("Noise features total: %d\n", len(noisePowerFeatures))
				fmt.Printf("FFT coefficients total: %d\n", len(fftCoefficients))
				if count%shardSize == 0 {
					indentedJsonString, err := json.MarshalIndent(allData, "", "\t")
					if err != nil {
						fmt.Printf("Cannot Marshall data to JSON\n")
						return err
					}
					ioutil.WriteFile(fmt.Sprintf("%s_%07d-%07d.json", filePrefix, count-shardSize, count),
						indentedJsonString, os.ModePerm)
					wroteExamples += len(allData)
					allData = nil
				}
			}
		}
		if !foundMatch {
			errorString := fmt.Sprintf("Did not find a match in the wavefiledirectory for %s", exampleID.WavfileIdentifier)
			err := errors.New(errorString)
			return err
		}
	}
	indentedJSONString, err := json.MarshalIndent(allData, "", "\t")
	if err != nil {
		return err
	}
	if allData != nil {
		ioutil.WriteFile(fmt.Sprintf("%s_%07d-%07d.json", filePrefix, count-len(allData), count), indentedJSONString, os.ModePerm)
		wroteExamples += len(allData)
	}
	if wroteExamples != dataExamples {
		errorString := fmt.Sprintf("wrote %d examples but read %d examples", wroteExamples, dataExamples)
		err := errors.New(errorString)
		return err
	}
	return nil
}


text:
@import ObjectiveC.runtime;

#import "ALPHAActions.h"

#import "ALPHAObjectActionItem.h"
#import "ALPHAObjectProperty.h"
#import "ALPHAObjectIvar.h"
#import "ALPHAObjectMethod.h"

#import "ALPHARuntimeUtility.h"

#import "ALPHAObjectModel.h"
#import "ALPHAObjectSource.h"

NSString *const ALPHAObjectDataIdentifier = @"com.unifiedsense.alpha.data.object";

@interface ALPHAObjectSource ()

@end

@implementation ALPHAObjectSource

#pragma mark - Initialization

- (instancetype)init
{
    self = [super init];

    if (self)
    {
        [self addDataIdentifier:ALPHAObjectDataIdentifier];
    }

    return self;
}

- (ALPHAModel *)modelForRequest:(ALPHARequest *)request
{

    NSString *search = request.parameters[ALPHASearchTextParameterKey];
    BOOL includeInheritance = [request.parameters[ALPHASearchScopeParameterKey] boolValue];

    //
    // Search & Inheritence included when generating object model
    //

    id object = nil;

    if (request.parameters[ALPHAObjectDataPointerIdentifier] && request.parameters[ALPHAObjectDataClassNameIdentifier])
    {
        object = [ALPHARuntimeUtility objectForPointerString:request.parameters[ALPHAObjectDataPointerIdentifier] className:request.parameters[ALPHAObjectDataClassNameIdentifier]];
    }

    if (!object)
    {
        return nil;
    }

    ALPHAObjectModel *model = [[ALPHAObjectModel alloc] initWithIdentifier:ALPHAObjectDataIdentifier];

    model.request = request;

    model.objectPointer = request.parameters[ALPHAObjectDataPointerIdentifier];
    model.objectClass = NSStringFromClass([object class]);
    model.objectDescription = [ALPHARuntimeUtility safeDescriptionForObject:object];

    model.objectContent = [self contentWithObject:object];
    model.objectMainSuperclass = [self mainSuperclassForObject:object];

    model.properties = [self propertiesWithObject:object search:search inheritance:includeInheritance];
    model.ivars = [self ivarsWithObject:object search:search inheritance:includeInheritance];
    model.methods = [self methodsWithObject:object search:search inheritance:includeInheritance];
    model.classMethods = [self classMethodsWithObject:object search:search inheritance:includeInheritance];
    model.superclasses = [self superclassesWithObject:object search:search];

    return model;
}

#pragma mark - Object content

- (ALPHAObjectContent *)contentWithObject:(id)object
{
    //
    // Currently handled specific Foundation objects
    // - NSArray
    // - NSUserDefaults
    // - NSDictionary
    // - NSSet
    // - NSOrderedSet
    //

    if ([object isKindOfClass:[NSArray class]])
    {
        return [ALPHAObjectContent objectContentForArray:object];
    }
    else if ([object isKindOfClass:[NSSet class]])
    {
        return [ALPHAObjectContent objectContentForSet:object];
    }
    else if ([object isKindOfClass:[NSDictionary class]])
    {
        return [ALPHAObjectContent objectContentForDictionary:object];
    }
    else if ([object isKindOfClass:[NSOrderedSet class]])
    {
        return [ALPHAObjectContent objectContentForOrderedSet:object];
    }
    else if ([object isKindOfClass:[NSUserDefaults class]])
    {
        return [ALPHAObjectContent objectContentForUserDefaults:object];
    }

    return nil;
}

- (NSString *)mainSuperclassForObject:(id)object
{
    //
    // If object is a class object, we return specific value
    //
    if (class_isMetaClass(object_getClass(object)))
    {
        return nil;
    }

    if (object_isClass(object))
    {
        return nil;
    }

    NSArray *mainSuperclassPrefixes = @[ @"NS", @"UI", @"CA" ];

    Class class = [object superclass];

    while (![mainSuperclassPrefixes containsObject:[ALPHARuntimeUtility prefixOfClassName:NSStringFromClass(class)]])
    {
        class = [class superclass];
    }

    if (class)
    {
        return NSStringFromClass(class);
    }

    return nil;
}

#pragma mark - Properties

- (NSArray *)propertiesWithObject:(id)object search:(NSString *)search inheritance:(BOOL)inheritance
{
    Class class = [object class];
    NSArray *properties = [[self class] propertiesForClass:class onObject:object];

    if (inheritance)
    {
        NSArray *inheritedProperties = [[self class] inheritedPropertiesForClass:class onObject:object];
        properties = [properties arrayByAddingObjectsFromArray:inheritedProperties];
    }

    if ([search length] > 0)
    {
        NSMutableArray *mutableUnsortedFilteredProperties = [NSMutableArray array];

        for (ALPHAObjectProperty *property in properties)
        {
            if ([property.name rangeOfString:search options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [mutableUnsortedFilteredProperties addObject:property];
            }
        }

        properties = mutableUnsortedFilteredProperties;
    }

    return [properties sortedArrayUsingComparator:^NSComparisonResult(ALPHAObjectProperty *property1, ALPHAObjectProperty *property2)
    {
        NSString *name1 = property1.name;
        NSString *name2 = property2.name;
        return [name1 caseInsensitiveCompare:name2];
    }];
}

+ (NSArray *)propertiesForClass:(Class)class onObject:(id)object
{
    NSMutableArray *properties = [NSMutableArray array];
    unsigned int propertyCount = 0;
    objc_property_t *propertyList = class_copyPropertyList(class, &propertyCount);

    if (propertyList)
    {
        for (unsigned int i = 0; i < propertyCount; i++)
        {
            ALPHAObjectProperty *property = [[ALPHAObjectProperty alloc] init];
            property.name = [NSString stringWithUTF8String:property_getName(propertyList[i])];
            property.type.cType = [ALPHARuntimeUtility typeEncodingForProperty:propertyList[i]];
            property.type.name = [ALPHARuntimeUtility prettyTypeForProperty:propertyList[i]];
            property.attributes = [ALPHARuntimeUtility attributesDictionaryForProperty:propertyList[i]];

            if (!class_isMetaClass(object_getClass(object)))
            {
                property.value = [ALPHARuntimeUtility valueForProperty:propertyList[i] onObject:object];
            }

            [properties addObject:property];
        }

        free (propertyList);
    }

    return properties;
}

+ (NSArray *)inheritedPropertiesForClass:(Class)class onObject:(id)object
{
    NSMutableArray *inheritedProperties = [NSMutableArray array];

    while ((class = [class superclass]))
    {
        [inheritedProperties addObjectsFromArray:[self propertiesForClass:class onObject:object]];
    }

    return inheritedProperties;
}

#pragma mark - Ivars

- (NSArray *)ivarsWithObject:(id)object search:(NSString *)search inheritance:(BOOL)inheritance
{
    Class class = [object class];
    NSArray *ivars = [[self class] ivarsForClass:class onObject:object];
    NSArray *inheritedIvars = [[self class] inheritedIvarsForClass:class onObject:object];

    if (inheritance)
    {
        ivars = [ivars arrayByAddingObjectsFromArray:inheritedIvars];
    }

    if ([search length] > 0)
    {
        NSMutableArray *mutableUnsortedFilteredIvars = [NSMutableArray array];

        for (ALPHAObjectIvar *ivar in ivars)
        {
            if ([ivar.name rangeOfString:search options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [mutableUnsortedFilteredIvars addObject:ivar];
            }
        }

        ivars = mutableUnsortedFilteredIvars;
    }

    return [ivars sortedArrayUsingComparator:^NSComparisonResult(ALPHAObjectIvar *ivar1, ALPHAObjectIvar *ivar2)
    {
        NSString *name1 = ivar1.name;
        NSString *name2 = ivar2.name;
        return [name1 caseInsensitiveCompare:name2];
    }];
}

+ (NSArray *)ivarsForClass:(Class)class onObject:(id)object
{
    NSMutableArray *ivars = [NSMutableArray array];
    unsigned int ivarCount = 0;
    Ivar *ivarList = class_copyIvarList(class, &ivarCount);

    if (ivarList)
    {
        for (unsigned int i = 0; i < ivarCount; i++)
        {
            ALPHAObjectIvar *ivar = [[ALPHAObjectIvar alloc] init];
            ivar.name = [NSString stringWithUTF8String:ivar_getName(ivarList[i])];
            ivar.type.name = [ALPHARuntimeUtility prettyTypeForIvar:ivarList[i]];
            ivar.type.cType = [ALPHARuntimeUtility typeEncodingForIvar:ivarList[i]];

            if (!class_isMetaClass(object_getClass(object)) && ![ivar.type.name isEqualToString:@"Class"])
            {
                ivar.value = [ALPHARuntimeUtility valueForIvar:ivarList[i] onObject:object];
            }

            [ivars addObject:ivar];
        }

        free (ivarList);
    }

    return ivars;
}

+ (NSArray *)inheritedIvarsForClass:(Class)class onObject:(id)object
{
    NSMutableArray *inheritedIvars = [NSMutableArray array];

    while ((class = [class superclass]))
    {
        [inheritedIvars addObjectsFromArray:[self ivarsForClass:class onObject:object]];
    }

    return inheritedIvars;
}

#pragma mark - Methods

- (NSArray *)methodsWithObject:(id)object search:(NSString *)search inheritance:(BOOL)inheritance
{
    Class class = [object class];
    NSArray *methods = [[self class] methodsForClass:class areClassMethods:NO];
    NSArray *inheritedMethods = [[self class] inheritedMethodsForClass:class areClassMethods:NO];

    return [self filteredMethodsFromMethods:methods inheritedMethods:inheritedMethods areClassMethods:NO search:search inheritance:inheritance];
}

- (NSArray *)classMethodsWithObject:(id)object search:(NSString *)search inheritance:(BOOL)inheritance
{
    const char *className = [NSStringFromClass([object class]) UTF8String];
    Class metaClass = objc_getMetaClass(className);

    NSArray *classMethods = [[self class] methodsForClass:metaClass areClassMethods:YES];
    NSArray *inheritedClassMethods = [[self class] inheritedMethodsForClass:metaClass areClassMethods:YES];

    return [self filteredMethodsFromMethods:classMethods inheritedMethods:inheritedClassMethods areClassMethods:YES search:search inheritance:inheritance];
}

- (NSArray *)filteredMethodsFromMethods:(NSArray *)methods inheritedMethods:(NSArray *)inheritedMethods areClassMethods:(BOOL)areClassMethods search:(NSString *)search inheritance:(BOOL)inheritance
{
    NSArray *candidateMethods = methods;

    if (inheritance)
    {
        candidateMethods = [candidateMethods arrayByAddingObjectsFromArray:inheritedMethods];
    }

    if ([search length] > 0)
    {
        NSMutableArray *mutableUnsortedFilteredMethods = [NSMutableArray array];

        for (ALPHAObjectMethod *method in candidateMethods)
        {
            if ([method.name rangeOfString:search options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [mutableUnsortedFilteredMethods addObject:method];
            }
        }

        candidateMethods = mutableUnsortedFilteredMethods;
    }

    return [candidateMethods sortedArrayUsingComparator:^NSComparisonResult(ALPHAObjectMethod *method1, ALPHAObjectMethod *method2)
    {
        NSString *name1 = method1.name;
        NSString *name2 = method2.name;
        return [name1 caseInsensitiveCompare:name2];
    }];
}

+ (NSArray *)methodsForClass:(Class)class areClassMethods:(BOOL)areClassMethods
{
    NSMutableArray *methods = [NSMutableArray array];
    unsigned int methodCount = 0;
    Method *methodList = class_copyMethodList(class, &methodCount);

    if (methodList)
    {
        for (unsigned int i = 0; i < methodCount; i++)
        {
            ALPHAObjectMethod *method = [[ALPHAObjectMethod alloc] init];
            method.name = NSStringFromSelector(method_getName(methodList[i]));

            char *returnType = method_copyReturnType(methodList[i]);

            method.returnType.name = [ALPHARuntimeUtility prettyReturnTypeForMethod:methodList[i]];
            method.returnType.cType = @(returnType);

            free (returnType);

            method.arguments = (NSArray<ALPHAObjectArgument> *)[self argumentListForMethod:methodList[i]];
            method.isClassMethod = areClassMethods;

            [methods addObject:method];
        }

        free(methodList);
    }
    return methods;
}

+ (NSArray *)argumentListForMethod:(Method)method
{
    NSMutableArray *components = [NSMutableArray array];

    NSString *selectorName = NSStringFromSelector(method_getName(method));
    NSArray *selectorComponents = [selectorName componentsSeparatedByString:@":"];
    unsigned int numberOfArguments = method_getNumberOfArguments(method);

    for (unsigned int argIndex = ALPHANumberOfImplicitArgsKey; argIndex < numberOfArguments; argIndex++)
    {
        ALPHAObjectArgument *argument = [[ALPHAObjectArgument alloc] init];
        argument.name = selectorComponents[argIndex - ALPHANumberOfImplicitArgsKey];

        char *argType = method_copyArgumentType(method, argIndex);

        argument.type.cType = @(argType);
        argument.type.name = [ALPHARuntimeUtility readableTypeForEncoding:@(argType)];

        free(argType);

        [components addObject:argument];
    }

    return components;
}

+ (NSArray *)inheritedMethodsForClass:(Class)class areClassMethods:(BOOL)areClassMethods
{
    NSMutableArray *inheritedMethods = [NSMutableArray array];

    while ((class = [class superclass]))
    {
        [inheritedMethods addObjectsFromArray:[self methodsForClass:class areClassMethods:areClassMethods]];
    }

    return inheritedMethods;
}

#pragma mark - Superclasses

+ (NSArray *)superclassesForClass:(Class)class
{
    NSMutableArray *superClasses = [NSMutableArray array];

    while ((class = [class superclass]))
    {
        [superClasses addObject:NSStringFromClass(class)];
    }

    return superClasses;
}

- (NSArray *)superclassesWithObject:(id)object search:(NSString *)search
{
    NSArray *superclasses = [[self class] superclassesForClass:[object class]];

    if ([search length] > 0)
    {
        NSMutableArray *filteredSuperclasses = [NSMutableArray array];

        for (NSString *superclass in superclasses)
        {
            if ([superclass rangeOfString:search options:NSCaseInsensitiveSearch].length > 0) {
                [filteredSuperclasses addObject:superclass];
            }
        }

        superclasses = filteredSuperclasses;
    }

    return superclasses;
}

#pragma mark - Actions

- (BOOL)canPerformAction:(id<ALPHAIdentifiableItem>)action
{
    return [action isKindOfClass:[ALPHAObjectActionItem class]];
}

- (void)performAction:(ALPHAObjectActionItem *)action completion:(ALPHADataSourceRequestCompletion)completion
{
    //
    // Check if we have correct action to be performed
    //

    NSError *error;

    if (![action isKindOfClass:[ALPHAObjectActionItem class]])
    {
        error = [NSError errorWithDomain:@"com.unifiedsense.alpha.error" code:2 userInfo:@{ @"action" : action }];
    }

    //
    // First find the referenced object
    //

    id object = [ALPHARuntimeUtility objectForPointerString:action.objectPointer className:action.objectClass];
    id returnObject = nil;

    if (!error && object)
    {
        returnObject = [self executeAction:action onObject:object withError:&error];
    }

    //
    // Call completion
    //

    if (completion)
    {
        completion (returnObject, error);
    }
}

- (id)executeAction:(ALPHAObjectActionItem *)action onObject:(id)object withError:(NSError **)error;
{
    if (!object)
    {
        return nil;
    }

    //
    // Property setter calls, method calls, handling NSUserDefaults too
    //

    if (action.selector)
    {
        SEL selector = NSSelectorFromString(action.selector);
        return [ALPHARuntimeUtility performSelector:selector onObject:object withArguments:action.arguments error:error];
    }

    //
    // iVars
    //

    else if (action.ivar)
    {
        unsigned int ivarCount = 0;
        Ivar *ivarList = class_copyIvarList([object class], &ivarCount);

        Ivar ivar = NULL;

        if (ivarList)
        {
            for (unsigned int i = 0; i < ivarCount; i++)
            {
                NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivarList[i])];

                if ([ivarName isEqualToString:action.ivar])
                {
                    ivar = ivarList[i];

                    break;
                }
            }

            free (ivarList);
        }

        if (ivar != NULL)
        {
            [ALPHARuntimeUtility setValue:[action.arguments firstObject] forIvar:ivar onObject:object];
        }
    }
    else if (*error)
    {
        *error = [NSError errorWithDomain:@"com.unifedsense.alpha.error" code:3 userInfo:@{}];
    }

    return nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
#import "UIView.h"

#import "ABPersonTableActionDelegate-Protocol.h"

@class ABPersonTableAction, NSString, UIButton;

@interface ABPersonTableFooterView : UIView <ABPersonTableActionDelegate>
{
    _Bool _editing;
    ABPersonTableAction *_deleteAction;
    UIView *_deleteView;
    UIView *_accessoryView;
    UIButton *_attributionButton;
    id <ABStyleProvider> _styleProvider;
}

@property(retain, nonatomic) UIView *accessoryView; // @synthesize accessoryView=_accessoryView;
@property(retain, nonatomic) id <ABStyleProvider> styleProvider; // @synthesize styleProvider=_styleProvider;
@property(nonatomic, getter=isEditing) _Bool tableEditing; // @synthesize tableEditing=_editing;
- (void)layoutSubviews;
- (void)setEditing:(_Bool)arg1 animated:(_Bool)arg2;
- (void)setEditing:(_Bool)arg1;
- (void)removeDeleteAction;
- (void)setDeleteActionWithTitle:(id)arg1 target:(id)arg2 selector:(SEL)arg3 animated:(_Bool)arg4;
@property(readonly, nonatomic, getter=isAttributionEnabled) _Bool attributionEnabled;
@property(readonly, nonatomic) NSString *attribution;
- (void)setAttribution:(id)arg1 enabled:(_Bool)arg2 target:(id)arg3 action:(SEL)arg4;
- (struct CGSize)sizeThatFits:(struct CGSize)arg1;
- (struct CGRect)attributionFrame;
- (struct CGRect)deleteViewFrame;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;

@end


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

namespace QueueIT.ScalingDynamoDB.BusinessLogic.Model
{
    public class ReadAndWriteValues
    {
        public ReadAndWriteValues(long InitReads, long InitWrites)
        {
            ReadChecks = InitReads;
            WriteChecks = InitWrites;
        }
        public long ReadChecks { get; set; }
        public long WriteChecks { get; set; }
    }
}


text:
namespace ash {
namespace quick_pair {

FastPairRepository* g_instance = nullptr;

// static
FastPairRepository* FastPairRepository::Get() {
  DCHECK(g_instance);
  return g_instance;
}

// static
void FastPairRepository::SetInstance(FastPairRepository* instance) {
  DCHECK(!g_instance || !instance);
  g_instance = instance;
}

FastPairRepository::FastPairRepository() {
  SetInstance(this);
}

FastPairRepository::~FastPairRepository() {
  SetInstance(nullptr);
}

}  // namespace quick_pair
}  // namespace ash


text:
package com.flj.latte.ec.pay;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.flj.latte.ec.R;
import com.imooc.core.delegates.LatteDelegate;
import com.imooc.core.net.RestClient;
import com.imooc.core.net.callback.ISuccess;
import com.imooc.core.util.log.LatteLogger;

/**
 * Created by Administrator on 2017/9/22 0022.
 */

public class FastPay implements View.OnClickListener {

    //设置支付回调监听
    private IAlPayResultListener mIAlPayResultListener = null;
    private Activity mActivity =null;

    private AlertDialog mDialog = null;
    private int mOrderID = -1;

    private FastPay(LatteDelegate delegate){
        this.mActivity = delegate.getProxyActivity();
        this.mDialog = new AlertDialog.Builder(delegate.getContext()).create();
    }

    public static FastPay create(LatteDelegate delegate){
        return new FastPay(delegate);

    }

    public void beginPayDialog(){

        mDialog.show();
        final Window window = mDialog.getWindow();
        if (window !=null){
            window.setContentView(R.layout.dialog_pay_panel);
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.anim_panel_up_from_bottom);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            //设置属性
            final WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.flags =WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            window.setAttributes(params);

            window.findViewById(R.id.btn_dialog_pay_alpay).setOnClickListener(this);
            window.findViewById(R.id.btn_dialog_pay_wechat).setOnClickListener(this);
            window.findViewById(R.id.btn_dialog_pay_cancel).setOnClickListener(this);

        }

    }

    public FastPay setPayResultListener(IAlPayResultListener listener){
        this.mIAlPayResultListener = listener;
        return this;
    }

    public FastPay setOrderId(int orderId){
        this.mOrderID = orderId;
        return this;
    }

    private void alPay(int orderId){

        final String singUrl = "服务器端支付地址"+orderId;
        //获取签名字符串
        RestClient.builder()
                .url(singUrl)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {

                        final String paySign = JSON.parseObject(response).getString("result");
                        LatteLogger.d("PAY_SIGN",paySign);

                        //必须是异步的调用客户端支付接口
                        final PayAsyncTask payAsyncTask = new PayAsyncTask(mActivity,mIAlPayResultListener);
                        payAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,paySign); //多线程同时执行 pool_executor
                    }
                })
                .build()
                .post();

    }

    private void weChatPay(int orderId){

    }

    @Override
    public void onClick(View view) {

        int id =view.getId();
        if (id == R.id.btn_dialog_pay_alpay){
            alPay(mOrderID);
            mDialog.cancel();
        }else if (id == R.id.btn_dialog_pay_wechat){
            weChatPay(mOrderID);
            mDialog.cancel();
        }else if (id == R.id.btn_dialog_pay_cancel){
            mDialog.cancel();

        }
    }
}


text:
<!doctype HTML>

    <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="./css/main.css">
    <title>Munaz Rahman | Computer Engineering Student</title>

        Munaz
        Rahman

About Me

            My name is Munaz Rahman and I am a student with an amazing passion for technology pursuing a Bachelor of Applied Science in Computer Engineering at the University of Waterloo.

            My passion for technology began when I picked up a book titled Look Mom! I Built My Own Web Site from my local library. At a young age, I immediately fell in love with the ability to design and create something of my own by writing lines of code. This truly sparked my love for programming so I continued to advance my skills in other programming languages.

            On top of programming I love building things using technology. I've participated in various robotic clubs, love attending hackathons and also working on projects of my own. I truly believe that technology, both through software and hardware, can be used to solve many problems faced by people today.

Résumé

            I am currently in a co-operative program and am constantly looking for new opportunities to grow my skills while contributing to your business. Take a look at my résumé here and feel free to contact me below!

Projects

Smart Mirror

                Using a Raspberry Pi, computer monitor and a two way mirror I created a smart mirror that displays weather, news, traffic and more while still functioning as a simple mirror. View the source code, including steps to build your own smart mirror, here.

Roomies | Android App | Node.js Backend

                Roomies is an Android app with a Node.js backend service that makes it easier for roommates to live with each other by allowing them to organize chores, track expenses and share grocery lists. Find it on the Google Play Store here, view the Android source code here and backend source code here.

Meetr | DeltaHacks 2016

                Meetr is an application aimed to help businesses conserve more energy by controlling the Nest smart thermostat in their office rooms based on their meeting times. By disabling the heating or air conditioning while meetings are not in effect, businesses can save more energy and money. This project was also the winner of the DeltaHacks 2016 GE Sustainability Prize. View the source code here.

Lets | Web Application | Hack the North 2015

                Lets is a web application I developed for my Hack the North 2015 project. It allows students to share events publicly using a responsive website. View the source code here.

WatApp | Pebble Smart Watch App

                WatApp is used by hundreds of University of Waterloo students to access the information they need on their wrists. Students can view information on campus restaurants, employer information sessions, cafeteria menus, parking availability and more. View the source code here, view it on the Pebble appstore here and download it from your smartphone here.

Minecraft Plugins

                My past addiction to Minecraft has led me to create various plugins that can be used on Minecraft servers. These plugins add content to the game by creating new minigames within the game itself without the need for users to download any additional files. View the source code for my plugins here.

Norton | Xbox 360 and PC Game

                Norton is a top-down shooter developed using Microsoft's XNA Game Studio and is playable on XBox 360 and PC. It requires the user to fight through various levels, each with increasing difficulty of enemy AI, using an XBox 360 controller or mouse and keyboard. View the source code here.

Contact Me

            You can contact me by emailing contact@munaz.me

            © 2016 Munaz Rahman

            GitHub |
            LinkedIn |
            Email


text:
<?php

/* @var $this yii\web\View */

$this->title = Yii::t('writesdown', 'Terms and Conditions');
?>

<?= $this->title ?>

                The WritesDown is free software. It is released under the terms of the following BSD License.

Copyright © 2015 by WritesDown All rights reserved.

                Redistribution and use in source and binary forms, with or without modification, are permitted provided
                that the following conditions are met:

                    Redistributions of source code must retain the above copyright notice, this list of conditions and
                    the following disclaimer.

                    Redistributions in binary form must reproduce the above copyright notice, this list of conditionsand
                    the following disclaimer in the documentation and/or other materials provided with the
                    distribution.

                    Neither the name of WritesDown nor the names of its contributors may be used to endorse or
                    promote products derived from this software without specific prior written permission.

                THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS
                OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
                OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
                CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
                OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
                WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Must

Retain the original copyright notice shown on the left.

Can

Use freely for commercial purposes in derivative works.

Modify.

Distribute.

Give partial production/distribution rights to third parties not included in the license.

Place a warranty on the software.

Cannot

Use contributors’ names, logos or trademarks.

                        Software is released without warranty and the software/license owner cannot be charged for
                        damages.

License of Official and User-contributed Documentation

                        The text contained in the official and user-contributed WritesDown
                        documentation is licensed to the public under the

                            GNU Free DocumentationLicense (GFDL)
                        .

                        Permission is granted to copy, distribute and/or modify this document under the terms of the GNU
                        Free Documentation License (GFDL), Version 1.2 or any later version published by the Free
                        Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no
                        Back-Cover Texts.

Must

Grant the same freedoms as in original license.

Acknowledge the authors in form of linking back to the original article.

Can

Copy.

Modify.

Redistribute.


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

namespace Michonne.Sources.Tests
{
    using System.Threading;

    using Michonne.Implementation;

    using NFluent;

    using NUnit.Framework;

    class ThreadedUnit
    {
        [Test]
        public void should_execute_async()
        {
            var runner = TestHelpers.GetThread();
            using (runner)
            {
                int init = Thread.CurrentThread.ManagedThreadId;
                int second = -1;
                object synch = new object();
                bool done = false;
                runner.Dispatch(
                    () =>
                        {
                            second = Thread.CurrentThread.ManagedThreadId;
                            lock (synch)
                            {
                                done = true;
                                Monitor.Pulse(synch);
                            }
                        });
                lock (synch)
                {
                    if (!done) Monitor.Wait(synch, 500);
                }
                Check.That(init).IsDistinctFrom(second);
            }
        }
    }
}


text:
namespace Songhay.Models;

/// <summary>
/// Defines DBMS metadata
/// </summary>
public class DbmsMetadata
{
    /// <summary>
    /// Gets or sets the connection string.
    /// </summary>
    public string? ConnectionString { get; set; }

    /// <summary>
    /// Gets or sets the connection string key.
    /// </summary>
    public string? ConnectionStringKey { get; set; }

    /// <summary>
    /// Gets or sets the encryption metadata.
    /// </summary>
    public EncryptionMetadata? EncryptionMetadata { get; set; }

    /// <summary>
    /// Gets or sets the name of the provider.
    /// </summary>
    public string? ProviderName { get; set; }

    /// <summary>
    /// Returns a <see cref="String" /> that represents this instance.
    /// </summary>
    /// <returns>
    /// A <see cref="String" /> that represents this instance.
    /// </returns>
    public override string ToString()
    {
        var sb = new StringBuilder();

        if (!string.IsNullOrWhiteSpace(ProviderName)) sb.Append($"{nameof(ProviderName)}: {ProviderName} | ");
        if (!string.IsNullOrWhiteSpace(ConnectionString))
            sb.Append($"{nameof(ConnectionString)}: {ConnectionString[..72]}... ");
        if (EncryptionMetadata != null) sb.Append("| has encryption metadata");

        return (sb.Length > 0) ? sb.ToString() : base.ToString() ?? GetType().Name;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:useLevel="false">

    <stroke
        android:width="1dp"
        android:color="#ff0000" />
    <solid android:color="#ff0000" />
    <size
        android:width="10dp"
        android:height="10dp" />
</shape>


text:
package com.facebook.buck.cli;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

import com.facebook.buck.cli.ActionGraphSerializer.ActionGraphNode;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.impl.FakeBuildRule;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;

public class ActionGraphSerializerTest {

  private final ActionGraphBuilder buildRuleResolver = new TestActionGraphBuilder();

  /**
   * Test for finding critical path in the following action graph:
   *
   * <pre>
   *                       a
   *                      /|\
   *                     / | \(runtime deps)
   *                    /  |  r2
   *                   /   |
   *                  /    | (runtime deps)
   *         b   c   d     r1
   *         \   \  /
   *          e   f
   *           \ /
   *            g
   *          /  \
   *         i    h
   *        / \
   *       j-->k
   *           |
   *           l
   *           |
   *           m
   * </pre>
   */
  @Test
  public void serializeActionGraph() {
    BuildRule m = createRule("m");
    BuildRule l = createRule("l", m);
    BuildRule k = createRule("k", l);
    BuildRule j = createRule("j", k);
    BuildRule i = createRule("i", j, k);
    BuildRule h = createRule("h");
    BuildRule g = createRule("g", i, h);
    BuildRule e = createRule("e", g);
    BuildRule f = createRule("f", g);
    BuildRule b = createRule("b", e);
    BuildRule c = createRule("c", f);
    BuildRule d = createRule("d", f);
    BuildRule r1 = createRule("r1");
    BuildRule r2 = createRule("r2");
    BuildRule a = createRuleWithRuntimeDeps("a", ImmutableSortedSet.of(d), r1, r2);

    ActionGraphSerializer actionGraphSerializer =
        new ActionGraphSerializer(
            buildRuleResolver,
            ImmutableSet.of(a.getBuildTarget(), b.getBuildTarget(), c.getBuildTarget()),
            null);

    actionGraphSerializer.serialize(
        actionGraphNodes -> {
          Iterator<ActionGraphNode> iterator = actionGraphNodes.iterator();
          assertLeaves(Arrays.asList(iterator.next(), iterator.next()), "h", "m");
          assertActionGraphNode(iterator.next(), "l", "m");
          assertActionGraphNode(iterator.next(), "k", "l");
          assertActionGraphNode(iterator.next(), "j", "k");
          assertActionGraphNode(iterator.next(), "i", "k", "j");
          assertActionGraphNode(iterator.next(), "g", "h", "i");
          assertActionGraphNode(iterator.next(), "f", "g");
          assertActionGraphNode(iterator.next(), "d", "f");
          assertLeaves(Arrays.asList(iterator.next(), iterator.next()), "r1", "r2");
          assertActionGraphNode(iterator.next(), "a", Collections.singletonList("d"), "r1", "r2");
          assertActionGraphNode(iterator.next(), "e", "g");
          assertActionGraphNode(iterator.next(), "b", "e");
          assertActionGraphNode(iterator.next(), "c", "f");
          assertThat(iterator.hasNext(), is(false));
        });
  }

  private BuildRule createRule(String buildTargetName, BuildRule... deps) {
    FakeBuildRule buildRule =
        new FakeBuildRule(
            BuildTargetFactory.newInstance("//:" + buildTargetName),
            ImmutableSortedSet.copyOf(deps));
    buildRuleResolver.addToIndex(buildRule);
    return buildRule;
  }

  private BuildRule createRuleWithRuntimeDeps(
      String buildTargetName, ImmutableSortedSet<BuildRule> deps, BuildRule... runtimeDeps) {
    FakeBuildRule buildRule =
        new FakeBuildRule(BuildTargetFactory.newInstance("//:" + buildTargetName), deps);
    buildRule.setRuntimeDeps(runtimeDeps);
    buildRule.updateBuildRuleResolver(buildRuleResolver);
    buildRuleResolver.addToIndex(buildRule);
    return buildRule;
  }

  private void assertLeaves(Collection<ActionGraphNode> leaves, String... expectedNames) {
    assertThat(leaves.size(), equalTo(expectedNames.length));

    List<String> extractedNames = new ArrayList<>();
    for (ActionGraphNode leaf : leaves) {
      assertThat(leaf.getBuildDeps(), is(empty()));
      assertThat(leaf.getRuntimeDeps(), is(empty()));

      BuildTarget buildTarget = leaf.getBuildTarget();
      String name = buildTarget.getFullyQualifiedName();
      extractedNames.add(name.replace("//:", ""));
    }

    assertThat(extractedNames, containsInAnyOrder(expectedNames));
  }

  private void assertActionGraphNode(ActionGraphNode node, String expectedName, String... deps) {
    assertActionGraphNode(node, expectedName, Arrays.asList(deps));
  }

  private void assertActionGraphNode(
      ActionGraphNode node, String expectedName, List<String> deps, String... runtimeDeps) {
    assertThat(node.getBuildTarget().getFullyQualifiedName(), equalTo("//:" + expectedName));

    if (runtimeDeps.length == 0) {
      assertThat(node.getRuntimeDeps(), is(empty()));
    } else {
      assertDeps(node.getRuntimeDeps(), runtimeDeps);
    }

    if (deps.isEmpty()) {
      assertThat(node.getBuildDeps(), is(empty()));
    } else {
      assertDeps(node.getBuildDeps(), deps.toArray(new String[0]));
    }
  }

  private void assertDeps(ImmutableSet<BuildRule> actual, String... expected) {
    assertThat(
        actual.stream()
            .map(BuildRule::getBuildTarget)
            .map(BuildTarget::getFullyQualifiedName)
            .map(s -> s.replace("//:", ""))
            .collect(Collectors.toList()),
        containsInAnyOrder(expected));
  }
}


text:
import { utoa } from "../utils"
import Languages, { LanguageCombination, RxJS4, RxJS5 } from "../languages"
import CodeEditor from "./codeEditor"
import * as Rx from "rxjs"
import { Observable } from "rxjs"
import h from "snabbdom/h"
import { VNode } from "snabbdom/vnode"

const hash = () => typeof window !== "undefined" ? window.location.hash.substr(1) : ""

const QueryString = {
  format: (object: any) => {
    let q = ""
    for (let k in sortSmallFirst(object)) {
      if (object.hasOwnProperty(k)) {
        q += (q ? "&" : "") + k + "=" + object[k]
      }
    }
    return q
  },
  parse: (queryString: string) => {
    return queryString.split("&").map(p => p.split("=")).reduce((p: any, n: string[]) => {
      if (n[0].endsWith("[]")) {
        let key = n[0].substr(0, n[0].length - 1)
        p[key] = p[key] || []
        p[key].push(n[1])
      } else {
        p[n[0]] = n[1]
      }
      return p
    }, {}) || {}
  },
  updated: (object: any) => {
    return QueryString.format(Object.assign(QueryString.parse(hash()), object))
  },
  get current(): any {
    return QueryString.parse(hash())
  },
}

const neverInNode = (subject: string) => Rx.Observable.defer(() =>
  Rx.Observable.throw(new Error(`Do not use ${subject} in a non-browser environment`))
)

let setting = false
export let Query = {
  $: typeof window === "object" ? Observable
    .fromEvent(window, "hashchange", () => hash())
    .startWith(hash())
    .map(str => QueryString.parse(str))
    .filter(_ => !setting) : neverInNode("shared/ui/Query"),
  $all: typeof window === "object" ? Observable
    .fromEvent(window, "hashchange", () => hash())
    .startWith(hash())
    .map(str => QueryString.parse(str))
    .distinctUntilChanged(equalHash) : neverInNode("shared/ui/Query"),
  set: (object: any) => {
    if (typeof window === "object") {
      setting = true
      if (!equalHash(QueryString.parse(window.location.hash), object)) {
        window.location.hash = QueryString.format(sortSmallFirst(object))
      }
      setTimeout(() => setting = false)
    }
  },
  get(field: string) {
    return QueryString.parse(hash())[field]
  },
  update: (object: any) => {
    Query.set(Object.assign(QueryString.parse(hash()), object))
  },
}

export const sameOriginWindowMessages = typeof window === "object" ? Rx.Observable
  .fromEvent(window, "message", (e: any) => {
    // For Chrome, the origin property is in the event.originalEvent object.
    let origin = e.origin || (e as any).originalEvent.origin
    if (origin !== window.location.origin) {
      return
    }

    return e.data
  })
  .flatMap(event => {
    // Emit Editor errors in this stream; todo: move this throw elsewhere
    if (event && event.type === "error") {
      return new Rx.Observable(o => o.error(event.error))
    }
    return Rx.Observable.of(event)
  }) : neverInNode("shared/ui/sameOriginWindowMessages")

export class LanguageMenu {
  public static get(lib: string): LanguageCombination {
    return Languages.find(l => l.id === lib) || RxJS5
  }

  public stream(): { dom: Rx.Observable<VNode>, language: Rx.Observable<LanguageCombination> } {
    let subject = new Rx.BehaviorSubject<LanguageCombination>(
      Languages.find(l => l.id === QueryString.current.lib) ||
      Languages[Languages.length - 1]
    )
    return {
      dom: subject.map(selected => h("div.select", [
        h("div.selected", selected.name),
        h("div.options", [
          ...Languages.map(l => h("div.option", {
            on: { click: () => subject.next(l) },
          }, l.name)),
          h("div.option", h("a",
            { attrs: { href: "https://github.com/hermanbanken/RxFiddle/pulls" } },
            "issue Pull Request"
          )),
        ]),
      ])), language: subject,
    }
  }
}

const rxErrorHelp = [
  h("p", [
    `Please note that global error handling is not implemented.
         Anything not captured in Rx onError's is thrown here.`, h("br"),
    `Make sure to handle errors in your subscribe calls by providing a function to the onError argument like so:`]),
  h("pre.user-select",
    { style: { width: "100%" } },
    `Rx.Observable
  .create(o => o.onError(new Error()))
  .subscribe(
    next => {},
    error => { /* this callback is needed */ }
  )`
  )]

export function errorHandler(e: Error): Rx.Observable<{ dom: VNode, timeSlider: VNode }> {
  if (e instanceof Error) {
    console.error(e)
  }
  return new Rx.Observable<{ dom: VNode, timeSlider: VNode }>(observer => {
    observer.next({
      dom: h("div.error", [
        h("p", [
          `An error occurred `,
          h("a.btn.btn-small", {
            on: {
              click: () => {
                observer.error(new Error("This error is catched and the stream is retry'd."))
                return false
              },
            },
          }, "Reload"),
        ]),
        h("pre.user-select",
          { style: { width: "100%" } },
          e.stack || `${e.name}: ${e.message}`
        ),
        ...(e.name !== "SyntaxError" ? rxErrorHelp : []),
      ]), timeSlider: undefined,
    })
  })
}

export function shareButton(editor: CodeEditor) {
  return h("a.btn", {
    attrs: { role: "button" },
    on: {
      click: (e: MouseEvent) => {
        editor.withValue(v => {
          Query.update({ code: utoa(v), type: "editor" });
          (e.target as HTMLAnchorElement).innerText = "Saved state in the url. Copy the url!"
        })
        return false
      },
      mouseenter: (e: MouseEvent) => {
        editor.withValue(v => {
          (e.target as HTMLAnchorElement).href = "#" + QueryString.updated({ code: utoa(v), type: "editor" })
        })
      },
      mouseout: (e: MouseEvent) => {
        (e.target as HTMLButtonElement).innerText = "Share"
      },
    },
  }, "Share")
}

function sortSmallFirst(object: any): any {
  return Object.keys(object)
    .sort((a, b) => object[a].length - object[b].length)
    .reduce((o, key) => {
      o[key] = object[key]
      return o
    }, {} as any)
}

function equalHash(a: any, b: any) {
  return (
    Object.keys(a).every(key => key in b && b[key] === a[key]) &&
    Object.keys(b).every(key => key in a && b[key] === a[key])
  )
}


text:
using System;
using System.Collections.Generic;
using System.Collections;
namespace Psi.Runtime
{

	public sealed class Array : Value, IList<Value>
	{
		private readonly List<Value> items = new List<Value>();

		public Array(ArrayType type) : base(type)
		{
			if (type.Dimensions != 1) throw new NotSupportedException("Arrays with more than one dimension are not supported yet!");
		}

		public Array(ArrayType type, IEnumerable<Value> initial) : this(type)
		{
			foreach(var v in initial)
				this.Add(v);
		}

		public Type ElementType => ((ArrayType)this.Type).ElementType;

		public int Dimensions => ((ArrayType)this.Type).Dimensions;

		public int Count => items.Count;

		public bool IsReadOnly => false;

		public Value this[int index]
		{
			get
			{
				return items[index];
			}

			set
			{
				if (value.Type != this.ElementType)
					throw new InvalidOperationException("Invalid element type!");
				items[index] = value;
			}
		}

		public int IndexOf(Value item)
		{
			return items.IndexOf(item);
		}

		public void Insert(int index, Value item)
		{
			if (item.Type != this.ElementType)
				throw new InvalidOperationException("Invalid element type!");
			items.Insert(index, item);
		}

		public void RemoveAt(int index)
		{
			items.RemoveAt(index);
		}

		public void Add(Value item)
		{
			if (item.Type != this.ElementType)
				throw new InvalidOperationException("Invalid element type!");
			items.Add(item);
		}

		public void Clear()
		{
			items.Clear();
		}

		public bool Contains(Value item)
		{
			return items.Contains(item);
		}

		public void CopyTo(Value[] array, int arrayIndex)
		{
			items.CopyTo(array, arrayIndex);
		}

		public bool Remove(Value item)
		{
			return items.Remove(item);
		}

		public IEnumerator<Value> GetEnumerator()
		{
			return ((IList<Value>)items).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IList<Value>)items).GetEnumerator();
		}
	}
}


text:
<?php
use Cake\Routing\Router;

Router::plugin('FertileForest', function ($routes) {
  $routes->fallbacks('DashedRoute');
});

//// 2015/09/23 for FertileForest plugin.
Router::connect('/demo', ['controller' => 'Demos', 'action' => 'index', 'plugin' => 'FertileForest']);
Router::connect('/demo/:action', ['controller' => 'Demos', 'plugin' => 'FertileForest']);


text:
package segment_test

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/scionproto/scion/go/co/reservation/segment"
	"github.com/scionproto/scion/go/co/reservation/segmenttest"
	"github.com/scionproto/scion/go/co/reservation/test"
	"github.com/scionproto/scion/go/lib/colibri/reservation"
	colpath "github.com/scionproto/scion/go/lib/slayers/path/colibri"
	"github.com/scionproto/scion/go/lib/util"
)

func TestNewIndex(t *testing.T) {
	r := segmenttest.NewReservation()
	require.Len(t, r.Indices, 0)
	expTime := util.SecsToTime(1)
	idx, err := r.NewIndex(0, expTime, 1, 3, 2, 5, reservation.CorePath)
	require.NoError(t, err)
	require.Len(t, r.Indices, 1)
	require.Equal(t, reservation.IndexNumber(0), idx)
	require.Equal(t, idx, r.Indices[0].Idx)
	require.Equal(t, expTime, r.Indices[0].Expiration)
	require.Equal(t, segment.IndexTemporary, r.Indices[0].State)
	require.Equal(t, reservation.BWCls(1), r.Indices[0].MinBW)
	require.Equal(t, reservation.BWCls(3), r.Indices[0].MaxBW)
	require.Equal(t, reservation.BWCls(2), r.Indices[0].AllocBW)
	require.NotNil(t, r.Indices[0].Token)
	tok := &reservation.Token{
		InfoField: reservation.InfoField{
			ExpirationTick: reservation.TickFromTime(expTime),
			BWCls:          2,
			RLC:            5,
			Idx:            idx,
			PathType:       reservation.CorePath,
		},
	}
	require.Equal(t, tok, r.Indices[0].Token)
	// add a second index
	idx, err = r.NewIndex(1, expTime, 1, 3, 2, 5, reservation.CorePath)
	require.NoError(t, err)
	require.Len(t, r.Indices, 2)
	require.Equal(t, reservation.IndexNumber(1), idx)
	require.Equal(t, idx, r.Indices[1].Idx)
	// remove first index and add another one
	r.Indices = r.Indices[1:]
	idx, err = r.NewIndex(2, expTime, 1, 3, 2, 5, reservation.CorePath)
	require.NoError(t, err)
	require.Len(t, r.Indices, 2)
	require.Equal(t, reservation.IndexNumber(2), idx)
	require.Equal(t, idx, r.Indices[1].Idx)
}

func TestReservationValidate(t *testing.T) {
	r := segmenttest.NewReservation()
	err := r.Validate()
	require.NoError(t, err)
	// wrong path
	r.Steps = nil
	err = r.Validate()
	require.Error(t, err)
	// more than one active index
	expTime := util.SecsToTime(1)
	r = segmenttest.NewReservation()
	r.NewIndex(0, expTime, 0, 0, 0, 0, reservation.CorePath)
	r.NewIndex(1, expTime, 0, 0, 0, 0, reservation.CorePath)
	require.Len(t, r.Indices, 2)
	r.Indices[0].SetStateForTesting(segment.IndexActive)
	r.Indices[1].SetStateForTesting(segment.IndexActive)
	err = r.Validate()
	require.Error(t, err)
	// ID not set
	r = segmenttest.NewReservation()
	r.ID = reservation.ID{}
	err = r.Validate()
	require.Error(t, err)
	// starts in this AS but ingress nonzero
	r = segmenttest.NewReservation()
	r.Steps[r.CurrentStep].Ingress = 1
	err = r.Validate()
	require.Error(t, err)
	// Does not start in this AS but ingress empty
	r = segmenttest.NewReservation()
	r.Steps = nil
	err = r.Validate()
	require.Error(t, err)
}

func TestIndex(t *testing.T) {
	r := segmenttest.NewReservation()
	expTime := util.SecsToTime(1)
	r.NewIndex(0, expTime, 0, 0, 0, 0, reservation.CorePath)
	idx, _ := r.NewIndex(1, expTime, 0, 0, 0, 0, reservation.CorePath)
	r.NewIndex(2, expTime, 0, 0, 0, 0, reservation.CorePath)
	require.Len(t, r.Indices, 3)
	index := r.Index(idx)
	require.Equal(t, &r.Indices[1], index)
	index = r.Index(reservation.IndexNumber(4))
	require.Nil(t, index)
	r.SetIndexConfirmed(idx)
	r.SetIndexActive(idx)
	index = r.Index(idx)
	require.Equal(t, &r.Indices[0], index)
}

func TestSetIndexConfirmed(t *testing.T) {
	r := segmenttest.NewReservation()
	expTime := util.SecsToTime(1)
	id, _ := r.NewIndex(0, expTime, 0, 0, 0, 0, reservation.CorePath)
	require.Equal(t, segment.IndexTemporary, r.Indices[0].State)
	err := r.SetIndexConfirmed(id)
	require.NoError(t, err)
	require.Equal(t, segment.IndexPending, r.Indices[0].State)

	// confirm already confirmed
	err = r.SetIndexConfirmed(id)
	require.NoError(t, err)
	require.Equal(t, segment.IndexPending, r.Indices[0].State)
}

func TestSetIndexActive(t *testing.T) {
	r := segmenttest.NewReservation()
	expTime := util.SecsToTime(1)

	// index not confirmed
	idx, _ := r.NewIndex(0, expTime, 0, 0, 0, 0, reservation.CorePath)
	err := r.SetIndexActive(idx)
	require.Error(t, err)

	// normal activation
	r.SetIndexConfirmed(idx)
	err = r.SetIndexActive(idx)
	require.NoError(t, err)
	require.Equal(t, segment.IndexActive, r.Indices[0].State)
	require.Equal(t, 0, r.GetActiveIndexForTesting())

	// already active
	err = r.SetIndexActive(idx)
	require.NoError(t, err)

	// remove previous indices
	r.NewIndex(1, expTime, 0, 0, 0, 0, reservation.CorePath)
	idx, _ = r.NewIndex(2, expTime, 0, 0, 0, 0, reservation.CorePath)
	require.Len(t, r.Indices, 3)
	require.Equal(t, 0, r.GetActiveIndexForTesting())
	r.SetIndexConfirmed(idx)
	err = r.SetIndexActive(idx)
	require.NoError(t, err)
	require.Len(t, r.Indices, 1)
	require.Equal(t, 0, r.GetActiveIndexForTesting())
	require.True(t, r.Indices[0].Idx == idx)
}

func TestRemoveIndex(t *testing.T) {
	r := segmenttest.NewReservation()
	expTime := util.SecsToTime(1)
	idx, _ := r.NewIndex(0, expTime, 0, 0, 0, 0, reservation.CorePath)
	err := r.RemoveIndex(idx)
	require.NoError(t, err)
	require.Len(t, r.Indices, 0)

	// remove second index
	idx, _ = r.NewIndex(1, expTime, 0, 0, 0, 0, reservation.CorePath)
	idx2, _ := r.NewIndex(2, expTime, 0, 0, 0, 0, reservation.CorePath)
	err = r.RemoveIndex(idx)
	require.NoError(t, err)
	require.Len(t, r.Indices, 1)
	require.True(t, r.Indices[0].Idx == idx2)
	err = r.Validate()
	require.NoError(t, err)

	// remove also removes older indices
	expTime = expTime.Add(time.Second)
	r.NewIndex(3, expTime, 0, 0, 0, 0, reservation.CorePath)
	idx, _ = r.NewIndex(4, expTime, 0, 0, 0, 0, reservation.CorePath)
	idx2, _ = r.NewIndex(5, expTime, 0, 0, 0, 0, reservation.CorePath)
	require.Len(t, r.Indices, 4)
	err = r.RemoveIndex(idx)
	require.NoError(t, err)
	require.Len(t, r.Indices, 1)
	require.True(t, r.Indices[0].Idx == idx2)
	err = r.Validate()
	require.NoError(t, err)
}

func TestMaxBlockedBW(t *testing.T) {
	r := segmenttest.NewReservation()
	r.Indices = r.Indices[:0]
	require.Equal(t, uint64(0), r.MaxBlockedBW())
	r.NewIndex(0, util.SecsToTime(1), 1, 1, 1, 1, reservation.CorePath)
	require.Equal(t, reservation.BWCls(1).ToKbps(), r.MaxBlockedBW())
	r.NewIndex(1, util.SecsToTime(1), 1, 1, 1, 1, reservation.CorePath)
	require.Equal(t, reservation.BWCls(1).ToKbps(), r.MaxBlockedBW())
	r.Indices[0].AllocBW = 11
	require.Equal(t, reservation.BWCls(11).ToKbps(), r.MaxBlockedBW())
}

func TestDeriveColibriPathAtSource(t *testing.T) {

	cases := map[string]struct {
		SegR *segment.Reservation
	}{
		"up": {
			SegR: &segment.Reservation{
				PathType:    reservation.UpPath,
				Steps:       test.NewSteps("1-ff00:0:1", 1, 2, "1-ff00:0:2", 3, 4, "1-ff00:0:3"),
				CurrentStep: 1,
				ID:          *test.MustParseID("ff00:0:1", "01234567"),
				Indices: segment.Indices{segment.Index{
					Token: &reservation.Token{
						InfoField: reservation.InfoField{
							Idx:            1,
							BWCls:          3,
							ExpirationTick: reservation.TickFromTime(util.SecsToTime(1000)),
						},
						HopFields: []reservation.HopField{
							{
								Ingress: 0,
								Egress:  1,
							},
							{
								Ingress: 2,
								Egress:  3,
							},
							{
								Ingress: 4,
								Egress:  0,
							},
						},
					},
				}},
			},
		},
		"down": {
			SegR: &segment.Reservation{
				PathType:    reservation.DownPath,
				Steps:       test.NewSteps("1-ff00:0:3", 4, 3, "1-ff00:0:2", 2, 1, "1-ff00:0:1"),
				CurrentStep: 1,
				ID:          *test.MustParseID("ff00:0:1", "01234567"),
				Indices: segment.Indices{segment.Index{
					Token: &reservation.Token{
						InfoField: reservation.InfoField{
							Idx:            1,
							BWCls:          3,
							ExpirationTick: reservation.TickFromTime(util.SecsToTime(1000)),
						},
						HopFields: []reservation.HopField{
							{
								Ingress: 0,
								Egress:  4,
							},
							{
								Ingress: 3,
								Egress:  2,
							},
							{
								Ingress: 1,
								Egress:  0,
							},
						},
					},
				}},
			},
		},
	}
	for name, tc := range cases {
		name, tc := name, tc
		t.Run(name, func(t *testing.T) {
			t.Parallel()
			colibriKeys := test.InitColibriKeys(t, len(tc.SegR.Steps))
			srcAS := tc.SegR.Steps.SrcIA().AS()
			dstAS := tc.SegR.Steps.DstIA().AS()
			test.TraverseASesAndStampMACs(t, tc.SegR, colibriKeys, srcAS, dstAS)
			colPath := colibriMinimalToRegular(t, tc.SegR.DeriveColibriPathAtSource())
			test.VerifyMACs(t, colPath, colibriKeys, srcAS, dstAS)
		})
	}
}

func TestDeriveColibriPathAtDestination(t *testing.T) {

	cases := map[string]struct {
		SegR *segment.Reservation
	}{
		"up": {
			SegR: &segment.Reservation{
				PathType:    reservation.UpPath,
				Steps:       test.NewSteps("1-ff00:0:1", 1, 2, "1-ff00:0:2", 3, 4, "1-ff00:0:3"),
				CurrentStep: 1,
				ID:          *test.MustParseID("ff00:0:1", "01234567"),
				Indices: segment.Indices{segment.Index{
					Token: &reservation.Token{
						InfoField: reservation.InfoField{
							Idx:            1,
							BWCls:          3,
							ExpirationTick: reservation.TickFromTime(util.SecsToTime(1000)),
						},
						HopFields: []reservation.HopField{
							{
								Ingress: 0,
								Egress:  1,
							},
							{
								Ingress: 2,
								Egress:  3,
							},
							{
								Ingress: 4,
								Egress:  0,
							},
						},
					},
				}},
			},
		},
		"down": {
			SegR: &segment.Reservation{
				PathType:    reservation.DownPath,
				Steps:       test.NewSteps("1-ff00:0:3", 4, 3, "1-ff00:0:2", 2, 1, "1-ff00:0:1"),
				CurrentStep: 1,
				ID:          *test.MustParseID("ff00:0:1", "01234567"),
				Indices: segment.Indices{segment.Index{
					Token: &reservation.Token{
						InfoField: reservation.InfoField{
							Idx:            1,
							BWCls:          3,
							ExpirationTick: reservation.TickFromTime(util.SecsToTime(1000)),
						},
						HopFields: []reservation.HopField{
							{
								Ingress: 0,
								Egress:  4,
							},
							{
								Ingress: 3,
								Egress:  2,
							},
							{
								Ingress: 1,
								Egress:  0,
							},
						},
					},
				}},
			},
		},
	}
	for name, tc := range cases {
		name, tc := name, tc
		t.Run(name, func(t *testing.T) {
			t.Parallel()
			colibriKeys := test.InitColibriKeys(t, len(tc.SegR.Steps))
			srcAS := tc.SegR.Steps.SrcIA().AS()
			dstAS := tc.SegR.Steps.DstIA().AS()
			test.TraverseASesAndStampMACs(t, tc.SegR, colibriKeys, srcAS, dstAS)
			colPath := colibriMinimalToRegular(t, tc.SegR.DeriveColibriPathAtDestination())
			test.VerifyMACs(t, colPath, colibriKeys, srcAS, dstAS)
		})
	}
}

func colibriMinimalToRegular(t *testing.T, min *colpath.ColibriPathMinimal) *colpath.ColibriPath {
	require.NotNil(t, min)
	colPath, err := min.ToColibriPath()
	require.NoError(t, err)
	return colPath
}


text:
// Registers the rules namespace.
Drupal.rules = Drupal.rules || {};

(function($) {
  Drupal.behaviors.rules_autocomplete = {
    attach: function(context) {
      var autocomplete_settings = Drupal.settings.rules_autocomplete;

      $('input.rules-autocomplete').once(function() {
        var input = this;
        new Drupal.rules.autocomplete(input, autocomplete_settings[$(input).attr('id')]);
      });
    }
  };

  /**
   * Rules autocomplete object.
   */
  Drupal.rules.autocomplete = function(input, settings) {
    this.id = settings.inputId;
    this.uri = settings.source;
    this.jqObject = $('#' + this.id);
    this.cache = new Array();
    this.jqObject.addClass('ui-corner-left');

    this.opendByFocus = false;
    this.focusOpens = true;
    this.groupSelected = false;

    this.button = $(' ');
    this.button.attr( {
      'tabIndex': -1,
      'title': 'Show all items'
    });
    this.button.insertAfter(this.jqObject);

    this.button.button( {
      icons: {
        primary: 'ui-icon-triangle-1-s'
      },
      text: false
    });

    // Don't round the left corners.
    this.button.removeClass('ui-corner-all');
    this.button.addClass('ui-corner-right ui-button-icon rules-autocomplete-button');

    this.jqObject.autocomplete();
    this.jqObject.autocomplete("option", "minLength", 0);
    // Add a custom class, so we can style the autocomplete box without
    // interfering with other jquery autocomplete widgets.
    this.jqObject.autocomplete("widget").addClass('rules-autocomplete');

    // Save the current rules_autocomplete object, so it can be used in
    // handlers.
    var instance = this;

    // Event handlers
    this.jqObject.focus(function() {
      if (instance.focusOpens) {
        instance.toggle();
        instance.opendByFocus = true;
      }
      else {
        instance.focusOpens = true;
      }
    });

    // Needed when the window is closed but the textfield has the focus.
    this.jqObject.click(function() {
      // Since the focus event happens earlier then the focus event, we need to
      // check here, if the window should be opened.
      if (!instance.opendByFocus) {
        instance.toggle();
      }
      else {
        instance.opendByFocus = false;
      }
    });

    this.jqObject.bind("autocompleteselect", function(event, ui) {
      // If a group was selected then set the groupSelected to true for the
      // overriden close function from jquery autocomplete.
      if (ui.item.value.substring(ui.item.value.length - 1, ui.item.value.length) == ":") {
        instance.groupSelected = true;
      }
      instance.focusOpens = false;
      instance.opendByFocus = false;
    });

    this.jqObject.autocomplete("option", "source", function(request, response) {
      if (request.term in instance.cache) {
        response(instance.cache[request.term]);
        return;
      }
      $.ajax( {
        url: instance.uri + '/' + request.term,
        dataType: "json",
        success: function(data) {
          instance.success(data, request, response);
        }
      });
    });

    // Newer versions of jQuery UI use element.data('ui-autocomplete'), older
    // versions use element.data('autocomplete').
    var autocompleteDataKey = typeof(this.jqObject.data('autocomplete')) === 'object' ? 'autocomplete' : 'ui-autocomplete';

    // Since jquery autocomplete by default strips html text by using .text()
    // we need our own _renderItem function to display html content.
    this.jqObject.data(autocompleteDataKey)._renderItem = function(ul, item) {
      return $("

").data("item.autocomplete", item).append("" + item.label + "").appendTo(ul);
    };

    // Override close function
    this.jqObject.data(autocompleteDataKey).close = function (event) {
      var value = this.element.val();
      // If the selector is not a group, then trigger the close event an and
      // hide the menu.
      if (value === undefined || instance.groupSelected === false) {
        clearTimeout(this.closing);
        if (this.menu.element.is(":visible")) {
          this._trigger("close", event);
          this.menu.element.hide();
          // Use deactivate for older versions of jQuery UI.
          if (typeof(this.menu.deactivate) === 'function') {
            this.menu.deactivate();
          }
        }
      }
      else {
        // Else keep all open and trigger a search for the group.
        instance.jqObject.autocomplete("search", instance.jqObject.val());
        // After the suggestion box was opened again, we want to be able to
        // close it.
        instance.groupSelected = false;
      }
    };

    this.button.click(function() {
      instance.toggle();
    });

  };

  /**
   * Success function for Rules autocomplete object.
   */
  Drupal.rules.autocomplete.prototype.success = function(data, request, response) {
    var list = new Array();
    jQuery.each(data, function(index, value) {
      list.push( {
        label: value,
        value: index
      });
    });

    this.cache[request.term] = list;
    response(list);
  };

  /**
   * Open the autocomplete window.
   * @param searchFor The term for will be searched for. If undefined then the
   *                  entered input text will be used.
   */
  Drupal.rules.autocomplete.prototype.open = function(searchFor) {
    // If searchFor is undefined, we want to search for the passed argument.
    this.jqObject.autocomplete("search", ((searchFor === undefined) ? this.jqObject.val() : searchFor));
    this.button.addClass("ui-state-focus");
  };

  /**
   * Close the autocomplete window.
   */
  Drupal.rules.autocomplete.prototype.close = function() {
    this.jqObject.autocomplete("close");
    this.button.removeClass("ui-state-focus");
  };

  /**
   * Toogle the autcomplete window.
   */
  Drupal.rules.autocomplete.prototype.toggle = function() {
    if (this.jqObject.autocomplete("widget").is(":visible")) {
      this.close();
      this.focusOpens = true;
    }
    else {
      var groups = this.jqObject.val().split(":");
      var selector = "";
      for (var i=0; i<groups.length-1; i++) {
        selector = selector.concat(groups[i]) + ":";
      }
      this.focusOpens = false;
      this.jqObject.focus();
      this.open(selector);
    }
  };

})(jQuery);


text:
module Envi.Readers.EnviFileReader where

import Control.Applicative ( (<$>) )
import Data.List ( intersperse )
import Data.Array.Repa.Repr.ByteString
import Data.Array.Repa as R
import Data.Char ( toUpper )
import Data.Maybe ( fromMaybe )
import System.FilePath.Windows ( replaceExtension )
import Text.Parsec as P
import Text.Parsec.String ( parseFromFile )
import qualified Data.ByteString as B
import qualified Data.Map as Map

import HyperData
import HyperDataProperties

type Properties = Map.Map String [String]

readHyperData :: FilePath -> IO HyperData
readHyperData path = do
  let headerFilePath = replaceExtension path ".hdr"
  (Right headerContents) <- readHeaderFile headerFilePath
  let properties = makeHyperDataProperties headerContents
  let numLines = fromMaybe 0 $ nlines properties
  let numSamples = fromMaybe 0 $ nsamples properties
  let numBands = fromMaybe 0 $ nbands properties
  let scale = fromMaybe 1 $ reflectanceScaleFactor properties
  let interleave' = fromMaybe "BIP" $ interleave properties
  let shape = shapeOfInterleave interleave' numSamples numLines numBands
  rawFile <- fromByteString shape <$> B.readFile path
  let rawData = R.map (/scale) $ R.map fromIntegral rawFile :: Array D DIM3 Double
  let permutedData = permuteOnInterleave rawData interleave'
  reshapedData <- computeP $ reshape (Z:. numBands :. (numLines * numSamples) :: DIM2) permutedData
  return $ HyperCube reshapedData properties -- TODO: return cube or lib depending on file type

shapeOfInterleave :: String -> Int -> Int -> Int -> DIM3
shapeOfInterleave i s l b
  | Prelude.map toUpper i == "BIL" = (Z :. l :. b :. s :: DIM3)
  | Prelude.map toUpper i == "BSQ" = (Z :. b :. l :. s :: DIM3)
  | otherwise = (Z :. s :. l :. b :: DIM3)

permuteOnInterleave :: Array D DIM3 e -> String -> Array D DIM3 e
permuteOnInterleave cube i
  | Prelude.map toUpper i == "BIL" || Prelude.map toUpper i == "BSQ" = toBip cube i
  | otherwise = cube

toBip :: (Source r e) => Array r DIM3 e -> String -> Array D DIM3 e
toBip cube i = backpermute e flop cube
  where
    e@(Z :. x :. y :. z) = extent cube
    flop (Z :. x :. y :. z)
      | Prelude.map toUpper i == "BIL" = (Z :. x :. z :. y)
      | Prelude.map toUpper i == "BSQ" = (Z :. z :. y :. x)

readHeaderFile :: FilePath -> IO (Either (Map.Map k a) Properties)
readHeaderFile path = do
  result <- parseFromFile enviParser path
  return $ case result of
    Left _ -> Left Map.empty
    Right xs -> Right $ Map.fromList xs

enviParser :: Parsec String () [(String, [String])]
enviParser = do
  _ <- word
  fields <- many $ do
    field <- ((try listFieldParser) <|> (try singleFieldParser))
    return field
  spaces
  return fields

singleFieldParser :: Parsec String () (String, [String])
singleFieldParser = do
  key <- keyParser
  _ <- char '='
  value <- singleValueParser
  return (key, [value])

listFieldParser :: Parsec String () (String,[String])
listFieldParser = do
  key <- keyParser
  _ <- char '='
  value <- listValueParser
  return (key, value)

keyParser :: Parsec String () String
keyParser = spaces >> wordsSepBySpaces >>= return

singleValueParser :: Parsec String () String
singleValueParser = spaces >> ((many1 digit) <|> wordsSepBySpaces) >>= return

listValueParser :: Parsec String () [String]
listValueParser = between (spaces >> char '{' >> spaces) (char '}') $ val `sepBy1` valueSeparator >>= return

fieldSeparator :: Parsec String () ()
fieldSeparator = spaces >> char '\n' >> spaces

valueSeparator :: Parsec String () ()
valueSeparator = spaces >> char ',' >> spaces

wordsSepBySpaces :: Parsec String () String
wordsSepBySpaces = concat . intersperse " " <$> word `sepEndBy` (many $ oneOf " ")

word :: Parsec String () String
word = many1 letter

val :: Parsec String () String
val = many1 $ alphaNum <|> oneOf "[]():+-=._ \t\r\n"

makeHyperDataProperties :: Properties -> HyperDataProperties
makeHyperDataProperties p = HyperDataProperties { description = Map.lookup "description" p
  , nsamples = read <$> concat <$> Map.lookup "samples" p
  , nlines = read <$> concat <$> Map.lookup  "lines" p
  , nbands = read <$> concat <$> Map.lookup "bands" p
  , headerOffset = read <$> concat <$> Map.lookup "header offset" p
  , fileType = concat <$> Map.lookup "file type" p
  , dataType = concat <$> Map.lookup "data type" p
  , interleave = concat <$> Map.lookup "interleave" p
  , sensorType = concat <$> Map.lookup "sensor type" p
  , byteOrder = read <$> concat <$> Map.lookup "byte order" p
  , reflectanceScaleFactor = read <$> concat <$> Map.lookup "reflectance scale factor" p
  , mapInfo = Map.lookup "map info" p
  , wavelengthUnits = concat <$> Map.lookup "wavelength units" p
  , bandNames = Map.lookup "band names" p
  , wavelengths = fmap read <$> Map.lookup "wavelength" p
  , fwhm = fmap read <$> Map.lookup "fwhm" p }


text:
The directory used by npm for globally installed npm modules.

## Install

Install with [npm](https://www.npmjs.com/):

```sh
$ npm install --save global-modules
```

## Usage

```js
var dir = require('global-modules');
//=> '/usr/local/lib/node_modules' (depends on OS)
```

## About

### Related projects

* [contains-path](https://www.npmjs.com/package/contains-path): Return true if a file path contains the given path. | [homepage](https://github.com/jonschlinkert/contains-path "Return true if a file path contains the given path.")
* [git-config-path](https://www.npmjs.com/package/git-config-path): Resolve the path to the user's global .gitconfig. | [homepage](https://github.com/jonschlinkert/git-config-path "Resolve the path to the user's global .gitconfig.")
* [global-prefix](https://www.npmjs.com/package/global-prefix): Get the npm global path prefix. | [homepage](https://github.com/jonschlinkert/global-prefix "Get the npm global path prefix.")
* [npm-paths](https://www.npmjs.com/package/npm-paths): Returns an array of unique "npm" directories based on the user's platform and environment. | [homepage](https://github.com/jonschlinkert/npm-paths "Returns an array of unique "npm" directories based on the user's platform and environment.")

### Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).

### Building docs

_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_

To generate the readme and API documentation with [verb](https://github.com/verbose/verb):

```sh
$ npm install -g verb verb-generate-readme && verb
```

### Running tests

Install dev dependencies:

```sh
$ npm install -d && npm test
```

### Author

**Jon Schlinkert**

* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)

### License

Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT license](https://github.com/jonschlinkert/global-modules/blob/master/LICENSE).

***

_This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on July 26, 2016._


text:
require "spec_helper"
require "codility/stacks_and_queues/brackets"

module Codility
  module StacksAndQueues
    RSpec.describe Brackets do
      context "when string is properly nested" do
        it "returns 1" do
          s = "{[()()]}"
          expect(Brackets.solution(s)).to eql(1)
        end
      end

      context "when string is not properly nested" do
        it "returns 0" do
          s = "([)()]"
          expect(Brackets.solution(s)).to eql(0)
        end
      end

      context "when last closing paren is missing" do
        it "returns 0" do
          s = "{[()()]"
          expect(Brackets.solution(s)).to eql(0)
        end
      end
    end
  end
end


text:
<?php

namespace Inass\EleccionBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery("SELECT e.id, e.nombre FROM EleccionBundle:Estado e ORDER BY e.nombre");
        $estados = $query->execute(null, \Doctrine\ORM\Query::HYDRATE_ARRAY);
        $query = $em->createQuery("SELECT n.id, n.evento, n.accion, e.nombre as estado FROM EleccionBundle:Novedad n JOIN n.estado e ORDER BY n.id DESC");
        $query->setMaxResults(5);
        $novedades = $query->execute(null, \Doctrine\ORM\Query::HYDRATE_ARRAY);
        return array('estados' => $estados, 'novedades' => $novedades);
    }

    /**
     * @Route("/dataEmpleados", name="datos_grafico_empleados")
     */
    public function dataEmpleadosAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery("SELECT COUNT(e.id) FROM EleccionBundle:Empleado e");
        $total = $query->getSingleScalarResult();
        $query = $em->createQuery("SELECT COUNT(e.id) FROM EleccionBundle:Empleado e WHERE e.voto = TRUE");
        $votos = $query->getSingleScalarResult();
        $_data = array(array('Efectivos', (int)$votos), array('Pendientes', (int)($total-$votos)));
        $response = new Response(json_encode($_data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     * @Route("/dataAdultos", name="datos_grafico_adultos")
     */
    public function dataAdultosAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery("SELECT SUM(e.votantes) AS votantes, SUM(e.votos) AS votos FROM EleccionBundle:Estado e");
        $rs = $query->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
        $_data = array(array('Efectivos', (int)$rs['votos']), array('Pendientes', (int)($rs['votantes']-$rs['votos'])));
        $response = new Response(json_encode($_data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     * @Route("/graficoxestado", name="grafico_estado")
     * @Template()
     */
    public function graficoxestadoAction(Request $request)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery("SELECT e.id, e.nombre FROM EleccionBundle:Estado e ORDER BY e.nombre");
        $estados = $query->execute(null, \Doctrine\ORM\Query::HYDRATE_ARRAY);
        $query = $em->createQuery("SELECT e.id, e.nombre FROM EleccionBundle:Estado e WHERE e.id = :estado");
        $query->setParameter('estado', $request->request->get('estado'));
        $rs = $query->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
        $query = $em->createQuery("SELECT n.id, n.evento, n.accion, e.nombre as estado FROM EleccionBundle:Novedad n JOIN n.estado e WHERE n.estado = :estado ORDER BY n.id DESC");
        $query->setParameter('estado', $request->request->get('estado'));
        $query->setMaxResults(5);
        $novedades = $query->execute(null, \Doctrine\ORM\Query::HYDRATE_ARRAY);
        return array('estado' => $request->request->get('estado'), 'titulo' => $rs['nombre'],'estados' => $estados, 'novedades' => $novedades);
    }

    /**
     * @Route("/dataEmpleadosxEstado", name="datos_grafico_empleados_x_estado")
     */
    public function dataEmpleadosxEstadoAction(Request $request)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery("SELECT COUNT(e.id) FROM EleccionBundle:Empleado e WHERE e.estado = :estado");
        $query->setParameter('estado', $request->request->get('id'));
        $total = $query->getSingleScalarResult();
        $query = $em->createQuery("SELECT COUNT(e.id) FROM EleccionBundle:Empleado e WHERE e.voto = TRUE AND e.estado = :estado ");
        $query->setParameter('estado', $request->request->get('id'));
        $votos = $query->getSingleScalarResult();
        $_data = array(array('Efectivos', (int)$votos), array('Pendientes', (int)($total-$votos)));
        $response = new Response(json_encode($_data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     * @Route("/dataAdultosxEstado", name="datos_grafico_adultos_x_estado")
     */
    public function dataAdultosxEstadoAction(Request $request)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery("SELECT SUM(e.votantes) AS votantes, SUM(e.votos) AS votos FROM EleccionBundle:Estado e WHERE e.id = :estado");
        $query->setParameter('estado', $request->request->get('id'));
        $rs = $query->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
        $_data = array(array('Efectivos', (int)$rs['votos']), array('Pendientes', (int)($rs['votantes']-$rs['votos'])));
        $response = new Response(json_encode($_data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
}