text:
function explore3d(varargin)
%EXPLORE3D   Explore your 3-D image interactively.
%   EXPLORE3D(ax) activates the 3-D explorer for the axes specified
%   by the handle "ax".  Once activated you can use the keyboard to
%   fly through your image in a manner similar to a flight simulator.
%
%   Once activated, the arrow keys will allow you to look up, down,
%   left, and right.  In addition, the following keys produce the
%   following actions:
%
%   f  - zoom forward
%   b  - zoom backward
%   r  - rotate right
%   l  - rotate left
%   a  - decrease your zooming step (for the "f" and "b" keys)
%   s  - increase your zooming step (for the "f" and "b" keys)
%   z  - decrease your angular step (for the arrow, "r", and "l" keys)
%   x  - increase your angular step (for the arrow, "r", and "l" keys)
%  ESC - closes EXPLORE3D and restores original figure properties
%
%  % EXAMPLE 1:
%  surf(peaks)
%  explore3d(gca)
%  Now you can fly!
%
% % EXAMPLE 2:
% % Run this code and then try to find the sphere
% figure('color',[0 0 0])
% [x,y,z]=sphere;
% xspot=round(5*(rand-0.5));
% yspot=round(5*(rand-0.5));
% surf(x+xspot-0.5,y+yspot+0.5,z./3)
% hold on
% xwall=[-1 -1 1 1];
% ywall=[0 0 0 0];
% zwall=[-1 1 1 -1];
% patch([-10 -10 10 10],[-10 10 10 -10],[2 2 2 2]+eps,'b')
% patch([-10 -10 10 10],[-10 10 10 -10],[-2 -2 -2 -2]-eps,'r')
% for j=1:25,
%     xspot=round(20*(rand-0.5));
%     yspot=round(20*(rand-0.5));
%     if round(rand),
%         patch(xwall+xspot,ywall+yspot,zwall,rand(1,3))
%     else
%         patch(ywall+xspot,xwall+yspot,zwall,rand(1,3))
%     end
% end
% view(3),axis([-15 15 -15 15 -5 5],'off')
% explore3d(gca)
% % Now see if you can find the sphere!
%

%  By Mickey Stahl  2-26-02
%  Engineering Development Group
%  Aspiring Developer

if strcmp(class(varargin{1}),'double')
    initialize(varargin{1})
else
    feval(varargin{:})
end

function initialize(ax)
drawnow
handles.ax=ax;
handles.fig=get(ax,'parent');
handles.axesProperties=get(ax);
handles.figureProperties=get(handles.fig);
set(ax,...
    'ALimMode','manual',...
    'CameraTargetMode','manual',...
    'camerapositionmode','manual',...
    'CameraViewAngleMode','manual',...
    'cameraupvectormode','manual',...
    'projection','perspective')
handles.dist=sqrt(sum((ctarg(ax)-cpos(ax)).^2));
handles.step=80;
handles.radianTurn=80;
set(handles.fig,'doublebuffer','on',...
    'keypressfcn','explore3d(''keypressfcn'',guidata(gcbo))')
path=ctarg(ax)-cpos(ax);
set(ax,'cameratarget',cpos(ax)+path./sqrt(sum(path.^2)));
guidata(handles.fig,handles)

function keypressfcn(handles)
ax=handles.ax;
c=abs(lower(get(handles.fig,'currentcharacter')));
persistent keydown;
if isempty(keydown)
    keydown=1;
end
%try
    if ~isempty(c) & keydown
        keydown=0;
        switch c
        case 102
            zoomcamera(handles,1)
        case 98
            zoomcamera(handles,-1)
        case 30
            movetarget(handles,1,1)
        case 31
            movetarget(handles,-1,1)
        case 28
            movetarget(handles,-1,0)
        case 29
            movetarget(handles,1,0)
        case 115
            if handles.step>1,
                handles.step=handles.step-1;
            end
        case 97
            handles.step=handles.step+1;
        case 122
            handles.radianTurn=handles.radianTurn+1;
        case 120
            if handles.radianTurn>1,
                handles.radianTurn=handles.radianTurn-1;
            end
        case 114
            rotatecamera(handles,1)
        case 108
            rotatecamera(handles,-1)
        case 27
            escape(handles)
        end
        if c==120 | c==122 | c==97 | c==115,
            guidata(handles.fig,handles)
            pause(0.05)
        end
        keydown=1;
    end
    %catch
   % keydown=1;
   %end

function rotatecamera(handles,right)
cp=cpos(handles.ax);
ct=ctarg(handles.ax)-cp;
cuv=cupvec(handles.ax);
right=right/handles.radianTurn;
rightline=cross(ct,cuv);
cuv=(cuv+right.*rightline);
cuv=cuv./sqrt(sum(cuv.^2));
set(handles.ax,...
    'cameraupvector',cuv);

function movetarget(handles,direction,updown)
cp=cpos(handles.ax);
ct=ctarg(handles.ax)-cp;
cuv=cupvec(handles.ax);
direction=direction/handles.radianTurn;
if updown
    cuv=cuv-direction.*ct;
    ct=ct+direction.*cuv;
    cuv=cuv./sqrt(sum(cuv.^2));
    ct=ct./sqrt(sum(ct.^2));
else
    rightline=cross(ct,cuv);
    ct=(ct+direction.*rightline);
    ct=ct./sqrt(sum(ct.^2));
end
set(handles.ax,...
    'cameratarget',cp+ct,...
    'cameraupvector',cuv);

function zoomcamera(handles,in)
ax=handles.ax;
path=ctarg(ax)-cpos(ax);
path=in*handles.dist.*path./(sqrt(sum(path.^2))*handles.step);
newcp = cpos(ax) + path;
newtarg=ctarg(ax)+ path;
set(ax,'cameraposition',newcp,...
    'cameratarget',newtarg)

function out = cpos(ax)
out = get(ax,'CameraPosition');
function out = ctarg(ax)
out = get(ax,'CameraTarget');
function out = cupvec(ax)
out = get(ax,'CameraUpVector');

function escape(handles)
h=[handles.fig handles.ax];
props(1).struct=handles.figureProperties;
props(2).struct=handles.axesProperties;
for j=1:2,
    names=fieldnames(props(j).struct);
    for k=1:length(names)
        try
            set(h(j),names{k},getfield(props(j).struct,names{k}))
        catch
        end
    end
end


text:
<?php
/**
 * TOP API: taobao.taohua.directory.get request
 *
 * @author auto create
 * @since 1.0, 2011-09-29 15:36:21
 */
class TaohuaDirectoryGetRequest
{
	/**
	 * 文档商品ID
	 **/
	private $itemId;

	private $apiParas = array();

	public function setItemId($itemId)
	{
		$this->itemId = $itemId;
		$this->apiParas["item_id"] = $itemId;
	}

	public function getItemId()
	{
		return $this->itemId;
	}

	public function getApiMethodName()
	{
		return "taobao.taohua.directory.get";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->itemId,"itemId");
	}
}

redpajama_set_name: RedPajamaGithub


text:
import test from 'blue-tape'
import copy from 'fast-copy'

import { entryMock, assetMock, entryWithResourceLinksMock } from '../mocks'
import { wrapEntry, wrapEntryCollection } from '../../../lib/entities/entry'

test('Entry is wrapped', (t) => {
  const wrappedEntry = wrapEntry(entryMock)
  t.looseEqual(wrappedEntry.toPlainObject(), entryMock)
  t.end()
})

test('Entry with field named metadata is wrapped', (t) => {
  const mock = Object.assign(entryMock, {
    fields: {
      field1: 'str',
      metadata: 'metadataFieldContent'
    }
  })
  const wrappedEntry = wrapEntry(mock)
  t.looseEqual(wrappedEntry.toPlainObject(), mock)
  t.end()
})

test('Localized entry is wrapped', (t) => {
  const entry = copy(entryMock)
  const field = entry.fields.field1
  entry.fields = {
    en: {
      field1: field
    }
  }
  const wrappedEntry = wrapEntry(entry)
  t.looseEqual(wrappedEntry.toPlainObject(), entry)
  t.end()
})

test('Entry collection is wrapped', (t) => {
  const entryCollection = {
    total: 1,
    skip: 0,
    limit: 100,
    items: [
      entryMock
    ]
  }
  const wrappedEntry = wrapEntryCollection(entryCollection, true)
  t.looseEqual(wrappedEntry.toPlainObject(), entryCollection)
  t.end()
})

test('Entry collection links are resolved', (t) => {
  const entryCollection = {
    total: 1,
    skip: 0,
    limit: 100,
    items: [
      copy(entryMock),
      copy(entryMock)
    ],
    includes: {
      Entry: [copy(entryMock)],
      Asset: [copy(assetMock)]
    }
  }
  // setup first entry
  entryCollection.items[0].sys.id = 'entry1'
  entryCollection.items[0].fields.linked1 = {
    sys: {
      id: 'asset1',
      type: 'Link',
      linkType: 'Asset'
    }
  }
  entryCollection.items[0].fields.linked2 = {
    sys: {
      id: 'entry3',
      type: 'Link',
      linkType: 'Entry'
    }
  }
  // setup first linked entry
  entryCollection.includes.Asset[0].sys.id = 'asset1'
  // setup second linked entry
  entryCollection.items[1].sys.id = 'entry3'
  entryCollection.items[1].fields.linked1 = {
    sys: {
      id: 'entry4',
      type: 'Link',
      linkType: 'Entry'
    }
  }
  entryCollection.includes.Entry[0].sys.id = 'entry4'
  entryCollection.includes.Entry[0].fields.linked1 = {
    sys: {
      id: 'entry3',
      type: 'Link',
      linkType: 'Entry'
    }
  }

  const wrappedCollection = wrapEntryCollection(entryCollection, { resolveLinks: true })
  const wrappedEntry = wrappedCollection.toPlainObject()

  // first linked entry resolved from includes
  t.equals(wrappedEntry.items[0].fields.linked1.sys.type, 'Asset', 'first linked entity is resolved')
  t.ok(wrappedEntry.items[0].fields.linked1.fields, 'first linked entity has fields')
  // second linked entry resolved from items list
  t.equals(wrappedEntry.items[0].fields.linked2.sys.type, 'Entry', 'second linked entity is resolved')
  t.ok(wrappedEntry.items[0].fields.linked2.fields, 'second linked entity has fields')
  t.equals(wrappedEntry.items[1].fields.linked1.sys.type, 'Entry', 'third linked entity is resolved')
  t.ok(wrappedEntry.items[1].fields.linked1.fields, 'third linked entity has fields')
  t.ok(wrappedCollection.stringifySafe(), 'stringifies safely')
  t.end()
})

test('Entry with resource links is wrapped', (t) => {
  const wrappedEntry = wrapEntry(entryWithResourceLinksMock)
  t.looseEqual(wrappedEntry.toPlainObject(), entryWithResourceLinksMock)
  t.end()
})

test('Entry collection with resource links is wrapped', (t) => {
  const entryCollection = {
    total: 1,
    skip: 0,
    limit: 100,
    items: [
      entryWithResourceLinksMock,
      entryWithResourceLinksMock
    ]
  }
  const wrappedEntry = wrapEntryCollection(entryCollection, true)
  t.looseEqual(wrappedEntry.toPlainObject(), entryCollection)
  t.end()
})


text:
package stscreds

import (
	"fmt"
	"io/ioutil"
	"strconv"
	"time"

	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/awserr"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/client"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/credentials"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/service/sts"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/service/sts/stsiface"
)

const (
	// ErrCodeWebIdentity will be used as an error code when constructing
	// a new error to be returned during session creation or retrieval.
	ErrCodeWebIdentity = "WebIdentityErr"

	// WebIdentityProviderName is the web identity provider name
	WebIdentityProviderName = "WebIdentityCredentials"
)

// now is used to return a time.Time object representing
// the current time. This can be used to easily test and
// compare test values.
var now = time.Now

// TokenFetcher should return WebIdentity token bytes or an error
type TokenFetcher interface {
	FetchToken(credentials.Context) ([]byte, error)
}

// FetchTokenPath is a path to a WebIdentity token file
type FetchTokenPath string

// FetchToken returns a token by reading from the filesystem
func (f FetchTokenPath) FetchToken(ctx credentials.Context) ([]byte, error) {
	data, err := ioutil.ReadFile(string(f))
	if err != nil {
		errMsg := fmt.Sprintf("unable to read file at %s", f)
		return nil, awserr.New(ErrCodeWebIdentity, errMsg, err)
	}
	return data, nil
}

// WebIdentityRoleProvider is used to retrieve credentials using
// an OIDC token.
type WebIdentityRoleProvider struct {
	credentials.Expiry

	// The policy ARNs to use with the web identity assumed role.
	PolicyArns []*sts.PolicyDescriptorType

	// Duration the STS credentials will be valid for. Truncated to seconds.
	// If unset, the assumed role will use AssumeRoleWithWebIdentity's default
	// expiry duration. See
	// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#STS.AssumeRoleWithWebIdentity
	// for more information.
	Duration time.Duration

	// The amount of time the credentials will be refreshed before they expire.
	// This is useful refresh credentials before they expire to reduce risk of
	// using credentials as they expire. If unset, will default to no expiry
	// window.
	ExpiryWindow time.Duration

	client stsiface.STSAPI

	tokenFetcher    TokenFetcher
	roleARN         string
	roleSessionName string
}

// NewWebIdentityCredentials will return a new set of credentials with a given
// configuration, role arn, and token file path.
//
// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible
// functional options, and wrap with credentials.NewCredentials helper.
func NewWebIdentityCredentials(c client.ConfigProvider, roleARN, roleSessionName, path string) *credentials.Credentials {
	svc := sts.New(c)
	p := NewWebIdentityRoleProvider(svc, roleARN, roleSessionName, path)
	return credentials.NewCredentials(p)
}

// NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the
// provided stsiface.STSAPI
//
// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible
// functional options.
func NewWebIdentityRoleProvider(svc stsiface.STSAPI, roleARN, roleSessionName, path string) *WebIdentityRoleProvider {
	return NewWebIdentityRoleProviderWithOptions(svc, roleARN, roleSessionName, FetchTokenPath(path))
}

// NewWebIdentityRoleProviderWithToken will return a new WebIdentityRoleProvider with the
// provided stsiface.STSAPI and a TokenFetcher
//
// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible
// functional options.
func NewWebIdentityRoleProviderWithToken(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher) *WebIdentityRoleProvider {
	return NewWebIdentityRoleProviderWithOptions(svc, roleARN, roleSessionName, tokenFetcher)
}

// NewWebIdentityRoleProviderWithOptions will return an initialize
// WebIdentityRoleProvider with the provided stsiface.STSAPI, role ARN, and a
// TokenFetcher. Additional options can be provided as functional options.
//
// TokenFetcher is the implementation that will retrieve the JWT token from to
// assume the role with. Use the provided FetchTokenPath implementation to
// retrieve the JWT token using a file system path.
func NewWebIdentityRoleProviderWithOptions(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher, optFns ...func(*WebIdentityRoleProvider)) *WebIdentityRoleProvider {
	p := WebIdentityRoleProvider{
		client:          svc,
		tokenFetcher:    tokenFetcher,
		roleARN:         roleARN,
		roleSessionName: roleSessionName,
	}

	for _, fn := range optFns {
		fn(&p)
	}

	return &p
}

// Retrieve will attempt to assume a role from a token which is located at
// 'WebIdentityTokenFilePath' specified destination and if that is empty an
// error will be returned.
func (p *WebIdentityRoleProvider) Retrieve() (credentials.Value, error) {
	return p.RetrieveWithContext(aws.BackgroundContext())
}

// RetrieveWithContext will attempt to assume a role from a token which is
// located at 'WebIdentityTokenFilePath' specified destination and if that is
// empty an error will be returned.
func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) {
	b, err := p.tokenFetcher.FetchToken(ctx)
	if err != nil {
		return credentials.Value{}, awserr.New(ErrCodeWebIdentity, "failed fetching WebIdentity token: ", err)
	}

	sessionName := p.roleSessionName
	if len(sessionName) == 0 {
		// session name is used to uniquely identify a session. This simply
		// uses unix time in nanoseconds to uniquely identify sessions.
		sessionName = strconv.FormatInt(now().UnixNano(), 10)
	}

	var duration *int64
	if p.Duration != 0 {
		duration = aws.Int64(int64(p.Duration / time.Second))
	}

	req, resp := p.client.AssumeRoleWithWebIdentityRequest(&sts.AssumeRoleWithWebIdentityInput{
		PolicyArns:       p.PolicyArns,
		RoleArn:          &p.roleARN,
		RoleSessionName:  &sessionName,
		WebIdentityToken: aws.String(string(b)),
		DurationSeconds:  duration,
	})

	req.SetContext(ctx)

	// InvalidIdentityToken error is a temporary error that can occur
	// when assuming an Role with a JWT web identity token.
	req.RetryErrorCodes = append(req.RetryErrorCodes, sts.ErrCodeInvalidIdentityTokenException)
	if err := req.Send(); err != nil {
		return credentials.Value{}, awserr.New(ErrCodeWebIdentity, "failed to retrieve credentials", err)
	}

	p.SetExpiration(aws.TimeValue(resp.Credentials.Expiration), p.ExpiryWindow)

	value := credentials.Value{
		AccessKeyID:     aws.StringValue(resp.Credentials.AccessKeyId),
		SecretAccessKey: aws.StringValue(resp.Credentials.SecretAccessKey),
		SessionToken:    aws.StringValue(resp.Credentials.SessionToken),
		ProviderName:    WebIdentityProviderName,
	}
	return value, nil
}


text:
import unittest
import inspect
import imath

import IECore

import Gaffer
import GafferImage
import GafferImageTest

class FormatPlugTest( GafferImageTest.ImageTestCase ) :

	def testConstructor( self ) :

		p = GafferImage.FormatPlug()
		self.assertEqual( p.getName(), "FormatPlug" )
		self.assertEqual( p.direction(), Gaffer.Plug.Direction.In )
		self.assertEqual( p.defaultValue(), GafferImage.Format() )
		self.assertEqual( p.getValue(), GafferImage.Format() )
		self.assertEqual( p.getFlags(), Gaffer.Plug.Flags.Default )

		p = GafferImage.FormatPlug(
			"p",
			Gaffer.Plug.Direction.Out,
			GafferImage.Format( 100, 200, 2 ),
			Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic
		)
		self.assertEqual( p.getName(), "p" )
		self.assertEqual( p.direction(), Gaffer.Plug.Direction.Out )
		self.assertEqual( p.defaultValue(), GafferImage.Format( 100, 200, 2 ) )
		self.assertEqual( p.getValue(), GafferImage.Format( 100, 200, 2 ) )
		self.assertEqual( p.getFlags(), Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )

	def testChildren( self ) :

		p = GafferImage.FormatPlug()
		self.assertEqual( p.keys(), [ "displayWindow", "pixelAspect" ] )
		self.assertTrue( isinstance( p["displayWindow"], Gaffer.Box2iPlug ) )
		self.assertTrue( isinstance( p["pixelAspect"], Gaffer.FloatPlug ) )

		self.assertRaises( RuntimeError, p.addChild, Gaffer.IntPlug() )

	def testValue( self ) :

		p = GafferImage.FormatPlug()
		v = GafferImage.Format( imath.Box2i( imath.V2i( 11, 12 ), imath.V2i( 100, 200 ) ), 2 )

		p.setValue( v )
		self.assertEqual( p.getValue(), v )
		self.assertEqual( p["displayWindow"].getValue(), v.getDisplayWindow() )
		self.assertEqual( p["pixelAspect"].getValue(), v.getPixelAspect() )

	def testDefaultFormatFromContext( self ) :

		constant = GafferImage.Constant()

		with Gaffer.Context() as context :

			# Even if we haven't specified a default context, we should still
			# be given something.
			self.assertFalse(
				GafferImage.BufferAlgo.empty(
					constant["out"]["format"].getValue().getDisplayWindow()
				)
			)

			# And if we specify something specific, we should get it.
			f = GafferImage.Format( 100, 200, 2 )
			GafferImage.FormatPlug.setDefaultFormat( context, f )
			self.assertEqual( GafferImage.FormatPlug.getDefaultFormat( context ), f )
			self.assertEqual( constant["out"]["format"].getValue(), f )

			f = GafferImage.Format( 200, 400, 1 )
			GafferImage.FormatPlug.setDefaultFormat( context, f )
			self.assertEqual( GafferImage.FormatPlug.getDefaultFormat( context ), f )
			self.assertEqual( constant["out"]["format"].getValue(), f )

	def testAcquireDefaultFormatPlug( self ) :

		s1 = Gaffer.ScriptNode()
		s2 = Gaffer.ScriptNode()

		p1A = GafferImage.FormatPlug.acquireDefaultFormatPlug( s1 )
		p1B = GafferImage.FormatPlug.acquireDefaultFormatPlug( s1 )

		p2A = GafferImage.FormatPlug.acquireDefaultFormatPlug( s2 )
		p2B = GafferImage.FormatPlug.acquireDefaultFormatPlug( s2 )

		self.assertTrue( p1A.isSame( p1B ) )
		self.assertTrue( p2A.isSame( p2B ) )
		self.assertFalse( p1A.isSame( p2A ) )

	def testDefaultFormatFromScript( self ) :

		s = Gaffer.ScriptNode()
		self.assertFalse( "defaultFormat" in s )

		s["c"] = GafferImage.Constant()
		self.assertFalse( "defaultFormat" in s )

		defaultFormatPlug = GafferImage.FormatPlug.acquireDefaultFormatPlug( s )
		self.assertTrue( defaultFormatPlug.isSame( s["defaultFormat"] ) )

		with s.context() :

			self.assertFalse(
				GafferImage.BufferAlgo.empty(
					s["c"]["out"]["format"].getValue().getDisplayWindow()
				)
			)

			f = GafferImage.Format( 100, 200, 2 )
			defaultFormatPlug.setValue( f )
			self.assertEqual( s["c"]["out"]["format"].getValue(), f )

			f = GafferImage.Format( 200, 400, 1 )
			defaultFormatPlug.setValue( f )
			self.assertEqual( s["c"]["out"]["format"].getValue(), f )

	def testDefaultFormatAfterScriptLoad( self ) :

		s = Gaffer.ScriptNode()
		s["c"] = GafferImage.Constant()

		f = GafferImage.Format( 100, 100 )
		GafferImage.FormatPlug.acquireDefaultFormatPlug( s ).setValue( f )
		with s.context() :
			self.assertEqual( s["c"]["out"]["format"].getValue(), f )

		s2 = Gaffer.ScriptNode( "s2" )
		s2.execute( s.serialise() )
		with s2.context() :
			self.assertEqual( s2["c"]["out"]["format"].getValue(), f )

	def testExpressions( self ) :

		s = Gaffer.ScriptNode()
		s["n1"] = Gaffer.Node()
		s["n2"] = Gaffer.Node()
		s["n1"]["user"]["f"] = GafferImage.FormatPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
		s["n2"]["user"]["f"] = GafferImage.FormatPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )

		s["e"] = Gaffer.Expression()
		s["e"].setExpression( inspect.cleandoc(
			"""
			f = parent["n1"]["user"]["f"]
			b = f.getDisplayWindow()
			b.setMin( b.min() - imath.V2i( 10 ) )
			b.setMax( b.max() + imath.V2i( 20 ) )
			f.setPixelAspect( 0.5 )
			f.setDisplayWindow( b )
			parent["n2"]["user"]["f"] = f
			"""
		) )

		s["n1"]["user"]["f"].setValue( GafferImage.Format( imath.Box2i( imath.V2i( 20, 30 ), imath.V2i( 100, 110 ) ), 1 ) )

		self.assertEqual( s["n2"]["user"]["f"].getValue(), GafferImage.Format( imath.Box2i( imath.V2i( 10, 20 ), imath.V2i( 120, 130 ) ), 0.5 ) )

	def testDefaultExpression( self ) :

		s = Gaffer.ScriptNode()
		s["n"] = Gaffer.Node()
		s["n"]["f"] = GafferImage.FormatPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )

		f = GafferImage.Format( 100, 200, 1 )
		s["n"]["f"].setValue( f )

		s["e"] = Gaffer.Expression()
		s["e"].setExpression( s["e"].defaultExpression( s["n"]["f"], "python" ) )

		self.assertTrue( s["n"]["f"].getInput().node().isSame( s["e"] ) )
		self.assertEqual( s["n"]["f"].getValue(), f )

	def testDefaultFormatHashRepeatability( self ) :

		allHashes = set()
		for i in range( 0, 1000 ) :
			c = Gaffer.Context()
			GafferImage.FormatPlug.setDefaultFormat( c, GafferImage.Format( 1920, 1080 ) )
			allHashes.add( str( c.hash() ) )

		self.assertEqual( len( allHashes ), 1 )

	def testSerialiseWithPartialExpressionConnection( self ) :

		s = Gaffer.ScriptNode()

		s["r"] = GafferImage.ImageReader()
		s["r"]["fileName"].setValue( "thisFileDoesNotExist" )

		s["n"] = Gaffer.Node()
		s["n"]["user"]["f"] = GafferImage.FormatPlug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
		s["n"]["user"]["f"]["displayWindow"].setValue( imath.Box2i( imath.V2i( 10, 11 ), imath.V2i( 20, 21 ) ) )

		# This expression will throw because the ImageReader is referencing
		# an invalid file.
		s["e"] = Gaffer.Expression()
		s["e"].setExpression( """parent["n"]["user"]["f"]["pixelAspect"] = parent["r"]["out"]["format"].getPixelAspectRatio()""" )

		# Despite that, we should still be able to serialise the script
		# without triggering expression evaluation. This is particularly
		# useful when dispatching a script where the ImageReader is
		# set up to read an image which won't exist until one of the tasks
		# has been executed.

		s2 = Gaffer.ScriptNode()
		s2.execute( s.serialise() )
		self.assertEqual( s2["n"]["user"]["f"]["displayWindow"].getValue(), s["n"]["user"]["f"]["displayWindow"].getValue() )

	def testDefaultValue( self ) :

		f1 = GafferImage.Format( 2000, 1000, 2.0 )
		f2 = GafferImage.Format( 64, 128, 1.0 )

		p = GafferImage.FormatPlug( defaultValue = f1 )
		self.assertEqual( p.getValue(), f1 )
		self.assertEqual( p.defaultValue(), f1 )
		self.assertTrue( p.isSetToDefault() )

		p.setValue( f2 )
		self.assertEqual( p.getValue(), f2 )
		self.assertEqual( p.defaultValue(), f1 )
		self.assertFalse( p.isSetToDefault() )

		p.resetDefault()
		self.assertEqual( p.getValue(), f2 )
		self.assertEqual( p.defaultValue(), f2 )
		self.assertTrue( p.isSetToDefault() )

if __name__ == "__main__":
	unittest.main()


text:
package edu.jhuapl.dorset.routing.tree;

import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;

/**
 * Node for a tree router.
 * <p>
 * Parent nodes return child nodes based on a request.
 * Leaf nodes return an array of agents to be returned by TreeRouter.
 */
public interface Node {

    /**
     * Get the child node that matches the request
     *
     * @param request  Request object
     * @return routing node
     */
    public Node selectChild(Request request);

    /**
     * Get children of this node
     *
     * @return Node array
     */
    public Node[] getChildren();

    /**
     * Is this node a leaf?
     *
     * @return boolean
     */
    public boolean isLeaf();

    /**
     * Get the agents for this leaf node
     *
     * @return Agent array
     */
    public Agent[] getValue();
}


text:
/*
 * Created by SharpDevelop.
 * User: thief
 * Date: 2010/06/11
 * Time: 10:52 PM
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Data;
using System.Data.Common;

namespace FeihtWorx.Data
{
	/// <summary>
	/// Description of Transaction.
	/// </summary>
	public class Transaction
	{
		internal DbTransaction ActualTransaction{ get; private set; }

		public Transaction(DbTransaction transaction)
		{
			if (transaction == null) {
				throw new ArgumentNullException("transaction");
			}
			ActualTransaction = transaction;
		}

		public void Rollback()
		{
			ActualTransaction.Rollback();
		}

		public void Commit()
		{
			ActualTransaction.Commit();
		}

	}
}


text:
package mesosphere.marathon
package integration

import java.util.UUID

import mesosphere.AkkaIntegrationTest
import mesosphere.marathon.integration.facades.MarathonFacade.extractDeploymentIds
import mesosphere.marathon.integration.setup.EmbeddedMarathonTest
import mesosphere.marathon.raml.{App, AppCheck, CommandCheck, ShellCommand}
import mesosphere.marathon.state.AbsolutePathId

class MesosCheckIntegrationTest extends AkkaIntegrationTest with EmbeddedMarathonTest {

  def appId(suffix: Option[String] = None): AbsolutePathId = testBasePath / s"app-${suffix.getOrElse(UUID.randomUUID)}"
  val appCommand: String = s"sleep 100"

  "AppDeploy with mesos checks" should {
    "provide a command check result status of 0" in {
      Given("a new app with checks")
      val id = appId(Some("with-successful-checks"))
      val app = App(id.toString, cmd = Some(appCommand), check = Some(ramlCommandCheck("true")))

      When("The app deploys")
      val result = marathon.createAppV2(app)

      Then("The app is created with a successful exit code")
      result should be(Created)
      extractDeploymentIds(result) should have size 1
      waitForDeployment(result)
      eventually {
        val currentTasks = marathon.tasks(id).value
        currentTasks should have size (1)
        currentTasks.head.check.get.command.get.exitCode should be(0)
      }
      marathon.deleteApp(id)
    }

    "provide a command check result status of 1" in {
      Given("a new app")
      val id = appId(Some("with-failing-checks"))
      val app = App(id.toString, cmd = Some(appCommand), check = Some(ramlCommandCheck("false")))

      When("the app is created")
      val result = marathon.createAppV2(app)

      Then("the app deploys successfully")
      result should be(Created)
      extractDeploymentIds(result) should have size 1
      waitForDeployment(result)
      And("the failing check status is exposed in /v2/tasks")
      eventually {
        val currentTasks = marathon.tasks(id).value
        currentTasks should have size (1)
        currentTasks.head.check.get.command.get.exitCode should be(1)
      }
      marathon.deleteApp(id)
    }
  }

  private def ramlCommandCheck(command: String) =
    AppCheck(
      exec = Some(CommandCheck(ShellCommand(command))),
      intervalSeconds = 1,
      delaySeconds = 1
    )
}


text:
@extends('store.master')

@section('main')

	@include('store.categories.category-panel-heading')

		@include('store.products.list')

@endsection


text:
import time
import subprocess
import Adafruit_DHT
from fluent import sender
from fluent import event

# consts
DHT22_GPIO = 4
LPS331_ADRS = "0x5d"
FL_TAG = "weather" # fluentd event tag
SEND_INTERVAL = 10 # sec

def cmd_exec(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if stderr != None and len(stderr.strip()) > 0:
        raise IOError("Error on executing cmd: " + stderr)
    return stdout.strip()

def i2cget(reg):
    return cmd_exec("i2cget -y 1 " + LPS331_ADRS + " " + reg)

def init_lps():

    # WHO_AM_I
    stdout = cmd_exec("i2cget -y 1 " + LPS331_ADRS + " 0x0f")
    if stdout != "0xbb":
        raise IOError("WHO_AM_I result mismatch.")

    # activate device
    cmd_exec("i2cset -y 1 " + LPS331_ADRS + " 0x20 0x90")

def read_lps():

    # reading from LPS
    out0 = i2cget("0x28")
    out1 = i2cget("0x29")
    out2 = i2cget("0x2a")

    # decoding the value
    return (int(out0, 16) + (int(out1, 16) * 0x100) + (int(out2, 16) * 0x10000)) / 4096.0

def send_metrics():

    # read atmospheric pressure from LPS
    atmos = read_lps()

    # read humidity and temp from DHT
    humidity, temp = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, DHT22_GPIO)

    # write metrics to local fluentd
    event.Event("metrics", {
        "atmos": atmos,
        "hum": humidity,
        "temp": temp
    })

# init LPS
init_lps()

# init fluentd
sender.setup(FL_TAG)

# measure and send the metrics periodically
last_checked = 0
while True:
    if time.time() - last_checked > SEND_INTERVAL:
        last_checked = time.time()
        send_metrics()
    time.sleep(0.5)


text:
#ifndef CCB_COMPRESSION_ZLIB_HH
#define CCB_COMPRESSION_ZLIB_HH

#include <vector>
#include "com/centreon/broker/namespace.hh"

CCB_BEGIN()

namespace compression {
/**
 *  @class zlib zlib.hh "com/centreon/broker/compression/zlib.hh"
 *  @brief Binding around the zlib library.
 *
 *  Compress and uncompress data.
 */
class zlib {
 public:
  static std::vector<char> compress(std::vector<char> const& data,
                                    int compression_level);
  static std::vector<char> uncompress(unsigned char const* data,
                                      unsigned long nbytes);
};
}  // namespace compression

CCB_END()

#endif  // !CCB_COMPRESSION_ZLIB_HH


text:
import Head from 'next/head'
import React from 'react'

const favicon = require('@assets/images/favicon.png')
const appleTouchIcon = require('@assets/images/touch-icon.png')
const DEFAULT = {
  desc: `Blockstack is a decentralized computing network and app ecosystem that puts users in control of their identity and data.`
}

const Meta = ({
  title,
  description = DEFAULT.desc,
  ogTitle = title,
  ...rest
}) => {
  const ogImageUrl = `https://meta.blockstack.sh/${encodeURI(
    ogTitle
  )}.png?theme=dark&md=1&fontSize=115px`
  return (
    <Head>
      <meta name="description" content={description} />
      <link rel="shorticon icon" href={favicon.src} type="image/x-icon" />
      <link rel="icon" href={favicon.src} type="image/x-icon" />
      <link rel="apple-touch-icon-precomposed" href={appleTouchIcon.src} />
      <meta property="og:image" content={ogImageUrl} />
      <meta name="twitter:image" content={ogImageUrl} />
      <meta property="og:site_name" content="Blockstack.org" />
      <meta property="og:title" content={title} />
      <meta property="og:description" content={description} />

      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:site" content="@blockstack" />
      <meta name="twitter:title" content={title} />
      <meta name="twitter:description" content={description} />
    </Head>
  )
}

export { Meta }


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

using System.Management.Automation;
using Microsoft.Azure.Commands.DataMigration.Common;
using Microsoft.Azure.Commands.DataMigration.Models;
using Microsoft.Azure.Management.DataMigration.Models;

namespace Microsoft.Azure.Commands.DataMigration.Cmdlets
{
    [Cmdlet("Stop", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DataMigrationService", DefaultParameterSetName = ComponentNameParameterSet, SupportsShouldProcess = true), OutputType(typeof(bool))]
    [Alias("Stop-" + ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DmsService")]
    public class StopDataMigrationService : DataMigrationCmdlet
    {
        [Parameter(
            Position = 0,
            Mandatory = true,
            ParameterSetName = ComponentObjectParameterSet,
            ValueFromPipeline = true,
            HelpMessage = "PSDataMigrationService Object.")]
        [ValidateNotNull]
        [Alias("DataMigrationService")]
        public PSDataMigrationService InputObject { get; set; }

        [Parameter(
            Position = 0,
            Mandatory = true,
            ParameterSetName = ResourceIdParameterSet,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "DataMigrationService Resource Id.")]
        [ValidateNotNullOrEmpty]
        public string ResourceId { get; set; }

        [Parameter(
            Mandatory = true,
            ParameterSetName = ComponentNameParameterSet,
            HelpMessage = "The name of the resource group."
                )]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(
            Mandatory = true,
            ParameterSetName = ComponentNameParameterSet,
            HelpMessage = "Database Migration Service Name.")]
        [ValidateNotNullOrEmpty]
        [Alias("ServiceName")]
        public string Name { get; set; }

        [Parameter(HelpMessage = "Returns an true/false. By default, this cmdlet does not generate any output.")]
        public SwitchParameter PassThru { get; set; }

        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.Name, Resources.stopService))
            {
                if (this.ParameterSetName.Equals(ComponentObjectParameterSet))
                {
                    this.ResourceGroupName = InputObject.ResourceGroupName;
                    this.Name = InputObject.Name;
                }

                if (this.ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    DmsResourceIdentifier ids = new DmsResourceIdentifier(this.ResourceId);
                    this.ResourceGroupName = ids.ResourceGroupName;
                    this.Name = ids.ServiceName;
                }

                bool result = false;
                try
                {
                    DataMigrationClient.Services.StopWithHttpMessagesAsync(ResourceGroupName, Name).GetAwaiter().GetResult();
                    result = true;
                }
                catch (ApiErrorException ex)
                {
                    ThrowAppropriateException(ex);
                }

                if (PassThru.IsPresent)
                {
                    WriteObject(result);
                }
            }
        }
    }
}


text:
declare module 'knockout' {
	interface ComponentInfo {
		readonly element: Node;
		readonly templateNodes: ReadonlyArray<Node>;
	}
}


text:
<?php

use Behat\Gherkin\Node\TableNode;
use Behat\Mink\Exception\ElementNotFoundException;
use \Behat\Mink\Mink;
use \Behat\Mink\Session;
use \Behat\Mink\Driver\Selenium2Driver;
use \Behat\MinkExtension\Context\MinkContext;

class FeatureContext extends MinkContext {

  private static $driver = null;
  protected $browserstackUsername;
  protected $browserstackPassword;
  protected $capabilities;

  public function __construct($params) {
    // If Browserstack info exists in the profile, create a Mink Selenium
    // session pointing to a Browserstack Selenium URL.
    if (isset($params['capabilities'])) {
      $this->setBrowserstackParams($params);
      $host = "http://{$this->browserstackUsername}:{$this->browserstackPassword}@hub.browserstack.com/wd/hub";

      // Reuse the Selenium driver across scenarios.
      if (self::$driver === null) {
        self::$driver = new Selenium2Driver('', $this->capabilities, $host);
      }

      $mink = new Mink(array(
        'selenium2' => new Session(self::$driver),
      ));

      $mink->setDefaultSessionName('selenium2');
      $this->setMink($mink);
      $this->setMinkParameters($params);
    }
    // If no Browserstack info exists in the profile, assume we are using the
    // regular Goutte and Selenium Mink drivers, and let them set themselves
    // up based on the configuration in behat.yml.
  }

  /**
   * Helper function to set up Browserstack credentials and browser/OS info.
   *
   * @param $params
   * @throws Exception
   */
  protected function setBrowserstackParams($params) {
    if (!isset($params['username'])) {
      throw new \Exception("Please specify your Browserstack username as a parameter to the feature context in behat.yml");
    }
    if (!isset($params['password'])) {
      throw new \Exception("Please specify your Browserstack password as a parameter to the feature context in behat.yml");
    }

    $this->browserstackUsername = $params['username'];
    $this->browserstackPassword = $params['password'];
    $this->capabilities = isset($params['capabilities']) ? $params['capabilities'] : null;
  }

  /**
   * @AfterScenario
   *
   * Deletes cookies in the Selenium-controlled browser after each scenario.
   */
  public function after($event) {
    // This try/catch/swallow is useful when sharing this feature context
    // with setups that don't include a shared Browserstack driver.
    try {
      if (isset(self::$driver)) {
        //self::$driver->reset();
      }
    }
    catch (\Exception $e) {

    }
  }

}


text:
from .namespaces_operations import NamespacesOperations
from .event_hubs_operations import EventHubsOperations
from .consumer_groups_operations import ConsumerGroupsOperations

__all__ = [
    'NamespacesOperations',
    'EventHubsOperations',
    'ConsumerGroupsOperations',
]


text:
import { observable, action } from 'mobx';
import ApiService from '../services/ApiService';
import User from './models/User';

/**
 * Store for the Users.
 */
class UserStore {
	apiService;
	@observable users = [];

	constructor(apiService = ApiService) {
		this.apiService = apiService;
	}

	getUserByEmail = (email) => this.users.filter(user => user.email === email).pop();

    /**
     * Loading new user from comment data.
     * TODO: use API to get users when API support CRUD for users.
     */
	@action
	loadUser = (userData) => {
		let user = new User(this);
		user.updateFromJson(userData);
		this.users.push(user);
		return user;
	}

    /**
     * Resolving user from comment data.
     * TODO: use user ID when API start to support CRUD for users.
     */
	resolveUserFromComment(commentJson) {
		let user = this.getUserByEmail(commentJson.email);
		if (user !== undefined) {
			return user;
		} else {
			return this.loadUser(commentJson);
		}
	}
}

export default UserStore;


text:
\hypertarget{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl}{}\section{testing\+:\+:gmock\+\_\+matchers\+\_\+test\+:\+:Divisible\+By\+Impl Class Reference}
\label{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl}\index{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_aab5d8d383a8cbf112fe087c4f0f3f699}{Divisible\+By\+Impl} (int a\+\_\+divider)
\item
{\footnotesize template$<$typename T $>$ }\\bool \hyperlink{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a7f2368362416d0e527f6ac0790003d69}{Match\+And\+Explain} (const \hyperlink{functions__7_8js_adf1f3edb9115acb0a1e04209b7a9937b}{T} \&n, \hyperlink{classtesting_1_1_match_result_listener}{Match\+Result\+Listener} $\ast$listener) const
\item
void \hyperlink{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a6dd6430816067c5f787eb2e722c59181}{Describe\+To} (ostream $\ast$os) const
\item
void \hyperlink{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a92e618b858b39fa72b1e4a3766956884}{Describe\+Negation\+To} (ostream $\ast$os) const
\item
void \hyperlink{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a86c8787ab835bc84a9ad7e3931d644cc}{set\+\_\+divider} (int a\+\_\+divider)
\item
int \hyperlink{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_ac1ecf78ff1aacb98ced9eb90185e2f75}{divider} () const
\end{DoxyCompactItemize}

\subsection{Detailed Description}

Definition at line 3963 of file gmock-\/matchers\+\_\+test.\+cc.

\subsection{Constructor \& Destructor Documentation}
\index{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}!Divisible\+By\+Impl@{Divisible\+By\+Impl}}
\index{Divisible\+By\+Impl@{Divisible\+By\+Impl}!testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}}
\subsubsection[{\texorpdfstring{Divisible\+By\+Impl(int a\+\_\+divider)}{DivisibleByImpl(int a_divider)}}]{\setlength{\rightskip}{0pt plus 5cm}testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl\+::\+Divisible\+By\+Impl (
\begin{DoxyParamCaption}
\item[{int}]{a\+\_\+divider}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [explicit]}}\hypertarget{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_aab5d8d383a8cbf112fe087c4f0f3f699}{}\label{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_aab5d8d383a8cbf112fe087c4f0f3f699}

Definition at line 3965 of file gmock-\/matchers\+\_\+test.\+cc.

\subsection{Member Function Documentation}
\index{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}!Describe\+Negation\+To@{Describe\+Negation\+To}}
\index{Describe\+Negation\+To@{Describe\+Negation\+To}!testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}}
\subsubsection[{\texorpdfstring{Describe\+Negation\+To(ostream $\ast$os) const }{DescribeNegationTo(ostream *os) const }}]{\setlength{\rightskip}{0pt plus 5cm}void testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl\+::\+Describe\+Negation\+To (
\begin{DoxyParamCaption}
\item[{ostream $\ast$}]{os}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [inline]}}\hypertarget{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a92e618b858b39fa72b1e4a3766956884}{}\label{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a92e618b858b39fa72b1e4a3766956884}

Definition at line 3979 of file gmock-\/matchers\+\_\+test.\+cc.

\index{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}!Describe\+To@{Describe\+To}}
\index{Describe\+To@{Describe\+To}!testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}}
\subsubsection[{\texorpdfstring{Describe\+To(ostream $\ast$os) const }{DescribeTo(ostream *os) const }}]{\setlength{\rightskip}{0pt plus 5cm}void testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl\+::\+Describe\+To (
\begin{DoxyParamCaption}
\item[{ostream $\ast$}]{os}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [inline]}}\hypertarget{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a6dd6430816067c5f787eb2e722c59181}{}\label{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a6dd6430816067c5f787eb2e722c59181}

Definition at line 3975 of file gmock-\/matchers\+\_\+test.\+cc.

\index{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}!divider@{divider}}
\index{divider@{divider}!testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}}
\subsubsection[{\texorpdfstring{divider() const }{divider() const }}]{\setlength{\rightskip}{0pt plus 5cm}int testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl\+::divider (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [inline]}}\hypertarget{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_ac1ecf78ff1aacb98ced9eb90185e2f75}{}\label{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_ac1ecf78ff1aacb98ced9eb90185e2f75}

Definition at line 3984 of file gmock-\/matchers\+\_\+test.\+cc.

\index{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}!Match\+And\+Explain@{Match\+And\+Explain}}
\index{Match\+And\+Explain@{Match\+And\+Explain}!testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}}
\subsubsection[{\texorpdfstring{Match\+And\+Explain(const T \&n, Match\+Result\+Listener $\ast$listener) const }{MatchAndExplain(const T &n, MatchResultListener *listener) const }}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename T $>$ bool testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl\+::\+Match\+And\+Explain (
\begin{DoxyParamCaption}
\item[{const {\bf T} \&}]{n, }
\item[{{\bf Match\+Result\+Listener} $\ast$}]{listener}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [inline]}}\hypertarget{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a7f2368362416d0e527f6ac0790003d69}{}\label{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a7f2368362416d0e527f6ac0790003d69}

Definition at line 3969 of file gmock-\/matchers\+\_\+test.\+cc.

\index{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}!set\+\_\+divider@{set\+\_\+divider}}
\index{set\+\_\+divider@{set\+\_\+divider}!testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl@{testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl}}
\subsubsection[{\texorpdfstring{set\+\_\+divider(int a\+\_\+divider)}{set_divider(int a_divider)}}]{\setlength{\rightskip}{0pt plus 5cm}void testing\+::gmock\+\_\+matchers\+\_\+test\+::\+Divisible\+By\+Impl\+::set\+\_\+divider (
\begin{DoxyParamCaption}
\item[{int}]{a\+\_\+divider}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\hypertarget{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a86c8787ab835bc84a9ad7e3931d644cc}{}\label{classtesting_1_1gmock__matchers__test_1_1_divisible_by_impl_a86c8787ab835bc84a9ad7e3931d644cc}

Definition at line 3983 of file gmock-\/matchers\+\_\+test.\+cc.

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/vendor/googletest/googlemock/test/\hyperlink{gmock-matchers__test_8cc}{gmock-\/matchers\+\_\+test.\+cc}\end{DoxyCompactItemize}


text:
package com.dianping.cat.analyzer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;

public class EventAggregator {

	private static ConcurrentHashMap<String, EventData> s_events = new ConcurrentHashMap<String, EventData>();

	private static String buildKey(String type, String name) {
		return type + ',' + name;
	}

	private static EventData createEventData(String type, String name) {
		return new EventData(type, name);
	}

	public static Map<String, EventData> getAndResetEvents() {
		Map<String, EventData> cloned = s_events;

		synchronized (EventAggregator.class) {
			s_events = new ConcurrentHashMap<String, EventData>();

			for (Map.Entry<String, EventData> entry : cloned.entrySet()) {
				String key = entry.getKey();
				EventData data = entry.getValue();

				if (s_events.size() < 2000 && data.getCount() > 0) {
					s_events.put(key, createEventData(data.getType(), data.getName()));
				}
			}
		}
		return cloned;
	}

	public static void logEvent(Event e) {
		makeSureEventExist(e).add(e);
	}

	private static EventData makeSureEventExist(Event event) {
		String key = buildKey(event.getType(), event.getName());
		EventData item = s_events.get(key);

		if (null == item) {
			synchronized (EventAggregator.class) {
				item = s_events.get(key);
				if (null == item) {
					item = createEventData(event.getType(), event.getName());

					s_events.put(key, item);
				}
			}
		}
		return item;
	}

	public static void sendEventData() {
		Map<String, EventData> events = getAndResetEvents();

		if (events.size() > 0) {
			Transaction t = Cat.newTransaction("_CatMergeTree", "_CatMergeTree");
			Cat.getManager().getThreadLocalMessageTree().setDiscard(false);

			for (EventData data : events.values()) {
				if (data.getCount() > 0) {
					Event tmp = Cat.newEvent(data.getType(), data.getName());
					StringBuilder sb = new StringBuilder(32);

					sb.append(CatConstants.BATCH_FLAG).append(data.getCount()).append(CatConstants.SPLIT)
					      .append(data.getError());
					tmp.addData(sb.toString());
					tmp.setStatus(Message.SUCCESS);
					tmp.complete();
				}
			}

			t.setStatus(Message.SUCCESS);
			t.complete();
		}
	}

	public static class EventData {
		private String m_key;

		private String m_type;

		private String m_name;

		private AtomicInteger m_count = new AtomicInteger();

		private AtomicInteger m_error = new AtomicInteger();

		public EventData(String type, String name) {
			m_type = type;
			m_name = name;
			m_key = buildKey(type, name);
		}

		public EventData add(Event e) {
			m_count.incrementAndGet();

			if (!e.isSuccess()) {
				m_error.incrementAndGet();
			}
			return this;
		}

		public int getCount() {
			return m_count.get();
		}

		public int getError() {
			return m_error.get();
		}

		public String getKey() {
			return m_key;
		}

		public String getName() {
			return m_name;
		}

		public String getType() {
			return m_type;
		}
	}

}


text:
layout: page
title: "Susan Walsh Hopewell"
comments: true
description: "blanks"
keywords: "Susan Walsh Hopewell,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: School of Education

**Classes taught**: EDUC 2625, EDUC 4321, EDUC 4351, EDUC 5455, EDUC 8610

#### EDUC 2625: Teaching English as a Second Language

**Terms taught**: Spring 2016

**Instructor rating**: 5.77

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.66

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.36

**Standard deviation in workload** (raw): 0.0

#### EDUC 4321: Integrated Reading and Writing for Elementary Schools

**Terms taught**: Fall 2011

**Instructor rating**: 5.68

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.9

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.97

**Standard deviation in workload** (raw): 0.0

#### EDUC 4351: Differentiating Instruction in Diverse Elementary Classrooms

**Terms taught**: Fall 2012, Fall 2014

**Instructor rating**: 4.9

**Standard deviation in instructor rating**: 0.38

**Average grade** (4.0 scale): 3.7

**Standard deviation in grades** (4.0 scale): 0.16

**Average workload** (raw): 3.13

**Standard deviation in workload** (raw): 0.07

#### EDUC 5455: Literacy for Linguistically Different Learners

**Terms taught**: Spring 2011, Spring 2011, Spring 2012, Spring 2014, Spring 2015

**Instructor rating**: 5.72

**Standard deviation in instructor rating**: 0.18

**Average grade** (4.0 scale): 3.79

**Standard deviation in grades** (4.0 scale): 0.08

**Average workload** (raw): 2.75

**Standard deviation in workload** (raw): 0.41

#### EDUC 8610: Advanced Topics in Educational Equity and Cultural Diversity

**Terms taught**: Fall 2016

**Instructor rating**: 5.17

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.65

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 3.45

**Standard deviation in workload** (raw): 0.0


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.mauriciotogneri.camerapreview.CameraPreview
        android:id="@+id/camerapreview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000"/>

</LinearLayout>


text:
require 'spec_helper'
require 'chef/knife/cookbook-missing-deps'

describe KnifeCookbookUtils::CookbookMissingDeps do

  let(:command) do
    KnifeCookbookUtils::CookbookMissingDeps.new.
      tap(&with_cookbook_listing).
      tap(&with_dependency_check)
  end

  let(:with_cookbook_listing) { with_stub.(:raw_cookbook_listing, raw_cookbook_listing) }
  let(:with_dependency_check) { ->(x) { x.stub(:dependencies_for_cookbook_version, &dependencies_for_cookbook_version)} }
  let(:with_stub)             { ->(stub_name, returns) { ->(x) { x.stub!(stub_name).and_return(returns) } } }

  let(:dependencies_for_cookbook_version) { ->(name, version) { {} } }

  let(:raw_cookbook_listing) do
    {
      "nginx"=>{
        "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/rbenv",
        "versions"=>[
          {"version"=>"1.7.0", "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/nginx/1.7.0"},
          {"version"=>"1.6.0", "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/nginx/1.6.0"},
          {"version"=>"1.4.0", "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/nginx/1.4.0"},
       ]},
      "rbenv"=>{
        "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/rbenv",
        "versions"=>[
          {"version"=>"1.4.1", "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/rbenv/1.4.1"},
          {"version"=>"1.4.0", "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/rbenv/1.4.0"},
       ]},
      "postgresql"=>{
        "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/postgresql",
        "versions"=>[{"version"=>"3.0.0", "url"=>"https://api.opscode.com/organizations/example-org/cookbooks/postgresql/3.0.0"}]},
    }
  end

  describe "#all_cookbooks" do
    subject { command.all_cookbooks }
    let(:expected) do
      {
        "nginx" => {
          "1.7.0" => "https://api.opscode.com/organizations/example-org/cookbooks/nginx/1.7.0",
          "1.6.0" => "https://api.opscode.com/organizations/example-org/cookbooks/nginx/1.6.0",
          "1.4.0" => "https://api.opscode.com/organizations/example-org/cookbooks/nginx/1.4.0", },
        "rbenv" => {
          "1.4.1" => "https://api.opscode.com/organizations/example-org/cookbooks/rbenv/1.4.1",
          "1.4.0" => "https://api.opscode.com/organizations/example-org/cookbooks/rbenv/1.4.0" },
        "postgresql" => {
          "3.0.0" => "https://api.opscode.com/organizations/example-org/cookbooks/postgresql/3.0.0" }
      }
    end

    it "should return a map of all cookbook and versions" do
      should eql expected
    end
  end

  describe "#missing_deps" do
    subject { command.missing_deps }

    context "without missing deps" do
      it { should eql Hash.new }
    end

    context "with missing deps" do
      let(:dependencies_for_cookbook_version) do
        proc do |name, version|
          if name == 'rbenv' and version == '1.4.1'
            { 'ohai' => '>= 1.1' }
          else
            { }
          end
        end
      end

      let(:expected) { { ['rbenv', '1.4.1'] => [['ohai', '>= 1.1']] } }

      it "should return a map of missing deps" do
        should eql expected
      end

    end
  end
end


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_IEEE_FUNCTIONS_NEGATE_HPP_INCLUDED
#define BOOST_SIMD_IEEE_FUNCTIONS_NEGATE_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>

namespace boost { namespace simd { namespace tag
  {
   /*!
     @brief negate generic tag

     Represents the negate function in generic contexts.

     @par Models:
        Hierarchy
   **/
    struct negate_ : ext::elementwise_<negate_>
    {
      /// @brief Parent hierarchy
      typedef ext::elementwise_<negate_> parent;
    };
  }
  /*!
    Retuns the first element negated is the the scond is less than 0

    @par Semantic:

    @code
    T r = negate(a0,a1);
    @endcode

    is similar to:

    @code
    T r =  a0*sign(a1);
    @endcode

    @param a0

    @param a1

    @return a value of same type as the inputs
  **/
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::negate_, negate, 2)
} }

#endif


text:
@interface OneViewController ()

@property (weak, nonatomic) IBOutlet UIButton *redButton;
@property (weak, nonatomic) IBOutlet UIButton *greenButton;
@property (weak, nonatomic) IBOutlet UIButton *blueButton;

@property (weak, nonatomic) IBOutlet UILabel *label;

@property (nonatomic, assign) CGFloat fontSize;

@end

@implementation OneViewController

- (IBAction)redButtonClick:(id)sender {
    [[ZZSkinManager sharedManager] startSkin:ZZSkinTypeRed];
}

- (IBAction)greenButtonClick:(id)sender {
    [[ZZSkinManager sharedManager] startSkin:ZZSkinTypeGreen];
}

- (IBAction)blueButtonClick:(id)sender {
    [[ZZSkinManager sharedManager] startSkin:ZZSkinTypeBlue];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setup];
}

- (void)setup {
    self.view.zz_skinConfig(^(UIView *item) {
        // item.backgroundColor = [ZZSkinManager colorWithIdentifier:@"ident1"];
    }).zz_skinConfig(^(UIView *item) {
        // item.backgroundColor = [ZZSkinManager colorWithIdentifier:@"ident2"];
    });

    self.redButton.layer.borderWidth = self.greenButton.layer.borderWidth = self.blueButton.layer.borderWidth = 2;
    block_id_t config = ^(UIButton *button) {
        UIColor *color = [ZZSkinManager colorWithIdentifier:@"ident1"];
        button.layer.borderColor = [color CGColor];
        [button setTitleColor:color forState:UIControlStateNormal];
    };
    self.redButton.zz_skinConfig(config);
    self.greenButton.zz_skinConfig(config);
    self.blueButton.zz_skinConfig(config);

    self.fontSize = 50.0;

    self.label.zz_skinConfig(^(UILabel *label) {
        label.textColor = [ZZSkinManager colorWithIdentifier:@"ident1"];
    }).zz_skinConfig(^(UILabel *label) {
        label.text = [ZZSkinManager stringWithIdentifier:@"ident1"];

        label.font = [UIFont systemFontOfSize:self.fontSize];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    self.fontSize = self.fontSize == 32.0 ? 50.0 : 32.0;

    [self.label zz_refresh];
}

@end


text:
function ListWindowsFeatures
{

param(
        [string]$feature,
        [string]$provider="dism"
         )

    $cachepath =  "${env:temp}/ListWindowsFeatures-${provider}.xml"
    $maxAge = 2

    $cache =  Get-Item $cachepath -erroraction SilentlyContinue

    if($cache -ne $null -and ((get-date) - $cache.LastWriteTime).minutes -lt $maxage){
        $features = Import-Clixml $cachepath |  Select *| Where-Object {(($_.name -like $feature) -or ($_.displayName -like $feature)) -and (($_.installed -eq $true) -or ($_.state -eq "Enabled"))}
        return $features
    }
    else{

        switch($provider)
        {
            "dism" { return features_dism | Select * | Where-Object {($_.name -eq $feature) -and ($_.state -eq "Enabled")}  }
            "powershell" { return features_powershell | Select * | Where-Object {(($_.name -like $feature) -or ($_.displayName -like $feature)) -and ($_.installed -eq $true)} }
            default {throw "Unsupported provider"}
        }

    }
}

function features_dism{
      try
        {
            $out = DISM /Online /Get-Features /Format:List | Where-Object {$_}

            if($LASTEXITCODE -ne 0)
            {
                Write-Error $out
                Break
            }

            $f = $out[4..($out.length-2)]
            $features = for($i=0; $i -lt $f.length;$i+=2)
            {
                $tmp = $f[$i],$f[$i+1] -replace '^([^:]+:\s)'

                New-Object PSObject -Property @{
                    Name = $tmp[0]
                    State = $tmp[1]
                }
            }

            $features | Export-Clixml $cachepath

            return $features
        }
        catch
        {
            Throw
        }
}

function features_powershell{
    $ProgressPreference = "SilentlyContinue"
     import-module servermanager
     $features = Get-WindowsFeature
     $features | Export-Clixml $cachepath
     return Get-WindowsFeature
}


text:
@interface WYLTravelViewController : UIViewController

@end


text:
"""Spam test case."""
__author__ = ('Lance Finn Helsten',)
__version__ = '0.7.4'
__copyright__ = """Copyright (C) 2014 Lance Helsten"""
__docformat__ = "reStructuredText en"

import sys
import os
import unittest

class Eggs_Test(unittest.TestCase):
    def test_succeed(self):
        self.assertTrue(True)

    def test_failure(self):
        self.assertFalse(False)


text:
package com.deputy.shiftlog.di.module;

import android.content.Context;

import com.deputy.shiftlog.app.ShiftLogApp;
import com.deputy.shiftlog.data.executor.ThreadExecutor;
import com.deputy.shiftlog.data.repository.ShiftLocalDataRepository;
import com.deputy.shiftlog.data.repository.ShiftRemoteDataRepository;
import com.deputy.shiftlog.data.repository.database.DatabaseManager;
import com.deputy.shiftlog.data.repository.database.ShiftLocalDataStore;
import com.deputy.shiftlog.data.repository.network.NetworkManager;
import com.deputy.shiftlog.data.repository.network.ShiftRemoteDataStore;
import com.deputy.shiftlog.domain.executor.PostExecutionThread;
import com.deputy.shiftlog.domain.executor.UiThread;
import com.deputy.shiftlog.domain.repository.ShiftLocalRepository;
import com.deputy.shiftlog.domain.repository.ShiftRemoteRepository;

import java.util.concurrent.Executor;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

/**
 * ShiftLog
 * Created by Iurii Rodyk on 01.09.2017.
 */

@Module
public class ApplicationModule {
    private final ShiftLogApp application;
    private DatabaseManager databaseManager;
    private NetworkManager networkManager;

    public ApplicationModule(ShiftLogApp application) {
        this.application = application;
    }

    @Provides @Singleton
    Context provideApplicationContext() {
        return this.application;
    }

    @Provides @Singleton
    PostExecutionThread providePostExecutionThread(UiThread uiThread) {
        return uiThread;
    }

    @Provides @Singleton
    Executor provideExecutor(ThreadExecutor threadExecutor) {
        return threadExecutor;
    }

    @Provides @Singleton
    ShiftLocalRepository provideShiftLocalRepository(ShiftLocalDataRepository shiftLocalDataRepository) {
        return shiftLocalDataRepository;
    }

    @Provides @Singleton
    ShiftRemoteRepository provideShiftRemoteRepository(ShiftRemoteDataRepository shiftRemoteDataRepository) {
        return shiftRemoteDataRepository;
    }

    @Provides @Singleton
    ShiftLocalDataStore provideShiftLocalDataStore(DatabaseManager databaseManager) {
        if(this.databaseManager == null)
            this.databaseManager = databaseManager;
        return this.databaseManager;
    }

    @Provides @Singleton
    ShiftRemoteDataStore provideShiftRemoteDataStore(NetworkManager networkManager) {
        if(this.networkManager == null)
            this.networkManager = networkManager;
        return this.networkManager;
    }
}


text:
package org.apache.flink.table.utils.python;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.io.InputFormat;
import org.apache.flink.api.java.io.CollectionInputFormat;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableDescriptor;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.dataview.ListView;
import org.apache.flink.table.api.dataview.MapView;
import org.apache.flink.table.data.DecimalData;
import org.apache.flink.table.data.GenericArrayData;
import org.apache.flink.table.data.GenericMapData;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
import org.apache.flink.table.runtime.typeutils.InternalSerializers;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.ArrayType;
import org.apache.flink.table.types.logical.BigIntType;
import org.apache.flink.table.types.logical.BinaryType;
import org.apache.flink.table.types.logical.BooleanType;
import org.apache.flink.table.types.logical.CharType;
import org.apache.flink.table.types.logical.DateType;
import org.apache.flink.table.types.logical.DayTimeIntervalType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.DoubleType;
import org.apache.flink.table.types.logical.FloatType;
import org.apache.flink.table.types.logical.IntType;
import org.apache.flink.table.types.logical.LocalZonedTimestampType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.MapType;
import org.apache.flink.table.types.logical.MultisetType;
import org.apache.flink.table.types.logical.NullType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.logical.SmallIntType;
import org.apache.flink.table.types.logical.StructuredType;
import org.apache.flink.table.types.logical.TimeType;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.table.types.logical.TinyIntType;
import org.apache.flink.table.types.logical.VarBinaryType;
import org.apache.flink.table.types.logical.VarCharType;
import org.apache.flink.table.types.logical.YearMonthIntervalType;
import org.apache.flink.table.types.logical.ZonedTimestampType;
import org.apache.flink.types.RowKind;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TimeZone;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

/** Python utilities. */
@Internal
public final class PythonTableUtils {

    private PythonTableUtils() {}

    /**
     * Create a table from {@link PythonDynamicTableSource} that read data from input file with
     * specific {@link DataType}.
     *
     * @param tEnv The TableEnvironment to create table.
     * @param filePath the file path of the input data.
     * @param schema The python data type.
     * @param batched Whether to read data in a batch
     * @return Table with InputFormat.
     */
    public static Table createTableFromElement(
            TableEnvironment tEnv, String filePath, DataType schema, boolean batched) {
        TableDescriptor.Builder builder =
                TableDescriptor.forConnector(PythonDynamicTableFactory.IDENTIFIER)
                        .option(PythonDynamicTableOptions.INPUT_FILE_PATH, filePath)
                        .option(PythonDynamicTableOptions.BATCH_MODE, batched)
                        .schema(Schema.newBuilder().fromRowDataType(schema).build());
        return tEnv.from(builder.build());
    }

    /**
     * Wrap the unpickled python data with an InputFormat. It will be passed to
     * PythonDynamicTableSource later.
     *
     * @param data The unpickled python data.
     * @param dataType The python data type.
     * @return An InputFormat containing the python data.
     */
    public static InputFormat<RowData, ?> getInputFormat(
            final List<Object[]> data, final DataType dataType) {
        Function<Object, Object> converter = converter(dataType.getLogicalType());
        Collection<RowData> dataCollection =
                data.stream()
                        .map(objects -> (RowData) converter.apply(objects))
                        .collect(Collectors.toList());
        return new CollectionInputFormat<>(
                dataCollection, InternalSerializers.create(dataType.getLogicalType()));
    }

    private static BiFunction<Integer, Function<Integer, Object>, Object> arrayConstructor(
            final LogicalType elementType) {
        if (elementType instanceof BooleanType) {
            return (length, elementGetter) -> {
                Boolean[] array = new Boolean[length];
                for (int i = 0; i < length; i++) {
                    array[i] = (Boolean) elementGetter.apply(i);
                }
                return new GenericArrayData(array);
            };
        }
        if (elementType instanceof TinyIntType) {
            return (length, elementGetter) -> {
                Byte[] array = new Byte[length];
                for (int i = 0; i < length; i++) {
                    array[i] = (Byte) elementGetter.apply(i);
                }
                return new GenericArrayData(array);
            };
        }

        if (elementType instanceof IntType) {
            return (length, elementGetter) -> {
                Integer[] array = new Integer[length];
                for (int i = 0; i < length; i++) {
                    array[i] = (Integer) elementGetter.apply(i);
                }
                return new GenericArrayData(array);
            };
        }
        if (elementType instanceof BigIntType) {
            return (length, elementGetter) -> {
                Long[] array = new Long[length];
                for (int i = 0; i < length; i++) {
                    array[i] = (Long) elementGetter.apply(i);
                }
                return new GenericArrayData(array);
            };
        }
        if (elementType instanceof FloatType) {
            return (length, elementGetter) -> {
                Float[] array = new Float[length];
                for (int i = 0; i < length; i++) {
                    array[i] = (Float) elementGetter.apply(i);
                }
                return new GenericArrayData(array);
            };
        }
        if (elementType instanceof DoubleType) {
            return (length, elementGetter) -> {
                Double[] array = new Double[length];
                for (int i = 0; i < length; i++) {
                    array[i] = (Double) elementGetter.apply(i);
                }
                return new GenericArrayData(array);
            };
        }
        if (elementType instanceof CharType || elementType instanceof VarCharType) {
            return (length, elementGetter) -> {
                StringData[] array = new StringData[length];
                for (int i = 0; i < length; i++) {
                    array[i] = (StringData) elementGetter.apply(i);
                }
                return new GenericArrayData(array);
            };
        }

        return (length, elementGetter) -> {
            Object[] array = new Object[length];
            for (int i = 0; i < length; i++) {
                array[i] = elementGetter.apply(i);
            }
            return new GenericArrayData(array);
        };
    }

    private static Function<Object, Object> converter(LogicalType logicalType) {

        if (logicalType instanceof NullType) {
            return n -> null;
        }

        if (logicalType instanceof BooleanType) {
            return b -> b instanceof Boolean ? b : null;
        }

        if (logicalType instanceof TinyIntType) {
            return c -> {
                if (c instanceof Byte) {
                    return c;
                }
                if (c instanceof Short) {
                    return ((Short) c).byteValue();
                }
                if (c instanceof Integer) {
                    return ((Integer) c).byteValue();
                }
                if (c instanceof Long) {
                    return ((Long) c).byteValue();
                }
                return null;
            };
        }

        if (logicalType instanceof SmallIntType) {
            return c -> {
                if (c instanceof Byte) {
                    return ((Byte) c).shortValue();
                }
                if (c instanceof Short) {
                    return c;
                }
                if (c instanceof Integer) {
                    return ((Integer) c).shortValue();
                }
                if (c instanceof Long) {
                    return ((Long) c).shortValue();
                }
                return null;
            };
        }

        if (logicalType instanceof IntType) {
            return c -> {
                if (c instanceof Byte) {
                    return ((Byte) c).intValue();
                }
                if (c instanceof Short) {
                    return ((Short) c).intValue();
                }
                if (c instanceof Integer) {
                    return c;
                }
                if (c instanceof Long) {
                    return ((Long) c).intValue();
                }
                return null;
            };
        }

        if (logicalType instanceof BigIntType) {
            return c -> {
                if (c instanceof Byte) {
                    return ((Byte) c).longValue();
                }
                if (c instanceof Short) {
                    return ((Short) c).longValue();
                }
                if (c instanceof Integer) {
                    return ((Integer) c).longValue();
                }
                if (c instanceof Long) {
                    return c;
                }
                return null;
            };
        }

        if (logicalType instanceof FloatType) {
            return c -> {
                if (c instanceof Float) {
                    return c;
                }
                if (c instanceof Double) {
                    return ((Double) c).floatValue();
                }
                return null;
            };
        }
        if (logicalType instanceof DoubleType) {
            return c -> {
                if (c instanceof Float) {
                    return ((Float) c).doubleValue();
                }
                if (c instanceof Double) {
                    return c;
                }
                return null;
            };
        }

        if (logicalType instanceof DecimalType) {
            int precision = ((DecimalType) logicalType).getPrecision();
            int scale = ((DecimalType) logicalType).getScale();
            return c ->
                    c instanceof BigDecimal
                            ? DecimalData.fromBigDecimal((BigDecimal) c, precision, scale)
                            : null;
        }

        if (logicalType instanceof DateType) {
            return c -> {
                if (c instanceof Integer) {
                    return (Integer) c;
                }
                return null;
            };
        }

        if (logicalType instanceof TimeType) {
            return c -> {
                if (c instanceof Integer || c instanceof Long) {
                    long millisLocal = ((Number) c).longValue() / 1000;
                    long millisUtc = millisLocal + getOffsetFromLocalMillis(millisLocal);
                    return (int) millisUtc;
                }
                return null;
            };
        }

        if (logicalType instanceof TimestampType) {
            return c ->
                    c instanceof Integer || c instanceof Long
                            ? TimestampData.fromLocalDateTime(
                                    Instant.ofEpochMilli(((Number) c).longValue() / 1000)
                                            .atZone(ZoneId.systemDefault())
                                            .toLocalDateTime())
                            : null;
        }

        if (logicalType instanceof ZonedTimestampType) {
            return c ->
                    c instanceof Integer || c instanceof Long
                            ? TimestampData.fromInstant(
                                    Instant.ofEpochMilli(((Number) c).longValue() / 1000))
                            : null;
        }

        if (logicalType instanceof LocalZonedTimestampType) {
            return c ->
                    c instanceof Integer || c instanceof Long
                            ? TimestampData.fromInstant(
                                    Instant.ofEpochMilli(((Number) c).longValue() / 1000))
                            : null;
        }

        if (logicalType instanceof DayTimeIntervalType) {
            return c ->
                    c instanceof Integer || c instanceof Long
                            ? ((Number) c).longValue() / 1000
                            : null;
        }

        if (logicalType instanceof YearMonthIntervalType) {
            return c ->
                    c instanceof Integer || c instanceof Long
                            ? ((Number) c).longValue() / 1000
                            : null;
        }

        if (logicalType instanceof CharType || logicalType instanceof VarCharType) {
            return c -> c != null ? StringData.fromString(c.toString()) : null;
        }

        if (logicalType instanceof BinaryType || logicalType instanceof VarBinaryType) {
            return c -> {
                if (c instanceof String) {
                    return ((String) c).getBytes(StandardCharsets.UTF_8);
                }
                if (c instanceof byte[]) {
                    return c;
                }
                return null;
            };
        }

        if (logicalType instanceof ArrayType) {
            LogicalType elementType = ((ArrayType) logicalType).getElementType();
            Function<Object, Object> elementConverter = converter(elementType);
            BiFunction<Integer, Function<Integer, Object>, Object> arrayConstructor =
                    arrayConstructor(elementType);
            return c -> {
                int length = -1;
                Function<Integer, Object> elementGetter = null;
                if (c instanceof List) {
                    length = ((List<?>) c).size();
                    elementGetter = i -> elementConverter.apply(((List<?>) c).get(i));
                }
                if (c != null && c.getClass().isArray()) {
                    length = Array.getLength(c);
                    elementGetter = i -> elementConverter.apply(Array.get(c, i));
                }
                if (elementGetter != null) {
                    return arrayConstructor.apply(length, elementGetter);
                }
                return null;
            };
        }

        if (logicalType instanceof MultisetType) {
            return c -> c;
        }

        if (logicalType instanceof MapType) {
            Function<Object, Object> keyConverter = converter(((MapType) logicalType).getKeyType());
            Function<Object, Object> valueConverter =
                    converter(((MapType) logicalType).getValueType());

            return c -> {
                if (c instanceof Map) {
                    Map<?, ?> mapData =
                            ((Map<?, ?>) c)
                                    .entrySet().stream()
                                            .collect(
                                                    Collectors.toMap(
                                                            e -> keyConverter.apply(e.getKey()),
                                                            e ->
                                                                    valueConverter.apply(
                                                                            e.getValue())));
                    return new GenericMapData(mapData);
                } else {
                    return null;
                }
            };
        }

        if (logicalType instanceof RowType) {
            LogicalType[] fieldTypes = logicalType.getChildren().toArray(new LogicalType[0]);
            List<Function<Object, Object>> fieldConverters =
                    Arrays.stream(fieldTypes)
                            .map(PythonTableUtils::converter)
                            .collect(Collectors.toList());
            return c -> {
                if (c != null && c.getClass().isArray()) {
                    int length = Array.getLength(c);
                    if (length - 1 != fieldTypes.length) {
                        throw new IllegalStateException(
                                "Input row doesn't have expected number of values required by the schema. "
                                        + fieldTypes.length
                                        + " fields are required while "
                                        + (length - 1)
                                        + " values are provided.");
                    }

                    GenericRowData row = new GenericRowData(length - 1);
                    row.setRowKind(RowKind.fromByteValue(((Number) Array.get(c, 0)).byteValue()));

                    for (int i = 0; i < row.getArity(); i++) {
                        row.setField(i, fieldConverters.get(i).apply(Array.get(c, i + 1)));
                    }

                    return row;
                }
                return null;
            };
        } else if (logicalType instanceof StructuredType) {
            Optional<Class<?>> implClass = ((StructuredType) logicalType).getImplementationClass();
            if (implClass.isPresent()
                    && (implClass.get() == ListView.class || implClass.get() == MapView.class)) {
                return converter(logicalType.getChildren().get(0));
            }
            throw new IllegalStateException(
                    "Failed to get the data converter for StructuredType with implementation "
                            + "class: "
                            + implClass.orElse(null));
        }

        throw new IllegalStateException("Failed to get converter for LogicalType: " + logicalType);
    }

    private static int getOffsetFromLocalMillis(final long millisLocal) {
        TimeZone localZone = TimeZone.getDefault();
        int result = localZone.getRawOffset();
        // the actual offset should be calculated based on milliseconds in UTC
        int offset = localZone.getOffset(millisLocal - (long) result);
        if (offset != result) {
            // DayLight Saving Time
            result = localZone.getOffset(millisLocal - (long) offset);
            if (result != offset) {
                // fallback to do the reverse lookup using java.time.LocalDateTime
                // this should only happen near the start or end of DST
                LocalDate localDate = LocalDate.ofEpochDay(millisLocal / 86400000L);
                LocalTime localTime =
                        LocalTime.ofNanoOfDay(
                                Math.floorMod(millisLocal, 86400000L) * 1000L * 1000L);
                LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
                long millisEpoch =
                        localDateTime.atZone(localZone.toZoneId()).toInstant().toEpochMilli();
                result = (int) (millisLocal - millisEpoch);
            }
        }

        return result;
    }
}


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

using Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;

namespace Google.Cloud.Diagnostics.Common
{
    ///
    /// Options for a <see cref="GoogleLogger"/>".
    /// These are options to configure when and what is logged,
    /// as where <see cref="LoggingServiceOptions"/> configure the logging service,
    /// including the target GCP project, etc.
    ///
    public sealed class LoggingOptions
    {
        /// The base log name for all logs.
        // We keep this as aspnetcore for backwards compatibility.
        // It might be a little awkward for someone writing a console application
        // to see their logs end up in something named "aspnetcore" but this is
        // just a name, and if they are really interested, they can specify their own.
        private const string _baseLogName = "aspnetcore";

        /// The minimum log level.
        public LogLevel LogLevel { get; }

        /// The name for the logs.
        public string LogName { get; }

        /// The monitored resource. See: https://cloud.google.com/logging/docs/api/v2/resource-list
        public MonitoredResource MonitoredResource { get; }

        /// The buffer options for the logger.
        public BufferOptions BufferOptions { get; }

        /// The retry options for the logger.
        public RetryOptions RetryOptions { get; }

        /// Custom labels for log entries.
        /// <remarks>Keys and values added to <see cref="Labels"/> should not be null.
        /// If they are, an exception will be thrown when attempting to log an entry.
        /// The entry won't be logged and the exception will be propagated depending
        /// on the value of <see cref="RetryOptions.ExceptionHandling"/>.</remarks>
        public Dictionary<string, string> Labels { get; }

        private LoggingOptions(
          LogLevel logLevel,
          string logName,
          Dictionary<string, string> labels,
          MonitoredResource monitoredResource,
          BufferOptions bufferOptions,
          RetryOptions retryOptions)
        {
            LogName = logName;
            LogLevel = GaxPreconditions.CheckEnumValue(logLevel, nameof(logLevel));
            Labels = labels;
            MonitoredResource = monitoredResource;
            BufferOptions = bufferOptions;
            RetryOptions = retryOptions;
        }

        ///
        /// Create a new instance of <see cref="LoggingOptions"/>.
        ///
        /// <param name="logLevel">Optional, the minimum log level. Defaults to <see cref="LogLevel.Information"/></param>
        /// <param name="logName">Optional, the name of the log. Defaults to 'aspnetcore'.</param>
        /// <param name="labels">Optional, custom labels to be added to log entries.
        /// Keys and values added to <paramref name="labels"/> should not be null.
        /// If they are, an exception will be thrown when attempting to log an entry.
        /// The entry won't be logged and the exception will be propagated depending
        /// on the value of <see cref="RetryOptions.ExceptionHandling"/>.</param>
        /// <param name="monitoredResource">Optional, the monitored resource. The monitored resource will
        /// be automatically detected if it is not set and will default to the global resource if the detection fails.
        /// See: https://cloud.google.com/logging/docs/api/v2/resource-list </param>
        /// <param name="bufferOptions">Optional, the buffer options. Defaults to a <see cref="BufferType.Timed"/></param>
        /// <param name="retryOptions">Optional, the retry options. Defaults to a <see cref="RetryType.None"/></param>
        public static LoggingOptions Create(LogLevel logLevel = LogLevel.Information, string logName = null,
          Dictionary<string, string> labels = null, MonitoredResource monitoredResource = null,
          BufferOptions bufferOptions = null, RetryOptions retryOptions = null) =>
          new LoggingOptions(logLevel, logName ?? _baseLogName,
            labels ?? new Dictionary<string, string>(), monitoredResource ?? MonitoredResourceBuilder.FromPlatform(),
            bufferOptions ?? BufferOptions.TimedBuffer(), retryOptions ?? RetryOptions.NoRetry());
    }
}


text:
#ifndef itkFrequencyExpandViaInverseFFTImageFilter_h
#define itkFrequencyExpandViaInverseFFTImageFilter_h

#include <itkImageToImageFilter.h>
#include <itkInverseFFTImageFilter.h>
#include <itkForwardFFTImageFilter.h>
#include <itkExpandWithZerosImageFilter.h>
#include "itkChangeInformationImageFilter.h"

namespace itk
{
/** \class FrequencyExpandViaInverseFFTImageFilter
 * \brief Expand the size of an image in the frequency domain by an integer
 * factor in each dimension.
 *
 * The input in the frequency domain is converted to the spatial domain using an
 * inverseFFT, then a ExpandWithZerosImageFilter is used, and the output is converted back
 * to the frequency domain with a ForwardFFT.
 *
 * FrequencyExpandViaInverseFFTImageFilter increases the size of an image in the frequency domain
 * (for example, the output of a FFTImageFilter), by an integer
 * factor in each dimension.
 * The output image size in each dimension is given by:
 *
 * OutputSize[j] = InputSize[j] * ExpandFactors[j]
 *
 * This code was contributed in the Insight Journal paper:
 * https://hdl.handle.net....
 *
 * \ingroup IsotropicWavelets
 */
template< typename TImageType >
class FrequencyExpandViaInverseFFTImageFilter:
  public ImageToImageFilter< TImageType, TImageType >
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(FrequencyExpandViaInverseFFTImageFilter);

  /** Standard class type alias. */
  using Self = FrequencyExpandViaInverseFFTImageFilter;
  using Superclass = ImageToImageFilter<TImageType, TImageType>;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(FrequencyExpandViaInverseFFTImageFilter, ImageToImageFilter);

  /** ImageDimension enumeration. */
  static constexpr unsigned int ImageDimension = TImageType::ImageDimension;

  /** Inherit some types from superclass. */
  using ImageType = typename Superclass::InputImageType;
  using PixelType = typename ImageType::PixelType;
  using ImagePointer = typename ImageType::Pointer;
  /** Typedef to describe the output image region type. */
  using ImageRegionType = typename TImageType::RegionType;
  /** Typedef of used filters */
  using InverseFFTFilterType = itk::InverseFFTImageFilter<ImageType>;
  using ExpandFilterType = itk::ExpandWithZerosImageFilter<typename InverseFFTFilterType::OutputImageType,
    typename InverseFFTFilterType::OutputImageType>;
  using ForwardFFTFilterType = itk::ForwardFFTImageFilter<typename InverseFFTFilterType::OutputImageType,
    ImageType>;
  using ChangeInformationFilterType = itk::ChangeInformationImageFilter< ImageType >;

  /** The type of the expand factors representation */
  using ExpandFactorsType = FixedArray< unsigned int, ImageDimension >;

  /** Set the expand factors. Values are clamped to
   * a minimum value of 1. Default is 1 for all dimensions. */
  itkSetMacro(ExpandFactors, ExpandFactorsType);
  virtual void SetExpandFactors(const unsigned int factor);

  /** Get the expand factors. */
  itkGetConstReferenceMacro(ExpandFactors, ExpandFactorsType);

  /** FrequencyExpandViaInverseFFTImageFilter produces an image which is a different resolution and
   * with a different pixel spacing than its input image.  As such,
   * FrequencyExpandViaInverseFFTImageFilter needs to provide an implementation for
   * UpdateOutputInformation() in order to inform the pipeline execution model.
   * The original documentation of this method is below.
   * \sa ProcessObject::GenerateOutputInformaton() */
  void GenerateOutputInformation() override;

  /** FrequencyExpandViaInverseFFTImageFilter needs a smaller input requested region than the output
   * requested region.  As such, ShrinkImageFilter needs to provide an
   * implementation for GenerateInputRequestedRegion() in order to inform
   * the pipeline execution model.
   * \sa ProcessObject::GenerateInputRequestedRegion() */
  void GenerateInputRequestedRegion() override;

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
  itkConceptMacro( ImageTypeHasNumericTraitsCheck,
                   ( Concept::HasNumericTraits< typename TImageType::PixelType > ) );
  // End concept checking
#endif

protected:
  FrequencyExpandViaInverseFFTImageFilter();
  ~FrequencyExpandViaInverseFFTImageFilter() override {}
  void PrintSelf(std::ostream & os, Indent indent) const override;

  void GenerateData() override;

private:
  ExpandFactorsType                             m_ExpandFactors;
  typename InverseFFTFilterType::Pointer        m_InverseFFT;
  typename ForwardFFTFilterType::Pointer        m_ForwardFFT;
  typename ExpandFilterType::Pointer            m_Expander;
  typename ChangeInformationFilterType::Pointer m_ChangeInformation;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkFrequencyExpandViaInverseFFTImageFilter.hxx"
#endif

#endif


text:
package org.springframework.boot.context.properties.source;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Function;

import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySource.StubPropertySource;
import org.springframework.util.Assert;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.ConcurrentReferenceHashMap.ReferenceType;

/**
 * Adapter to convert Spring's {@link MutablePropertySources} to
 * {@link ConfigurationPropertySource ConfigurationPropertySources}.
 *
 * @author Phillip Webb
 */
class SpringConfigurationPropertySources
		implements Iterable<ConfigurationPropertySource> {

	private final Iterable<PropertySource<?>> sources;

	private final Map<PropertySource<?>, ConfigurationPropertySource> cache = new ConcurrentReferenceHashMap<>(
			16, ReferenceType.SOFT);

	SpringConfigurationPropertySources(Iterable<PropertySource<?>> sources) {
		Assert.notNull(sources, "Sources must not be null");
		this.sources = sources;
	}

	@Override
	public Iterator<ConfigurationPropertySource> iterator() {
		return new SourcesIterator(this.sources.iterator(), this::adapt);
	}

	private ConfigurationPropertySource adapt(PropertySource<?> source) {
		ConfigurationPropertySource result = this.cache.get(source);
		// Most PropertySources test equality only using the source name, so we need to
		// check the actual source hasn't also changed.
		if (result != null && result.getUnderlyingSource() == source) {
			return result;
		}
		result = SpringConfigurationPropertySource.from(source);
		this.cache.put(source, result);
		return result;
	}

	private static class SourcesIterator
			implements Iterator<ConfigurationPropertySource> {

		private final Deque<Iterator<PropertySource<?>>> iterators;

		private ConfigurationPropertySource next;

		private final Function<PropertySource<?>, ConfigurationPropertySource> adapter;

		SourcesIterator(Iterator<PropertySource<?>> iterator,
				Function<PropertySource<?>, ConfigurationPropertySource> adapter) {
			this.iterators = new ArrayDeque<>(4);
			this.iterators.push(iterator);
			this.adapter = adapter;
		}

		@Override
		public boolean hasNext() {
			return fetchNext() != null;
		}

		@Override
		public ConfigurationPropertySource next() {
			ConfigurationPropertySource next = fetchNext();
			if (next == null) {
				throw new NoSuchElementException();
			}
			this.next = null;
			return next;
		}

		private ConfigurationPropertySource fetchNext() {
			if (this.next == null) {
				if (this.iterators.isEmpty()) {
					return null;
				}
				if (!this.iterators.peek().hasNext()) {
					this.iterators.pop();
					return fetchNext();
				}
				PropertySource<?> candidate = this.iterators.peek().next();
				if (candidate.getSource() instanceof ConfigurableEnvironment) {
					push((ConfigurableEnvironment) candidate.getSource());
					return fetchNext();
				}
				if (isIgnored(candidate)) {
					return fetchNext();
				}
				this.next = this.adapter.apply(candidate);
			}
			return this.next;
		}

		private void push(ConfigurableEnvironment environment) {
			this.iterators.push(environment.getPropertySources().iterator());
		}

		private boolean isIgnored(PropertySource<?> candidate) {
			return (candidate instanceof StubPropertySource
					|| candidate instanceof ConfigurationPropertySourcesPropertySource);
		}

	}

}