text:
using namespace gpopt;

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::CLogicalConstTableGet
//
//	@doc:
//		ctor - for pattern
//
//---------------------------------------------------------------------------
CLogicalConstTableGet::CLogicalConstTableGet
	(
	CMemoryPool *mp
	)
	:
	CLogical(mp),
	m_pdrgpcoldesc(NULL),
	m_pdrgpdrgpdatum(NULL),
	m_pdrgpcrOutput(NULL)
{
	m_fPattern = true;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::CLogicalConstTableGet
//
//	@doc:
//		ctor
//
//---------------------------------------------------------------------------
CLogicalConstTableGet::CLogicalConstTableGet
	(
	CMemoryPool *mp,
	CColumnDescriptorArray *pdrgpcoldesc,
	IDatum2dArray *pdrgpdrgpdatum
	)
	:
	CLogical(mp),
	m_pdrgpcoldesc(pdrgpcoldesc),
	m_pdrgpdrgpdatum(pdrgpdrgpdatum),
	m_pdrgpcrOutput(NULL)
{
	GPOS_ASSERT(NULL != pdrgpcoldesc);
	GPOS_ASSERT(NULL != pdrgpdrgpdatum);

	// generate a default column set for the list of column descriptors
	m_pdrgpcrOutput = PdrgpcrCreateMapping(mp, pdrgpcoldesc, UlOpId());

#ifdef GPOS_DEBUG
	for (ULONG ul = 0; ul < pdrgpdrgpdatum->Size(); ul++)
	{
		IDatumArray *pdrgpdatum = (*pdrgpdrgpdatum)[ul];
		GPOS_ASSERT(pdrgpdatum->Size() == pdrgpcoldesc->Size());
	}
#endif
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::CLogicalConstTableGet
//
//	@doc:
//		ctor
//
//---------------------------------------------------------------------------
CLogicalConstTableGet::CLogicalConstTableGet
	(
	CMemoryPool *mp,
	CColRefArray *pdrgpcrOutput,
	IDatum2dArray *pdrgpdrgpdatum
	)
	:
	CLogical(mp),
	m_pdrgpcoldesc(NULL),
	m_pdrgpdrgpdatum(pdrgpdrgpdatum),
	m_pdrgpcrOutput(pdrgpcrOutput)
{
	GPOS_ASSERT(NULL != pdrgpcrOutput);
	GPOS_ASSERT(NULL != pdrgpdrgpdatum);

	// generate column descriptors for the given output columns
	m_pdrgpcoldesc = PdrgpcoldescMapping(mp, pdrgpcrOutput);

#ifdef GPOS_DEBUG
	for (ULONG ul = 0; ul < pdrgpdrgpdatum->Size(); ul++)
	{
		IDatumArray *pdrgpdatum = (*pdrgpdrgpdatum)[ul];
		GPOS_ASSERT(pdrgpdatum->Size() == m_pdrgpcoldesc->Size());
	}
#endif
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::~CLogicalConstTableGet
//
//	@doc:
//		dtor
//
//---------------------------------------------------------------------------
CLogicalConstTableGet::~CLogicalConstTableGet()
{
	CRefCount::SafeRelease(m_pdrgpcoldesc);
	CRefCount::SafeRelease(m_pdrgpdrgpdatum);
	CRefCount::SafeRelease(m_pdrgpcrOutput);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::HashValue
//
//	@doc:
//		Operator specific hash function
//
//---------------------------------------------------------------------------
ULONG
CLogicalConstTableGet::HashValue() const
{
	ULONG ulHash = gpos::CombineHashes(COperator::HashValue(),
								gpos::CombineHashes(
										gpos::HashPtr<CColumnDescriptorArray>(m_pdrgpcoldesc),
										gpos::HashPtr<IDatum2dArray>(m_pdrgpdrgpdatum)));
	ulHash = gpos::CombineHashes(ulHash, CUtils::UlHashColArray(m_pdrgpcrOutput));

	return ulHash;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::Matches
//
//	@doc:
//		Match function on operator level
//
//---------------------------------------------------------------------------
BOOL
CLogicalConstTableGet::Matches
	(
	COperator *pop
	)
	const
{
	if (pop->Eopid() != Eopid())
	{
		return false;
	}

	CLogicalConstTableGet *popCTG = CLogicalConstTableGet::PopConvert(pop);

	// match if column descriptors, const values and output columns are identical
	return m_pdrgpcoldesc->Equals(popCTG->Pdrgpcoldesc()) &&
			m_pdrgpdrgpdatum->Equals(popCTG->Pdrgpdrgpdatum()) &&
			m_pdrgpcrOutput->Equals(popCTG->PdrgpcrOutput());
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::PopCopyWithRemappedColumns
//
//	@doc:
//		Return a copy of the operator with remapped columns
//
//---------------------------------------------------------------------------
COperator *
CLogicalConstTableGet::PopCopyWithRemappedColumns
	(
	CMemoryPool *mp,
	UlongToColRefMap *colref_mapping,
	BOOL must_exist
	)
{
	CColRefArray *colref_array = NULL;
	if (must_exist)
	{
		colref_array = CUtils::PdrgpcrRemapAndCreate(mp, m_pdrgpcrOutput, colref_mapping);
	}
	else
	{
		colref_array = CUtils::PdrgpcrRemap(mp, m_pdrgpcrOutput, colref_mapping, must_exist);
	}
	m_pdrgpdrgpdatum->AddRef();

	return GPOS_NEW(mp) CLogicalConstTableGet(mp, colref_array, m_pdrgpdrgpdatum);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::DeriveOutputColumns
//
//	@doc:
//		Derive output columns
//
//---------------------------------------------------------------------------
CColRefSet *
CLogicalConstTableGet::DeriveOutputColumns
	(
	CMemoryPool *mp,
	CExpressionHandle & // exprhdl
	)
{
	CColRefSet *pcrs = GPOS_NEW(mp) CColRefSet(mp);
	pcrs->Include(m_pdrgpcrOutput);

	return pcrs;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::DeriveMaxCard
//
//	@doc:
//		Derive max card
//
//---------------------------------------------------------------------------
CMaxCard
CLogicalConstTableGet::DeriveMaxCard
	(
	CMemoryPool *, // mp
	CExpressionHandle & // exprhdl
	)
	const
{
	return CMaxCard(m_pdrgpdrgpdatum->Size());
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::FInputOrderSensitive
//
//	@doc:
//		Not called for leaf operators
//
//---------------------------------------------------------------------------
BOOL
CLogicalConstTableGet::FInputOrderSensitive() const
{
	GPOS_ASSERT(!"Unexpected function call of FInputOrderSensitive");
	return false;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::PxfsCandidates
//
//	@doc:
//		Get candidate xforms
//
//---------------------------------------------------------------------------
CXformSet *
CLogicalConstTableGet::PxfsCandidates
	(
	CMemoryPool *mp
	)
	const
{
	CXformSet *xform_set = GPOS_NEW(mp) CXformSet(mp);
	(void) xform_set->ExchangeSet(CXform::ExfImplementConstTableGet);
	return xform_set;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::PdrgpcoldescMapping
//
//	@doc:
//		Construct column descriptors from column references
//
//---------------------------------------------------------------------------
CColumnDescriptorArray *
CLogicalConstTableGet::PdrgpcoldescMapping
	(
	CMemoryPool *mp,
	CColRefArray *colref_array
	)
	const
{
	GPOS_ASSERT(NULL != colref_array);
	CColumnDescriptorArray *pdrgpcoldesc = GPOS_NEW(mp) CColumnDescriptorArray(mp);

	const ULONG length = colref_array->Size();
	for (ULONG ul = 0; ul < length; ul++)
	{
		CColRef *colref = (*colref_array)[ul];

		ULONG length = gpos::ulong_max;
		if (CColRef::EcrtTable == colref->Ecrt())
		{
			CColRefTable *pcrTable = CColRefTable::PcrConvert(colref);
			length = pcrTable->Width();
		}

		CColumnDescriptor *pcoldesc = GPOS_NEW(mp) CColumnDescriptor
													(
													mp,
													colref->RetrieveType(),
													colref->TypeModifier(),
													colref->Name(),
													ul + 1, //attno
													true, // IsNullable
													length
													);
		pdrgpcoldesc->Append(pcoldesc);
	}

	return pdrgpcoldesc;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::PstatsDerive
//
//	@doc:
//		Derive statistics
//
//---------------------------------------------------------------------------
IStatistics *
CLogicalConstTableGet::PstatsDerive
	(
	CMemoryPool *mp,
	CExpressionHandle &exprhdl,
	IStatisticsArray * // not used
	)
	const
{
	GPOS_ASSERT(Esp(exprhdl) > EspNone);
	CReqdPropRelational *prprel = CReqdPropRelational::GetReqdRelationalProps(exprhdl.Prp());
	CColRefSet *pcrs = prprel->PcrsStat();
	ULongPtrArray *colids = GPOS_NEW(mp) ULongPtrArray(mp);
	pcrs->ExtractColIds(mp, colids);
	ULongPtrArray *pdrgpulColWidth = CUtils::Pdrgpul(mp, m_pdrgpcrOutput);

	IStatistics *stats = CStatistics::MakeDummyStats
										(
										mp,
										colids,
										pdrgpulColWidth,
										m_pdrgpdrgpdatum->Size()
										);

	// clean up
	colids->Release();
	pdrgpulColWidth->Release();

	return stats;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalConstTableGet::OsPrint
//
//	@doc:
//		debug print
//
//---------------------------------------------------------------------------
IOstream &
CLogicalConstTableGet::OsPrint
	(
	IOstream &os
	)
	const
{
	if (m_fPattern)
	{
		return COperator::OsPrint(os);
	}
	else
	{
		os << SzId() << " ";
		os << "Columns: [";
		CUtils::OsPrintDrgPcr(os, m_pdrgpcrOutput);
		os << "] ";
		os << "Values: [";
		for (ULONG ulA = 0; ulA < m_pdrgpdrgpdatum->Size(); ulA++)
		{
			if (0 < ulA)
			{
				os << "; ";
			}
			os << "(";
			IDatumArray *pdrgpdatum = (*m_pdrgpdrgpdatum)[ulA];

			const ULONG length = pdrgpdatum->Size();
			for (ULONG ulB = 0; ulB < length; ulB++)
			{
				IDatum *datum = (*pdrgpdatum)[ulB];
				datum->OsPrint(os);

				if (ulB < length-1)
				{
					os << ", ";
				}
			}
			os << ")";
		}
		os << "]";

	}

	return os;
}

// EOF


text:
#include "common_tools.h"
#include "opengl.h"

typedef void (APIENTRY *glNamedBufferStorageEXTPROC) (jint, uintptr_t, uintptr_t, jint);

EXTERN_C_ENTER

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_ARBBufferStorage_nglNamedBufferStorageEXT__IJJI(JNIEnv *__env, jclass clazz, jint buffer, jlong size, jlong dataAddress, jint flags) {
    glNamedBufferStorageEXTPROC glNamedBufferStorageEXT = (glNamedBufferStorageEXTPROC)tlsGetFunction(1127);
    uintptr_t data = (uintptr_t)dataAddress;
    UNUSED_PARAM(clazz)
    glNamedBufferStorageEXT(buffer, (uintptr_t)size, data, flags);
}

EXTERN_C_EXIT

redpajama_set_name: RedPajamaGithub


text:
import json

import falcon

from falcon_autocrud.resource import CollectionResource, SingleResource

from card_table import commands
from card_table.common import ensure_modifiable, require_record
from card_table.storage import db_verifier, Game, Stack, Card, Command

def create_api(middleware, db_engine):
    app = falcon.API(middleware=middleware)
    app.add_route('/health', HealthResource(db_engine))
    app.add_route('/games', GameCollectionResource(db_engine))
    app.add_route('/games/{id}', GameResource(db_engine))
    app.add_route('/stacks', StackCollectionResource(db_engine))
    app.add_route('/stacks/{id}', StackResource(db_engine))
    app.add_route('/cards', CardCollectionResource(db_engine))
    app.add_route('/cards/{id}', CardResource(db_engine))
    app.add_route('/commands', CommandCollectionResource(db_engine))
    app.add_route('/commands/{id}', CommandResource(db_engine))
    return app

class HealthResource(object):

    error_txt = 'Service failed health check'
    ok_txt = json.dumps({'title': '200 OK',
                         'description': 'Service passed health check'})

    def __init__(self, db_engine):
        self.is_db_available = db_verifier(db_engine)

    def on_get(self, req, resp):
        if self.is_db_available():
            resp.status = falcon.HTTP_200
            resp.body = self.ok_txt
        else:
            raise falcon.HTTPServiceUnavailable(description=self.error_txt,
                                                retry_after=60)

class ResourceHelper(object):
    """ Helper for Resources to serialize Enum and Dict in responses """

    def after_get(self, req, resp, collection, *args, **kwargs):
        self._serialize_all_enums(self.model, req.context['result'])

    def after_patch(self, req, resp, *args, **kwargs):
        self._serialize_all_enums(self.model, req.context['result'])

    def after_post(self, req, resp, new, *args, **kwargs):
        self._serialize_all_enums(self.model, req.context['result'])

    # falcon_autocrud + json.dump doesn't handle Enum types correctly,
    #   this function patches around that issue. [patch submitted]
    # transform particular subdicts to strings when inbound, to store as Text
    @staticmethod
    def _serialize_all_enums(model, target):
        """ Helper to serialize special field types for each item in target

        :param model: a class which implements serialize_specials(item)
        :param target: where to search for items
        """
        data = target['data']
        try:
            if isinstance(data, list):
                for item in data:
                    model.serialize_specials(item)
            else:
                model.serialize_specials(data)
        except AttributeError:
            # may not be implemented
            pass

class Protected(object):

    IMMUTABLE_PROPERTY = 'This property is not modifiable.'

    def before_patch(self, req, resp, db_session, resource, *args, **kwargs):
        """ Common handling of protected / immutable properties """
        ensure_modifiable(self.model, req.context['doc'])

    def before_post(self, req, resp, db_session, resource, *args, **kwargs):
        """ Common handling of protected properties """
        ensure_modifiable(self.model, req.context['doc'],
                          allow_immutables=True)

class RestCollectionResource(CollectionResource, Protected, ResourceHelper):
    pass

class RestResource(SingleResource, Protected, ResourceHelper):

    @staticmethod
    def after_delete(req, resp, item, *args, **kwargs):
        """ Common handler fixes up behavior of DELETE requests """
        resp.status = falcon.HTTP_NO_CONTENT
        req.context['result'] = None

class CommandCollectionResource(RestCollectionResource):
    model = Command

    def before_post(self, req, resp, db_session, resource, *args, **kwargs):
        super(CommandCollectionResource, self).before_post(
            req, resp, db_session, resource, *args, **kwargs)

        commands.execute(db_session, resource)

class CommandResource(RestResource):
    model = Command

    def modify_patch(self, req, resp, resource, *args, **kwargs):
        super(CommandResource, self).modify_patch(
            req, resp, resource, *args, **kwargs)

        if getattr(resource, 'changes', None):
            resource.changes = json.dumps(resource.changes)

class CardCollectionResource(RestCollectionResource):
    model = Card

    def before_post(self, req, resp, db_session, resource, *args, **kwargs):
        super(CardCollectionResource, self).before_post(
            req, resp, db_session, resource, *args, **kwargs)

        require_record(db_session, Stack, 'stack_id', req.context['doc'])

class CardResource(RestResource):
    model = Card
    # TODO validate the card is landing in a valid stack, in the same game?

class StackCollectionResource(RestCollectionResource):
    model = Stack

    def before_post(self, req, resp, db_session, resource, *args, **kwargs):
        super(StackCollectionResource, self).before_post(
            req, resp, db_session, resource, *args, **kwargs)

        require_record(db_session, Game, 'game_id', req.context['doc'])

class StackResource(RestResource):
    model = Stack
    # TODO validate the stack is in a valid game?

class GameCollectionResource(RestCollectionResource):
    model = Game

class GameResource(RestResource):
    model = Game


text:
import os
import time

import psutil
from twitter.common.exceptions import ExceptionalThread
from twitter.common.metrics import LambdaGauge, MutatorGauge, Observable
from twitter.common.quantity import Amount, Time

class ExecutorVars(Observable, ExceptionalThread):
  """
    Executor exported /vars wrapper.

    Currently writes to disk and communicates through the Aurora Observer,
    pending MESOS-433.
  """
  MUTATOR_METRICS = ('rss', 'cpu', 'thermos_pss', 'thermos_cpu')
  COLLECTION_INTERVAL = Amount(1, Time.MINUTES)

  def __init__(self, clock=time):
    self._clock = clock
    self._self = psutil.Process(os.getpid())
    self._orphan = False
    self.metrics.register(LambdaGauge('orphan', lambda: int(self._orphan)))
    self._metrics = dict((metric, MutatorGauge(metric, 0)) for metric in self.MUTATOR_METRICS)
    for metric in self._metrics.values():
      self.metrics.register(metric)
    ExceptionalThread.__init__(self)
    self.daemon = True

  def write_metric(self, metric, value):
    self._metrics[metric].write(value)

  @classmethod
  def thermos_children(cls, parent):
    try:
      for child in parent.children():
        yield child  # thermos_runner
        try:
          for grandchild in child.children():
            yield grandchild  # thermos_coordinator
        except psutil.Error:
          continue
    except psutil.Error:
      return

  @classmethod
  def aggregate_memory(cls, process, attribute='pss'):
    try:
      return sum(getattr(mmap, attribute) for mmap in process.memory_maps())
    except (OSError, psutil.Error, AttributeError):
      # psutil on OS X does not support get_memory_maps
      return 0

  @classmethod
  def cpu_rss_pss(cls, process):
    return (process.cpu_percent(0),
            process.memory_info().rss,
            cls.aggregate_memory(process, attribute='pss'))

  def run(self):
    while True:
      self._clock.sleep(self.COLLECTION_INTERVAL.as_(Time.SECONDS))
      self.sample()

  def sample(self):
    try:
      executor_cpu, executor_rss, _ = self.cpu_rss_pss(self._self)
      self.write_metric('cpu', executor_cpu)
      self.write_metric('rss', executor_rss)
      self._orphan = self._self.ppid() == 1
    except psutil.Error:
      return False

    try:
      child_stats = map(self.cpu_rss_pss, self.thermos_children(self._self))
      self.write_metric('thermos_cpu', sum(stat[0] for stat in child_stats))
      self.write_metric('thermos_pss', sum(stat[2] for stat in child_stats))
    except psutil.Error:
      pass

    return True


text:
package io.pebbletemplates.pebble;

import io.pebbletemplates.pebble.cache.CacheKey;
import io.pebbletemplates.pebble.cache.PebbleCache;
import io.pebbletemplates.pebble.cache.tag.ConcurrentMapTagCache;
import io.pebbletemplates.pebble.cache.tag.NoOpTagCache;
import io.pebbletemplates.pebble.cache.template.ConcurrentMapTemplateCache;
import io.pebbletemplates.pebble.cache.template.NoOpTemplateCache;
import io.pebbletemplates.pebble.error.LoaderException;
import io.pebbletemplates.pebble.lexer.LexerImpl;
import io.pebbletemplates.pebble.lexer.Syntax;
import io.pebbletemplates.pebble.lexer.TokenStream;
import io.pebbletemplates.pebble.node.RootNode;
import io.pebbletemplates.pebble.parser.Parser;
import io.pebbletemplates.pebble.parser.ParserImpl;
import io.pebbletemplates.pebble.parser.ParserOptions;
import io.pebbletemplates.pebble.attributes.methodaccess.BlacklistMethodAccessValidator;
import io.pebbletemplates.pebble.attributes.methodaccess.MethodAccessValidator;
import io.pebbletemplates.pebble.extension.escaper.EscapingStrategy;
import io.pebbletemplates.pebble.loader.ClasspathLoader;
import io.pebbletemplates.pebble.loader.DelegatingLoader;
import io.pebbletemplates.pebble.loader.FileLoader;
import io.pebbletemplates.pebble.loader.Loader;
import io.pebbletemplates.pebble.loader.StringLoader;
import io.pebbletemplates.pebble.extension.*;
import io.pebbletemplates.pebble.template.EvaluationOptions;
import io.pebbletemplates.pebble.template.PebbleTemplate;
import io.pebbletemplates.pebble.template.PebbleTemplateImpl;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;

import io.pebbletemplates.pebble.utils.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The main class used for compiling templates. The PebbleEngine is responsible for delegating
 * responsibility to the lexer, parser, compiler, and template cache.
 *
 * @author Mitchell
 */
public class PebbleEngine {

  private final Logger logger = LoggerFactory.getLogger(PebbleEngine.class);

  private final Loader<?> loader;

  private final Syntax syntax;

  private final boolean strictVariables;

  private final Locale defaultLocale;

  private final int maxRenderedSize;

  private final PebbleCache<CacheKey, Object> tagCache;

  private final ExecutorService executorService;

  private final PebbleCache<Object, PebbleTemplate> templateCache;

  private final ExtensionRegistry extensionRegistry;

  private final ParserOptions parserOptions;

  private final EvaluationOptions evaluationOptions;

  /**
   * Constructor for the Pebble Engine given an instantiated Loader. This method does only load
   * those userProvidedExtensions listed here.
   *
   * @param loader The template loader for this engine
   * @param syntax the syntax to use for parsing the templates.
   */
  private PebbleEngine(Loader<?> loader,
      Syntax syntax,
      boolean strictVariables,
      Locale defaultLocale,
      int maxRenderedSize,
      PebbleCache<CacheKey, Object> tagCache,
      PebbleCache<Object, PebbleTemplate> templateCache,
      ExecutorService executorService,
      ExtensionRegistry extensionRegistry,
      ParserOptions parserOptions,
      EvaluationOptions evaluationOptions) {

    this.loader = loader;
    this.syntax = syntax;
    this.strictVariables = strictVariables;
    this.defaultLocale = defaultLocale;
    this.maxRenderedSize = maxRenderedSize;
    this.tagCache = tagCache;
    this.executorService = executorService;
    this.templateCache = templateCache;
    this.extensionRegistry = extensionRegistry;
    this.parserOptions = parserOptions;
    this.evaluationOptions = evaluationOptions;
  }

  /**
   * Loads, parses, and compiles a template into an instance of PebbleTemplate and returns this
   * instance.
   *
   * @param templateName The name of the template
   * @return PebbleTemplate The compiled version of the template
   */
  public PebbleTemplate getTemplate(String templateName) {
    return this.getTemplate(templateName, this.loader);
  }

  /**
   * Loads, parses, and compiles a template using a StringLoader into an instance of PebbleTemplate
   * and returns this instance.
   *
   * @param templateName The name of the template
   * @return PebbleTemplate The compiled version of the template
   */
  public PebbleTemplate getLiteralTemplate(String templateName) {
    return this.getTemplate(templateName, new StringLoader());
  }

  private PebbleTemplate getTemplate(String templateName, Loader loader) {
    /*
     * template name will be null if user uses the extends tag with an
     * expression that evaluates to null
     */
    if (templateName == null) {
      return null;
    }

    if (loader == null) {
      throw new LoaderException(null, "Loader has not yet been specified.");
    }

    Object cacheKey = loader.createCacheKey(templateName);
    return this.templateCache
        .computeIfAbsent(cacheKey, k -> this.getPebbleTemplate(templateName, loader, cacheKey));
  }

  private PebbleTemplate getPebbleTemplate(String templateName, Loader loader, Object cacheKey) {

    Reader templateReader = loader.getReader(cacheKey);

    try {
      this.logger.trace("Tokenizing template named {}", templateName);
      LexerImpl lexer = new LexerImpl(this.syntax,
          this.extensionRegistry.getUnaryOperators().values(),
          this.extensionRegistry.getBinaryOperators().values());
      TokenStream tokenStream = lexer.tokenize(templateReader, templateName);
      this.logger.trace("TokenStream: {}", tokenStream);

      Parser parser = new ParserImpl(this.extensionRegistry.getUnaryOperators(),
          this.extensionRegistry.getBinaryOperators(), this.extensionRegistry.getTokenParsers(),
              this.parserOptions);
      RootNode root = parser.parse(tokenStream);

      PebbleTemplateImpl instance = new PebbleTemplateImpl(this, root, templateName);

      for (NodeVisitorFactory visitorFactory : this.extensionRegistry.getNodeVisitors()) {
        visitorFactory.createVisitor(instance).visit(root);
      }

      return instance;

    } finally {
      try {
        templateReader.close();
      } catch (IOException e) {
        // can't do much about it
      }
    }
  }

  /**
   * Returns the loader
   *
   * @return The loader
   */
  public Loader<?> getLoader() {
    return this.loader;
  }

  /**
   * Returns the template cache
   *
   * @return The template cache
   */
  public PebbleCache<Object, PebbleTemplate> getTemplateCache() {
    return this.templateCache;
  }

  /**
   * Returns the strict variables setting
   *
   * @return The strict variables setting
   */
  public boolean isStrictVariables() {
    return this.strictVariables;
  }

  /**
   * Returns the default locale
   *
   * @return The default locale
   */
  public Locale getDefaultLocale() {
    return this.defaultLocale;
  }

  /**
   * Returns the max rendered size.
   *
   *  @return The max rendered size.
   */
  public int getMaxRenderedSize() {
    return this.maxRenderedSize;
  }

  /**
   * Returns the executor service
   *
   * @return The executor service
   */
  public ExecutorService getExecutorService() {
    return this.executorService;
  }

  /**
   * Returns the syntax which is used by this PebbleEngine.
   *
   * @return the syntax used by the PebbleEngine.
   */
  public Syntax getSyntax() {
    return this.syntax;
  }

  /**
   * Returns the extension registry.
   *
   * @return The extension registry
   */
  public ExtensionRegistry getExtensionRegistry() {
    return this.extensionRegistry;
  }

  /**
   * Returns the tag cache
   *
   * @return The tag cache
   */
  public PebbleCache<CacheKey, Object> getTagCache() {
    return this.tagCache;
  }

  /**
   * A builder to configure and construct an instance of a PebbleEngine.
   */
  public static class Builder {

    private Loader<?> loader;

    private Syntax syntax;

    private boolean strictVariables = false;

    private boolean enableNewLineTrimming = true;

    private Locale defaultLocale;

    private int maxRenderedSize = -1;

    private ExecutorService executorService;

    private PebbleCache<Object, PebbleTemplate> templateCache;

    private boolean cacheActive = true;

    private PebbleCache<CacheKey, Object> tagCache;

    private boolean literalDecimalTreatedAsInteger = false;

    private boolean greedyMatchMethod = false;

    private boolean literalNumbersAsBigDecimals = false;

    private MethodAccessValidator methodAccessValidator = new BlacklistMethodAccessValidator();

    private final ExtensionRegistryFactory factory = new ExtensionRegistryFactory();

    /**
     * Creates the builder.
     */
    public Builder() {

    }

    /**
     * Sets the loader used to find templates.
     *
     * @param loader A template loader
     * @return This builder object
     */
    public Builder loader(Loader<?> loader) {
      this.loader = loader;
      return this;
    }

    /**
     * Adds an extension, can be safely invoked several times to add different extensions.
     *
     * @param extensions One or more extensions to add
     * @return This builder object
     */
    public Builder extension(Extension... extensions) {
      this.factory.extension(extensions);
      return this;
    }

    /**
     * Sets the syntax to be used.
     *
     * @param syntax The syntax to be used
     * @return This builder object
     */
    public Builder syntax(Syntax syntax) {
      this.syntax = syntax;
      return this;
    }

    /**
     * Changes the strictVariables setting of the PebbleEngine. The default value of
     * this setting is "false".
     *

     * The following examples will all print empty strings if strictVariables is false but will
     * throw exceptions if it is true:
     *

     * {{ nonExistingVariable }} {{ nonExistingVariable.attribute }} {{ nullVariable.attribute }} {{
     * existingVariable.nullAttribute.attribute }} {{ existingVariable.nonExistingAttribute }} {{
     * array[-1] }}
     *
     * @param strictVariables Whether or not strict variables is used
     * @return This builder object
     */
    public Builder strictVariables(boolean strictVariables) {
      this.strictVariables = strictVariables;
      return this;
    }

    /**
     * Changes the newLineTrimming setting of the PebbleEngine. The default value of
     * this setting is "true".
     *

     * By default, Pebble will trim a newline that immediately follows a Pebble tag. For example,
     * {{key1}}\n{{key2}} will have the newline removed.
     *

     *

     * If newLineTrimming is set to false, then the first newline following a Pebble
     * tag won't be trimmed.  All newlines will be preserved
     *

     *
     * @param enableNewLineTrimming Whether or not the newline should be trimmed.
     * @return This builder object
     */
    public Builder newLineTrimming(boolean enableNewLineTrimming) {
      this.enableNewLineTrimming = enableNewLineTrimming;
      return this;
    }

    /**
     * Sets the Locale passed to all templates constructed by this PebbleEngine.
     *

     * An individual template can always be given a new locale during evaluation.
     *
     * @param defaultLocale The default locale
     * @return This builder object
     */
    public Builder defaultLocale(Locale defaultLocale) {
      this.defaultLocale = defaultLocale;
      return this;
    }

    /**
     * Sets the maximum size of the rendered template to protect against macro bombs.
     * See for example https://github.com/PebbleTemplates/pebble/issues/526.
     * If the rendered template exceeds this limit, then a PebbleException is thrown.
     * The default value is -1 and it means unlimited.
     * @param maxRenderedSize The maximum allowed size of the rendered template.
     * @return This builder object.
     */
    public Builder maxRenderedSize(int maxRenderedSize) {
      this.maxRenderedSize = maxRenderedSize;
      return this;
    }

    /**
     * Sets the executor service which is required if using one of Pebble's multithreading features
     * such as the "parallel" tag.
     *
     * @param executorService The executor service
     * @return This builder object
     */
    public Builder executorService(ExecutorService executorService) {
      this.executorService = executorService;
      return this;
    }

    /**
     * Sets the cache used by the engine to store compiled PebbleTemplate instances.
     *
     * @param templateCache The template cache
     * @return This builder object
     */
    public Builder templateCache(PebbleCache<Object, PebbleTemplate> templateCache) {
      this.templateCache = templateCache;
      return this;
    }

    /**
     * Sets the cache used by the "cache" tag.
     *
     * @param tagCache The tag cache
     * @return This builder object
     */
    public Builder tagCache(PebbleCache<CacheKey, Object> tagCache) {
      this.tagCache = tagCache;
      return this;
    }

    /**
     * Sets whether or not escaping should be performed automatically.
     *
     * @param autoEscaping The auto escaping setting
     * @return This builder object
     */
    public Builder autoEscaping(boolean autoEscaping) {
      this.factory.autoEscaping(autoEscaping);
      return this;
    }

    /**
     * Sets whether or not core operators overrides should be allowed.
     *
     * @param allowOverrideCoreOperators Whether or not core operators overrides should be allowed.
     * @return This builder object
     */
    public Builder allowOverrideCoreOperators(boolean allowOverrideCoreOperators) {
      this.factory.allowOverrideCoreOperators(allowOverrideCoreOperators);
      return this;
    }

    /**
     * Sets the default escaping strategy of the built-in escaper extension.
     *
     * @param strategy The name of the default escaping strategy
     * @return This builder object
     */
    public Builder defaultEscapingStrategy(String strategy) {
      this.factory.defaultEscapingStrategy(strategy);
      return this;
    }

    /**
     * Adds an escaping strategy to the built-in escaper extension.
     *
     * @param name The name of the escaping strategy
     * @param strategy The strategy implementation
     * @return This builder object
     */
    public Builder addEscapingStrategy(String name, EscapingStrategy strategy) {
      this.factory.addEscapingStrategy(name, strategy);
      return this;
    }

    /**
     * Enable/disable all caches, i.e. cache used by the engine to store compiled PebbleTemplate
     * instances and tags cache
     *
     * @param cacheActive toggle to enable/disable all caches
     * @return This builder object
     */
    public Builder cacheActive(boolean cacheActive) {
      this.cacheActive = cacheActive;
      return this;
    }

    /**
     * Validator that can be used to validate object/method access
     *
     * @param methodAccessValidator Validator that can be used to validate object/method access
     * @return This builder object
     */
    public Builder methodAccessValidator(MethodAccessValidator methodAccessValidator) {
      this.methodAccessValidator = methodAccessValidator;
      return this;
    }

    /**
     * Enable/disable treat literal decimal as Integer. Default is disabled, treated as Long.
     *
     * @param literalDecimalTreatedAsInteger toggle to enable/disable literal decimal treated as
     * integer
     * @return This builder object
     */
    public Builder literalDecimalTreatedAsInteger(boolean literalDecimalTreatedAsInteger) {
      this.literalDecimalTreatedAsInteger = literalDecimalTreatedAsInteger;
      return this;
    }

    /**
     * Enable/disable treat literal numbers as BigDecimals. Default is disabled, treated as Long/Double.
     *
     * @param literalNumbersAsBigDecimals toggle to enable/disable literal numbers treated as
     * BigDecimals
     * @return This builder object
     */
    public Builder literalNumbersAsBigDecimals(boolean literalNumbersAsBigDecimals) {
      this.literalNumbersAsBigDecimals = literalNumbersAsBigDecimals;
      return this;
    }

    /**
     * Enable/disable greedy matching mode for finding java method. Default is disabled. If enabled,
     * when can not find perfect method (method name, parameter length and parameter type are all
     * satisfied), reduce the limit of the parameter type, try to find other method which has
     * compatible parameter types.
     *
     * For example,
     *
 {{ obj.number(2) }}

     * the expression can match all of below methods.
     *

     *   public Long getNumber(Long v) {...}
     *   public Integer getNumber(Integer v) {...}
     *   public Short getNumber(Short v) {...}
     *   public Byte getNumber(Byte v) {...}
     *   ...
     *

     *
     * @param greedyMatchMethod toggle to enable/disable greedy match method
     * @return This builder object
     * @see TypeUtils#compatibleCast(Object, Class)
     */
    public Builder greedyMatchMethod(boolean greedyMatchMethod) {
      this.greedyMatchMethod = greedyMatchMethod;
      return this;
    }

    /**
     * Registers an implementation of {@link ExtensionCustomizer} to change runtime-behaviour of standard
     * functionality.
     *
     * @param customizer The customizer which wraps any non-user-provided extension
     * @return This build object
     */
    public Builder registerExtensionCustomizer(Function<Extension, ExtensionCustomizer> customizer) {
      this.factory.registerExtensionCustomizer(customizer);
      return this;
    }

    /**
     * Creates the PebbleEngine instance.
     *
     * @return A PebbleEngine object that can be used to create PebbleTemplate objects.
     */
    public PebbleEngine build() {

      ExtensionRegistry extensionRegistry = this.factory.buildExtensionRegistry();

      // default loader
      if (this.loader == null) {
        List<Loader<?>> defaultLoadingStrategies = new ArrayList<>();
        defaultLoadingStrategies.add(new ClasspathLoader());
        defaultLoadingStrategies.add(new FileLoader());
        this.loader = new DelegatingLoader(defaultLoadingStrategies);
      }

      // default locale
      if (this.defaultLocale == null) {
        this.defaultLocale = Locale.getDefault();
      }

      if (this.cacheActive) {
        // default caches
        if (this.templateCache == null) {
          this.templateCache = new ConcurrentMapTemplateCache();
        }

        if (this.tagCache == null) {
          this.tagCache = new ConcurrentMapTagCache();
        }
      } else {
        this.templateCache = new NoOpTemplateCache();
        this.tagCache = new NoOpTagCache();
      }

      if (this.syntax == null) {
        this.syntax = new Syntax.Builder().setEnableNewLineTrimming(this.enableNewLineTrimming)
            .build();
      }

      ParserOptions parserOptions = new ParserOptions();
      parserOptions.setLiteralDecimalTreatedAsInteger(this.literalDecimalTreatedAsInteger);
      parserOptions.setLiteralNumbersAsBigDecimals(this.literalNumbersAsBigDecimals);

      EvaluationOptions evaluationOptions = new EvaluationOptions(this.greedyMatchMethod,
          this.methodAccessValidator);
      return new PebbleEngine(this.loader, this.syntax, this.strictVariables, this.defaultLocale, this.maxRenderedSize,
          this.tagCache, this.templateCache,
          this.executorService, extensionRegistry, parserOptions, evaluationOptions);
    }
  }

  public EvaluationOptions getEvaluationOptions() {
    return this.evaluationOptions;
  }
}


text:
// -----------------------------------------------------------------------
// <copyright file="ISubscriptionUsageSummary.java" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

package com.microsoft.store.partnercenter.usage;

import com.microsoft.store.partnercenter.IPartnerComponent;
import com.microsoft.store.partnercenter.genericoperations.IEntityGetOperations;
import com.microsoft.store.partnercenter.models.usage.SubscriptionUsageSummary;
import com.microsoft.store.partnercenter.models.utils.Tuple;

/**
 * This interface defines the operations available on a customer's subscription usage summary.
 */
public interface ISubscriptionUsageSummary
    extends IPartnerComponent<Tuple<String, String>>, IEntityGetOperations<SubscriptionUsageSummary>
{
	/***
	 * Retrieves the customer's subscription usage summary.
	 * @return The customer's subscription usage summary.
	 */
	SubscriptionUsageSummary get();
}


text:
INCLUDE(CheckCXXSourceCompiles)

check_library_exists(atomic __atomic_fetch_add_4 "" HAVE_LIBATOMIC)
if (HAVE_LIBATOMIC)
  list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
endif()

CHECK_CXX_SOURCE_COMPILES("
#ifdef _MSC_VER
#include <windows.h>
#endif
int main() {
#ifdef _MSC_VER
        volatile LONG val = 1;
        MemoryBarrier();
        InterlockedCompareExchange(&val, 0, 1);
        InterlockedIncrement(&val);
        InterlockedDecrement(&val);
#else
        volatile unsigned long val = 1;
        __sync_synchronize();
        __sync_val_compare_and_swap(&val, 1, 0);
        __sync_add_and_fetch(&val, 1);
        __sync_sub_and_fetch(&val, 1);
#endif
        return 0;
      }
" LLVM_HAS_ATOMICS)

if( NOT LLVM_HAS_ATOMICS )
  message(STATUS "Warning: LLVM will be built thread-unsafe because atomic builtins are missing")
endif()


text:
from unittest import mock
from aiohttp import web

import pytest
from aiohttp.test_utils import make_mocked_coro

from sockjs import protocol
from sockjs.transports import base

@pytest.fixture
def make_transport(make_manager, make_request, make_handler, make_fut):
    def maker(method="GET", path="/", query_params={}):
        handler = make_handler(None)
        manager = make_manager(handler)
        request = make_request(method, path, query_params=query_params)
        request.app.freeze()
        session = manager.get("TestSessionStreaming", create=True, request=request)
        return base.StreamingTransport(manager, session, request)

    return maker

async def test_transport_ctor(make_request):
    manager = object()
    session = object()
    request = make_request("GET", "/")

    transport = base.Transport(manager, session, request)
    assert transport.manager is manager
    assert transport.session is session
    assert transport.request is request

async def test_streaming_send(make_transport):
    trans = make_transport()

    resp = trans.response = mock.Mock()
    resp.write = make_mocked_coro(None)
    stop = await trans.send("text data")
    assert not stop
    assert trans.size == len(b"text data\n")
    resp.write.assert_called_with(b"text data\n")

    trans.maxsize = 1
    stop = await trans.send("text data")
    assert stop

async def test_handle_session_interrupted(make_transport, make_fut):
    trans = make_transport()
    trans.session.interrupted = True
    trans.send = make_fut(1)
    trans.response = web.StreamResponse()
    await trans.handle_session()
    trans.send.assert_called_with('c[1002,"Connection interrupted"]')

async def test_handle_session_closing(make_transport, make_fut):
    trans = make_transport()
    trans.send = make_fut(1)
    trans.session.interrupted = False
    trans.session.state = protocol.STATE_CLOSING
    trans.session._remote_closed = make_fut(1)
    trans.response = web.StreamResponse()
    await trans.handle_session()
    trans.session._remote_closed.assert_called_with()
    trans.send.assert_called_with('c[3000,"Go away!"]')

async def test_handle_session_closed(make_transport, make_fut):
    trans = make_transport()
    trans.send = make_fut(1)
    trans.session.interrupted = False
    trans.session.state = protocol.STATE_CLOSED
    trans.session._remote_closed = make_fut(1)
    trans.response = web.StreamResponse()
    await trans.handle_session()
    trans.session._remote_closed.assert_called_with()
    trans.send.assert_called_with('c[3000,"Go away!"]')

async def test_session_has_request(make_transport, make_fut):
    transp = make_transport(method="POST")
    transp.session._remote_messages = make_fut(1)
    assert isinstance(transp.session.request, web.Request)


text:
package org.opencds.cqf.r4.builders;

import java.util.Date;

import org.opencds.cqf.common.builders.BaseBuilder;
import org.opencds.cqf.cql.engine.runtime.DateTime;

public class JavaDateBuilder extends BaseBuilder<Date> {

    public JavaDateBuilder() {
        super(new Date());
    }

    public JavaDateBuilder buildFromDateTime(DateTime dateTime) {
        complexProperty = Date.from(dateTime.getDateTime().toInstant());
        return this;
    }
}


text:
"""
This module tests the test API.  These are high-level integration tests.  Lower level unit tests
should go in test_render.py
"""

import os
import re
import sys

import mock
import pytest
import yaml

from conda_build import api, render
from conda_build.conda_interface import subdir, reset_context, cc_conda_build
from tests import utils

from .utils import metadata_dir, thisdir

def test_render_need_download(testing_workdir, testing_config):
    # first, test that the download/render system renders all it can,
    #    and accurately returns its needs

    with pytest.raises((ValueError, SystemExit)):
        metadata, need_download, need_reparse_in_env = api.render(
            os.path.join(metadata_dir, "source_git_jinja2"),
            config=testing_config,
            no_download_source=True)[0]
        assert need_download
        assert need_reparse_in_env

    # Test that allowing source download lets it to the right thing.
    metadata, need_download, need_reparse_in_env = api.render(
        os.path.join(metadata_dir, "source_git_jinja2"),
        config=testing_config,
        no_download_source=False,
        finalize=False)[0]
    assert not need_download
    assert metadata.meta["package"]["version"] == "1.20.2"

def test_render_yaml_output(testing_workdir, testing_config):
    metadata, need_download, need_reparse_in_env = api.render(
        os.path.join(metadata_dir, "source_git_jinja2"),
        config=testing_config)[0]
    yaml_metadata = api.output_yaml(metadata)
    assert "package:" in yaml_metadata

    # writes file with yaml data in it
    api.output_yaml(metadata, os.path.join(testing_workdir, "output.yaml"))
    assert "package:" in open(os.path.join(testing_workdir, "output.yaml")).read()

def test_get_output_file_path(testing_workdir, testing_metadata):
    testing_metadata = render.finalize_metadata(testing_metadata)
    api.output_yaml(testing_metadata, 'recipe/meta.yaml')

    build_path = api.get_output_file_paths(os.path.join(testing_workdir, 'recipe'),
                                          config=testing_metadata.config,
                                          no_download_source=True)[0]
    assert build_path == os.path.join(testing_metadata.config.croot,
                                      testing_metadata.config.host_subdir,
                                      "test_get_output_file_path-1.0-1.tar.bz2")

def test_get_output_file_path_metadata_object(testing_metadata):
    testing_metadata.final = True
    build_path = api.get_output_file_paths(testing_metadata)[0]
    assert build_path == os.path.join(testing_metadata.config.croot,
                                      testing_metadata.config.host_subdir,
                "test_get_output_file_path_metadata_object-1.0-1.tar.bz2")

def test_get_output_file_path_jinja2(testing_workdir, testing_config):
    # If this test does not raise, it's an indicator that the workdir is not
    #    being cleaned as it should.
    recipe = os.path.join(metadata_dir, "source_git_jinja2")

    # First get metadata with a recipe that is known to need a download:
    with pytest.raises((ValueError, SystemExit)):
        build_path = api.get_output_file_paths(recipe,
                                               config=testing_config,
                                               no_download_source=True)[0]

    metadata, need_download, need_reparse_in_env = api.render(
        recipe,
        config=testing_config,
        no_download_source=False)[0]
    build_path = api.get_output_file_paths(metadata)[0]
    _hash = metadata.hash_dependencies()
    python = ''.join(metadata.config.variant['python'].split('.')[:2])
    assert build_path == os.path.join(testing_config.croot, testing_config.host_subdir,
                                      "conda-build-test-source-git-jinja2-1.20.2-"
                                      "py{0}{1}_0_g262d444.tar.bz2".format(python, _hash))

@mock.patch('conda_build.source')
def test_output_without_jinja_does_not_download(mock_source, testing_workdir, testing_config):
        api.get_output_file_path(os.path.join(metadata_dir, "source_git"),
                                              config=testing_config)[0]
        mock_source.provide.assert_not_called()

def test_pin_compatible_semver(testing_config):
    recipe_dir = os.path.join(metadata_dir, '_pin_compatible')
    metadata = api.render(recipe_dir, config=testing_config)[0][0]
    assert 'zlib >=1.2.11,<2.0a0' in metadata.get_value('requirements/run')

@pytest.mark.slow
@pytest.mark.skipif(
    utils.on_win and sys.version_info < (3, 6),
    reason="Failing tests on Azure for Python 2.7"
)
def test_resolved_packages_recipe(testing_config):
    recipe_dir = os.path.join(metadata_dir, '_resolved_packages_host_build')
    metadata = api.render(recipe_dir, config=testing_config)[0][0]
    assert all(len(pkg.split()) == 3 for pkg in metadata.get_value('requirements/run'))
    run_requirements = set(x.split()[0] for x in metadata.get_value('requirements/run'))
    for package in [
        'curl',  # direct dependency
        'numpy',  # direct dependency
        'zlib',  # indirect dependency of curl
        'python',  # indirect dependency of numpy
    ]:
        assert package in run_requirements

@pytest.mark.slow
def test_host_entries_finalized(testing_config):
    recipe = os.path.join(metadata_dir, '_host_entries_finalized')
    metadata = api.render(recipe, config=testing_config)
    assert len(metadata) == 2
    outputs = api.get_output_file_paths(metadata)
    assert any('py27' in out for out in outputs)
    assert any('py36' in out for out in outputs)

def test_hash_no_apply_to_custom_build_string(testing_metadata, testing_workdir):
    testing_metadata.meta['build']['string'] = 'steve'
    testing_metadata.meta['requirements']['build'] = ['zlib 1.2.8']

    api.output_yaml(testing_metadata, 'meta.yaml')
    metadata = api.render(testing_workdir)[0][0]

    assert metadata.build_id() == 'steve'

def test_pin_depends(testing_config):
    """This is deprecated functionality - replaced by the more general variants pinning scheme"""
    recipe = os.path.join(metadata_dir, '_pin_depends_strict')
    m = api.render(recipe, config=testing_config)[0][0]
    # the recipe python is not pinned, but having pin_depends set will force it to be.
    assert any(re.search(r'python\s+[23]\.', dep) for dep in m.meta['requirements']['run'])

def test_cross_recipe_with_only_build_section(testing_config):
    recipe = os.path.join(metadata_dir, '_cross_prefix_elision_compiler_used')
    metadata = api.render(recipe, config=testing_config, bypass_env_check=True)[0][0]
    assert metadata.config.host_subdir != subdir
    assert metadata.config.build_prefix != metadata.config.host_prefix
    assert not metadata.build_is_host

def test_setting_condarc_vars_with_env_var_expansion(testing_workdir):
    os.makedirs('config')
    # python won't be used - the stuff in the recipe folder will override it
    python_versions = ['2.6', '3.4', '3.10']
    config = {'python': python_versions,
              'bzip2': ['0.9', '1.0']}
    with open(os.path.join('config', 'conda_build_config.yaml'), 'w') as f:
        yaml.dump(config, f, default_flow_style=False)

    cc_conda_build_backup = cc_conda_build.copy()
    # hacky equivalent of changing condarc
    # careful, this is global and affects other tests!  make sure to clear it!
    cc_conda_build.update({'config_file': '${TEST_WORKDIR}/config/conda_build_config.yaml'})

    os.environ['TEST_WORKDIR'] = testing_workdir
    try:
        m = api.render(os.path.join(thisdir, 'test-recipes', 'variants', '19_used_variables'),
                    bypass_env_check=True, finalize=False)[0][0]
        # this one should have gotten clobbered by the values in the recipe
        assert m.config.variant['python'] not in python_versions
        # this confirms that we loaded the config file correctly
        assert len(m.config.squished_variants['bzip2']) == 2
    finally:
        cc_conda_build.clear()
        cc_conda_build.update(cc_conda_build_backup)

def test_self_reference_run_exports_pin_subpackage_picks_up_version_correctly():
    recipe = os.path.join(metadata_dir, '_self_reference_run_exports')
    m = api.render(recipe)[0][0]
    run_exports = m.meta.get('build', {}).get('run_exports', [])
    assert run_exports
    assert len(run_exports) == 1
    assert run_exports[0].split()[1] == '>=1.0.0,<2.0a0'

def test_run_exports_with_pin_compatible_in_subpackages(testing_config):
    recipe = os.path.join(metadata_dir, '_run_exports_in_outputs')
    ms = api.render(recipe, config=testing_config)
    for m, _, _ in ms:
        if m.name().startswith('gfortran_'):
            run_exports = set(m.meta.get('build', {}).get('run_exports', {}).get('strong', []))
            assert len(run_exports) == 1
            # len after splitting should be more than one because of pin_compatible.  If it's only zlib, we've lost the
            #    compatibility bound info.  This is generally due to lack of rendering of an output, such that the
            #    compatibility bounds just aren't added in.
            assert all(len(export.split()) > 1 for export in run_exports), run_exports

def test_ignore_build_only_deps(testing_config):
    ms = api.render(os.path.join(thisdir, 'test-recipes', 'variants', 'python_in_build_only'),
                    bypass_env_check=True, finalize=False)
    assert len(ms) == 1

def test_merge_build_host_build_key(testing_workdir, testing_metadata):
    m = api.render(os.path.join(metadata_dir, '_no_merge_build_host'))[0][0]
    assert not any('bzip2' in dep for dep in m.meta['requirements']['run'])

def test_merge_build_host_empty_host_section(testing_config):
    m = api.render(os.path.join(metadata_dir, '_empty_host_avoids_merge'))[0][0]
    assert not any('bzip2' in dep for dep in m.meta['requirements']['run'])

@pytest.mark.skipif(sys.platform != "linux2", reason="package on remote end is only on linux")
@pytest.mark.xfail(reason="It needs to be fixed for Python v2.7. #3681")
def test_run_exports_from_repo_without_channeldata(testing_config):
    ms = api.render(os.path.join(metadata_dir, '_run_export_no_channeldata'), config=testing_config)
    assert ms[0][0].meta['requirements']['build'] == ["exporty"]
    # these two will be missing if run_exports has failed.
    assert ms[0][0].meta['requirements']['host'] == ["exporty"]
    assert ms[0][0].meta['requirements']['run'] == ["exporty"]


text:
if [ ! $1 ]
then
    echo "First argument must be a release number (like '0.4.0')"
    exit
fi

git checkout -b rel_$1 dev


text:
package com.facebook.buck.cxx.toolchain.objectfile;

import java.util.Optional;

/**
 * Represents the binding context for the Mach-O bind actions. The actions themselves implicitly
 * operate on a shared binding context to produce actions.
 *
 * <p>Note that the binding context here is *incomplete* as we're only interested in a subset of the
 * data. This can be expanded over time as needed.
 */
public class MachoBindContext {
  /** Defines the library ordinal, using 1-based indexing, in the list of dependent libraries. */
  public Optional<Integer> libraryOrdinal = Optional.empty();
  /** Defines the symbol name being bound. */
  public Optional<String> symbolName = Optional.empty();
}


text:
TargetingList is an object that holds retargeting information (target list).

### Service

+ [RetargetingListService](../../services/RetargetingListService.md)

### Namespace

[RetargetingListService#Namespace](../../services/RetargetingListService.md#namespace)

| Field | Type | Description | response | add | set |
| ----- | ---- | ----------- | -------- | --------- | --------- |
| accountId | xsd:long | Account ID. | yes | Requirement | Requirement | |
| owner | enum [TargetListOwner](./TargetListOwner.md) | Target list owner information. | yes | - | - | |
| retargetingAccountStatus | [RetargetingAccountStatus](./RetargetingAccountStatus.md) | Status of Retargeting account. | yes | - | - | |
| targetListId | xsd:long | Target List ID. | yes | - | Requirement | |
| targetListTrackId | xsd:long | Tracking ID of Target list. | yes | - | - | |
| targetListType | enum [TargetListType](./TargetListType.md) | Type of Target List. | yes | Requirement | Requirement | |
| targetListName | xsd:string | Target List name. | yes | Requirement | Optional | |
| targetListDescription | xsd:string | Description of Target List. | yes | Optional | Optional | |
| closingReason | enum [ClosingReason](./ClosingReason.md) | Reason for Closing. | yes | Ignore | Ignore | |
| reachStorageStatus | enum [ReachStorageStatus](./ReachStorageStatus.md) | Flag status of holding Cookie.
*Default: OPEN
*Always be "OPEN" for default list. | yes | Optional
`*LogicalTargetList:Ignore` | Optional
`*LogicalTargetList:Ignore` | |
| reachStorageSpan | xsd:long | Days to hold Cookie.
*Default: 180
*Can set from 1-540 days | yes | ‐ | Optional
`*LogicalTargetList:Ignore` | |
| reach | xsd:long | Number of users stored to the list. | yes | - | - | |

この 作品 は クリエイティブ・コモンズ 表示 - 改変禁止 2.1 日本 ライセンスの下に提供されています。


text:
import os, sys, inspect, thread, time
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
arch_dir = '../lib/x64' if sys.maxsize > 2**32 else '../lib/x86'
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))

import Leap
from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture, SwipeGesture

class SampleListener(Leap.Listener):

    def on_connect(self, controller):
        print "Connected"

    def on_frame(self, controller):
        print "Frame available"

def main():
    listener = SampleListener()
    controller = Leap.Controller()
    controller.add_listener(listener)
    # Keep this process running until Enter is pressed
    print "Press Enter to quit..."
    try:
        sys.stdin.readline()
    except KeyboardInterrupt:
        pass
    finally:
        controller.remove_listener(listener)

if __name__ == "__main__":
    main()


text:
using System;
using System.Collections.ObjectModel;
using SimMetrics.Net.API;

namespace SimMetrics.Net.Utilities
{
    public class TokeniserQGram3 : AbstractTokeniserQGramN
    {
        public TokeniserQGram3()
        {
            StopWordHandler = new DummyStopTermHandler();
            TokenUtilities = new TokeniserUtilities<string>();
            CharacterCombinationIndex = 0;
            QGramLength = 3;
        }

        public override Collection<string> Tokenize(string word)
        {
            return base.Tokenize(word, false, QGramLength, CharacterCombinationIndex);
        }

        public override string ToString()
        {
            if (string.IsNullOrEmpty(SuppliedWord))
            {
                return string.Format("{0} : not word passed for tokenising yet.", ShortDescriptionString);
            }
            return string.Format("{0} - currently holding : {1}.{2}The method is using a QGram length of {3}.", ShortDescriptionString, SuppliedWord, Environment.NewLine, Convert.ToInt32(QGramLength));
        }

        public override string ShortDescriptionString => "TokeniserQGram3";
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Jil;

namespace StackExchange.Opserver.Data.PagerDuty
{
    public partial class PagerDutyAPI
    {
        public Task<LogEntry> GetEventEntryAsync(string id)
        {
            return GetFromPagerDutyAsync($"log_entries/{id}", getFromJson:
                response => JSON.Deserialize<LogEntry>(response, JilOptions));
        }

        public Task<List<LogEntry>> GetIncidentEntriesAsync(string id)
        {
            return GetFromPagerDutyAsync($"incidents/{id}/log_entries", getFromJson:
                response => JSON.Deserialize<LogEntries>(response, JilOptions).Logs);
        }
    }

    public class LogEntries
    {
        [DataMember(Name="log_entries")]
        public List<LogEntry> Logs { get; set; }
    }

    public class LogEntry
    {
        [DataMember(Name="id")]
        public string Id { get; set; }
        [DataMember(Name="created_at")]
        public DateTime? CreationTime { get; set; }
        [DataMember(Name = "type")]
        public string LogType { get; set; }
        [DataMember(Name = "agent")]
        public LogAgent Agent { get; set; }
        public LogDetail Detail {
            get
            {
                var r = new LogDetail();
                if (LogType == "notify")
                {
                    r.Message = NotifyUser.FullName + " via " + NotificationAction.NotifyAddress;
                }
                else
                {
                    switch (Agent.Service)
                    {
                        case "user":
                            r.Message = Agent.Person.FullName + " via " + Channel.ChannelType;
                            break;
                        case "service":
                            r.Message = "Action Performed by: " + Channel.ChannelType;
                            break;
                        default:
                            r.Message = "I have no idea what i'm doing";
                            break;
                    }
                }
                return r;
            }
        }
        [DataMember(Name = "channel")]
        public LogChannel Channel { get; set; }
        [DataMember(Name = "note")]
        public string Note { get; set; }
        [DataMember(Name="user")]
        public PagerDutyPerson NotifyUser { get; set; }
        [DataMember(Name = "notification")]
        public Notification NotificationAction { get; set; }
    }

    public class LogAgent
    {
        [DataMember(Name="id")]
        public string AgentId { get; set; }
        [DataMember(Name="type")]
        public string Service { get; set; }
        public PagerDutyPerson Person => PagerDutyAPI.Instance.AllUsers.Data?.FirstOrDefault(u => u.Id == AgentId);
    }
    public class Notification
    {
        [DataMember(Name = "type")]
        public string NotifyType { get; set; }
        [DataMember(Name = "address")]
        public string NotifyAddress { get; set; }
        [DataMember(Name = "success")]
        public string NotifyStatus { get; set; }
    }

    public class LogDetail
    {
        public string Message { get; set; }
    }

    public class LogChannel
    {
        [DataMember(Name = "type")]
        public string ChannelType { get; set; }
        [DataMember(Name = "summary")]
        public string Summary { get; set; }
    }
}


text:
chorus.dialogs.DataSourceUsage = chorus.dialogs.Base.extend({
    constructorName: "DataSourceUsage",

    templateName: "data_source_usage",
    title: t("data_sources.usage.title"),
    useLoadingSection: true,
    additionalClass: 'with_sub_header',

    setup: function() {
        this.dataSource = this.options.dataSource;
        this.usage = this.resource = this.dataSource.usage();
        this.usage.fetchIfNotLoaded();
        this.requiredResources.push(this.usage);
    },

    additionalContext: function(context) {
        var online = this.dataSource.get("state") !== 'offline';
        _.each(context.workspaces, function(workspace) {
            if(online) {
                workspace.formattedSize = I18n.toHumanSize(workspace.sizeInBytes, {precision: 0, format: "%n %u"});
            } else {
                workspace.percentageUsed = 0;
                workspace.formattedSize = t('data_sources.usage.offline');
            }
        });

        if(online) {
            return {
                formattedSandboxesSize: I18n.toHumanSize(context.sandboxesSizeInBytes, {precision: 0, format: "%n %u"})
            };
        }
        else {
            return {formattedSandboxesSize: t('data_sources.usage.offline')};
        }
    }
});


text:
#include "clar_libgit2.h"
#include "checkout_helpers.h"

#include "git2/checkout.h"
#include "fileops.h"
#include "repository.h"

static git_repository *g_repo;

void test_checkout_index__initialize(void)
{
	git_tree *tree;

	g_repo = cl_git_sandbox_init("testrepo");

	cl_git_pass(git_repository_head_tree(&tree, g_repo));

	reset_index_to_treeish((git_object *)tree);
	git_tree_free(tree);

	cl_git_rewritefile(
		"./testrepo/.gitattributes",
		"* text eol=lf\n");
}

void test_checkout_index__cleanup(void)
{
	cl_git_sandbox_cleanup();

	/* try to remove alternative dir */
	if (git_path_isdir("alternative"))
		git_futils_rmdir_r("alternative", NULL, GIT_RMDIR_REMOVE_FILES);
}

void test_checkout_index__cannot_checkout_a_bare_repository(void)
{
	test_checkout_index__cleanup();

	g_repo = cl_git_sandbox_init("testrepo.git");

	cl_git_fail(git_checkout_index(g_repo, NULL, NULL));
}

void test_checkout_index__can_create_missing_files(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_assert_equal_i(false, git_path_isfile("./testrepo/README"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/branch_file.txt"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/new.txt"));

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/README", "hey there\n");
	check_file_contents("./testrepo/branch_file.txt", "hi\nbye!\n");
	check_file_contents("./testrepo/new.txt", "my new file\n");
}

void test_checkout_index__can_remove_untracked_files(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	git_futils_mkdir("./testrepo/dir/subdir/subsubdir", NULL, 0755, GIT_MKDIR_PATH);
	cl_git_mkfile("./testrepo/dir/one", "one\n");
	cl_git_mkfile("./testrepo/dir/subdir/two", "two\n");

	cl_assert_equal_i(true, git_path_isdir("./testrepo/dir/subdir/subsubdir"));

	opts.checkout_strategy =
		GIT_CHECKOUT_SAFE_CREATE | GIT_CHECKOUT_REMOVE_UNTRACKED;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	cl_assert_equal_i(false, git_path_isdir("./testrepo/dir"));
}

void test_checkout_index__honor_the_specified_pathspecs(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	char *entries[] = { "*.txt" };

	opts.paths.strings = entries;
	opts.paths.count = 1;

	cl_assert_equal_i(false, git_path_isfile("./testrepo/README"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/branch_file.txt"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/new.txt"));

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	cl_assert_equal_i(false, git_path_isfile("./testrepo/README"));
	check_file_contents("./testrepo/branch_file.txt", "hi\nbye!\n");
	check_file_contents("./testrepo/new.txt", "my new file\n");
}

void test_checkout_index__honor_the_gitattributes_directives(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	const char *attributes =
		"branch_file.txt text eol=crlf\n"
		"new.txt text eol=lf\n";

	cl_git_mkfile("./testrepo/.gitattributes", attributes);
	cl_repo_set_bool(g_repo, "core.autocrlf", false);

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/README", "hey there\n");
	check_file_contents("./testrepo/new.txt", "my new file\n");
	check_file_contents("./testrepo/branch_file.txt", "hi\r\nbye!\r\n");
}

void test_checkout_index__honor_coreautocrlf_setting_set_to_true(void)
{
#ifdef GIT_WIN32
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	const char *expected_readme_text = "hey there\r\n";

	cl_git_pass(p_unlink("./testrepo/.gitattributes"));
	cl_repo_set_bool(g_repo, "core.autocrlf", true);

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/README", expected_readme_text);
#endif
}

void test_checkout_index__honor_coresymlinks_setting_set_to_true(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_repo_set_bool(g_repo, "core.symlinks", true);

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

#ifdef GIT_WIN32
	check_file_contents("./testrepo/link_to_new.txt", "new.txt");
#else
	{
		char link_data[1024];
		size_t link_size = 1024;

		link_size = p_readlink("./testrepo/link_to_new.txt", link_data, link_size);
		link_data[link_size] = '\0';
		cl_assert_equal_i(link_size, strlen("new.txt"));
		cl_assert_equal_s(link_data, "new.txt");
		check_file_contents("./testrepo/link_to_new.txt", "my new file\n");
	}
#endif
}

void test_checkout_index__honor_coresymlinks_setting_set_to_false(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_repo_set_bool(g_repo, "core.symlinks", false);

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/link_to_new.txt", "new.txt");
}

void test_checkout_index__donot_overwrite_modified_file_by_default(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_git_mkfile("./testrepo/new.txt", "This isn't what's stored!");

	/* set this up to not return an error code on conflicts, but it
	 * still will not have permission to overwrite anything...
	 */
	opts.checkout_strategy = GIT_CHECKOUT_SAFE | GIT_CHECKOUT_ALLOW_CONFLICTS;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/new.txt", "This isn't what's stored!");
}

void test_checkout_index__can_overwrite_modified_file(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_git_mkfile("./testrepo/new.txt", "This isn't what's stored!");

	opts.checkout_strategy = GIT_CHECKOUT_FORCE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/new.txt", "my new file\n");
}

void test_checkout_index__options_disable_filters(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_git_mkfile("./testrepo/.gitattributes", "*.txt text eol=crlf\n");

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;
	opts.disable_filters = false;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/new.txt", "my new file\r\n");

	p_unlink("./testrepo/new.txt");

	opts.disable_filters = true;
	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/new.txt", "my new file\n");
}

void test_checkout_index__options_dir_modes(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	struct stat st;
	git_oid oid;
	git_commit *commit;
	mode_t um;

	if (!cl_is_chmod_supported())
		return;

	cl_git_pass(git_reference_name_to_id(&oid, g_repo, "refs/heads/dir"));
	cl_git_pass(git_commit_lookup(&commit, g_repo, &oid));

	reset_index_to_treeish((git_object *)commit);

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;
	opts.dir_mode = 0701;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	/* umask will influence actual directory creation mode */
	(void)p_umask(um = p_umask(022));

	cl_git_pass(p_stat("./testrepo/a", &st));
	cl_assert_equal_i_fmt(st.st_mode, (GIT_FILEMODE_TREE | 0701) & ~um, "%07o");

	/* File-mode test, since we're on the 'dir' branch */
	cl_git_pass(p_stat("./testrepo/a/b.txt", &st));
	cl_assert_equal_i_fmt(st.st_mode, GIT_FILEMODE_BLOB_EXECUTABLE, "%07o");

	git_commit_free(commit);
}

void test_checkout_index__options_override_file_modes(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	struct stat st;

	if (!cl_is_chmod_supported())
		return;

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;
	opts.file_mode = 0700;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	cl_git_pass(p_stat("./testrepo/new.txt", &st));
	cl_assert_equal_i_fmt(st.st_mode & GIT_MODE_PERMS_MASK, 0700, "%07o");
}

void test_checkout_index__options_open_flags(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_git_mkfile("./testrepo/new.txt", "hi\n");

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;
	opts.file_open_flags = O_CREAT | O_RDWR | O_APPEND;

	opts.checkout_strategy = GIT_CHECKOUT_FORCE;
	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./testrepo/new.txt", "hi\nmy new file\n");
}

struct notify_data {
	const char *file;
	const char *sha;
};

static int test_checkout_notify_cb(
	git_checkout_notify_t why,
	const char *path,
	const git_diff_file *baseline,
	const git_diff_file *target,
	const git_diff_file *workdir,
	void *payload)
{
	struct notify_data *expectations = (struct notify_data *)payload;

	GIT_UNUSED(workdir);

	cl_assert_equal_i(GIT_CHECKOUT_NOTIFY_CONFLICT, why);
	cl_assert_equal_s(expectations->file, path);
	cl_assert_equal_i(0, git_oid_streq(&baseline->oid, expectations->sha));
	cl_assert_equal_i(0, git_oid_streq(&target->oid, expectations->sha));

	return 0;
}

void test_checkout_index__can_notify_of_skipped_files(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	struct notify_data data;

	cl_git_mkfile("./testrepo/new.txt", "This isn't what's stored!");

	/*
	 * $ git ls-tree HEAD
	 * 100644 blob a8233120f6ad708f843d861ce2b7228ec4e3dec6    README
	 * 100644 blob 3697d64be941a53d4ae8f6a271e4e3fa56b022cc    branch_file.txt
	 * 100644 blob a71586c1dfe8a71c6cbf6c129f404c5642ff31bd    new.txt
	 */
	data.file = "new.txt";
	data.sha = "a71586c1dfe8a71c6cbf6c129f404c5642ff31bd";

	opts.checkout_strategy =
		GIT_CHECKOUT_SAFE_CREATE | GIT_CHECKOUT_ALLOW_CONFLICTS;
	opts.notify_flags = GIT_CHECKOUT_NOTIFY_CONFLICT;
	opts.notify_cb = test_checkout_notify_cb;
	opts.notify_payload = &data;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));
}

static int dont_notify_cb(
	git_checkout_notify_t why,
	const char *path,
	const git_diff_file *baseline,
	const git_diff_file *target,
	const git_diff_file *workdir,
	void *payload)
{
	GIT_UNUSED(why);
	GIT_UNUSED(path);
	GIT_UNUSED(baseline);
	GIT_UNUSED(target);
	GIT_UNUSED(workdir);
	GIT_UNUSED(payload);

	cl_assert(false);

	return 0;
}

void test_checkout_index__wont_notify_of_expected_line_ending_changes(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_git_pass(p_unlink("./testrepo/.gitattributes"));
	cl_repo_set_bool(g_repo, "core.autocrlf", true);

	cl_git_mkfile("./testrepo/new.txt", "my new file\r\n");

	opts.checkout_strategy =
		GIT_CHECKOUT_SAFE_CREATE | GIT_CHECKOUT_ALLOW_CONFLICTS;
	opts.notify_flags = GIT_CHECKOUT_NOTIFY_CONFLICT;
	opts.notify_cb = dont_notify_cb;
	opts.notify_payload = NULL;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));
}

static void checkout_progress_counter(
	const char *path, size_t cur, size_t tot, void *payload)
{
	GIT_UNUSED(path); GIT_UNUSED(cur); GIT_UNUSED(tot);
	(*(int *)payload)++;
}

void test_checkout_index__calls_progress_callback(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	int calls = 0;

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;
	opts.progress_cb = checkout_progress_counter;
	opts.progress_payload = &calls;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));
	cl_assert(calls > 0);
}

void test_checkout_index__can_overcome_name_clashes(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	git_index *index;

	cl_git_pass(git_repository_index(&index, g_repo));
	git_index_clear(index);

	cl_git_mkfile("./testrepo/path0", "content\r\n");
	cl_git_pass(p_mkdir("./testrepo/path1", 0777));
	cl_git_mkfile("./testrepo/path1/file1", "content\r\n");

	cl_git_pass(git_index_add_bypath(index, "path0"));
	cl_git_pass(git_index_add_bypath(index, "path1/file1"));

	cl_git_pass(p_unlink("./testrepo/path0"));
	cl_git_pass(git_futils_rmdir_r(
		"./testrepo/path1", NULL, GIT_RMDIR_REMOVE_FILES));

	cl_git_mkfile("./testrepo/path1", "content\r\n");
	cl_git_pass(p_mkdir("./testrepo/path0", 0777));
	cl_git_mkfile("./testrepo/path0/file0", "content\r\n");

	cl_assert(git_path_isfile("./testrepo/path1"));
	cl_assert(git_path_isfile("./testrepo/path0/file0"));

	opts.checkout_strategy =
		GIT_CHECKOUT_SAFE_CREATE | GIT_CHECKOUT_ALLOW_CONFLICTS;
	cl_git_pass(git_checkout_index(g_repo, index, &opts));

	cl_assert(git_path_isfile("./testrepo/path1"));
	cl_assert(git_path_isfile("./testrepo/path0/file0"));

	opts.checkout_strategy = GIT_CHECKOUT_FORCE;
	cl_git_pass(git_checkout_index(g_repo, index, &opts));

	cl_assert(git_path_isfile("./testrepo/path0"));
	cl_assert(git_path_isfile("./testrepo/path1/file1"));

	git_index_free(index);
}

void test_checkout_index__validates_struct_version(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	const git_error *err;

	opts.version = 1024;
	cl_git_fail(git_checkout_index(g_repo, NULL, &opts));

	err = giterr_last();
	cl_assert_equal_i(err->klass, GITERR_INVALID);

	opts.version = 0;
	giterr_clear();
	cl_git_fail(git_checkout_index(g_repo, NULL, &opts));

	err = giterr_last();
	cl_assert_equal_i(err->klass, GITERR_INVALID);
}

void test_checkout_index__can_update_prefixed_files(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_assert_equal_i(false, git_path_isfile("./testrepo/README"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/branch_file.txt"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/new.txt"));

	cl_git_mkfile("./testrepo/READ", "content\n");
	cl_git_mkfile("./testrepo/README.after", "content\n");
	cl_git_pass(p_mkdir("./testrepo/branch_file", 0777));
	cl_git_pass(p_mkdir("./testrepo/branch_file/contained_dir", 0777));
	cl_git_mkfile("./testrepo/branch_file/contained_file", "content\n");
	cl_git_pass(p_mkdir("./testrepo/branch_file.txt.after", 0777));

	opts.checkout_strategy =
		GIT_CHECKOUT_SAFE_CREATE | GIT_CHECKOUT_REMOVE_UNTRACKED;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	/* remove untracked will remove the .gitattributes file before the blobs
	 * were created, so they will have had crlf filtering applied on Windows
	 */
	check_file_contents_nocr("./testrepo/README", "hey there\n");
	check_file_contents_nocr("./testrepo/branch_file.txt", "hi\nbye!\n");
	check_file_contents_nocr("./testrepo/new.txt", "my new file\n");

	cl_assert(!git_path_exists("testrepo/READ"));
	cl_assert(!git_path_exists("testrepo/README.after"));
	cl_assert(!git_path_exists("testrepo/branch_file"));
	cl_assert(!git_path_exists("testrepo/branch_file.txt.after"));
}

void test_checkout_index__can_checkout_a_newly_initialized_repository(void)
{
	test_checkout_index__cleanup();

	g_repo = cl_git_sandbox_init("empty_standard_repo");
	cl_git_remove_placeholders(git_repository_path(g_repo), "dummy-marker.txt");

	cl_git_pass(git_checkout_index(g_repo, NULL, NULL));
}

void test_checkout_index__issue_1397(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	test_checkout_index__cleanup();

	g_repo = cl_git_sandbox_init("issue_1397");

	cl_repo_set_bool(g_repo, "core.autocrlf", true);

	opts.checkout_strategy = GIT_CHECKOUT_FORCE;

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	check_file_contents("./issue_1397/crlf_file.txt", "first line\r\nsecond line\r\nboth with crlf");
}

void test_checkout_index__target_directory(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	checkout_counts cts;
	memset(&cts, 0, sizeof(cts));

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;
	opts.target_directory = "alternative";
	cl_assert(!git_path_isdir("alternative"));

	opts.notify_flags = GIT_CHECKOUT_NOTIFY_ALL;
	opts.notify_cb = checkout_count_callback;
	opts.notify_payload = &cts;

	/* create some files that *would* conflict if we were using the wd */
	cl_git_mkfile("testrepo/README", "I'm in the way!\n");
	cl_git_mkfile("testrepo/new.txt", "my new file\n");

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	cl_assert_equal_i(0, cts.n_untracked);
	cl_assert_equal_i(0, cts.n_ignored);
	cl_assert_equal_i(4, cts.n_updates);

	check_file_contents("./alternative/README", "hey there\n");
	check_file_contents("./alternative/branch_file.txt", "hi\nbye!\n");
	check_file_contents("./alternative/new.txt", "my new file\n");

	cl_git_pass(git_futils_rmdir_r(
		"alternative", NULL, GIT_RMDIR_REMOVE_FILES));
}

void test_checkout_index__target_directory_from_bare(void)
{
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;
	git_index *index;
	git_object *head = NULL;
	checkout_counts cts;
	memset(&cts, 0, sizeof(cts));

	test_checkout_index__cleanup();

	g_repo = cl_git_sandbox_init("testrepo.git");
	cl_assert(git_repository_is_bare(g_repo));

	cl_git_pass(git_repository_index(&index, g_repo));
	cl_git_pass(git_revparse_single(&head, g_repo, "HEAD^{tree}"));
	cl_git_pass(git_index_read_tree(index, (const git_tree *)head));
	cl_git_pass(git_index_write(index));
	git_index_free(index);

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	opts.notify_flags = GIT_CHECKOUT_NOTIFY_ALL;
	opts.notify_cb = checkout_count_callback;
	opts.notify_payload = &cts;

	/* fail to checkout a bare repo */
	cl_git_fail(git_checkout_index(g_repo, NULL, &opts));

	opts.target_directory = "alternative";
	cl_assert(!git_path_isdir("alternative"));

	cl_git_pass(git_checkout_index(g_repo, NULL, &opts));

	cl_assert_equal_i(0, cts.n_untracked);
	cl_assert_equal_i(0, cts.n_ignored);
	cl_assert_equal_i(3, cts.n_updates);

	/* files will have been filtered if needed, so strip CR */
	check_file_contents_nocr("./alternative/README", "hey there\n");
	check_file_contents_nocr("./alternative/branch_file.txt", "hi\nbye!\n");
	check_file_contents_nocr("./alternative/new.txt", "my new file\n");

	cl_git_pass(git_futils_rmdir_r(
		"alternative", NULL, GIT_RMDIR_REMOVE_FILES));

	git_object_free(head);
}

void test_checkout_index__can_get_repo_from_index(void)
{
	git_index *index;
	git_checkout_opts opts = GIT_CHECKOUT_OPTS_INIT;

	cl_assert_equal_i(false, git_path_isfile("./testrepo/README"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/branch_file.txt"));
	cl_assert_equal_i(false, git_path_isfile("./testrepo/new.txt"));

	opts.checkout_strategy = GIT_CHECKOUT_SAFE_CREATE;

	cl_git_pass(git_repository_index(&index, g_repo));

	cl_git_pass(git_checkout_index(NULL, index, &opts));

	check_file_contents("./testrepo/README", "hey there\n");
	check_file_contents("./testrepo/branch_file.txt", "hi\nbye!\n");
	check_file_contents("./testrepo/new.txt", "my new file\n");

	git_index_free(index);
}


text:
//
//  GTLServiceImage.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   image/v1
// Description:
//   Rogag API for Images
// Classes:
//   GTLServiceImage (0 custom class methods, 0 custom properties)

#import "GTLImage.h"

@implementation GTLServiceImage

#if DEBUG
// Method compiled in debug builds just to check that all the needed support
// classes are present at link time.
+ (NSArray *)checkClasses {
  NSArray *classes = [NSArray arrayWithObjects:
                      [GTLQueryImage class],
                      [GTLImageAppError class],
                      [GTLImageGetUrlRequest class],
                      [GTLImageGetUrlResponse class],
                      [GTLImageUserAuthentication class],
                      nil];
  return classes;
}
#endif  // DEBUG

- (id)init {
  self = [super init];
  if (self) {
    // Version from discovery.
    self.apiVersion = @"v1";

    // From discovery.  Where to send JSON-RPC.
    // Turn off prettyPrint for this service to save bandwidth (especially on
    // mobile). The fetcher logging will pretty print.
    self.rpcURL = [NSURL URLWithString:@"https://rogag-server-stage.appspot.com/_ah/api/rpc?prettyPrint=false"];
  }
  return self;
}

@end


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class MdTextFormat extends React.Component<IconBaseProps> { }
export = MdTextFormat;


text:
namespace chromeos_update_engine {

namespace extent_mapper {

// Uses the FIBMAP ioctl to get all blocks used by a file and return them
// as extents. Blocks are relative to the start of the filesystem. If
// there is a sparse "hole" in the file, the blocks for that will be
// represented by an extent whose start block is kSpareseHole.
// The resulting extents are stored in 'out'. Keep in mind that while
// the blocksize of a filesystem is often 4096 bytes, that is not always
// the case, so one should consult GetFilesystemBlockSize(), too.
// Returns true on success.
bool ExtentsForFileFibmap(const std::string& path, std::vector<Extent>* out);

// Puts the blocksize of the filesystem, as used by the FIBMAP ioctl, into
// out_blocksize by using the FIGETBSZ ioctl. Returns true on success.
bool GetFilesystemBlockSize(const std::string& path, uint32_t* out_blocksize);

}  // namespace extent_mapper

}  // namespace chromeos_update_engine

#endif  // CHROMEOS_PLATFORM_UPDATE_ENGINE_EXTENT_MAPPER_H__


text:
/*****************************************************************************/
/*  Copyright (c) 2015, Karl Pauwels                                         */
/*  All rights reserved.                                                     */
/*                                                                           */
/*  Redistribution and use in source and binary forms, with or without       */
/*  modification, are permitted provided that the following conditions       */
/*  are met:                                                                 */
/*                                                                           */
/*  1. Redistributions of source code must retain the above copyright        */
/*  notice, this list of conditions and the following disclaimer.            */
/*                                                                           */
/*  2. Redistributions in binary form must reproduce the above copyright     */
/*  notice, this list of conditions and the following disclaimer in the      */
/*  documentation and/or other materials provided with the distribution.     */
/*                                                                           */
/*  3. Neither the name of the copyright holder nor the names of its         */
/*  contributors may be used to endorse or promote products derived from     */
/*  this software without specific prior written permission.                 */
/*                                                                           */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      */
/*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT        */
/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */
/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT     */
/*  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   */
/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT         */
/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */
/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */
/*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT      */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */
/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */
/*****************************************************************************/

#pragma once

#include <vector>

namespace pose {

class NormalEquations {
public:
  NormalEquations();
  void reset();
  double squaredNormDeltaT() const;
  void compose(const float *CO, const float *CD);
  void solve(float *dTdR);
  void preCondition();
  const std::vector<double> &getA() { return (_A); }
  const std::vector<double> &getB() { return (_B); }
  const std::vector<double> &getdTdR() { return (_dTdR); }
  void show() const;

private:
  std::vector<double> _A, _B, _dTdR;
};
}


text:
'use strict';

const Joi = require('joi');

module.exports = Joi.object().keys({
  username: Joi.string().token().max(20).trim().required(),
  password: Joi.string().min(8).max(72).required(),
  friend_code_3ds: Joi.string().regex(/^\d{4}-\d{4}-\d{4}$/).empty(['', null])
    .options({
      language: {
        string: { regex: { base: 'must be a valid 3DS friend code' } }
      }
    }),
  friend_code_switch: Joi.string().regex(/^SW-\d{4}-\d{4}-\d{4}$/).empty(['', null])
    .options({
      language: {
        string: { regex: { base: 'must be a valid Switch friend code' } }
      }
    }),
  referrer: Joi.string().empty(['', null]),
  title: Joi.string().max(300).trim().required(),
  shiny: Joi.boolean().required(),
  game: Joi.string().max(50).trim().required(),
  dex_type: Joi.number().integer().required()
});


text:
package ru.breffi.storyclmsdk.Models;

import java.util.Date;

public class User {
	 public String id;
	 public String username;
	 public String email;
	 public String phone;
	 public String name;
	 public String location;
	 public Date birthDate;
	 public Boolean gender;

}


text:
define(
	function () {

		var scrollbarPropRx = /-cssx-scrollbar-(width|height)/;

		// TODO: combine these two functions into one

		function getScrollbarSize () {
			//  summary: figures out the height and width of the scrollbars on this system.
			//  something like this exists in dojox, but we don't want to rely on dojox
			//  Returns an object with w and h properties (width and height, Number) in pixels
			var sbSize = {w: 15, h: 15}; // default
			var testEl = document.createElement('div');
			testEl.style.cssText = 'width:100px;height:100px;overflow:scroll;bottom:100%;right:100%;position:absolute;visibility:hidden;';
			document.body.appendChild(testEl);
			try {
				sbSize = {
					w: testEl.offsetWidth - Math.max(testEl.clientWidth, testEl.scrollWidth),
					h: testEl.offsetHeight - Math.max(testEl.clientHeight, testEl.scrollHeight)
				};
				document.body.removeChild(testEl);
			}
			catch (ex) {
				// squelch
			}
			return sbSize;
		}

		function getSbSize () {
			var sbSize = getScrollbarSize();
			sbSize = { w: sbSize.w + 'px', h: sbSize.h + 'px' };
			getSbSize = function () { return sbSize; };
			return sbSize;
		}

		return {

			onValue: function (value, rule, name) {
				return value.replace(scrollbarPropRx, function (full, which) {
					return which == 'width' ? getSbSize().w : getSbSize().h;
				});
			}

		};

	}
);


text:
package org.apache.commons.compress.archivers.zip;

import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;

/**
 * Tests https://issues.apache.org/jira/browse/COMPRESS-598
 */
public class Crash_f2efd9eaeb86cda597d07b5e3c3d81363633c2da_Test {

    @Test
    public void test() throws IOException {
        final byte[] input = FileUtils
            .readFileToByteArray(new File("src/test/resources/org/apache/commons/compress/fuzz/crash-f2efd9eaeb86cda597d07b5e3c3d81363633c2da"));
        try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new ByteArrayInputStream(input))) {
            //
            // I do not think this is supposed to be recoverable... then... what?
            //
            assertThrows(NullPointerException.class, () -> {
                for (;;) {
                    final ArchiveEntry zipEntry = zis.getNextEntry();
                    if (zipEntry == null) {
                        break;
                    }
                    final long entrySize = zipEntry.getSize();
                    if (entrySize == -1) {
                        IOUtils.toByteArray(zis);
                    } else {
                        IOUtils.toByteArray(zis, entrySize);
                    }
                    // Eventually throws a NullPointerException
                    zis.getCompressedCount();
                }
            });
        }
    }

}


text:
package com.flipkart.foxtrot.common;

/**
 * User: Santanu Sinha (santanu.sinha@flipkart.com)
 * Date: 21/03/14
 * Time: 12:08 AM
 */
public enum Period {
    seconds, minutes, hours, days
}


text:
package one.util.huntbugs.warning.rule;

import one.util.huntbugs.warning.WarningType;

/**
 * @author Tagir Valeev
 *
 */
public interface Rule {
    WarningType adjust(WarningType wt);

    public static final Rule NULL = new Rule() {
        @Override
        public WarningType adjust(WarningType wt) {
            return wt;
        }
    };
}