text:
package features

import (
	"reflect"
	"sort"
	"strings"

	"github.com/kr/pretty"
	"k8s.io/ingress-gce/pkg/composite"
	"k8s.io/ingress-gce/pkg/utils"
	"k8s.io/klog/v2"
)

// This values are copied from GCP Load balancer
var defaultCdnPolicy = composite.BackendServiceCdnPolicy{
	CacheKeyPolicy:          &composite.CacheKeyPolicy{IncludeHost: true, IncludeProtocol: true, IncludeQueryString: true},
	CacheMode:               "CACHE_ALL_STATIC",
	ClientTtl:               3600,
	DefaultTtl:              3600,
	MaxTtl:                  86400,
	NegativeCaching:         true,
	RequestCoalescing:       true,
	ServeWhileStale:         86400,
	SignedUrlCacheMaxAgeSec: 0,
}

// EnsureCDN reads the CDN configuration specified in the ServicePort.BackendConfig
// and applies it to the BackendService. It returns true if there were existing
// settings on the BackendService that were overwritten.
func EnsureCDN(sp utils.ServicePort, be *composite.BackendService) bool {
	if sp.BackendConfig.Spec.Cdn == nil {
		return false
	}
	klog.V(3).Infof("BackendConfig.Spec.Cdn before merge = %s", prettyPrint(sp.BackendConfig.Spec.Cdn))
	klog.V(3).Infof("CdnPolicy before merge = %+v", prettyPrint(be.CdnPolicy))
	newConfig := renderConfig(sp)
	if hasDiff(newConfig, be) {
		klog.V(2).Infof("Updated CDN settings for service %v/%v.", sp.ID.Service.Namespace, sp.ID.Service.Name)
		applyConfig(newConfig, be)
		return true
	}
	return false
}

func prettyPrint(a interface{}) string {
	value := pretty.Sprint(a)
	return strings.ReplaceAll(value, "\n", "")
}

type negativeCachePolicySortInterface []*composite.BackendServiceCdnPolicyNegativeCachingPolicy

func (l negativeCachePolicySortInterface) Len() int           { return len(l) }
func (l negativeCachePolicySortInterface) Less(i, j int) bool { return l[i].Code < l[j].Code }
func (l negativeCachePolicySortInterface) Swap(i, j int)      { l[i], l[j] = l[j], l[i] }

func negativeCachingPolicyEqual(x, y []*composite.BackendServiceCdnPolicyNegativeCachingPolicy) bool {

	xSorted := negativeCachePolicySortInterface(append([]*composite.BackendServiceCdnPolicyNegativeCachingPolicy{}, x...))
	ySorted := negativeCachePolicySortInterface(append([]*composite.BackendServiceCdnPolicyNegativeCachingPolicy{}, y...))
	sort.Sort(xSorted)
	sort.Sort(ySorted)

	return reflect.DeepEqual(xSorted, ySorted)
}

func renderConfig(sp utils.ServicePort) *composite.BackendService {
	cdnConfig := sp.BackendConfig.Spec.Cdn
	be := &composite.BackendService{}
	be.EnableCDN = cdnConfig.Enabled

	if !be.EnableCDN {
		return be
	}

	be.CdnPolicy = &composite.BackendServiceCdnPolicy{}

	if cdnConfig.CachePolicy != nil {
		beCacheKeyPolicy := &composite.CacheKeyPolicy{}
		beCacheKeyPolicy.IncludeHost = cdnConfig.CachePolicy.IncludeHost
		beCacheKeyPolicy.IncludeProtocol = cdnConfig.CachePolicy.IncludeProtocol
		beCacheKeyPolicy.IncludeQueryString = cdnConfig.CachePolicy.IncludeQueryString
		if cdnConfig.CachePolicy.IncludeQueryString {
			// we must check for an empty list here as the user might set  'queryStringBlacklist:[]' and compare with DeepEqual will fail
			if len(cdnConfig.CachePolicy.QueryStringBlacklist) > 0 {
				beCacheKeyPolicy.QueryStringBlacklist = cdnConfig.CachePolicy.QueryStringBlacklist
			}
			// we must check for an empty list here as the user might set  'queryStringWhitelist:[]' and compare with DeepEqual will fail
			if len(cdnConfig.CachePolicy.QueryStringWhitelist) > 0 {
				beCacheKeyPolicy.QueryStringWhitelist = cdnConfig.CachePolicy.QueryStringWhitelist
			}
		}
		be.CdnPolicy.CacheKeyPolicy = beCacheKeyPolicy
	} else {
		be.CdnPolicy.CacheKeyPolicy = defaultCdnPolicy.CacheKeyPolicy
	}

	if cdnConfig.CacheMode != nil {
		be.CdnPolicy.CacheMode = *cdnConfig.CacheMode
	} else {
		be.CdnPolicy.CacheMode = defaultCdnPolicy.CacheMode
	}

	if cdnConfig.RequestCoalescing != nil {
		be.CdnPolicy.RequestCoalescing = *cdnConfig.RequestCoalescing
	} else {
		be.CdnPolicy.RequestCoalescing = defaultCdnPolicy.RequestCoalescing
	}

	if cdnConfig.ServeWhileStale != nil {
		be.CdnPolicy.ServeWhileStale = *cdnConfig.ServeWhileStale
	} else {
		be.CdnPolicy.ServeWhileStale = defaultCdnPolicy.ServeWhileStale
	}

	// MaxTtl must be specified with CACHE_ALL_STATIC cache_mode only
	if be.CdnPolicy.CacheMode != "CACHE_ALL_STATIC" {
		be.CdnPolicy.MaxTtl = 0
	} else if cdnConfig.MaxTtl != nil {
		be.CdnPolicy.MaxTtl = *cdnConfig.MaxTtl
		if be.CdnPolicy.MaxTtl == 0 {
			be.CdnPolicy.ForceSendFields = append(be.CdnPolicy.ForceSendFields, "MaxTtl")
		}
	} else {
		be.CdnPolicy.MaxTtl = defaultCdnPolicy.MaxTtl
	}

	// if USE_ORIGIN_HEADERS ClientTtl must be ignored
	if be.CdnPolicy.CacheMode == "USE_ORIGIN_HEADERS" {
		be.CdnPolicy.ClientTtl = 0
	} else if cdnConfig.ClientTtl != nil {
		be.CdnPolicy.ClientTtl = *cdnConfig.ClientTtl
		if be.CdnPolicy.ClientTtl == 0 {
			be.CdnPolicy.ForceSendFields = append(be.CdnPolicy.ForceSendFields, "ClientTtl")
		}
	} else {
		be.CdnPolicy.ClientTtl = defaultCdnPolicy.ClientTtl
	}

	// if USE_ORIGIN_HEADERS DefaultTtl must be ignored
	if be.CdnPolicy.CacheMode == "USE_ORIGIN_HEADERS" {
		be.CdnPolicy.DefaultTtl = 0
	} else if cdnConfig.DefaultTtl != nil {
		be.CdnPolicy.DefaultTtl = *cdnConfig.DefaultTtl
		if be.CdnPolicy.DefaultTtl == 0 {
			be.CdnPolicy.ForceSendFields = append(be.CdnPolicy.ForceSendFields, "DefaultTtl")
		}
	} else {
		be.CdnPolicy.DefaultTtl = defaultCdnPolicy.DefaultTtl
	}

	if cdnConfig.NegativeCaching != nil {
		be.CdnPolicy.NegativeCaching = *cdnConfig.NegativeCaching
	} else {
		be.CdnPolicy.NegativeCaching = defaultCdnPolicy.NegativeCaching
	}

	negativeCachingPolicy := []*composite.BackendServiceCdnPolicyNegativeCachingPolicy{}
	if be.CdnPolicy.NegativeCaching {
		for _, policyRef := range cdnConfig.NegativeCachingPolicy {
			negativeCachingPolicy = append(
				negativeCachingPolicy,
				&composite.BackendServiceCdnPolicyNegativeCachingPolicy{
					Code: policyRef.Code,
					Ttl:  policyRef.Ttl,
				},
			)
		}
	}

	if len(negativeCachingPolicy) > 0 {
		be.CdnPolicy.NegativeCachingPolicy = negativeCachingPolicy
	}

	if cdnConfig.SignedUrlCacheMaxAgeSec != nil {
		be.CdnPolicy.SignedUrlCacheMaxAgeSec = *cdnConfig.SignedUrlCacheMaxAgeSec
	} else {
		be.CdnPolicy.SignedUrlCacheMaxAgeSec = defaultCdnPolicy.SignedUrlCacheMaxAgeSec
	}

	bypassCacheOnRequestHeaders := []*composite.BackendServiceCdnPolicyBypassCacheOnRequestHeader{}
	for _, policyRef := range cdnConfig.BypassCacheOnRequestHeaders {
		bypassCacheOnRequestHeaders = append(
			bypassCacheOnRequestHeaders,
			&composite.BackendServiceCdnPolicyBypassCacheOnRequestHeader{
				HeaderName: policyRef.HeaderName,
			},
		)
	}
	if len(bypassCacheOnRequestHeaders) > 0 {
		be.CdnPolicy.BypassCacheOnRequestHeaders = bypassCacheOnRequestHeaders
	}

	return be
}

func hasDiff(new *composite.BackendService, current *composite.BackendService) bool {

	if new.EnableCDN != current.EnableCDN {
		return true
	}

	if !new.EnableCDN {
		return false
	}

	if current.CdnPolicy == nil {
		return true
	}

	// In order to use reflect.DeepEqual we need to handle the special cases

	// SignedUrlKeyNames are not handled by this function and must be preserved as they are
	if current.CdnPolicy != nil && current.CdnPolicy.SignedUrlKeyNames != nil {
		new.CdnPolicy.SignedUrlKeyNames = current.CdnPolicy.SignedUrlKeyNames
	}

	// for NegativeCachingPolicy order does not matter, so if there are equal regardless of order
	// we take the current one
	if negativeCachingPolicyEqual(new.CdnPolicy.NegativeCachingPolicy, current.CdnPolicy.NegativeCachingPolicy) {
		new.CdnPolicy.NegativeCachingPolicy = current.CdnPolicy.NegativeCachingPolicy
	}

	// for all other fields we can use reflect.DeepEqual
	return !reflect.DeepEqual(new.CdnPolicy, current.CdnPolicy)
}

func applyConfig(new *composite.BackendService, current *composite.BackendService) {
	current.EnableCDN = new.EnableCDN
	current.CdnPolicy = new.CdnPolicy
}


text:
const env = process.env;
const nodeEnv = env.NODE_ENV || 'development';
const logging = nodeEnv === 'test' ? false : console.log;
let database = env.DB_NAME;
let kafkaConsumerGroup = 'invoices-consumer-service';
let kafkaOffsetReset = 'earliest';

if (nodeEnv === 'test' || nodeEnv === 'development') {
  database = nodeEnv === 'test' ? database + '_test' : database + '_dev';
  // Avoid group restabilization to improve consumer initialization time
  kafkaConsumerGroup = kafkaConsumerGroup + Math.random();
  // Avoid reprocessing messages when running tests
  kafkaOffsetReset = nodeEnv === 'test' ? 'latest' : kafkaOffsetReset;
}

const config = {
  username: env.DB_USER,
  password: env.DB_PASSWORD,
  database: database,
  host: env.DB_HOST,
  dialect: 'postgres',
  logging: logging,
  seederStorage: 'sequelize',
  kafkaProducer: {
    'client.id': 'invoices-producer-service',
    'metadata.broker.list': `${env.KAFKA_HOST}:${env.KAFKA_PORT}`,
    'compression.codec': 'snappy',
    'retry.backoff.ms': 200,
    'message.send.max.retries': 10,
    'socket.keepalive.enable': true,
    'queue.buffering.max.messages': 100000,
    'queue.buffering.max.ms': 1000,
    'batch.num.messages': 1000000,
    'dr_cb': true,
    'event_cb': true,
    topic: 'invoice'
  },
  kafkaConsumer: {
    'group.id': kafkaConsumerGroup,
    'metadata.broker.list': `${env.KAFKA_HOST}:${env.KAFKA_PORT}`,
    'enable.auto.commit': false,
    'event_cb': true,
    'offsetReset': kafkaOffsetReset,
    topics: [ 'user' ]
  }
};

module.exports = config;

redpajama_set_name: RedPajamaGithub


text:
Contributing to Mizuu's development
============

#### Contributing code?

1. [Fork Mizuu][1].
2. `git checkout -b descriptive-branch-name dev` and make your commits.
3. When you think your code is ready, start a pull request against the dev branch. Please reference [existing issues][2] when possible.

#### No code?
* You can [suggest features][2].
* You can [discuss a bug][2] or [report a bug][2]!
* You can [translate strings][3].

Branch structure
----------------

The repository is made up of two main branches: master (stable) and dev (unstable / work in progress).

* **master** has the latest stable code, its tags are released as versions of Mizuu on GitHub, www.mizuu.tv and Google Play.
* **dev** includes the latest unstable code from contributers (you!).

Since Mizuu was just recently open-sourced, there's still some work to do with branching and the overall structure of the development, but this is on the to-do list. For now, use the tagged commits as release versions.

Setup
-----

Mizuu is developed using Android Studio and is built with Java 1.7.

In order to use the project with the various web services, you'll need to add an `api_keys.xml` file to `/res/values/` with the following content:

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="tmdb_api_key">add_your_own</string>
    <string name="tvdb_api_key">add_your_own</string>
    <string name="youtube_api_key">add_your_own</string>
    <string name="trakt_api_key">add_your_own</string>
</resources>
```

 [1]: https://github.com/MizzleDK/Mizuu/fork
 [2]: https://github.com/MizzleDK/Mizuu/issues
 [3]: http://translate.mizuu.tv/


text:
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace Hype.HypeApi
{
	[DataContract]
	public class Song
	{
		[DataMember(Name="itemid")]
		public string ItemID { get; internal set; }

		[DataMember(Name="artist")]
		public string Artist { get; internal set; }

		[DataMember(Name="title")]
		public string Title { get; internal set; }

		[DataMember(Name="thumb_url")]
		public string ThumbnailUrlSmall { get; internal set; }

		[DataMember(Name="thumb_url_medium")]
		public string ThumbnailUrlMedium { get; internal set;}

		[DataMember(Name="thumb_url_large")]
		public string ThumbnailUrlLarge { get; internal set; }

		public
	}
}


text:
@implementation CacheManager

static id instance;
+(instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance==nil) {
            instance=[self new];
        }
    });
    return instance;
}

- (id)init {
    if ((self = [super init])) {
        _myCache = [self createCache];
    }
    return self;
}

- (Cache *)createCache {
    return [Cache sharedInstance];
}

- (NSString *)cacheKeyForURL:(NSURL *)url {
    if (self.cacheKeyFilter) {
        return self.cacheKeyFilter(url);
    }
    else {
        return [url absoluteString];
    }
}

- (BOOL)cachedDataExistsForURL:(NSURL *)url {
    NSString *key = [self cacheKeyForURL:url];
    if ([self.myCache dataFromMemoryCacheForKey:key] != nil) return YES;
    return [self.myCache diskDataExistsWithKey:key];
}

- (BOOL)diskDataExistsForURL:(NSURL *)url {
    NSString *key = [self cacheKeyForURL:url];
    return [self.myCache diskDataExistsWithKey:key];
}

- (void)cachedDataExistsForURL:(NSURL *)url
                     completion:(CheckCacheCompletionBlock)completionBlock {
    NSString *key = [self cacheKeyForURL:url];

    BOOL isInMemoryCache = ([self.myCache dataFromMemoryCacheForKey:key] != nil);

    if (isInMemoryCache) {
        // making sure we call the completion block on the main queue
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionBlock) {
                completionBlock(YES);
            }
        });
        return;
    }

    [self.myCache diskDataExistsWithKey:key completion:^(BOOL isInDiskCache) {
        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
        if (completionBlock) {
            completionBlock(isInDiskCache);
        }
    }];
}

- (void)diskDataExistsForURL:(NSURL *)url
                   completion:(CheckCacheCompletionBlock)completionBlock {
    NSString *key = [self cacheKeyForURL:url];

    [self.myCache diskDataExistsWithKey:key completion:^(BOOL isInDiskCache) {
        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
        if (completionBlock) {
            completionBlock(isInDiskCache);
        }
    }];
}

- (void)saveDataToCache:(NSData *)data forURL:(NSURL *)url
{
    if (data && url) {
        NSString *key = [self cacheKeyForURL:url];
        [self.myCache storeData:data forKey:key toDisk:YES];
    }
}

//获取缓存
-(NSData *) getCache:(NSString *)key
{
    if (key) {
        return [self.myCache dataFromDiskCacheForKey:key];
    }
    return nil;
}

-(void) getCache:(NSString *)key done:(QueryCompletedBlock)doneBlock
{
    if (key) {
        [self.myCache queryDiskCacheForKey:key done:^(NSData *data, MyCacheType cacheType) {
            if (data) {
                doneBlock((NSData*)data,cacheType);
            }else{
                doneBlock(nil,cacheType);
            }
        }];
    }
}

//设置缓存
-(void) setCache: (NSData *)data key:(NSString *)key
{
    if (data && key) {
        NSString *key_str = [self cacheKeyForURL:[NSURL URLWithString:key]];
        [self.myCache storeData:data forKey:key_str toDisk:NO];
    }
}

@end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Orchis gennarii nothosubsp. kusadasiensis B.Baumann & H.Baumann

### Remarks
null


text:
module JBLAS
  # Mixin for collecting enumerable operations.
  #
  # Collected in MatrixMixin.
  module MatrixEnumMixin
    include Enumerable

    # Iterate over rows.
    def each_row
      (0...rows).each do |i|
        yield row(i)
      end
    end

    # Iterate over columns.
    def each_column
      (0...columns).each do |j|
        yield column(j)
      end
    end

    # Each iterates over each element, going down rows first.
    def each
      (0...length).each do |i|
        yield get(i)
      end
    end

    # Map each element.
    #
    # Returns a new matrix of the same type. This means that the block
    # must return something which can again be stored in the matrix.
    def map(&block)
      return dup.map!(&block)
    end

    # Map each element and store the result in the matrix.
    #
    # Note that the result must be again something
    # which can be stored in the matrix. Otherwise you should do an
    # to_a first.
    def map!(&block)
      (0...length).each do |i|
        put(i, block.call(get(i)))
      end
      self
    end
  end
end


text:
package com.intellij.openapi.roots.ui.configuration.artifacts.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonShortcuts;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.packaging.ui.TreeNodePresentation;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * @author nik
 */
public abstract class ArtifactEditorNavigateActionBase extends DumbAwareAction {
  public ArtifactEditorNavigateActionBase(JComponent contextComponent) {
    super(ProjectBundle.message("action.name.facet.navigate"));
    registerCustomShortcutSet(CommonShortcuts.getEditSource(), contextComponent);
  }

  public void update(final AnActionEvent e) {
    final TreeNodePresentation presentation = getPresentation();
    e.getPresentation().setEnabled(presentation != null && presentation.canNavigateToSource());
  }

  @Nullable
  protected abstract TreeNodePresentation getPresentation();

  public void actionPerformed(final AnActionEvent e) {
    final TreeNodePresentation presentation = getPresentation();
    if (presentation != null) {
      presentation.navigateToSource();
    }
  }
}


text:
/******************************************************************************

gif_lib.h - service library for decoding and encoding GIF images

*****************************************************************************/

#ifndef _GIF_LIB_H_
#define _GIF_LIB_H_ 1

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define GIFLIB_MAJOR 5
#define GIFLIB_MINOR 0
#define GIFLIB_RELEASE 4

#define GIF_ERROR   0
#define GIF_OK      1

#include <stddef.h>
#include <stdbool.h>

#define GIF_STAMP "GIFVER"          /* First chars in file - GIF stamp.  */
#define GIF_STAMP_LEN sizeof(GIF_STAMP) - 1
#define GIF_VERSION_POS 3           /* Version first character in stamp. */
#define GIF87_STAMP "GIF87a"        /* First chars in file - GIF stamp.  */
#define GIF89_STAMP "GIF89a"        /* First chars in file - GIF stamp.  */

typedef unsigned char GifPixelType;
typedef unsigned char *GifRowType;
typedef unsigned char GifByteType;
typedef unsigned int GifPrefixType;
typedef int GifWord;

typedef struct GifColorType {
    GifByteType Red, Green, Blue;
} GifColorType;

typedef struct ColorMapObject {
    int ColorCount;
    int BitsPerPixel;
    bool SortFlag;
    GifColorType *Colors;    /* on malloc(3) heap */
} ColorMapObject;

typedef struct GifImageDesc {
    GifWord Left, Top, Width, Height;   /* Current image dimensions. */
    bool Interlace;                     /* Sequential/Interlaced lines. */
    ColorMapObject *ColorMap;           /* The local color map */
} GifImageDesc;

typedef struct ExtensionBlock {
    int ByteCount;
    GifByteType *Bytes; /* on malloc(3) heap */
    int Function;       /* The block function code */
#define CONTINUE_EXT_FUNC_CODE    0x00    /* continuation subblock */
#define COMMENT_EXT_FUNC_CODE     0xfe    /* comment */
#define GRAPHICS_EXT_FUNC_CODE    0xf9    /* graphics control (GIF89) */
#define PLAINTEXT_EXT_FUNC_CODE   0x01    /* plaintext */
#define APPLICATION_EXT_FUNC_CODE 0xff    /* application block */
} ExtensionBlock;

typedef struct SavedImage {
    GifImageDesc ImageDesc;
    GifByteType *RasterBits;         /* on malloc(3) heap */
    int ExtensionBlockCount;         /* Count of extensions before image */
    ExtensionBlock *ExtensionBlocks; /* Extensions before image */
} SavedImage;

typedef struct GifFileType {
    GifWord SWidth, SHeight;         /* Size of virtual canvas */
    GifWord SColorResolution;        /* How many colors can we generate? */
    GifWord SBackGroundColor;        /* Background color for virtual canvas */
    GifByteType AspectByte;	     /* Used to compute pixel aspect ratio */
    ColorMapObject *SColorMap;       /* Global colormap, NULL if nonexistent. */
    int ImageCount;                  /* Number of current image (both APIs) */
    GifImageDesc Image;              /* Current image (low-level API) */
    SavedImage *SavedImages;         /* Image sequence (high-level API) */
    int ExtensionBlockCount;         /* Count extensions past last image */
    ExtensionBlock *ExtensionBlocks; /* Extensions past last image */
    int Error;			     /* Last error condition reported */
    void *UserData;                  /* hook to attach user data (TVT) */
    void *Private;                   /* Don't mess with this! */
} GifFileType;

#define GIF_ASPECT_RATIO(n)	((n)+15.0/64.0)

typedef enum {
    UNDEFINED_RECORD_TYPE,
    SCREEN_DESC_RECORD_TYPE,
    IMAGE_DESC_RECORD_TYPE, /* Begin with ',' */
    EXTENSION_RECORD_TYPE,  /* Begin with '!' */
    TERMINATE_RECORD_TYPE   /* Begin with ';' */
} GifRecordType;

/* func type to read gif data from arbitrary sources (TVT) */
typedef int (*InputFunc) (GifFileType *, GifByteType *, int);

/* func type to write gif data to arbitrary targets.
 * Returns count of bytes written. (MRB)
 */
typedef int (*OutputFunc) (GifFileType *, const GifByteType *, int);

/******************************************************************************
 GIF89 structures
******************************************************************************/

typedef struct GraphicsControlBlock {
    int DisposalMode;
#define DISPOSAL_UNSPECIFIED      0       /* No disposal specified. */
#define DISPOSE_DO_NOT            1       /* Leave image in place */
#define DISPOSE_BACKGROUND        2       /* Set area too background color */
#define DISPOSE_PREVIOUS          3       /* Restore to previous content */
    bool UserInputFlag;      /* User confirmation required before disposal */
    int DelayTime;           /* pre-display delay in 0.01sec units */
    int TransparentColor;    /* Palette index for transparency, -1 if none */
#define NO_TRANSPARENT_COLOR	-1
} GraphicsControlBlock;

/******************************************************************************
 GIF encoding routines
******************************************************************************/

/* Main entry points */
GifFileType *EGifOpenFileName(const char *GifFileName,
                              const bool GifTestExistence, int *Error);
GifFileType *EGifOpenFileHandle(const int GifFileHandle, int *Error);
GifFileType *EGifOpen(void *userPtr, OutputFunc writeFunc, int *Error);
int EGifSpew(GifFileType * GifFile);
char *EGifGetGifVersion(GifFileType *GifFile); /* new in 5.x */
int EGifCloseFile(GifFileType * GifFile);

#define E_GIF_ERR_OPEN_FAILED    1    /* And EGif possible errors. */
#define E_GIF_ERR_WRITE_FAILED   2
#define E_GIF_ERR_HAS_SCRN_DSCR  3
#define E_GIF_ERR_HAS_IMAG_DSCR  4
#define E_GIF_ERR_NO_COLOR_MAP   5
#define E_GIF_ERR_DATA_TOO_BIG   6
#define E_GIF_ERR_NOT_ENOUGH_MEM 7
#define E_GIF_ERR_DISK_IS_FULL   8
#define E_GIF_ERR_CLOSE_FAILED   9
#define E_GIF_ERR_NOT_WRITEABLE  10

/* These are legacy.  You probably do not want to call them directly */
int EGifPutScreenDesc(GifFileType *GifFile,
                      const int GifWidth, const int GifHeight,
		      const int GifColorRes,
                      const int GifBackGround,
                      const ColorMapObject *GifColorMap);
int EGifPutImageDesc(GifFileType *GifFile,
		     const int GifLeft, const int GifTop,
                     const int GifWidth, const int GifHeight,
		     const bool GifInterlace,
                     const ColorMapObject *GifColorMap);
void EGifSetGifVersion(GifFileType *GifFile, const bool gif89);
int EGifPutLine(GifFileType *GifFile, GifPixelType *GifLine,
                int GifLineLen);
int EGifPutPixel(GifFileType *GifFile, const GifPixelType GifPixel);
int EGifPutComment(GifFileType *GifFile, const char *GifComment);
int EGifPutExtensionLeader(GifFileType *GifFile, const int GifExtCode);
int EGifPutExtensionBlock(GifFileType *GifFile,
                         const int GifExtLen, const void *GifExtension);
int EGifPutExtensionTrailer(GifFileType *GifFile);
int EGifPutExtension(GifFileType *GifFile, const int GifExtCode,
		     const int GifExtLen,
                     const void *GifExtension);
int EGifPutCode(GifFileType *GifFile, int GifCodeSize,
                const GifByteType *GifCodeBlock);
int EGifPutCodeNext(GifFileType *GifFile,
                    const GifByteType *GifCodeBlock);

/******************************************************************************
 GIF decoding routines
******************************************************************************/

/* Main entry points */
GifFileType *DGifOpenFileName(const char *GifFileName, int *Error);
GifFileType *DGifOpenFileHandle(int GifFileHandle, int *Error);
int DGifSlurp(GifFileType * GifFile);
GifFileType *DGifOpen(void *userPtr, InputFunc readFunc, int *Error);    /* new one (TVT) */
int DGifCloseFile(GifFileType * GifFile);

#define D_GIF_ERR_OPEN_FAILED    101    /* And DGif possible errors. */
#define D_GIF_ERR_READ_FAILED    102
#define D_GIF_ERR_NOT_GIF_FILE   103
#define D_GIF_ERR_NO_SCRN_DSCR   104
#define D_GIF_ERR_NO_IMAG_DSCR   105
#define D_GIF_ERR_NO_COLOR_MAP   106
#define D_GIF_ERR_WRONG_RECORD   107
#define D_GIF_ERR_DATA_TOO_BIG   108
#define D_GIF_ERR_NOT_ENOUGH_MEM 109
#define D_GIF_ERR_CLOSE_FAILED   110
#define D_GIF_ERR_NOT_READABLE   111
#define D_GIF_ERR_IMAGE_DEFECT   112
#define D_GIF_ERR_EOF_TOO_SOON   113

/* These are legacy.  You probably do not want to call them directly */
int DGifGetScreenDesc(GifFileType *GifFile);
int DGifGetRecordType(GifFileType *GifFile, GifRecordType *GifType);
int DGifGetImageDesc(GifFileType *GifFile);
int DGifGetLine(GifFileType *GifFile, GifPixelType *GifLine, int GifLineLen);
int DGifGetPixel(GifFileType *GifFile, GifPixelType GifPixel);
int DGifGetComment(GifFileType *GifFile, char *GifComment);
int DGifGetExtension(GifFileType *GifFile, int *GifExtCode,
                     GifByteType **GifExtension);
int DGifGetExtensionNext(GifFileType *GifFile, GifByteType **GifExtension);
int DGifGetCode(GifFileType *GifFile, int *GifCodeSize,
                GifByteType **GifCodeBlock);
int DGifGetCodeNext(GifFileType *GifFile, GifByteType **GifCodeBlock);
int DGifGetLZCodes(GifFileType *GifFile, int *GifCode);

/******************************************************************************
 Color table quantization (deprecated)
******************************************************************************/
int GifQuantizeBuffer(unsigned int Width, unsigned int Height,
                   int *ColorMapSize, GifByteType * RedInput,
                   GifByteType * GreenInput, GifByteType * BlueInput,
                   GifByteType * OutputBuffer,
                   GifColorType * OutputColorMap);

/******************************************************************************
 Error handling and reporting.
******************************************************************************/
extern char *GifErrorString(int ErrorCode);     /* new in 2012 - ESR */

/*****************************************************************************
 Everything below this point is new after version 1.2, supporting `slurp
 mode' for doing I/O in two big belts with all the image-bashing in core.
******************************************************************************/

/******************************************************************************
 Color map handling from gif_alloc.c
******************************************************************************/

extern ColorMapObject *GifMakeMapObject(int ColorCount,
                                     const GifColorType *ColorMap);
extern void GifFreeMapObject(ColorMapObject *Object);
extern ColorMapObject *GifUnionColorMap(const ColorMapObject *ColorIn1,
                                     const ColorMapObject *ColorIn2,
                                     GifPixelType ColorTransIn2[]);
extern int GifBitSize(int n);

/******************************************************************************
 Support for the in-core structures allocation (slurp mode).
******************************************************************************/

extern void GifApplyTranslation(SavedImage *Image, GifPixelType Translation[]);
extern int GifAddExtensionBlock(int *ExtensionBlock_Count,
				ExtensionBlock **ExtensionBlocks,
				int Function,
				unsigned int Len, unsigned char ExtData[]);
extern void GifFreeExtensions(int *ExtensionBlock_Count,
			      ExtensionBlock **ExtensionBlocks);
extern SavedImage *GifMakeSavedImage(GifFileType *GifFile,
                                  const SavedImage *CopyFrom);
extern void GifFreeSavedImages(GifFileType *GifFile);

/******************************************************************************
 5.x functions for GIF89 graphics control blocks
******************************************************************************/

int DGifExtensionToGCB(const size_t GifExtensionLength,
		       const GifByteType *GifExtension,
		       GraphicsControlBlock *GCB);
size_t EGifGCBToExtension(const GraphicsControlBlock *GCB,
		       GifByteType *GifExtension);

int DGifSavedExtensionToGCB(GifFileType *GifFile,
			    int ImageIndex,
			    GraphicsControlBlock *GCB);
int EGifGCBToSavedExtension(const GraphicsControlBlock *GCB,
			    GifFileType *GifFile,
			    int ImageIndex);

/******************************************************************************
 The library's internal utility font
******************************************************************************/

#define GIF_FONT_WIDTH  8
#define GIF_FONT_HEIGHT 8
extern const unsigned char GifAsciiTable8x8[][GIF_FONT_WIDTH];

extern void GifDrawText8x8(SavedImage *Image,
                     const int x, const int y,
                     const char *legend, const int color);

extern void GifDrawBox(SavedImage *Image,
                    const int x, const int y,
                    const int w, const int d, const int color);

extern void GifDrawRectangle(SavedImage *Image,
                   const int x, const int y,
                   const int w, const int d, const int color);

extern void GifDrawBoxedText8x8(SavedImage *Image,
                          const int x, const int y,
                          const char *legend,
                          const int border, const int bg, const int fg);

#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _GIF_LIB_H */

/* end */


text:
using System.Collections.Generic;
using CodingProblemsTests.Extensions;
using CodingProblemsTests.Structures;

namespace CodingProblemsTests.Utils
{
    public static class ListNodeUtils
    {
        public static ListNode Create(int[] source)
        {
            ListNode head = null;
            ListNode prev = null;
            foreach (var n in source)
            {
                ListNode node = new ListNode(n);
                if (head == null) head = node;
                if (prev != null) prev.next = node;
                prev = node;
            }
            return head;
        }

        public static int[] ToArray(ListNode node)
        {
            var list = new List<int>();
            while (node != null)
            {
                list.Add(node.val);
                node = node.next;
            }
            return list.ToArray();
        }
        public static string ToString(ListNode node)
        {
            return ToArray(node).JoinStrings(",");
        }
    }
}


text:
.. EN-Revision: none
.. _zend.service.amazon.ec2.images:

Zend\Service_Amazon\Ec2: Amazon Maschinen Images (AMI)
======================================================

Amazon Maschinen Images (AMIs) sind mit einer bereits wachsenden Listen von Betriebssystemen vorkonfiguriert.

.. _zend.service.amazon.ec2.images.info:

AMI Informations Tools
----------------------

.. _zend.service.amazon.ec2.images.register:

.. rubric:: Ein AMI mit EC2 registrieren

*register* Jedes *AMI* ist mit einer eideutigen ID assoziiert welche vom Amazon EC2 Service über die RegisterImage
Operation zur Verfügung gestellt wird. Wärend der Registrierung empfängt Amazon EC2 das spezifizierte Manifest
des Images von Amazon S3 und überprüft ob das Image dem Benutzer gehört der das Image registriert.

*register* gibt die imageId für das registrierte Image zurück.

.. code-block:: php
   :linenos:

   $ec2_img = new Zend\Service\Amazon\Ec2\Image('aws_key','aws_secret_key');
   $ip = $ec2_img->register('imageLocation');

.. _zend.service.amazon.ec2.images.deregister:

.. rubric:: De-Registrieren einer AMI von EC2

*deregister*, de-registriert ein *AMI*. Einmal de-registriert können Instanzen dieses *AMI* nicht mehr gestartet
werden.

*deregister* gibt ein boolsches ``TRUE`` oder ``FALSE`` zurück.

.. code-block:: php
   :linenos:

   $ec2_img = new Zend\Service\Amazon\Ec2\Image('aws_key','aws_secret_key');
   $ip = $ec2_img->deregister('imageId');

.. _zend.service.amazon.ec2.images.describe:

.. rubric:: Beschreiben einer AMI

*describe* gibt Informationen über *AMI*\ s, AKIs und ARIs zurück die für den Benutzer verfügbar sind. Die
zurückgegebenen Informationen enthalten den Imagetyp, Produktcodes, Architektur, Kernel und *RAM* Disk IDs. Images
die für den Benutzer verfügbar sind, enthalten öffentliche Images die zum Starten für jeden Benutzer vorhanden
sind, private Images die dem Benutzer gehören der die Anfrage stellt, und private Images die anderen Benutzern
gehören welche dem Benutzer explizit die Rechte zum Starten gegeben haben.

      .. _zend.service.amazon.ec2.images.describe-table:

      .. table:: Die Rechte für das Starten fallen in drei Kategorien

         +--------+-----------------------------------------------------------------------------------------------------------------------------+
         |Name    |Beschreibung                                                                                |
         +========+=============================================================================================================================+
         |public  |Der Eigentümer des AMI gibt allen Gruppen das Recht das AMI zu starten. Alle Benutzer haben Startberechtigung für diese AMIs.|
         +--------+-----------------------------------------------------------------------------------------------------------------------------+
         |explicit|Der Eigentümer des AMI gibt einem spezifischen Benutzer die Startberechtigung.                                               |
         +--------+-----------------------------------------------------------------------------------------------------------------------------+
         |implicit|Ein Benutzer hat implizit die Startberechtigung für alle AMIs die Ihm gehören.                                               |
         +--------+-----------------------------------------------------------------------------------------------------------------------------+

Die Liste der zurückgegebenen *AMI*\ s kann durch die Spezifikation von *AMI* IDs, *AMI* Eigentümer oder
Benutzern mit Starterechtigung, geändert werden. Wenn keine Option spezifiziert wird, gibt Amazon EC2 alle *AMI*\
s zurück für die der Benutzer eine Startberechtigung hat.

Wenn eine oder mehrere *AMI* IDs spezifiziert werden, werden nur die *AMI*\ s zurückgegeben welche die
spezifizierten IDs besitzen. Wenn man eine ungültige *AMI* ID spezifiziert, wird ein Fehler zurückgegeben. Wenn
man eine *AMI* ID spezifiziert für die man keinen Zugriff hat, wird diese nicht in den zurückgegebenen
Ergebnissen enthalten sein.

Wenn ein oder mehrere *AMI* Eigentümer spezifiziert werden, werden nur die *AMI*\ s der spezifizierten
Eigentümer, für die man auch Zugriffsrechte hat, zurückgegeben. Die Ergebnisse können account für die Account
IDs des spezifizierten Eigentümers enthalten, amazon für *AMI*\ s die Amazon selbst gehören oder self für
*AMI*\ s die man selbst besitzt.

Wenn man eine Liste von ausführbaren Benutzern spezifiziert, werden nur die Benutzer zurückgegeben die eine
Startberechtigung für die *AMI*\ s haben. Man kann mit account, Account IDs spezifizieren (wenn man die *AMI*\ s
besitzt), self für *AMI*\ s die man selbst besitzt oder explizite Zugriffsrechte hat, oder all für öffentliche
*AMI*\ s.

*describe* gibt ein Array für alle Images zurück die den übergebenen Kriterien entsprechen. Das Array enthält
imageId, imageLocation, imageState, imageOwnerId, isPublic, architecture, imageType, kernedId, ramdiskId und
platform.

.. code-block:: php
   :linenos:

   $ec2_img = new Zend\Service\Amazon\Ec2\Image('aws_key','aws_secret_key');
   $ip = $ec2_img->describe();

.. _zend.service.amazon.ec2.images.attribute:

Utilities für AMI Attribute
---------------------------

.. _zend.service.amazon.ec2.images.attribute.modify:

.. rubric:: Image Attribute verändern

Ein Attribut eines *AMI* verändern

      .. _zend.service.amazon.ec2.images.attribute.modify-table:

      .. table:: Gültige Attribute

         +----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
         |Name            |Beschreibung                                                                                |
         +================+===============================================================================================================================================================================================================================================================================================================+
         |launchPermission|Kontrolliert wer die Berechtigung hat das AMI zu starten. Startberechtigung kann spezifischen Benutzern durch das hinzufügen von userIds gegeben werden. Um das AMI öffentlich zu machen, sollte man die add Gruppe hinzufügen.                                                                                |
         +----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
         |productCodes    |Assoziiert einen Produktcode mit AMIs. Das erlaubt es Entwicklern Benutzer für die Verwendung von AMIs zu benennen. Der Benutzer muß für das Produkt angemeldet sein bevor er das AMI starten kann. Das ist ein Write-Once Attribut; nachdem es gesetzt wurde kann es nicht mehr geändert oder gelöscht werden.|
         +----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

*modifyAttribute* gibt ein boolsches ``TRUE`` oder ``FALSE`` zurück.

.. code-block:: php
   :linenos:

   $ec2_img = new Zend\Service\Amazon\Ec2\Image('aws_key','aws_secret_key');
   // Ändert die Startberechtigung (launchPermission) eines AMI
   $return = $ec2_img->modifyAttribute('imageId',
                                       'launchPermission',
                                       'add',
                                       'userId',
                                       'userGroup');

   // Setzt den Produktcode des AMI.
   $return = $ec2_img->modifyAttribute('imageId',
                                       'productCodes',
                                       'add',
                                       null,
                                       null,
                                       'productCode');

.. _zend.service.amazon.ec2.images.attribute.reset:

.. rubric:: Zurücksetzen eines AMI Attributes

*resetAttribute* setzt die Attribute eines *AMI* auf dessen Standardwerte zurück. **Das productCodes Attribut kann
nicht zurückgesetzt werden.**

.. code-block:: php
   :linenos:

   $ec2_img = new Zend\Service\Amazon\Ec2\Image('aws_key','aws_secret_key');
   $return = $ec2_img->resetAttribute('imageId', 'launchPermission');

.. _zend.service.amazon.ec2.images.attribute.describe:

.. rubric:: AMI Attribute beschreiben

*describeAttribute* gibt Informationen über ein Attribut eines *AMI* zurück. Pro Aufruf kann nur ein Attribut
spezifiziert werden. Aktuell werden nur launchPermission und productCodes unterstützt.

*describeAttribute* gibt ein Array mit dem Wert des Attributes zurück das angefragt wurde.

.. code-block:: php
   :linenos:

   $ec2_img = new Zend\Service\Amazon\Ec2\Image('aws_key','aws_secret_key');
   $return = $ec2_img->describeAttribute('imageId', 'launchPermission');


text:
package org.kuali.kra.coi.personfinancialentity;

import org.kuali.kra.coi.notesandattachments.attachments.FinancialEntityAttachmentSummary;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class FinancialEntitySummaryBean implements Serializable {

    private static final long serialVersionUID = -8525835671837464825L;
    private String address;
    private String webAddress;
    private String relationshipDescription;
    private String sponsorName;
    private String statusDescription;
    private String ownershipType;
    private String entitySponsorsResearch;
    private String details;
    private Map<String, String> relationshipDetails;
    private List<FinancialEntityAttachmentSummary> attachmentSummary;
    private FinancialEntityForm financialEntityForm;

    public FinancialEntitySummaryBean(FinancialEntityForm financialEntityForm) {
        this.financialEntityForm = financialEntityForm;
    }
    public FinancialEntityForm getFinancialEntityForm() {
        return financialEntityForm;
    }
    public void setFinancialEntityForm(FinancialEntityForm financialEntityForm) {
        this.financialEntityForm = financialEntityForm;
    }
    public String getDetails() {
        return details;
    }
    public void setDetails(String details) {
        this.details = details;
    }
    public Map<String, String> getRelationshipDetails() {
        return relationshipDetails;
    }
    public void setRelationshipDetails(Map<String, String> relationshipDetails) {
        this.relationshipDetails = relationshipDetails;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getWebAddress() {
        return webAddress;
    }
    public void setWebAddress(String webAddress) {
        this.webAddress = webAddress;
    }
    public String getRelationshipDescription() {
        return relationshipDescription;
    }
    public void setRelationshipDescription(String relationshipDescription) {
        this.relationshipDescription = relationshipDescription;
    }
    public String getSponsorName() {
        return sponsorName;
    }
    public void setSponsorName(String sponsorName) {
        this.sponsorName = sponsorName;
    }
    public String getStatusDescription() {
        return statusDescription;
    }
    public void setStatusDescription(String statusDescription) {
        this.statusDescription = statusDescription;
    }
    public String getOwnershipType() {
        return ownershipType;
    }
    public void setOwnershipType(String ownershipType) {
        this.ownershipType = ownershipType;
    }
    public List<FinancialEntityAttachmentSummary> getAttachmentSummary() {
        return attachmentSummary;
    }
    public void setAttachmentSummary(List<FinancialEntityAttachmentSummary> attachmentSummary) {
        this.attachmentSummary = attachmentSummary;
    }
    public String getEntitySponsorsResearch() {
        return entitySponsorsResearch;
    }
    public void setEntitySponsorsResearch(String entitySponsorsResearch) {
        this.entitySponsorsResearch = entitySponsorsResearch;
    }

}


text:
package org.testng.xml.internal;

import java.util.List;
import java.util.Set;
import org.testng.TestNGException;
import org.testng.collections.Lists;
import org.testng.collections.Sets;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;

/** A utility class to work with {@link XmlSuite} */
public final class XmlSuiteUtils {

  private XmlSuiteUtils() {
    // Utility class. Defeat instantiation.
  }

  /**
   * A validator that runs through the list of suites and checks if each of the suites contains any
   * {@link XmlTest} with the same name. If found, then a {@link TestNGException} is raised.
   *
   * @param suites - The list of {@link XmlSuite} to validate.
   */
  public static void validateIfSuitesContainDuplicateTests(List<XmlSuite> suites) {
    for (XmlSuite suite : suites) {
      ensureNoDuplicateTestsArePresent(suite);
      validateIfSuitesContainDuplicateTests(suite.getChildSuites());
    }
  }

  /**
   * Ensure that two XmlSuite don't have the same name
   *
   * @param suites - The List of {@link XmlSuite} that are to be tested and names updated if
   *     duplicate names found.
   */
  public static void adjustSuiteNamesToEnsureUniqueness(List<XmlSuite> suites) {
    adjustSuiteNamesToEnsureUniqueness(suites, Sets.newHashSet());
  }

  public static XmlSuite newXmlSuiteUsing(List<String> classes) {
    XmlSuite xmlSuite = new XmlSuite();
    xmlSuite.setVerbose(0);
    xmlSuite.setName("Jar suite");
    XmlTest xmlTest = new XmlTest(xmlSuite);
    xmlTest.setXmlClasses(constructXmlClassesUsing(classes));
    return xmlSuite;
  }

  /**
   * Ensures that the current suite doesn't contain any duplicate {@link XmlTest} instances. If
   * duplicates are found, then a {@link TestNGException} is raised.
   *
   * @param xmlSuite - The {@link XmlSuite} to work with.
   */
  static void ensureNoDuplicateTestsArePresent(XmlSuite xmlSuite) {
    Set<String> testNames = Sets.newHashSet();
    for (XmlTest test : xmlSuite.getTests()) {
      if (!testNames.add(test.getName())) {
        throw new TestNGException(
            "Two tests in the same suite ["
                + xmlSuite.getName()
                + "] "
                + "cannot have the same name: "
                + test.getName());
      }
    }
  }

  private static List<XmlClass> constructXmlClassesUsing(List<String> classes) {
    List<XmlClass> xmlClasses = Lists.newLinkedList();
    for (String cls : classes) {
      XmlClass xmlClass = new XmlClass(cls);
      xmlClasses.add(xmlClass);
    }
    return xmlClasses;
  }

  private static void adjustSuiteNamesToEnsureUniqueness(List<XmlSuite> suites, Set<String> names) {
    for (XmlSuite suite : suites) {
      String name = suite.getName();

      int count = 0;
      String tmpName = name;
      while (names.contains(tmpName)) {
        tmpName = name + " (" + count++ + ")";
      }

      if (count > 0) {
        suite.setName(tmpName);
        names.add(tmpName);
      } else {
        names.add(name);
      }

      adjustSuiteNamesToEnsureUniqueness(suite.getChildSuites(), names);
    }
  }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="determine">
        <note>
            Frames file for 'determine' based on annotation-on-the-fly on the financial
            subcorpus.  No verbnet entry.
        </note>

        <roleset id="determine.01" name="set, establish, decide" vncls="84">
            <roles>
                <role descr="decider" n="0">
                    <vnrole vncls="84" vntheta="Agent"/>
                </role>
                <role descr="thing determined" n="1">
                    <vnrole vncls="84" vntheta="Theme"/>
                </role>
                <role descr="grounds" n="2"/>
                <role descr="attribute of arg1" n="3"/>
            </roles>

            <example name="passive, no attribute">
                <text>
                    [The exact amount of the refund]-1 will be determined *trace*-1 next year,
                    based on actual collections made until Dec 31 of this year.
                </text>
                <arg n="1">*trace*</arg>
                <arg f="MOD" n="m">will</arg>
                <rel>determined</rel>
                <arg f="TMP" n="m">next year</arg>
                <arg n="2">based on actual collections made until Dec 31 of
                    this year
                </arg>
            </example>

            <example name="with agent and attribute">
                <text>
                    John determined the cheap diamonds to actually be plastic.
                </text>
                <arg n="0">John</arg>
                <rel>determined</rel>
                <arg n="1">the cheap diamonds</arg>
                <arg n="3">to actually be plastic</arg>
            </example>

            <note>
                Skip adjectival usages like "We are (very) determined".  Adding "very"
                is a good test for adjectivality.
            </note>

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


text:
<md-content ng-controller="homeController as vm">

        <md-input-container>
            Files from
            <input type="email" ng-model="vm.email" placeholder="who@sentfiles.net" />
        </md-input-container>
        <md-button class="md-primary md-raised" ng-disabled="vm.loading" ng-click="vm.loadData()">
            Get files
        </md-button>

        <md-progress-circular ng-show="vm.loading" md-mode="indeterminate"></md-progress-circular>

        <md-button ng-repeat="file in vm.dataObject" class="md-raised" ng-click="vm.view(file.emailId, file.id, file.name)" ng-bind="file.name">
            <md-tooltip autohide ng-show="vm.isImage(file.contentType)">Show image - ({{file.size}} bytes)</md-tooltip>
        </md-button>

        <md-whiteframe class="md-whiteframe-1dp">

        </md-whiteframe>
        <md-button class="md-primary md-raised"  ng-disabled="vm.loading" ng-click="vm.upload()">
            Save to SharePoint
        </md-button>

{{vm.dataObject | json}}

</md-content>


text:
<?php

/**
 * Test Controller
 */
class FoundationController extends AppController {

    public function index() {
        View::template('foundation');
    }

}


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end
  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end
  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end
  # This block must be here, do not combine with the other `before(:each)` block.
  # This makes it so Capybara can see the database.
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end

  config.include FactoryGirl::Syntax::Methods
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.include RequestSpecHelper, type: :request
end

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end


text:
module NavbarHelper
  # Generate

 appropriate for the Bootstrap navbar.
  # If :active_when hash is provided in the options, a class=active will
  # automatically be added to the
 when appropriate.
  #
  # Example:
  #
  #     <%= navbar_link_to(
  #           "Home",
  #           root_path,
  #           :active_when => { :controller => "home" }) %>
  #
  def navbar_link_to(label, path, options={})
    active_when = options.delete(:active_when) { Hash.new }
    active = active_when.all? do |key, value|
      value === params[key].to_s
    end

    content_tag(:li, :class => ("active" if active)) do
      link_to(label, path, options)
    end
  end
end


text:
package net.bytebuddy.matcher;

import lombok.EqualsAndHashCode;
import net.bytebuddy.description.ByteCodeElement;

/**
 * An element matcher that matches a Java descriptor.
 *
 * @param <T> The type of the matched entity.
 */
@EqualsAndHashCode(callSuper = false)
public class DescriptorMatcher<T extends ByteCodeElement> extends ElementMatcher.Junction.AbstractBase<T> {

    /**
     * A matcher to apply to the descriptor.
     */
    private final ElementMatcher<String> matcher;

    /**
     * Creates a new matcher for an element's descriptor.
     *
     * @param matcher A matcher to apply to the descriptor.
     */
    public DescriptorMatcher(ElementMatcher<String> matcher) {
        this.matcher = matcher;
    }

    @Override
    public boolean matches(T target) {
        return matcher.matches(target.getDescriptor());
    }

    @Override
    public String toString() {
        return "hasDescriptor(" + matcher + ")";
    }
}


text:
(function (globalScope) {

    function loadLatest(element, parentId) {

        var options = {

            IncludeItemTypes: "Audio",
            Limit: 9,
            Fields: "PrimaryImageAspectRatio",
            ParentId: parentId,
            ImageTypeLimit: 1,
            EnableImageTypes: "Primary,Backdrop,Thumb"
        };

        Emby.Models.latestItems(options).then(function (result) {

            var section = element.querySelector('.latestSection');

            DefaultTheme.CardBuilder.buildCards(result, {
                parentContainer: section,
                itemsContainer: section.querySelector('.itemsContainer'),
                shape: 'autoHome',
                width: DefaultTheme.CardBuilder.homePortraitWidth
            });
        });
    }

    function loadPlaylists(element, parentId) {

        var options = {

            SortBy: "SortName",
            SortOrder: "Ascending",
            IncludeItemTypes: "Playlist",
            Recursive: true,
            ParentId: parentId,
            Fields: "PrimaryImageAspectRatio,SortName,CumulativeRunTimeTicks,CanDelete",
            StartIndex: 0,
            Limit: 9
        };

        Emby.Models.playlists(options).then(function (result) {

            var section = element.querySelector('.playlistsSection');

            DefaultTheme.CardBuilder.buildCards(result.Items, {
                parentContainer: section,
                itemsContainer: section.querySelector('.itemsContainer'),
                shape: 'autoHome',
                width: DefaultTheme.CardBuilder.homePortraitWidth
            });
        });
    }

    function loadRecentlyPlayed(element, parentId) {

        var options = {

            SortBy: "DatePlayed",
            SortOrder: "Descending",
            IncludeItemTypes: "Audio",
            Limit: 9,
            Recursive: true,
            Fields: "PrimaryImageAspectRatio",
            Filters: "IsPlayed",
            ParentId: parentId,
            ImageTypeLimit: 1,
            EnableImageTypes: "Primary,Backdrop,Thumb"
        };

        Emby.Models.items(options).then(function (result) {

            var section = element.querySelector('.recentlyPlayedSection');

            DefaultTheme.CardBuilder.buildCards(result.Items, {
                parentContainer: section,
                itemsContainer: section.querySelector('.itemsContainer'),
                shape: 'autoHome',
                width: DefaultTheme.CardBuilder.homePortraitWidth,
                action: 'instantmix'
            });
        });
    }

    function loadFrequentlyPlayed(element, parentId) {

        var options = {

            SortBy: "PlayCount",
            SortOrder: "Descending",
            IncludeItemTypes: "Audio",
            Limit: 9,
            Recursive: true,
            Fields: "PrimaryImageAspectRatio",
            Filters: "IsPlayed",
            ParentId: parentId,
            ImageTypeLimit: 1,
            EnableImageTypes: "Primary,Backdrop,Thumb"
        };

        Emby.Models.items(options).then(function (result) {

            var section = element.querySelector('.frequentlyPlayedSection');

            DefaultTheme.CardBuilder.buildCards(result.Items, {
                parentContainer: section,
                itemsContainer: section.querySelector('.itemsContainer'),
                shape: 'autoHome',
                width: DefaultTheme.CardBuilder.homePortraitWidth,
                action: 'instantmix'
            });
        });
    }

    function gotoMusicView(tab, parentId) {

        Emby.Page.show(Emby.PluginManager.mapPath('defaulttheme', 'music/music.html?tab=' + tab + "&parentid=" + parentId));
    }

    function view(element, parentId) {
        var self = this;

        loadLatest(element, parentId);
        loadPlaylists(element, parentId);
        loadRecentlyPlayed(element, parentId);
        loadFrequentlyPlayed(element, parentId);

        element.querySelector('.artistsCard').addEventListener('click', function () {
            gotoMusicView('albumartists', parentId);
        });

        element.querySelector('.albumsCard').addEventListener('click', function () {
            gotoMusicView('albums', parentId);
        });

        element.querySelector('.genresCard').addEventListener('click', function () {
            gotoMusicView('genres', parentId);
        });

        self.destroy = function () {

        };
    }

    if (!globalScope.DefaultTheme) {
        globalScope.DefaultTheme = {};
    }

    globalScope.DefaultTheme.musicView = view;

})(this);


text:
package aws

import (
	"fmt"
	"testing"

	"github.com/juju/errgo"
	"github.com/stretchr/testify/assert"
)

func TestValidAmazonAccountID(t *testing.T) {
	tests := []struct {
		name            string
		amazonAccountID string
		err             error
	}{
		{
			name:            "ID has wrong length",
			amazonAccountID: "foo",
			err:             wrongAmazonAccountIDLengthError,
		},
		{
			name:            "ID contains letters",
			amazonAccountID: "123foo123foo",
			err:             malformedAmazonAccountIDError,
		},
		{
			name:            "ID is empty",
			amazonAccountID: "",
			err:             emptyAmazonAccountIDError,
		},
		{
			name:            "ID has correct format",
			amazonAccountID: "123456789012",
			err:             nil,
		},
	}

	for _, tc := range tests {
		err := validateAccountID(tc.amazonAccountID)
		assert.Equal(t, errgo.Cause(tc.err), errgo.Cause(err), fmt.Sprintf("[%s] The return value was not what we expected", tc.name))
	}
}


text:
{-
Work around this warning:
libraries/Cabal/Distribution/Simple.hs:78:0:
    Warning: In the use of `runTests'
             (imported from Distribution.Simple.UserHooks):
             Deprecated: "Please use the new testing interface instead!"
-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}

module Distribution.Simple (
        module Distribution.Package,
        module Distribution.Version,
        module Distribution.License,
        module Distribution.Simple.Compiler,
        module Language.Haskell.Extension,
        -- * Simple interface
        defaultMain, defaultMainNoRead, defaultMainArgs,
        -- * Customization
        UserHooks(..), Args,
        defaultMainWithHooks, defaultMainWithHooksArgs,
        -- ** Standard sets of hooks
        simpleUserHooks,
        autoconfUserHooks,
        defaultUserHooks, emptyUserHooks,
        -- ** Utils
        defaultHookedPackageDesc
  ) where

-- local
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Simple.UserHooks
import Distribution.Package --must not specify imports, since we're exporting module.
import Distribution.PackageDescription
         ( PackageDescription(..), GenericPackageDescription, Executable(..)
         , updatePackageDescription, hasLibs
         , HookedBuildInfo, emptyHookedBuildInfo )
import Distribution.PackageDescription.Parse
         ( readPackageDescription, readHookedBuildInfo )
import Distribution.PackageDescription.Configuration
         ( flattenPackageDescription )
import Distribution.Simple.Program
         ( defaultProgramConfiguration, addKnownPrograms, builtinPrograms
         , restoreProgramConfiguration, reconfigurePrograms )
import Distribution.Simple.PreProcess (knownSuffixHandlers, PPSuffixHandler)
import Distribution.Simple.Setup
import Distribution.Simple.Command

import Distribution.Simple.Build        ( build, repl )
import Distribution.Simple.SrcDist      ( sdist )
import Distribution.Simple.Register
         ( register, unregister )

import Distribution.Simple.Configure
         ( getPersistBuildConfig, maybeGetPersistBuildConfig
         , writePersistBuildConfig, checkPersistBuildConfigOutdated
         , configure, checkForeignDeps )

import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) )
import Distribution.Simple.Bench (bench)
import Distribution.Simple.BuildPaths ( srcPref)
import Distribution.Simple.Test (test)
import Distribution.Simple.Install (install)
import Distribution.Simple.Haddock (haddock, hscolour)
import Distribution.Simple.Utils
         (die, notice, info, warn, setupMessage, chattyTry,
          defaultPackageDesc, defaultHookedPackageDesc,
          rawSystemExitWithEnv, cabalVersion, topHandler )
import Distribution.System
         ( OS(..), buildOS )
import Distribution.Verbosity
import Language.Haskell.Extension
import Distribution.Version
import Distribution.License
import Distribution.Text
         ( display )

-- Base
import System.Environment(getArgs, getProgName)
import System.Directory(removeFile, doesFileExist,
                        doesDirectoryExist, removeDirectoryRecursive)
import System.Exit       (exitWith,ExitCode(..))
import System.IO.Error   (isDoesNotExistError)
import Control.Exception (throwIO)
import Distribution.Compat.Environment (getEnvironment)
import Distribution.Compat.Exception (catchIO)

import Control.Monad   (when)
import Data.Foldable   (traverse_)
import Data.List       (intercalate, unionBy, nub, (\\))

-- | A simple implementation of @main@ for a Cabal setup script.
-- It reads the package description file using IO, and performs the
-- action specified on the command line.
defaultMain :: IO ()
defaultMain = getArgs >>= defaultMainHelper simpleUserHooks

-- | A version of 'defaultMain' that is passed the command line
-- arguments, rather than getting them from the environment.
defaultMainArgs :: [String] -> IO ()
defaultMainArgs = defaultMainHelper simpleUserHooks

-- | A customizable version of 'defaultMain'.
defaultMainWithHooks :: UserHooks -> IO ()
defaultMainWithHooks hooks = getArgs >>= defaultMainHelper hooks

-- | A customizable version of 'defaultMain' that also takes the command
-- line arguments.
defaultMainWithHooksArgs :: UserHooks -> [String] -> IO ()
defaultMainWithHooksArgs = defaultMainHelper

-- | Like 'defaultMain', but accepts the package description as input
-- rather than using IO to read it.
defaultMainNoRead :: GenericPackageDescription -> IO ()
defaultMainNoRead pkg_descr =
  getArgs >>=
  defaultMainHelper simpleUserHooks { readDesc = return (Just pkg_descr) }

defaultMainHelper :: UserHooks -> Args -> IO ()
defaultMainHelper hooks args = topHandler $
  case commandsRun (globalCommand commands) commands args of
    CommandHelp   help                 -> printHelp help
    CommandList   opts                 -> printOptionsList opts
    CommandErrors errs                 -> printErrors errs
    CommandReadyToGo (flags, commandParse)  ->
      case commandParse of
        _ | fromFlag (globalVersion flags)        -> printVersion
          | fromFlag (globalNumericVersion flags) -> printNumericVersion
        CommandHelp     help           -> printHelp help
        CommandList     opts           -> printOptionsList opts
        CommandErrors   errs           -> printErrors errs
        CommandReadyToGo action        -> action

  where
    printHelp help = getProgName >>= putStr . help
    printOptionsList = putStr . unlines
    printErrors errs = do
      putStr (intercalate "\n" errs)
      exitWith (ExitFailure 1)
    printNumericVersion = putStrLn $ display cabalVersion
    printVersion        = putStrLn $ "Cabal library version "
                                  ++ display cabalVersion

    progs = addKnownPrograms (hookedPrograms hooks) defaultProgramConfiguration
    commands =
      [configureCommand progs `commandAddAction` \fs as ->
                                                 configureAction    hooks fs as >> return ()
      ,buildCommand     progs `commandAddAction` buildAction        hooks
      ,replCommand      progs `commandAddAction` replAction         hooks
      ,installCommand         `commandAddAction` installAction      hooks
      ,copyCommand            `commandAddAction` copyAction         hooks
      ,haddockCommand         `commandAddAction` haddockAction      hooks
      ,cleanCommand           `commandAddAction` cleanAction        hooks
      ,sdistCommand           `commandAddAction` sdistAction        hooks
      ,hscolourCommand        `commandAddAction` hscolourAction     hooks
      ,registerCommand        `commandAddAction` registerAction     hooks
      ,unregisterCommand      `commandAddAction` unregisterAction   hooks
      ,testCommand            `commandAddAction` testAction         hooks
      ,benchmarkCommand       `commandAddAction` benchAction        hooks
      ]

-- | Combine the preprocessors in the given hooks with the
-- preprocessors built into cabal.
allSuffixHandlers :: UserHooks
                  -> [PPSuffixHandler]
allSuffixHandlers hooks
    = overridesPP (hookedPreProcessors hooks) knownSuffixHandlers
    where
      overridesPP :: [PPSuffixHandler] -> [PPSuffixHandler] -> [PPSuffixHandler]
      overridesPP = unionBy (\x y -> fst x == fst y)

configureAction :: UserHooks -> ConfigFlags -> Args -> IO LocalBuildInfo
configureAction hooks flags args = do
                let distPref = fromFlag $ configDistPref flags
                pbi <- preConf hooks args flags

                (mb_pd_file, pkg_descr0) <- confPkgDescr

                --    get_pkg_descr (configVerbosity flags')
                --let pkg_descr = updatePackageDescription pbi pkg_descr0
                let epkg_descr = (pkg_descr0, pbi)

                --(warns, ers) <- sanityCheckPackage pkg_descr
                --errorOut (configVerbosity flags') warns ers

                localbuildinfo0 <- confHook hooks epkg_descr flags

                -- remember the .cabal filename if we know it
                -- and all the extra command line args
                let localbuildinfo = localbuildinfo0 {
                                       pkgDescrFile = mb_pd_file,
                                       extraConfigArgs = args
                                     }
                writePersistBuildConfig distPref localbuildinfo

                let pkg_descr = localPkgDescr localbuildinfo
                postConf hooks args flags pkg_descr localbuildinfo
                return localbuildinfo
              where
                verbosity = fromFlag (configVerbosity flags)
                confPkgDescr :: IO (Maybe FilePath, GenericPackageDescription)
                confPkgDescr = do
                  mdescr <- readDesc hooks
                  case mdescr of
                    Just descr -> return (Nothing, descr)
                    Nothing -> do
                      pdfile <- defaultPackageDesc verbosity
                      descr  <- readPackageDescription verbosity pdfile
                      return (Just pdfile, descr)

buildAction :: UserHooks -> BuildFlags -> Args -> IO ()
buildAction hooks flags args = do
  let distPref  = fromFlag $ buildDistPref flags
      verbosity = fromFlag $ buildVerbosity flags

  lbi <- getBuildConfig hooks verbosity distPref
  progs <- reconfigurePrograms verbosity
             (buildProgramPaths flags)
             (buildProgramArgs flags)
             (withPrograms lbi)

  hookedAction preBuild buildHook postBuild
               (return lbi { withPrograms = progs })
               hooks flags { buildArgs = args } args

replAction :: UserHooks -> ReplFlags -> Args -> IO ()
replAction hooks flags args = do
  let distPref  = fromFlag $ replDistPref flags
      verbosity = fromFlag $ replVerbosity flags

  lbi <- getBuildConfig hooks verbosity distPref
  progs <- reconfigurePrograms verbosity
             (replProgramPaths flags)
             (replProgramArgs flags)
             (withPrograms lbi)

  pbi <- preRepl hooks args flags
  let lbi' = lbi { withPrograms = progs }
      pkg_descr0 = localPkgDescr lbi'
      pkg_descr = updatePackageDescription pbi pkg_descr0
  replHook hooks pkg_descr lbi' hooks flags args
  postRepl hooks args flags pkg_descr lbi'

hscolourAction :: UserHooks -> HscolourFlags -> Args -> IO ()
hscolourAction hooks flags args
    = do let distPref  = fromFlag $ hscolourDistPref flags
             verbosity = fromFlag $ hscolourVerbosity flags
         hookedAction preHscolour hscolourHook postHscolour
                      (getBuildConfig hooks verbosity distPref)
                      hooks flags args

haddockAction :: UserHooks -> HaddockFlags -> Args -> IO ()
haddockAction hooks flags args = do
  let distPref  = fromFlag $ haddockDistPref flags
      verbosity = fromFlag $ haddockVerbosity flags

  lbi <- getBuildConfig hooks verbosity distPref
  progs <- reconfigurePrograms verbosity
             (haddockProgramPaths flags)
             (haddockProgramArgs flags)
             (withPrograms lbi)

  hookedAction preHaddock haddockHook postHaddock
               (return lbi { withPrograms = progs })
               hooks flags args

cleanAction :: UserHooks -> CleanFlags -> Args -> IO ()
cleanAction hooks flags args = do
                pbi <- preClean hooks args flags

                pdfile <- defaultPackageDesc verbosity
                ppd <- readPackageDescription verbosity pdfile
                let pkg_descr0 = flattenPackageDescription ppd
                -- We don't sanity check for clean as an error
                -- here would prevent cleaning:
                --sanityCheckHookedBuildInfo pkg_descr0 pbi
                let pkg_descr = updatePackageDescription pbi pkg_descr0

                cleanHook hooks pkg_descr () hooks flags
                postClean hooks args flags pkg_descr ()
  where verbosity = fromFlag (cleanVerbosity flags)

copyAction :: UserHooks -> CopyFlags -> Args -> IO ()
copyAction hooks flags args
    = do let distPref  = fromFlag $ copyDistPref flags
             verbosity = fromFlag $ copyVerbosity flags
         hookedAction preCopy copyHook postCopy
                      (getBuildConfig hooks verbosity distPref)
                      hooks flags args

installAction :: UserHooks -> InstallFlags -> Args -> IO ()
installAction hooks flags args
    = do let distPref  = fromFlag $ installDistPref flags
             verbosity = fromFlag $ installVerbosity flags
         hookedAction preInst instHook postInst
                      (getBuildConfig hooks verbosity distPref)
                      hooks flags args

sdistAction :: UserHooks -> SDistFlags -> Args -> IO ()
sdistAction hooks flags args = do
                let distPref = fromFlag $ sDistDistPref flags
                pbi <- preSDist hooks args flags

                mlbi <- maybeGetPersistBuildConfig distPref
                pdfile <- defaultPackageDesc verbosity
                ppd <- readPackageDescription verbosity pdfile
                let pkg_descr0 = flattenPackageDescription ppd
                sanityCheckHookedBuildInfo pkg_descr0 pbi
                let pkg_descr = updatePackageDescription pbi pkg_descr0

                sDistHook hooks pkg_descr mlbi hooks flags
                postSDist hooks args flags pkg_descr mlbi
  where verbosity = fromFlag (sDistVerbosity flags)

testAction :: UserHooks -> TestFlags -> Args -> IO ()
testAction hooks flags args = do
    let distPref  = fromFlag $ testDistPref flags
        verbosity = fromFlag $ testVerbosity flags
    localBuildInfo <- getBuildConfig hooks verbosity distPref
    let pkg_descr = localPkgDescr localBuildInfo
    -- It is safe to do 'runTests' before the new test handler because the
    -- default action is a no-op and if the package uses the old test interface
    -- the new handler will find no tests.
    runTests hooks args False pkg_descr localBuildInfo
    hookedActionWithArgs preTest testHook postTest
            (getBuildConfig hooks verbosity distPref)
            hooks flags args

benchAction :: UserHooks -> BenchmarkFlags -> Args -> IO ()
benchAction hooks flags args = do
    let distPref  = fromFlag $ benchmarkDistPref flags
        verbosity = fromFlag $ benchmarkVerbosity flags
    hookedActionWithArgs preBench benchHook postBench
            (getBuildConfig hooks verbosity distPref)
            hooks flags args

registerAction :: UserHooks -> RegisterFlags -> Args -> IO ()
registerAction hooks flags args
    = do let distPref  = fromFlag $ regDistPref flags
             verbosity = fromFlag $ regVerbosity flags
         hookedAction preReg regHook postReg
                      (getBuildConfig hooks verbosity distPref)
                      hooks flags args

unregisterAction :: UserHooks -> RegisterFlags -> Args -> IO ()
unregisterAction hooks flags args
    = do let distPref  = fromFlag $ regDistPref flags
             verbosity = fromFlag $ regVerbosity flags
         hookedAction preUnreg unregHook postUnreg
                      (getBuildConfig hooks verbosity distPref)
                      hooks flags args

hookedAction :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
        -> (UserHooks -> PackageDescription -> LocalBuildInfo
                      -> UserHooks -> flags -> IO ())
        -> (UserHooks -> Args -> flags -> PackageDescription
                      -> LocalBuildInfo -> IO ())
        -> IO LocalBuildInfo
        -> UserHooks -> flags -> Args -> IO ()
hookedAction pre_hook cmd_hook =
    hookedActionWithArgs pre_hook (\h _ pd lbi uh flags -> cmd_hook h pd lbi uh flags)

hookedActionWithArgs :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
        -> (UserHooks -> Args -> PackageDescription -> LocalBuildInfo
                      -> UserHooks -> flags -> IO ())
        -> (UserHooks -> Args -> flags -> PackageDescription
                      -> LocalBuildInfo -> IO ())
        -> IO LocalBuildInfo
        -> UserHooks -> flags -> Args -> IO ()
hookedActionWithArgs pre_hook cmd_hook post_hook get_build_config hooks flags args = do
   pbi <- pre_hook hooks args flags
   localbuildinfo <- get_build_config
   let pkg_descr0 = localPkgDescr localbuildinfo
   --pkg_descr0 <- get_pkg_descr (get_verbose flags)
   sanityCheckHookedBuildInfo pkg_descr0 pbi
   let pkg_descr = updatePackageDescription pbi pkg_descr0
   -- TODO: should we write the modified package descr back to the
   -- localbuildinfo?
   cmd_hook hooks args pkg_descr localbuildinfo hooks flags
   post_hook hooks args flags pkg_descr localbuildinfo

sanityCheckHookedBuildInfo :: PackageDescription -> HookedBuildInfo -> IO ()
sanityCheckHookedBuildInfo PackageDescription { library = Nothing } (Just _,_)
    = die $ "The buildinfo contains info for a library, "
         ++ "but the package does not have a library."

sanityCheckHookedBuildInfo pkg_descr (_, hookExes)
    | not (null nonExistant)
    = die $ "The buildinfo contains info for an executable called '"
         ++ head nonExistant ++ "' but the package does not have a "
         ++ "executable with that name."
  where
    pkgExeNames  = nub (map exeName (executables pkg_descr))
    hookExeNames = nub (map fst hookExes)
    nonExistant  = hookExeNames \\ pkgExeNames

sanityCheckHookedBuildInfo _ _ = return ()

getBuildConfig :: UserHooks -> Verbosity -> FilePath -> IO LocalBuildInfo
getBuildConfig hooks verbosity distPref = do
  lbi_wo_programs <- getPersistBuildConfig distPref
  -- Restore info about unconfigured programs, since it is not serialized
  let lbi = lbi_wo_programs {
    withPrograms = restoreProgramConfiguration
                     (builtinPrograms ++ hookedPrograms hooks)
                     (withPrograms lbi_wo_programs)
  }

  case pkgDescrFile lbi of
    Nothing -> return lbi
    Just pkg_descr_file -> do
      outdated <- checkPersistBuildConfigOutdated distPref pkg_descr_file
      if outdated
        then reconfigure pkg_descr_file lbi
        else return lbi

  where
    reconfigure :: FilePath -> LocalBuildInfo -> IO LocalBuildInfo
    reconfigure pkg_descr_file lbi = do
      notice verbosity $ pkg_descr_file ++ " has been changed. "
                      ++ "Re-configuring with most recently used options. "
                      ++ "If this fails, please run configure manually.\n"
      let cFlags = configFlags lbi
      let cFlags' = cFlags {
            -- Since the list of unconfigured programs is not serialized,
            -- restore it to the same value as normally used at the beginning
            -- of a configure run:
            configPrograms = restoreProgramConfiguration
                               (builtinPrograms ++ hookedPrograms hooks)
                               (configPrograms cFlags),

            -- Use the current, not saved verbosity level:
            configVerbosity = Flag verbosity
          }
      configureAction hooks cFlags' (extraConfigArgs lbi)

-- --------------------------------------------------------------------------
-- Cleaning

clean :: PackageDescription -> CleanFlags -> IO ()
clean pkg_descr flags = do
    let distPref = fromFlag $ cleanDistPref flags
    notice verbosity "cleaning..."

    maybeConfig <- if fromFlag (cleanSaveConf flags)
                     then maybeGetPersistBuildConfig distPref
                     else return Nothing

    -- remove the whole dist/ directory rather than tracking exactly what files
    -- we created in there.
    chattyTry "removing dist/" $ do
      exists <- doesDirectoryExist distPref
      when exists (removeDirectoryRecursive distPref)

    -- Any extra files the user wants to remove
    mapM_ removeFileOrDirectory (extraTmpFiles pkg_descr)

    -- If the user wanted to save the config, write it back
    traverse_ (writePersistBuildConfig distPref) maybeConfig

  where
        removeFileOrDirectory :: FilePath -> IO ()
        removeFileOrDirectory fname = do
            isDir <- doesDirectoryExist fname
            isFile <- doesFileExist fname
            if isDir then removeDirectoryRecursive fname
              else when isFile $ removeFile fname
        verbosity = fromFlag (cleanVerbosity flags)

-- --------------------------------------------------------------------------
-- Default hooks

-- | Hooks that correspond to a plain instantiation of the
-- \"simple\" build system
simpleUserHooks :: UserHooks
simpleUserHooks =
    emptyUserHooks {
       confHook  = configure,
       postConf  = finalChecks,
       buildHook = defaultBuildHook,
       replHook  = defaultReplHook,
       copyHook  = \desc lbi _ f -> install desc lbi f, -- has correct 'copy' behavior with params
       testHook  = defaultTestHook,
       benchHook = defaultBenchHook,
       instHook  = defaultInstallHook,
       sDistHook = \p l h f -> sdist p l f srcPref (allSuffixHandlers h),
       cleanHook = \p _ _ f -> clean p f,
       hscolourHook = \p l h f -> hscolour p l (allSuffixHandlers h) f,
       haddockHook  = \p l h f -> haddock  p l (allSuffixHandlers h) f,
       regHook   = defaultRegHook,
       unregHook = \p l _ f -> unregister p l f
      }
  where
    finalChecks _args flags pkg_descr lbi =
      checkForeignDeps pkg_descr lbi (lessVerbose verbosity)
      where
        verbosity = fromFlag (configVerbosity flags)

-- | Basic autoconf 'UserHooks':
--
-- * 'postConf' runs @.\/configure@, if present.
--
-- * the pre-hooks 'preBuild', 'preClean', 'preCopy', 'preInst',
--   'preReg' and 'preUnreg' read additional build information from
--   /package/@.buildinfo@, if present.
--
-- Thus @configure@ can use local system information to generate
-- /package/@.buildinfo@ and possibly other files.

{-# DEPRECATED defaultUserHooks
     "Use simpleUserHooks or autoconfUserHooks, unless you need Cabal-1.2\n             compatibility in which case you must stick with defaultUserHooks" #-}
defaultUserHooks :: UserHooks
defaultUserHooks = autoconfUserHooks {
          confHook = \pkg flags -> do
                       let verbosity = fromFlag (configVerbosity flags)
                       warn verbosity
                         "defaultUserHooks in Setup script is deprecated."
                       confHook autoconfUserHooks pkg flags,
          postConf = oldCompatPostConf
    }
    -- This is the annoying old version that only runs configure if it exists.
    -- It's here for compatibility with existing Setup.hs scripts. See:
    -- https://github.com/haskell/cabal/issues/158
    where oldCompatPostConf args flags pkg_descr lbi
              = do let verbosity = fromFlag (configVerbosity flags)
                   noExtraFlags args
                   confExists <- doesFileExist "configure"
                   when confExists $
                       runConfigureScript verbosity
                         backwardsCompatHack flags lbi

                   pbi <- getHookedBuildInfo verbosity
                   sanityCheckHookedBuildInfo pkg_descr pbi
                   let pkg_descr' = updatePackageDescription pbi pkg_descr
                   postConf simpleUserHooks args flags pkg_descr' lbi

          backwardsCompatHack = True

autoconfUserHooks :: UserHooks
autoconfUserHooks
    = simpleUserHooks
      {
       postConf    = defaultPostConf,
       preBuild    = \_ flags ->
                       -- not using 'readHook' here because 'build' takes
                       -- extra args
                       getHookedBuildInfo $ fromFlag $ buildVerbosity flags,
       preClean    = readHook cleanVerbosity,
       preCopy     = readHook copyVerbosity,
       preInst     = readHook installVerbosity,
       preHscolour = readHook hscolourVerbosity,
       preHaddock  = readHook haddockVerbosity,
       preReg      = readHook regVerbosity,
       preUnreg    = readHook regVerbosity
      }
    where defaultPostConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO ()
          defaultPostConf args flags pkg_descr lbi
              = do let verbosity = fromFlag (configVerbosity flags)
                   noExtraFlags args
                   confExists <- doesFileExist "configure"
                   if confExists
                     then runConfigureScript verbosity
                            backwardsCompatHack flags lbi
                     else die "configure script not found."

                   pbi <- getHookedBuildInfo verbosity
                   sanityCheckHookedBuildInfo pkg_descr pbi
                   let pkg_descr' = updatePackageDescription pbi pkg_descr
                   postConf simpleUserHooks args flags pkg_descr' lbi

          backwardsCompatHack = False

          readHook :: (a -> Flag Verbosity) -> Args -> a -> IO HookedBuildInfo
          readHook get_verbosity a flags = do
              noExtraFlags a
              getHookedBuildInfo verbosity
            where
              verbosity = fromFlag (get_verbosity flags)

runConfigureScript :: Verbosity -> Bool -> ConfigFlags -> LocalBuildInfo
                   -> IO ()
runConfigureScript verbosity backwardsCompatHack flags lbi = do

  env <- getEnvironment
  let programConfig = withPrograms lbi
  (ccProg, ccFlags) <- configureCCompiler verbosity programConfig
  -- The C compiler's compilation and linker flags (e.g.
  -- "C compiler flags" and "Gcc Linker flags" from GHC) have already
  -- been merged into ccFlags, so we set both CFLAGS and LDFLAGS
  -- to ccFlags
  -- We don't try and tell configure which ld to use, as we don't have
  -- a way to pass its flags too
  let env' = appendToEnvironment ("CFLAGS",  unwords ccFlags)
             env
      args' = args ++ ["--with-gcc=" ++ ccProg]
  handleNoWindowsSH $
    rawSystemExitWithEnv verbosity "sh" args' env'

  where
    args = "./configure" : configureArgs backwardsCompatHack flags

    appendToEnvironment (key, val) [] = [(key, val)]
    appendToEnvironment (key, val) (kv@(k, v) : rest)
     | key == k  = (key, v ++ " " ++ val) : rest
     | otherwise = kv : appendToEnvironment (key, val) rest

    handleNoWindowsSH action
      | buildOS /= Windows
      = action

      | otherwise
      = action
          `catchIO` \ioe -> if isDoesNotExistError ioe
                              then die notFoundMsg
                              else throwIO ioe

    notFoundMsg = "The package has a './configure' script. This requires a "
               ++ "Unix compatibility toolchain such as MinGW+MSYS or Cygwin."

getHookedBuildInfo :: Verbosity -> IO HookedBuildInfo
getHookedBuildInfo verbosity = do
  maybe_infoFile <- defaultHookedPackageDesc
  case maybe_infoFile of
    Nothing       -> return emptyHookedBuildInfo
    Just infoFile -> do
      info verbosity $ "Reading parameters from " ++ infoFile
      readHookedBuildInfo verbosity infoFile

defaultTestHook :: Args -> PackageDescription -> LocalBuildInfo
                -> UserHooks -> TestFlags -> IO ()
defaultTestHook args pkg_descr localbuildinfo _ flags =
    test args pkg_descr localbuildinfo flags

defaultBenchHook :: Args -> PackageDescription -> LocalBuildInfo
                 -> UserHooks -> BenchmarkFlags -> IO ()
defaultBenchHook args pkg_descr localbuildinfo _ flags =
    bench args pkg_descr localbuildinfo flags

defaultInstallHook :: PackageDescription -> LocalBuildInfo
                   -> UserHooks -> InstallFlags -> IO ()
defaultInstallHook pkg_descr localbuildinfo _ flags = do
  let copyFlags = defaultCopyFlags {
                      copyDistPref   = installDistPref flags,
                      copyDest       = toFlag NoCopyDest,
                      copyVerbosity  = installVerbosity flags
                  }
  install pkg_descr localbuildinfo copyFlags
  let registerFlags = defaultRegisterFlags {
                          regDistPref  = installDistPref flags,
                          regInPlace   = installInPlace flags,
                          regPackageDB = installPackageDB flags,
                          regVerbosity = installVerbosity flags
                      }
  when (hasLibs pkg_descr) $ register pkg_descr localbuildinfo registerFlags

defaultBuildHook :: PackageDescription -> LocalBuildInfo
        -> UserHooks -> BuildFlags -> IO ()
defaultBuildHook pkg_descr localbuildinfo hooks flags =
  build pkg_descr localbuildinfo flags (allSuffixHandlers hooks)

defaultReplHook :: PackageDescription -> LocalBuildInfo
        -> UserHooks -> ReplFlags -> [String] -> IO ()
defaultReplHook pkg_descr localbuildinfo hooks flags args =
  repl pkg_descr localbuildinfo flags (allSuffixHandlers hooks) args

defaultRegHook :: PackageDescription -> LocalBuildInfo
        -> UserHooks -> RegisterFlags -> IO ()
defaultRegHook pkg_descr localbuildinfo _ flags =
    if hasLibs pkg_descr
    then register pkg_descr localbuildinfo flags
    else setupMessage verbosity
           "Package contains no library to register:" (packageId pkg_descr)
  where verbosity = fromFlag (regVerbosity flags)


text:
package com.ebay.pulsar.analytics.holap.query;

import java.util.List;

import com.ebay.pulsar.analytics.datasource.Table;
import com.ebay.pulsar.analytics.exception.SqlTranslationException;
import com.ebay.pulsar.analytics.metricstore.druid.filter.BaseFilter;
import com.ebay.pulsar.analytics.metricstore.druid.query.sql.DruidFilterTranslator;
import com.ebay.pulsar.analytics.query.sql.FilterHavingParser;
import com.foundationdb.sql.parser.ValueNode;

////////////////////////////////////////////////////////////
// The DruidFilterParser can be used as the following:
//
// DruidFilterParser parser = new DruidFilterParser();
// BaseFilter userFilter = parser.parseWhere(req.getFilter(), tableMeta);
////////////////////////////////////////////////////////////

public class DruidFilterParser extends FilterHavingParser{
	private DruidFilterTranslator filterTranslator = new DruidFilterTranslator();

	public BaseFilter parseWhere(String whereClause, Table tableMeta) throws SqlTranslationException {
		// Construct SQL Statement "SELECT * FROM TBL WHERE "
		StringBuilder strBuilder = new StringBuilder (SELECT_FROM_WHERE);
		strBuilder.append(whereClause);

		BaseFilter filter = null;
		QueryWhereHaving queryDesc = parse(strBuilder.toString(), tableMeta);
		List<ValueNode> vNodes = queryDesc.getWhereClauses();
		if (vNodes != null && !vNodes.isEmpty()) {
			// Should only have 1 node
			ValueNode vNode = vNodes.get(0);
			filter = filterTranslator.valueNodeToFilter(vNode, tableMeta);
		}
		return filter;
	}
}


text:
import gc
import easydict
import numpy as np
import tensorflow as tf

from luminoth.models.base.base_network import (
    BaseNetwork, _R_MEAN, _G_MEAN, _B_MEAN, VALID_ARCHITECTURES
)

class BaseNetworkTest(tf.test.TestCase):

    def setUp(self):
        self.config = easydict.EasyDict({
            'architecture': 'vgg_16',
        })
        tf.reset_default_graph()

    def testDefaultImageSize(self):
        m = BaseNetwork(easydict.EasyDict({'architecture': 'vgg_16'}))
        self.assertEqual(m.default_image_size, 224)

        m = BaseNetwork(easydict.EasyDict({'architecture': 'resnet_v1_50'}))
        self.assertEqual(m.default_image_size, 224)

    def testSubtractChannels(self):
        m = BaseNetwork(self.config)
        inputs = tf.placeholder(tf.float32, [1, 2, 2, 3])
        subtracted_inputs = m._subtract_channels(inputs)
        # White image
        r = 255. - _R_MEAN
        g = 255. - _G_MEAN
        b = 255. - _B_MEAN
        with self.test_session() as sess:
            res = sess.run(subtracted_inputs, feed_dict={
                inputs: np.ones([1, 2, 2, 3]) * 255
            })
            # Assert close and not equals because of floating point
            # differences between TF and numpy
            self.assertAllClose(
                res,
                # numpy broadcast multiplication
                np.ones([1, 2, 2, 3]) * [r, g, b]
            )

    def testAllArchitectures(self):
        for architecture in VALID_ARCHITECTURES:
            self.config.architecture = architecture
            m = BaseNetwork(self.config)
            inputs = tf.placeholder(tf.float32, [1, None, None, 3])
            # Should not fail.
            m(inputs)
            # Free up memory for Travis
            tf.reset_default_graph()
            gc.collect(generation=2)

    def testTrainableVariables(self):
        inputs = tf.placeholder(tf.float32, [1, 224, 224, 3])

        model = BaseNetwork(easydict.EasyDict({'architecture': 'vgg_16'}))
        model(inputs)
        # Variables in VGG16:
        #   0 conv1/conv1_1/weights:0
        #   1 conv1/conv1_1/biases:0
        #   (...)
        #   30 fc8/weights:0
        #   31 fc8/biases:0

        self.assertEqual(len(model.get_trainable_vars()), 32)

        model = BaseNetwork(
            easydict.EasyDict(
                {'architecture': 'vgg_16', 'fine_tune_from': 'conv5/conv5_3'}
            )
        )
        model(inputs)
        # Variables from `conv5/conv5_3` to the end:
        #   conv5/conv5_3/weights:0
        #   conv5/conv5_3/biases:0
        #   fc6/weights:0
        #   fc6/biases:0
        #   fc7/weights:0
        #   fc7/biases:0
        #   fc8/weights:0
        #   fc8/biases:0
        self.assertEqual(len(model.get_trainable_vars()), 8)

        #
        # Check invalid fine_tune_from raises proper exception
        #
        model = BaseNetwork(
            easydict.EasyDict(
                {'architecture': 'vgg_16', 'fine_tune_from': 'conv5/conv99'}
            )
        )
        model(inputs)
        with self.assertRaises(ValueError):
            model.get_trainable_vars()

if __name__ == '__main__':
    tf.test.main()


text:
package org.commonjava.indy.ftest.core.urls;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.commonjava.indy.model.core.dto.EndpointView;
import org.commonjava.indy.model.core.dto.EndpointViewListing;
import org.junit.Test;

public class CreateHostedStoreAndVerifyUrlInAllEndpointsTest
    extends AbstractCoreUrlsTest
{

    @Test
    public void verifyHostedStoreUrlsEndpoints()
        throws Exception
    {
        final EndpointViewListing endpoints = client.stats()
                                                    .getAllEndpoints();
        for ( final EndpointView endpoint : endpoints )
        {
            final String endpointUrl = client.content()
                                             .contentUrl( endpoint.getStoreKey() );

            assertThat( "Resource URI: '" + endpoint.getResourceUri() + "' for endpoint: " + endpoint.getKey()
                + " should be: '" + endpointUrl + "'", endpoint.getResourceUri(), equalTo( endpointUrl ) );
        }
    }

}


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

using Muscularity.Core.Programs;

using Xunit;

namespace Muscularity.Core.Tests.Programs
{
    public class PrescriptionParserTests
    {
        public PrescriptionParserTests()
        {
            Parser = new PrescriptionParser();
        }

        protected PrescriptionParser Parser { get; private set; }

        [Fact]
        public void ParseSets_ReturnsEmptySets_WhenParsingNull()
        {
            var sets = Parser.ParseSets(null);
            Assert.Empty(sets);
        }

        [Fact]
        public void ParseSets_ReturnsEmptySets_WhenParsingEmptyString()
        {
            var sets = Parser.ParseSets(string.Empty);
            Assert.Empty(sets);
        }

        [Fact]
        public void ParseSets_ReturnsEmptySets_WhenParsingWhiteSpace()
        {
            var sets = Parser.ParseSets("    ");
            Assert.Empty(sets);
        }

        [Fact]
        public void ParseSets_ParsesSets_WhenUsingSetsXRepsFormat()
        {
            var inputs = new[]
            {
                "3 x 5",
                "3 X 5",
                "3x5",
                "3X5"
            };

            foreach(var input in inputs)
            {
                var sets = Parser.ParseSets(input);
                Assert.Equal(3, sets.Count);

                foreach(var set in sets)
                {
                    Assert.True(set.FromReps.HasValue);
                    Assert.Equal(5, set.FromReps.Value);
                    Assert.False(set.ToReps.HasValue);
                    Assert.False(set.Intensity.HasValue);
                    Assert.False(set.ToFailure.HasValue);
                }
            }
        }

        [Fact]
        public void ParseSets_ParsesSets_WhenUsingSetsXRepRangeFormat()
        {
            var inputs = new[]
            {
                "3 x 5-7",
                "3 X 5 - 7",
                "3x5-7",
                "3X5 - 7"
            };

            foreach(var input in inputs)
            {
                var sets = Parser.ParseSets(input);
                Assert.Equal(3, sets.Count);

                foreach(var set in sets)
                {
                    Assert.True(set.FromReps.HasValue);
                    Assert.Equal(5, set.FromReps.Value);
                    Assert.True(set.ToReps.HasValue);
                    Assert.Equal(7, set.ToReps.Value);
                    Assert.False(set.Intensity.HasValue);
                    Assert.False(set.ToFailure.HasValue);
                }
            }
        }

        [Fact]
        public void ParseSets_ParsesSets_WhenUsingSetsXRepsAtIntensityFormat()
        {
            var inputs = new[]
            {
                "3 x 5 @ 75%",
                "3 X 5@75%",
                "3x5@75%",
                "3X5 @ 75%"
            };

            foreach(var input in inputs)
            {
                var sets = Parser.ParseSets(input);
                Assert.Equal(3, sets.Count);

                foreach(var set in sets)
                {
                    Assert.True(set.FromReps.HasValue);
                    Assert.Equal(5, set.FromReps.Value);
                    Assert.False(set.ToReps.HasValue);
                    Assert.True(set.Intensity.HasValue);
                    Assert.Equal(.75m, set.Intensity.Value);
                    Assert.False(set.ToFailure.HasValue);
                }
            }
        }

        [Fact]
        public void ParseSets_ParsesSets_WhenUsingSetsXCommaSeparatedRepsFormat()
        {
            var inputs = new[]
            {
                "3 x 5,4,3",
                "3 X 5, 4, 3",
                "3x5,4,3",
                "3X5, 4, 3"
            };

            foreach(var input in inputs)
            {
                var sets = Parser.ParseSets(input);
                Assert.Equal(3, sets.Count);

                var reps = new[] { 5, 4, 3 };

                for(var i = 0; i < reps.Length; i++)
                {
                    var set = sets[i];

                    Assert.True(set.FromReps.HasValue);
                    Assert.Equal(reps[i], set.FromReps.Value);
                    Assert.False(set.ToReps.HasValue);
                    Assert.False(set.Intensity.HasValue);
                    Assert.False(set.ToFailure.HasValue);
                }
            }
        }

        [Fact]
        public void ParseSets_ParsesSets_WhenUsingSetsXCommaSeparatedRepsWithIntensityFormat()
        {
            var inputs = new[]
            {
                "3 x 5@75%,4@80%,3@85%",
                "3 X 5 @ 75%, 4 @ 80%, 3 @ 85%",
                "3x5@75%,4@80%,3@85%",
                "3X5@75%, 4@80%, 3@85%"
            };

            foreach(var input in inputs)
            {
                var sets = Parser.ParseSets(input);
                Assert.Equal(3, sets.Count);

                var reps = new[] { 5, 4, 3 };
                var intensities = new[] { .75m, .8m, .85m };

                for(var i = 0; i < reps.Length; i++)
                {
                    var set = sets[i];

                    Assert.True(set.FromReps.HasValue);
                    Assert.Equal(reps[i], set.FromReps.Value);
                    Assert.False(set.ToReps.HasValue);
                    Assert.True(set.Intensity.HasValue);
                    Assert.Equal(intensities[i], set.Intensity.Value);
                    Assert.False(set.ToFailure.HasValue);
                }
            }
        }
    }
}