text:
import React from 'react';
import { t, validateNonEmpty } from '@superset-ui/core';
import {
  ColumnMeta,
  ControlPanelConfig,
  D3_FORMAT_DOCS,
  D3_FORMAT_OPTIONS,
  D3_TIME_FORMAT_OPTIONS,
  formatSelectOptions,
  getStandardizedControls,
  sections,
} from '@superset-ui/chart-controls';
import OptionDescription from './OptionDescription';

const config: ControlPanelConfig = {
  controlPanelSections: [
    sections.legacyRegularTime,
    {
      label: t('Query'),
      expanded: true,
      controlSetRows: [
        ['metrics'],
        ['adhoc_filters'],
        ['groupby'],
        ['limit'],
        ['timeseries_limit_metric'],
        ['order_desc'],
        [
          {
            name: 'contribution',
            config: {
              type: 'CheckboxControl',
              label: t('Contribution'),
              default: false,
              description: t('Compute the contribution to the total'),
            },
          },
        ],
        ['row_limit'],
      ],
    },
    {
      label: t('Time Series Options'),
      expanded: true,
      controlSetRows: [
        [
          {
            name: 'time_series_option',
            config: {
              type: 'SelectControl',
              label: t('Options'),
              validators: [validateNonEmpty],
              default: 'not_time',
              valueKey: 'value',
              options: [
                {
                  label: t('Not Time Series'),
                  value: 'not_time',
                  description: t('Ignore time'),
                },
                {
                  label: t('Time Series'),
                  value: 'time_series',
                  description: t('Standard time series'),
                },
                {
                  label: t('Aggregate Mean'),
                  value: 'agg_mean',
                  description: t('Mean of values over specified period'),
                },
                {
                  label: t('Aggregate Sum'),
                  value: 'agg_sum',
                  description: t('Sum of values over specified period'),
                },
                {
                  label: t('Difference'),
                  value: 'point_diff',
                  description: t(
                    'Metric change in value from `since` to `until`',
                  ),
                },
                {
                  label: t('Percent Change'),
                  value: 'point_percent',
                  description: t(
                    'Metric percent change in value from `since` to `until`',
                  ),
                },
                {
                  label: t('Factor'),
                  value: 'point_factor',
                  description: t(
                    'Metric factor change from `since` to `until`',
                  ),
                },
                {
                  label: t('Advanced Analytics'),
                  value: 'adv_anal',
                  description: t('Use the Advanced Analytics options below'),
                },
              ],
              optionRenderer: (op: ColumnMeta) => (
                <OptionDescription option={op} />
              ),
              valueRenderer: (op: ColumnMeta) => (
                <OptionDescription option={op} />
              ),
              description: t('Settings for time series'),
            },
          },
        ],
      ],
    },
    {
      label: t('Chart Options'),
      expanded: true,
      tabOverride: 'customize',
      controlSetRows: [
        ['color_scheme'],
        [
          {
            name: 'number_format',
            config: {
              type: 'SelectControl',
              freeForm: true,
              label: t('Number format'),
              renderTrigger: true,
              default: 'SMART_NUMBER',
              choices: D3_FORMAT_OPTIONS,
              description: D3_FORMAT_DOCS,
            },
          },
          {
            name: 'date_time_format',
            config: {
              type: 'SelectControl',
              freeForm: true,
              label: t('Date Time Format'),
              renderTrigger: true,
              default: 'smart_date',
              choices: D3_TIME_FORMAT_OPTIONS,
              description: D3_FORMAT_DOCS,
            },
          },
        ],
        [
          {
            name: 'partition_limit',
            config: {
              type: 'TextControl',
              label: t('Partition Limit'),
              isInt: true,
              default: '5',
              description: t(
                'The maximum number of subdivisions of each group; ' +
                  'lower values are pruned first',
              ),
            },
          },
          {
            name: 'partition_threshold',
            config: {
              type: 'TextControl',
              label: t('Partition Threshold'),
              isFloat: true,
              default: '0.05',
              description: t(
                'Partitions whose height to parent height proportions are ' +
                  'below this value are pruned',
              ),
            },
          },
        ],
        [
          {
            name: 'log_scale',
            config: {
              type: 'CheckboxControl',
              label: t('Log Scale'),
              default: false,
              renderTrigger: true,
              description: t('Use a log scale'),
            },
          },
        ],
        [
          {
            name: 'equal_date_size',
            config: {
              type: 'CheckboxControl',
              label: t('Equal Date Sizes'),
              default: true,
              renderTrigger: true,
              description: t(
                'Check to force date partitions to have the same height',
              ),
            },
          },
        ],
        [
          {
            name: 'rich_tooltip',
            config: {
              type: 'CheckboxControl',
              label: t('Rich Tooltip'),
              renderTrigger: true,
              default: true,
              description: t(
                'The rich tooltip shows a list of all series for that point in time',
              ),
            },
          },
        ],
      ],
    },
    {
      label: t('Advanced Analytics'),
      tabOverride: 'data',
      description: t(
        'This section contains options ' +
          'that allow for advanced analytical post processing ' +
          'of query results',
      ),
      controlSetRows: [
        // eslint-disable-next-line react/jsx-key
        [
{t('Rolling Window')}
],
        [
          {
            name: 'rolling_type',
            config: {
              type: 'SelectControl',
              label: t('Rolling Function'),
              default: 'None',
              choices: formatSelectOptions([
                'None',
                'mean',
                'sum',
                'std',
                'cumsum',
              ]),
              description: t(
                'Defines a rolling window function to apply, works along ' +
                  'with the [Periods] text box',
              ),
            },
          },
        ],
        [
          {
            name: 'rolling_periods',
            config: {
              type: 'TextControl',
              label: t('Periods'),
              isInt: true,
              description: t(
                'Defines the size of the rolling window function, ' +
                  'relative to the time granularity selected',
              ),
            },
          },
          {
            name: 'min_periods',
            config: {
              type: 'TextControl',
              label: t('Min Periods'),
              isInt: true,
              description: t(
                'The minimum number of rolling periods required to show ' +
                  'a value. For instance if you do a cumulative sum on 7 days ' +
                  'you may want your "Min Period" to be 7, so that all data points ' +
                  'shown are the total of 7 periods. This will hide the "ramp up" ' +
                  'taking place over the first 7 periods',
              ),
            },
          },
        ],
        // eslint-disable-next-line react/jsx-key
        [
{t('Time Comparison')}
],
        [
          {
            name: 'time_compare',
            config: {
              type: 'SelectControl',
              multi: true,
              freeForm: true,
              label: t('Time Shift'),
              choices: formatSelectOptions([
                '1 day',
                '1 week',
                '28 days',
                '30 days',
                '52 weeks',
                '1 year',
                '104 weeks',
                '2 years',
                '156 weeks',
                '3 years',
              ]),
              description: t(
                'Overlay one or more timeseries from a ' +
                  'relative time period. Expects relative time deltas ' +
                  'in natural language (example:  24 hours, 7 days, ' +
                  '52 weeks, 365 days). Free text is supported.',
              ),
            },
          },
          {
            name: 'comparison_type',
            config: {
              type: 'SelectControl',
              label: t('Calculation type'),
              default: 'values',
              choices: [
                ['values', 'Actual Values'],
                ['absolute', 'Difference'],
                ['percentage', 'Percentage change'],
                ['ratio', 'Ratio'],
              ],
              description: t(
                'How to display time shifts: as individual lines; as the ' +
                  'difference between the main time series and each time shift; ' +
                  'as the percentage change; or as the ratio between series and time shifts.',
              ),
            },
          },
        ],
        [
{t('Resample')}
],
        [
          {
            name: 'resample_rule',
            config: {
              type: 'SelectControl',
              freeForm: true,
              label: t('Rule'),
              default: null,
              choices: formatSelectOptions([
                '1T',
                '1H',
                '1D',
                '7D',
                '1M',
                '1AS',
              ]),
              description: t('Pandas resample rule'),
            },
          },
          {
            name: 'resample_method',
            config: {
              type: 'SelectControl',
              freeForm: true,
              label: t('Method'),
              default: null,
              choices: formatSelectOptions([
                'asfreq',
                'bfill',
                'ffill',
                'median',
                'mean',
                'sum',
              ]),
              description: t('Pandas resample method'),
            },
          },
        ],
      ],
    },
  ],
  formDataOverrides: formData => ({
    ...formData,
    groupby: getStandardizedControls().popAllColumns(),
    metrics: getStandardizedControls().popAllMetrics(),
  }),
};

export default config;


text:
<?php

class File extends Linkable
{
	const DEBUG = false;
	const TYPE  = T::FILE;

	public function getData()
	{
		return $this->getProperty()->data;
	}

	public function getLastPublishedBy()
	{
		return $this->getProperty()->lastPublishedBy;
	}

	public function getLastPublishedDate()
	{
		return $this->getProperty()->lastPublishedDate;
	}

	public function getMaintainAbsoluteLinks()
	{
		return $this->getProperty()->maintainAbsoluteLinks;
	}

	public function getRewriteLinks()
	{
		return $this->getProperty()->rewriteLinks;
	}

	public function getShouldBeIndexed()
	{
		return $this->getProperty()->shouldBeIndexed;
	}

	public function getShouldBePublished()
	{
		return $this->getProperty()->shouldBePublished;
	}

	public function getText()
	{
		return $this->getProperty()->text;
	}

	public function publish( Destination $destination=NULL )
	{
		if( $destination != NULL )
		{
			$destination_std           = new stdClass();
			$destination_std->id       = $destination->getId();
			$destination_std->type     = $destination->getType();
		}

		if( $this->getProperty()->shouldBePublished )
		{
			$service = $this->getService();
			$service->publish(
				$service->createId( $this->getType(), $this->getId() ), $destination_std );
		}
		return $this;
	}

	public function setData( $data )
	{
		$this->getProperty()->data = $data;
		return $this;
	}

	public function setMaintainAbsoluteLinks( $bool )
	{
		if( !BooleanValues::isBoolean( $bool ) )
			throw new UnacceptableValueException( "The value $required must be a boolean" );

		$this->getProperty()->maintainAbsoluteLinks = $bool;

		return $this;
	}

	public function setRewriteLinks( $bool )
	{
		if( !BooleanValues::isBoolean( $bool ) )
			throw new UnacceptableValueException( "The value $required must be a boolean" );

		$this->getProperty()->rewriteLinks = $bool;

		return $this;
	}

	public function setShouldBeIndexed( $bool )
	{
		if( !BooleanValues::isBoolean( $bool ) )
			throw new UnacceptableValueException( "The value $required must be a boolean" );

		$this->getProperty()->shouldBeIndexed = $bool;
		return $this;
	}

	public function setShouldBePublished( $bool )
	{
		if( !BooleanValues::isBoolean( $bool ) )
			throw new UnacceptableValueException( "The value $required must be a boolean" );

		$this->getProperty()->shouldBePublished = $bool;
		return $this;
	}

	public function setText( $text )
	{
		$this->getProperty()->text = $text;
		$this->getProperty()->data = $text;
		return $this;
	}
}
?>

redpajama_set_name: RedPajamaGithub


text:
#ifndef _HMM_MAP_EDITOR_ARTIFICIAL_MAP_GENERATOR_
#define _HMM_MAP_EDITOR_ARTIFICIAL_MAP_GENERATOR_

class iMapGenerator
{
public:
	iMapGenerator(iMapHandler& map)
	: m_Map(map)
	{ }

	bool Generate();

private:
	iMapHandler&	m_Map;
};

#endif //_HMM_MAP_EDITOR_ARTIFICIAL_MAP_GENERATOR_


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test if One Value is Below or At Least as Large as Another</title>

        Go to Test if One Value is Below or At Least as Large as Another and complete all steps in this
        challenge.


text:
using System;
using System.Runtime.InteropServices;

namespace Vlc.DotNet.Core.Interops.Signatures
{
    /// <summary>
    /// Get Rate at which movie is playing.
    /// </summary>
    /// <returns>Get the requested movie play rate.</returns>
    [LibVlcFunction("libvlc_media_player_get_time")]
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    internal delegate long GetTime(IntPtr mediaPlayerInstance);
}


text:
define([
  'okta',
  'util/FactorUtil',
  'util/FormController',
  'util/FormType',
  'util/RouterUtil',
  'views/enroll-factors/BarcodeView',
  'views/enroll-factors/Footer'
],
function (Okta, FactorUtil, FormController, FormType, RouterUtil, BarcodeView, Footer) {

  var _ = Okta._;

  // Note: Keep-alive is set to 5 seconds - using 5 seconds here will result
  // in network connection lost errors in Safari and IE.
  var PUSH_INTERVAL = 6000;

  return FormController.extend({
    className: 'barcode-push',
    Model: function () {
      return {
        local: {
          '__factorType__': ['string', false, this.options.factorType],
          '__provider__': ['string', false, this.options.provider]
        }
      };
    },

    Form: {
      title: function () {
        var factorName = FactorUtil.getFactorLabel(this.model.get('__provider__'), this.model.get('__factorType__'));
        return Okta.loc('enroll.totp.title', 'login', [factorName]);
      },
      subtitle: _.partial(Okta.loc, 'mfa.scanBarcode', 'login'),
      noButtonBar: true,
      attributes: { 'data-se': 'step-scan' },
      className: 'barcode-scan',
      initialize: function () {
        this.listenTo(this.model, 'error errors:clear', function () {
          this.clearErrors();
        });
      },

      formChildren: [
        FormType.View({View: BarcodeView})
      ]
    },

    Footer: Footer,

    initialize: function () {
      this.pollForEnrollment();
    },

    pollForEnrollment: function () {
      return this.model.doTransaction(function(transaction) {
        return transaction.poll(PUSH_INTERVAL);
      });
    },

    trapAuthResponse: function () {
      if (this.options.appState.get('isMfaEnrollActivate')) {
        return true;
      }
    }
  });

});


text:
#pragma once

#include "RegExp.h"
#include "JSCInlines.h"
#include "Yarr.h"
#include "YarrInterpreter.h"
#include "YarrJIT.h"

#define REGEXP_FUNC_TEST_DATA_GEN 0

#if REGEXP_FUNC_TEST_DATA_GEN
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#endif

namespace JSC {

#if REGEXP_FUNC_TEST_DATA_GEN
class RegExpFunctionalTestCollector {
    // This class is not thread safe.
protected:
    static const char* const s_fileName;

public:
    static RegExpFunctionalTestCollector* get();

    ~RegExpFunctionalTestCollector();

    void outputOneTest(RegExp*, String, int, int*, int);
    void clearRegExp(RegExp* regExp)
    {
        if (regExp == m_lastRegExp)
            m_lastRegExp = 0;
    }

private:
    RegExpFunctionalTestCollector();

    void outputEscapedString(const String&, bool escapeSlash = false);

    static RegExpFunctionalTestCollector* s_instance;
    FILE* m_file;
    RegExp* m_lastRegExp;
};
#endif // REGEXP_FUNC_TEST_DATA_GEN

ALWAYS_INLINE bool RegExp::hasCodeFor(Yarr::YarrCharSize charSize)
{
    if (hasCode()) {
#if ENABLE(YARR_JIT)
        if (m_state != JITCode)
            return true;
        if ((charSize == Yarr::Char8) && (m_regExpJITCode.has8BitCode()))
            return true;
        if ((charSize == Yarr::Char16) && (m_regExpJITCode.has16BitCode()))
            return true;
#else
        UNUSED_PARAM(charSize);
        return true;
#endif
    }
    return false;
}

ALWAYS_INLINE void RegExp::compileIfNecessary(VM& vm, Yarr::YarrCharSize charSize)
{
    if (hasCodeFor(charSize))
        return;

    compile(&vm, charSize);
}

template<typename VectorType>
ALWAYS_INLINE int RegExp::matchInline(VM& vm, const String& s, unsigned startOffset, VectorType& ovector)
{
#if ENABLE(REGEXP_TRACING)
    m_rtMatchCallCount++;
    m_rtMatchTotalSubjectStringLen += (double)(s.length() - startOffset);
#endif

    ASSERT(m_state != ParseError);
    compileIfNecessary(vm, s.is8Bit() ? Yarr::Char8 : Yarr::Char16);

    int offsetVectorSize = (m_numSubpatterns + 1) * 2;
    ovector.resize(offsetVectorSize);
    int* offsetVector = ovector.data();

    int result;
#if ENABLE(YARR_JIT)
    if (m_state == JITCode) {
        if (s.is8Bit())
            result = m_regExpJITCode.execute(s.characters8(), startOffset, s.length(), offsetVector).start;
        else
            result = m_regExpJITCode.execute(s.characters16(), startOffset, s.length(), offsetVector).start;
#if ENABLE(YARR_JIT_DEBUG)
        matchCompareWithInterpreter(s, startOffset, offsetVector, result);
#endif
    } else
#endif
        result = Yarr::interpret(m_regExpBytecode.get(), s, startOffset, reinterpret_cast<unsigned*>(offsetVector));

    // FIXME: The YARR engine should handle unsigned or size_t length matches.
    // The YARR Interpreter is "unsigned" clean, while the YARR JIT hasn't been addressed.
    // The offset vector handling needs to change as well.
    // Right now we convert a match where the offsets overflowed into match failure.
    // There are two places in WebCore that call the interpreter directly that need to
    // have their offsets changed to int as well. They are yarr/RegularExpression.cpp
    // and inspector/ContentSearchUtilities.cpp
    if (s.length() > INT_MAX) {
        bool overflowed = false;

        if (result < -1)
            overflowed = true;

        for (unsigned i = 0; i <= m_numSubpatterns; i++) {
            if ((offsetVector[i*2] < -1) || ((offsetVector[i*2] >= 0) && (offsetVector[i*2+1] < -1))) {
                overflowed = true;
                offsetVector[i*2] = -1;
                offsetVector[i*2+1] = -1;
            }
        }

        if (overflowed)
            result = -1;
    }

    ASSERT(result >= -1);

#if REGEXP_FUNC_TEST_DATA_GEN
    RegExpFunctionalTestCollector::get()->outputOneTest(this, s, startOffset, offsetVector, result);
#endif

#if ENABLE(REGEXP_TRACING)
    if (result != -1)
        m_rtMatchFoundCount++;
#endif

    return result;
}

ALWAYS_INLINE bool RegExp::hasMatchOnlyCodeFor(Yarr::YarrCharSize charSize)
{
    if (hasCode()) {
#if ENABLE(YARR_JIT)
        if (m_state != JITCode)
            return true;
        if ((charSize == Yarr::Char8) && (m_regExpJITCode.has8BitCodeMatchOnly()))
            return true;
        if ((charSize == Yarr::Char16) && (m_regExpJITCode.has16BitCodeMatchOnly()))
            return true;
#else
        UNUSED_PARAM(charSize);
        return true;
#endif
    }

    return false;
}

ALWAYS_INLINE void RegExp::compileIfNecessaryMatchOnly(VM& vm, Yarr::YarrCharSize charSize)
{
    if (hasMatchOnlyCodeFor(charSize))
        return;

    compileMatchOnly(&vm, charSize);
}

ALWAYS_INLINE MatchResult RegExp::matchInline(VM& vm, const String& s, unsigned startOffset)
{
#if ENABLE(REGEXP_TRACING)
    m_rtMatchOnlyCallCount++;
    m_rtMatchOnlyTotalSubjectStringLen += (double)(s.length() - startOffset);
#endif

    ASSERT(m_state != ParseError);
    compileIfNecessaryMatchOnly(vm, s.is8Bit() ? Yarr::Char8 : Yarr::Char16);

#if ENABLE(YARR_JIT)
    if (m_state == JITCode) {
        MatchResult result = s.is8Bit() ?
            m_regExpJITCode.execute(s.characters8(), startOffset, s.length()) :
            m_regExpJITCode.execute(s.characters16(), startOffset, s.length());
#if ENABLE(REGEXP_TRACING)
        if (!result)
            m_rtMatchOnlyFoundCount++;
#endif
        return result;
    }
#endif

    int offsetVectorSize = (m_numSubpatterns + 1) * 2;
    int* offsetVector;
    Vector<int, 32> nonReturnedOvector;
    nonReturnedOvector.resize(offsetVectorSize);
    offsetVector = nonReturnedOvector.data();
    int r = Yarr::interpret(m_regExpBytecode.get(), s, startOffset, reinterpret_cast<unsigned*>(offsetVector));
#if REGEXP_FUNC_TEST_DATA_GEN
    RegExpFunctionalTestCollector::get()->outputOneTest(this, s, startOffset, offsetVector, result);
#endif

    if (r >= 0) {
#if ENABLE(REGEXP_TRACING)
        m_rtMatchOnlyFoundCount++;
#endif
        return MatchResult(r, reinterpret_cast<unsigned*>(offsetVector)[1]);
    }

    return MatchResult::failed();
}

} // namespace JSC


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

    <item android:drawable="@drawable/dk_suspension_item_right_normal" android:state_pressed="true"></item>
    <item android:drawable="@drawable/dk_suspension_item_right_press"></item>
	<!-- <item android:drawable="@drawable/dk_suspension_item_right_press" android:state_pressed="true"></item>
    <item android:drawable="@drawable/dk_suspension_item_right_normal"></item> -->
</selector>


text:
package sftp

import (
	"io/ioutil"
	"math/rand"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/graymeta/stow"
	"github.com/graymeta/stow/test"
	"github.com/stretchr/testify/require"
)

func TestStow(t *testing.T) {
	config := stow.ConfigMap{
		ConfigHost:     os.Getenv("SFTP_HOST"),
		ConfigPort:     os.Getenv("SFTP_PORT"),
		ConfigUsername: os.Getenv("SFTP_USERNAME"),
	}
	if config[ConfigHost] == "" ||
		config[ConfigPort] == "" ||
		config[ConfigUsername] == "" {
		t.Skip("skipping tests because environment isn't configured")
	}

	b, err := ioutil.ReadFile(os.Getenv("SFTP_PRIVATE_KEY_FILE"))
	require.NoError(t, err)
	config[ConfigPrivateKey] = string(b)
	config[ConfigPrivateKeyPassphrase] = os.Getenv("SFTP_PRIVATE_KEY_PASSPHRASE")

	t.Run("stow_tests", func(t *testing.T) {
		test.All(t, Kind, config)
	})

	t.Run("additional_tests", func(t *testing.T) {
		location, err := stow.Dial(Kind, config)
		require.NoError(t, err)
		defer location.Close()

		t.Run("set of files 1", func(t *testing.T) {
			cont, err := location.CreateContainer("stowtest" + randName(10))
			require.NoError(t, err)
			defer location.RemoveContainer(cont.ID())

			files := []string{
				"a.jpg",
				"bar/a.jpg",
				"bar/b.jpg",
				"bar/baz/a.jpg",
				"bar/baz/b.jpg",
				"foo/a.jpg",
				"foo/b.jpg",
				"z.jpg",
			}

			setupFiles(t, cont, files)

			t.Run("no prefix, no cursor, len 4", func(t *testing.T) {
				items, cursor, err := cont.Items("", "", 4)
				require.NoError(t, err)
				require.Len(t, items, 4)
				require.Equal(t, files[0], items[0].ID())
				require.Equal(t, files[1], items[1].ID())
				require.Equal(t, files[2], items[2].ID())
				require.Equal(t, files[3], items[3].ID())
				require.Equal(t, cursor, "bar/baz/a.jpg")
			})

			t.Run("no prefix, no cursor, len 5", func(t *testing.T) {
				items, cursor, err := cont.Items("", "", 5)
				require.NoError(t, err)
				require.Len(t, items, 5)
				require.Equal(t, files[0], items[0].ID())
				require.Equal(t, files[1], items[1].ID())
				require.Equal(t, files[2], items[2].ID())
				require.Equal(t, files[3], items[3].ID())
				require.Equal(t, files[4], items[4].ID())
				require.Equal(t, cursor, "bar/baz/b.jpg")
			})

			t.Run("no prefix, no cursor, len 100", func(t *testing.T) {
				items, cursor, err := cont.Items("", "", 100)
				require.NoError(t, err)
				require.Len(t, items, len(files))
				require.Equal(t, "", cursor)
			})

			t.Run("no prefix, with cursor, len 100", func(t *testing.T) {
				items, cursor, err := cont.Items("", "bar/baz/a.jpg", 100)
				require.NoError(t, err)
				require.Len(t, items, 4)
				require.Equal(t, "", cursor)
			})
		})

		t.Run("set of files 2", func(t *testing.T) {
			cont, err := location.CreateContainer("stowtest" + randName(10))
			require.NoError(t, err)
			defer location.RemoveContainer(cont.ID())

			files := []string{
				"bar/baz/a.jpg",
				"bar/baz/b.jpg",
				"bar/baz/c.jpg",
				"bar/baz/d.jpg",
				"bar/baz/e.jpg",
			}

			setupFiles(t, cont, files)

			t.Run("no prefix, no cursor, len 3", func(t *testing.T) {
				items, cursor, err := cont.Items("", "", 3)
				require.NoError(t, err)
				require.Len(t, items, 3)
				require.Equal(t, files[2], cursor)
			})

			t.Run("no prefix, no cursor, len 5", func(t *testing.T) {
				items, cursor, err := cont.Items("", "", 5)
				require.NoError(t, err)
				require.Len(t, items, 5)
				require.Equal(t, "", cursor)
			})

			t.Run("no prefix, with cursor, len 5", func(t *testing.T) {
				items, cursor, err := cont.Items("", "bar/baz/b.jpg", 5)
				require.NoError(t, err)
				require.Len(t, items, 3)
				require.Equal(t, "", cursor)
			})

			t.Run("no prefix, with cursor (a), len 5", func(t *testing.T) {
				items, cursor, err := cont.Items("", "a", 5)
				require.NoError(t, err)
				require.Len(t, items, 5)
				require.Equal(t, "", cursor)
			})
		})
	})

	t.Run("stow_tests - with base path", func(t *testing.T) {
		basePath := os.Getenv("SFTP_BASEPATH")
		if basePath == "" {
			t.Skip("skipping base paths test due to SFTP_BASEPATH not being set")
		}
		config[ConfigBasePath] = basePath
		test.All(t, Kind, config)
	})
}

func setupFiles(t *testing.T, c stow.Container, files []string) {
	for _, file := range files {
		_, err := c.Put(file, strings.NewReader(""), 0, nil)
		require.NoError(t, err)
	}
}

var letters = []rune("abcdefghijklmnopqrstuvwxyz")

func init() {
	rand.Seed(int64(time.Now().Nanosecond()))
}

func randName(length int) string {
	b := make([]rune, length)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}


text:
package org.littlewings.javaee7.bitronix

import bitronix.tm.TransactionManagerServices
import org.littlewings.javaee7.standalonejta.StandaloneJtaSpecSupport

class BitronixJtaSpec extends StandaloneJtaSpecSupport {
  // Init Bitronix
  override def beforeAll(): Unit =
    TransactionManagerServices.getResourceLoader.init()
}


text:
#ifndef __CCApplication_h__
#define __CCApplication_h__

#include "ccMacros.h"
#include <string>

#define COCOS2D_ENGINE_LAUNCH( _MODE_ )								\
XM_APP_MAIN_BEGIN													\
	XM_APP_PROPERTY_SET;											\
	xmRealizeWindow ( XM_OPEN_GL_MODE | _MODE_, &ccEventProc );	    \
XM_APP_MAIN_END

KD_API KDvoid KD_APIENTRY  ccEventProc ( const KDEvent* pEvent );

NS_CC_BEGIN

/**
 *	@brief Enum the language type supported now
 */
typedef enum LanguageType
{
    kCCLanguageEnglish	= 0	,
    kCCLanguageChinese		,
    kCCLanguageFrench		,
    kCCLanguageItalian		,
    kCCLanguageGerman		,
    kCCLanguageSpanish		,
    kCCLanguageRussian		,
    kCCLanguageKorean		,
} ccLanguageType;

typedef enum TargetPlatform
{
	kCCTargetWindows		,
	kCCTargetLinux			,
	kCCTargetMacOS			,
	kCCTargetAndroid		,
	kCCTargetIphone			,
	kCCTargetIpad			,
	kCCTargetBlackBerry		,
	kCCTargetNaCl			,
	kCCTargetEmscripten		,
	kCCTargetTizen			,
	kCCTargetWinRT			,
	kCCTargetWP8			,
	kCCTargetWince			,
	kCCTargetBada			,
	kCCTargetUnknown		,
} ccTargetPlatform;

class CCApplicationProtocol
{
	public :

		/**
		 *	@brief  Implement CCDirector and CCScene init code here.
		 *	@return true    Initialize success, app continue.
		 *	@return false   Initialize failed, app terminate.
		 */
		virtual KDbool			applicationDidFinishLaunching ( KDvoid ) = 0;

		/**
		 *	@brief  The function be called when the application will ternimate
		 *	@param  the pointer of the application
		 */
		virtual	KDvoid			applicationWillTerminate ( KDvoid ) = 0;

		/**
		 *	@brief  The function be called when the application enter background
		 *	@param  the pointer of the application
		 */
		virtual KDvoid			applicationDidEnterBackground ( KDvoid ) = 0;

		/**
		 *	@brief  The function be called when the application enter foreground
		 *	@param  the pointer of the application
		 */
		virtual KDvoid			applicationWillEnterForeground ( KDvoid ) = 0;
};

class CCApplication : public CCApplicationProtocol
{
	protected :

		CCApplication ( KDvoid );

	public :

		static CCApplication*	sharedApplication ( KDvoid );

	public :

		const KDchar*			getVersion ( KDvoid );

		ccLanguageType			getCurrentLanguage ( KDvoid );

		/** Get target platform */
		ccTargetPlatform		getTargetPlatform  ( KDvoid );

		/* set the Resource root path */
		KDvoid					setResourceRootPath ( const KDchar* szRootResDir );

		/* get the Resource root path */
		const std::string&		getResourceRootPath ( KDvoid );

		KDvoid					setStartupScriptFilename ( const KDchar* szStartupScriptFile );

		const std::string&		getStartupScriptFilename ( KDvoid );

	protected :

		std::string				m_sStartupScriptFilename;
		std::string				m_sResourceRootPath;
};

class AppDelegate : public CCApplication
{
	public :

		virtual	KDbool			applicationDidFinishLaunching	( KDvoid );

		virtual KDvoid			applicationWillTerminate		( KDvoid );

		virtual KDvoid			applicationWillEnterForeground	( KDvoid );

		virtual KDvoid			applicationDidEnterBackground	( KDvoid );
};

NS_CC_END

#endif // __CCApplication_h__


text:
#include <aws/meteringmarketplace/model/BatchMeterUsageResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::MarketplaceMetering::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

BatchMeterUsageResult::BatchMeterUsageResult()
{
}

BatchMeterUsageResult::BatchMeterUsageResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

BatchMeterUsageResult& BatchMeterUsageResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("Results"))
  {
    Aws::Utils::Array<JsonView> resultsJsonList = jsonValue.GetArray("Results");
    for(unsigned resultsIndex = 0; resultsIndex < resultsJsonList.GetLength(); ++resultsIndex)
    {
      m_results.push_back(resultsJsonList[resultsIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("UnprocessedRecords"))
  {
    Aws::Utils::Array<JsonView> unprocessedRecordsJsonList = jsonValue.GetArray("UnprocessedRecords");
    for(unsigned unprocessedRecordsIndex = 0; unprocessedRecordsIndex < unprocessedRecordsJsonList.GetLength(); ++unprocessedRecordsIndex)
    {
      m_unprocessedRecords.push_back(unprocessedRecordsJsonList[unprocessedRecordsIndex].AsObject());
    }
  }

  return *this;
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/datalabeling/v1beta1/annotation.proto

package com.google.cloud.datalabeling.v1beta1;

public interface AnnotationOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.datalabeling.v1beta1.Annotation)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Output only. Unique name of this annotation, format is:
   * projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/{annotated_dataset}/examples/{example_id}/annotations/{annotation_id}
   *

   *
   * string name = 1;
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Output only. Unique name of this annotation, format is:
   * projects/{project_id}/datasets/{dataset_id}/annotatedDatasets/{annotated_dataset}/examples/{example_id}/annotations/{annotation_id}
   *

   *
   * string name = 1;
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * Output only. The source of the annotation.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationSource annotation_source = 2;
   *
   * @return The enum numeric value on the wire for annotationSource.
   */
  int getAnnotationSourceValue();
  /**
   *
   *
   *

   * Output only. The source of the annotation.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationSource annotation_source = 2;
   *
   * @return The annotationSource.
   */
  com.google.cloud.datalabeling.v1beta1.AnnotationSource getAnnotationSource();

  /**
   *
   *
   *

   * Output only. This is the actual annotation value, e.g classification,
   * bounding box values are stored here.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationValue annotation_value = 3;
   *
   * @return Whether the annotationValue field is set.
   */
  boolean hasAnnotationValue();
  /**
   *
   *
   *

   * Output only. This is the actual annotation value, e.g classification,
   * bounding box values are stored here.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationValue annotation_value = 3;
   *
   * @return The annotationValue.
   */
  com.google.cloud.datalabeling.v1beta1.AnnotationValue getAnnotationValue();
  /**
   *
   *
   *

   * Output only. This is the actual annotation value, e.g classification,
   * bounding box values are stored here.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationValue annotation_value = 3;
   */
  com.google.cloud.datalabeling.v1beta1.AnnotationValueOrBuilder getAnnotationValueOrBuilder();

  /**
   *
   *
   *

   * Output only. Annotation metadata, including information like votes
   * for labels.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationMetadata annotation_metadata = 4;
   *
   * @return Whether the annotationMetadata field is set.
   */
  boolean hasAnnotationMetadata();
  /**
   *
   *
   *

   * Output only. Annotation metadata, including information like votes
   * for labels.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationMetadata annotation_metadata = 4;
   *
   * @return The annotationMetadata.
   */
  com.google.cloud.datalabeling.v1beta1.AnnotationMetadata getAnnotationMetadata();
  /**
   *
   *
   *

   * Output only. Annotation metadata, including information like votes
   * for labels.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationMetadata annotation_metadata = 4;
   */
  com.google.cloud.datalabeling.v1beta1.AnnotationMetadataOrBuilder
      getAnnotationMetadataOrBuilder();

  /**
   *
   *
   *

   * Output only. Sentiment for this annotation.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationSentiment annotation_sentiment = 6;
   *
   * @return The enum numeric value on the wire for annotationSentiment.
   */
  int getAnnotationSentimentValue();
  /**
   *
   *
   *

   * Output only. Sentiment for this annotation.
   *

   *
   * .google.cloud.datalabeling.v1beta1.AnnotationSentiment annotation_sentiment = 6;
   *
   * @return The annotationSentiment.
   */
  com.google.cloud.datalabeling.v1beta1.AnnotationSentiment getAnnotationSentiment();
}


text:
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation.Provider;
using System.Reflection;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using Pash.Implementation;
using Pash.ParserIntrinsics;
using Irony.Parsing;
using System.IO;
using System.Management.Automation.Language;
using Extensions.Enumerable;

namespace Pash.Implementation
{
    internal class CommandManager
    {
        public struct SnapinProviderPair
        {
            public PSSnapInInfo snapinInfo;
            public Type providerType;
            public CmdletProviderAttribute providerAttr;
        }

        private Dictionary<string, PSSnapInInfo> _snapins;
        private Dictionary<string, List<CmdletInfo>> _cmdLets;
        private Dictionary<string, ScriptInfo> _scripts;
        private Dictionary<string, AliasInfo> _aliases;
        internal Collection<SnapinProviderPair> _providers;
        private ExecutionContext _context;

        public CommandManager()
            : this(null)
        {
        }

        public CommandManager(ExecutionContext context)
        {
            _context = context;

            _snapins = new Dictionary<string, PSSnapInInfo>(StringComparer.CurrentCultureIgnoreCase);
            _cmdLets = new Dictionary<string, List<CmdletInfo>>(StringComparer.CurrentCultureIgnoreCase);
            _scripts = new Dictionary<string, ScriptInfo>(StringComparer.CurrentCultureIgnoreCase);
            _aliases = new Dictionary<string, AliasInfo>(StringComparer.CurrentCultureIgnoreCase);
            _providers = new Collection<SnapinProviderPair>();

            // if no execution scope is provided load all the initial settings from the config file
            if (context == null)
            {
                // TODO: move this to config.ps1
                foreach (var snapinTypeName in new[] {
                    "System.Management.Automation.PSCorePSSnapIn, System.Management.Automation",
                    "Microsoft.PowerShell.PSUtilityPSSnapIn, Microsoft.PowerShell.Commands.Utility",
                    "Microsoft.Commands.Management.PSManagementPSSnapIn, Microsoft.PowerShell.Commands.Management",
                })
                {
                    var tmpProviders = new Collection<SnapinProviderPair>();

                    // Load all PSSnapin's
                    foreach (CmdletInfo cmdLetInfo in LoadCmdletsFromPSSnapin(snapinTypeName, out tmpProviders))
                    {
                        // Register PSSnapin
                        if (_snapins.ContainsKey(cmdLetInfo.PSSnapIn.Name))
                        {
                            _snapins.Add(cmdLetInfo.PSSnapIn.Name, cmdLetInfo.PSSnapIn);
                        }

                        // Copy all the found Cmdlets
                        List<CmdletInfo> cmdletList = null;
                        if (_cmdLets.ContainsKey(cmdLetInfo.Name))
                        {
                            cmdletList = _cmdLets[cmdLetInfo.Name];
                        }
                        else
                        {
                            cmdletList = new List<CmdletInfo>();
                            _cmdLets.Add(cmdLetInfo.Name, cmdletList);
                        }
                        cmdletList.Add(cmdLetInfo);
                    }

                    foreach (SnapinProviderPair providerTypePair in tmpProviders)
                    {
                        _providers.Add(providerTypePair);
                    }
                }
            }
        }

        public void SetAlias(string name, string definition)
        {
            if (this._aliases.ContainsKey(name))
                this._aliases[name] = new AliasInfo(name, definition, this);
            else
                NewAlias(name, definition);
        }

        public void NewAlias(string name, string definition)
        {
            if (this._aliases.ContainsKey(name)) throw new Exception("duplicate alias");
            AliasInfo aliasInfo = new AliasInfo(name, definition, this);

            _aliases.Add(aliasInfo.Name, aliasInfo);
        }

        private void LoadScripts()
        {
            foreach (ScriptConfigurationEntry entry in _context.RunspaceConfiguration.Scripts)
            {
                try
                {
                    _scripts.Add(entry.Name, new ScriptInfo(entry.Name, new ScriptBlock(PowerShellGrammar.ParseInteractiveInput(entry.Definition))));
                    continue;
                }
                catch
                {
                    throw new Exception("DuplicateScriptName: " + entry.Name);
                }
            }
        }

        public CommandProcessorBase CreateCommandProcessor(Command command)
        {
            string cmdName = command.CommandText;

            CommandInfo commandInfo = null;

            if (command.CommandText == null)
            {
                commandInfo = new ScriptInfo("", command.ScriptBlockAst.GetScriptBlock());
            }

            if (command.IsScript)
            {
                // TODO: take care of the script commands
                throw new NotImplementedException(this.ToString());
            }

            if (commandInfo == null && _aliases.ContainsKey(cmdName))
            {
                commandInfo = _aliases[cmdName].ReferencedCommand;
            }

            if (commandInfo == null && _cmdLets.ContainsKey(cmdName))
            {
                commandInfo = _cmdLets[cmdName].First();
            }

            if (commandInfo == null && _scripts.ContainsKey(cmdName))
            {
                commandInfo = _scripts[cmdName];
            }

            // TODO: if the command wasn't found should we treat is as a Script?
            if (commandInfo == null)
            {
                var parseTree = PowerShellGrammar.ParseInteractiveInput(command.CommandText);
                var statements = parseTree.EndBlock.Statements;
                if (statements.Count == 1 && statements.Single() is PipelineAst)
                {
                    var pipelineAst = statements.Single() as PipelineAst;
                    if (pipelineAst.PipelineElements.Count == 1 && pipelineAst.PipelineElements.Single() is CommandAst)
                    {
                        var commandAst = pipelineAst.PipelineElements.Single() as CommandAst;
                        if (commandAst.CommandElements.Count == 1 && commandAst.CommandElements.Single() is StringConstantExpressionAst)
                        {
                            var stringAst = commandAst.CommandElements.Single() as StringConstantExpressionAst;

                            if (File.Exists(stringAst.Value) && Path.GetExtension(stringAst.Value) == ".ps1")
                            {
                                // I think we should be using a ScriptFile parser, but this will do for now.
                                commandInfo = new ScriptInfo(stringAst.Value, new ScriptBlock(PowerShellGrammar.ParseInteractiveInput(File.ReadAllText(stringAst.Value))));
                            }

                            else
                            {
                                throw new Exception(string.Format("Command '{0}' not found.", cmdName));
                            }
                        }
                    }
                }

                if (commandInfo == null)
                    commandInfo = new ScriptInfo("", new ScriptBlock(parseTree));
            }

            if (commandInfo != null)
            {
                switch (commandInfo.CommandType)
                {
                    case CommandTypes.Cmdlet:
                        return new CommandProcessor(commandInfo as CmdletInfo);

                    case CommandTypes.Function:
                        // TODO: teat the function as a script
                        break;

                    case CommandTypes.Script:
                        return new ScriptProcessor(commandInfo as ScriptInfo);
                }
            }

            throw new Exception(string.Format("Command '{0}' not found.", cmdName));
        }

        internal CommandInfo FindCommand(string command)
        {
            // TODO: find the CommandInfo from CommandManager

            List<CmdletInfo> cmdletsList;
            if (_cmdLets.TryGetValue(command, out cmdletsList))
            {
                if (cmdletsList.Count > 0)
                    return cmdletsList[0];
            }

            ScriptInfo scriptInfo;
            if (_scripts.TryGetValue(command, out scriptInfo))
                return scriptInfo;

            AliasInfo aliasInfo;
            if (_aliases.TryGetValue(command, out aliasInfo))
                return aliasInfo;

            // TODO: search functions (in a context?)

            return null;
        }

        internal IEnumerable<CommandInfo> FindCommands(string pattern)
        {
            return from List<CmdletInfo> cmdletInfoList in _cmdLets.Values
                   from CmdletInfo info in cmdletInfoList
                   select info;
        }

        // TODO: separate providers from cmdlets
        internal Collection<CmdletInfo> LoadCmdletsFromPSSnapin(string strType, out Collection<SnapinProviderPair> providers)
        {
            Type snapinType = Type.GetType(strType, true);
            Assembly assembly = snapinType.Assembly;

            PSSnapIn snapin = Activator.CreateInstance(snapinType) as PSSnapIn;

            PSSnapInInfo snapinInfo = new PSSnapInInfo(snapin.Name, false, string.Empty, assembly.GetName().Name, string.Empty, new Version(1, 0), null, null, null, snapin.Description, snapin.Vendor);

            var snapinProviderPairs = from Type type in assembly.GetTypes()
                                      where !type.IsSubclassOf(typeof(Cmdlet))
                                      where type.IsSubclassOf(typeof(CmdletProvider))
                                      from CmdletProviderAttribute providerAttr in type.GetCustomAttributes(typeof(CmdletProviderAttribute), true)
                                      select new SnapinProviderPair
                                        {
                                            snapinInfo = snapinInfo,
                                            providerType = type,
                                            providerAttr = providerAttr
                                        };

            providers = snapinProviderPairs.ToCollection();

            var cmdletInfos = from Type type in assembly.GetTypes()
                              where type.IsSubclassOf(typeof(Cmdlet))
                              from CmdletAttribute cmdletAttribute in type.GetCustomAttributes(typeof(CmdletAttribute), true)
                              select new CmdletInfo(cmdletAttribute.FullName, type, null, snapinInfo, _context);

            return cmdletInfos.ToCollection();
        }

        // HACK: all functions are currently stored as scripts. But I'm confused, so I don't know how to fix it.
        internal void SetFunction(/*FunctionInfo */ScriptInfo functionInfo)
        {
            this._scripts[functionInfo.Name] = functionInfo;
        }
    }

}


text:
@interface ANTLRTreeVisitor : NSObject {
   id<ANTLRTreeAdaptor> adaptor;
}
+ (ANTLRTreeVisitor *)newANTLRTreeVisitor:(id<ANTLRTreeAdaptor>) anAdaptor;
+ (ANTLRTreeVisitor *)newANTLRTreeVisitor;
- (id)init;
- (id)initWithAdaptor:(id<ANTLRTreeAdaptor>)anAdaptor;
- (ANTLRTreeVisitor *)visit:(id<ANTLRTree>)t Action:(ANTLRTreeVisitorAction *)action;

@end


text:
package org.apache.johnzon.core;

import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonStructure;
import javax.json.JsonValue;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParsingException;

public class JsonReaderImpl implements JsonReader {
    private final JohnzonJsonParser parser;
    private boolean closed = false;

    private boolean subStreamReader;

    public JsonReaderImpl(final JsonParser parser) {
        this(parser, false);
    }

    /**
     *
     * @param parser
     * @param subStreamReader {@code true} if the Stream already got started and the first
     *           operation should not be next() but {@link JohnzonJsonParser#current()} instead.
     */
    public JsonReaderImpl(final JsonParser parser, boolean subStreamReader) {
        if (parser instanceof JohnzonJsonParser) {
            this.parser = (JohnzonJsonParser) parser;
        } else {
            this.parser = new JohnzonJsonParser.JohnzonJsonParserWrapper(parser);
        }

        this.subStreamReader = subStreamReader;
    }

    @Override
    public JsonStructure read() {
        return JsonStructure.class.cast(readValue());
    }

    @Override
    public JsonValue readValue() {
        checkClosed();

        if (!parser.hasNext()) {
            throw new IllegalStateException("Nothing to read");
        }

        JsonParser.Event next;
        if (subStreamReader) {
            next = parser.current();
        } else {
            next = parser.next();
        }

        switch (next) {
            case START_OBJECT:
                final JsonObjectBuilder objectBuilder = new JsonObjectBuilderImpl();
                parseObject(objectBuilder);
                if (!subStreamReader) {
                    if (parser.hasNext()) {
                        throw new JsonParsingException("Expected end of file", parser.getLocation());
                    }
                    close();
                }
                return objectBuilder.build();
            case START_ARRAY:
                final JsonArrayBuilder arrayBuilder = new JsonArrayBuilderImpl();
                parseArray(arrayBuilder);
                if (!subStreamReader) {
                    if (parser.hasNext()) {
                        throw new JsonParsingException("Expected end of file", parser.getLocation());
                    }
                    close();
                }
                return arrayBuilder.build();
            case VALUE_STRING:
                final JsonStringImpl string = new JsonStringImpl(parser.getString());
                if (!subStreamReader) {
                    if (parser.hasNext()) {
                        throw new JsonParsingException("Expected end of file", parser.getLocation());
                    }
                    close();
                }
                return string;
            case VALUE_FALSE:
                if (!subStreamReader) {
                    if (parser.hasNext()) {
                        throw new JsonParsingException("Expected end of file", parser.getLocation());
                    }
                    close();
                }
                return JsonValue.FALSE;
            case VALUE_TRUE:
                if (!subStreamReader) {
                    if (parser.hasNext()) {
                        throw new JsonParsingException("Expected end of file", parser.getLocation());
                    }
                    close();
                }
                return JsonValue.TRUE;
            case VALUE_NULL:
                if (!subStreamReader) {
                    if (parser.hasNext()) {
                        throw new JsonParsingException("Expected end of file", parser.getLocation());
                    }
                    close();
                }
                return JsonValue.NULL;
            case VALUE_NUMBER:
                final JsonNumber number = new JsonNumberImpl(parser.getBigDecimal());
                if (!subStreamReader) {
                    if (parser.hasNext()) {
                        throw new JsonParsingException("Expected end of file", parser.getLocation());
                    }
                    close();
                }
                return number;
            default:
                close();
                throw new JsonParsingException("Unknown structure: " + next, parser.getLocation());
        }
    }

    @Override
    public JsonObject readObject() {
        final JsonStructure read = read();
        checkType(JsonObject.class, read);
        return JsonObject.class.cast(read);
    }

    @Override
    public JsonArray readArray() {
        final JsonStructure read = read();
        checkType(JsonArray.class, read);
        return JsonArray.class.cast(read);
    }

    private void checkType(final Class<?> expected, final JsonStructure read) {
        if (!expected.isInstance(read)) {
            throw new JsonParsingException("Expecting " + expected + " but got " + read, parser.getLocation());
        }
    }

    @Override
    public void close() {

        if (!closed) {
            closed = true;
            parser.close();
        }

    }

    private void parseObject(final JsonObjectBuilder builder) {
        String key = null;
        while (parser.hasNext()) {
            final JsonParser.Event next = parser.next();
            switch (next) {
                case KEY_NAME:
                    key = parser.getString();
                    break;

                case VALUE_STRING:
                    builder.add(key, new JsonStringImpl(parser.getString()));
                    break;

                case START_OBJECT:
                    JsonObjectBuilder subObject = null;
                    parseObject(subObject = new JsonObjectBuilderImpl());
                    builder.add(key, subObject);
                    break;

                case START_ARRAY:
                    JsonArrayBuilder subArray = null;
                    parseArray(subArray = new JsonArrayBuilderImpl());
                    builder.add(key, subArray);
                    break;

                case VALUE_NUMBER:
                    if (parser.isIntegralNumber() && parser.isNotTooLong()) {
                        builder.add(key, new JsonLongImpl(parser.getLong()));
                    } else {
                        builder.add(key, new JsonNumberImpl(parser.getBigDecimal()));
                    }
                    break;

                case VALUE_NULL:
                    builder.addNull(key);
                    break;

                case VALUE_TRUE:
                    builder.add(key, true);
                    break;

                case VALUE_FALSE:
                    builder.add(key, false);
                    break;

                case END_OBJECT:
                    return;

                case END_ARRAY:
                    throw new JsonParsingException("']', shouldn't occur", parser.getLocation());

                default:
                    throw new JsonParsingException(next.name() + ", shouldn't occur", parser.getLocation());
            }
        }
    }

    private void parseArray(final JsonArrayBuilder builder) {
        while (parser.hasNext()) {
            final JsonParser.Event next = parser.next();
            switch (next) {
                case VALUE_STRING:
                    builder.add(new JsonStringImpl(parser.getString()));
                    break;

                case VALUE_NUMBER:
                    if (parser.isIntegralNumber()) {
                        builder.add(new JsonLongImpl(parser.getLong()));
                    } else {
                        builder.add(new JsonNumberImpl(parser.getBigDecimal()));
                    }
                    break;

                case START_OBJECT:
                    JsonObjectBuilder subObject = null;
                    parseObject(subObject = new JsonObjectBuilderImpl());
                    builder.add(subObject);
                    break;

                case START_ARRAY:
                    JsonArrayBuilder subArray = null;
                    parseArray(subArray = new JsonArrayBuilderImpl());
                    builder.add(subArray);
                    break;

                case END_ARRAY:
                    return;

                case VALUE_NULL:
                    builder.addNull();
                    break;

                case VALUE_TRUE:
                    builder.add(true);
                    break;

                case VALUE_FALSE:
                    builder.add(false);
                    break;

                case KEY_NAME:
                    throw new JsonParsingException("array doesn't have keys", parser.getLocation());

                case END_OBJECT:
                    throw new JsonParsingException("'}', shouldn't occur", parser.getLocation());

                default:
                    throw new JsonParsingException(next.name() + ", shouldn't occur", parser.getLocation());
            }
        }
    }

    private void checkClosed() {
        if (closed) {
            throw new IllegalStateException("read(), readObject(), readArray() or close() method was already called");
        }

    }
}


text:
"""
Example that displays how to switch between Emacs and Vi input mode.

"""
from prompt_toolkit import prompt
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.styles import style_from_dict
from prompt_toolkit.token import Token

def run():
    # Create a set of key bindings that have Vi mode enabled if the
    # ``vi_mode_enabled`` is True..
    manager = KeyBindingManager.for_prompt()

    # Add an additional key binding for toggling this flag.
    @manager.registry.add_binding(Keys.F4)
    def _(event):
        " Toggle between Emacs and Vi mode. "
        if event.cli.editing_mode == EditingMode.VI:
            event.cli.editing_mode = EditingMode.EMACS
        else:
            event.cli.editing_mode = EditingMode.VI

    # Add a bottom toolbar to display the status.
    style = style_from_dict({
        Token.Toolbar: 'reverse',
    })

    def get_bottom_toolbar_tokens(cli):
        " Display the current input mode. "
        text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
        return [
            (Token.Toolbar, ' [F4] %s ' % text)
        ]

    prompt('> ', key_bindings_registry=manager.registry,
           get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
           style=style)

if __name__ == '__main__':
    run()


text:
package net.spy.memcached.protocol.ascii;

import java.nio.ByteBuffer;

import net.spy.memcached.ops.NoopOperation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatusCode;
import net.spy.memcached.ops.VersionOperation;

/**
 * Operation to request the version of a client server.
 */
final class VersionOperationImpl extends OperationImpl implements
    VersionOperation, NoopOperation {

  private static final byte[] REQUEST = "version\r\n".getBytes();

  public VersionOperationImpl(OperationCallback c) {
    super(c);
  }

  @Override
  public void handleLine(String line) {
    assert line.startsWith("VERSION ");
    getCallback().receivedStatus(new OperationStatus(true,
      line.substring("VERSION ".length()), StatusCode.SUCCESS));
    transitionState(OperationState.COMPLETE);
  }

  @Override
  public void initialize() {
    setBuffer(ByteBuffer.wrap(REQUEST));
  }

  @Override
  public String toString() {
    return "Cmd: version";
  }
}


text:
require "config"
require "ast"

#
# "Optimization" passes. These are used to lower the representation for
# backends that cannot handle some of our higher-level instructions.
#

#
# A temporary - a variable that will be allocated to a register after we're
# done.
#

class Node
    def replaceTemporariesWithRegisters(kind)
        mapChildren {
            | node |
            node.replaceTemporariesWithRegisters(kind)
        }
    end
end

class Tmp < NoChildren
    attr_reader :firstMention, :lastMention
    attr_reader :kind
    attr_accessor :register

    def initialize(codeOrigin, kind)
        super(codeOrigin)
        @kind = kind
    end

    def dump
        "$tmp#{object_id}"
    end

    def mention!(position)
        if not @firstMention or position < @firstMention
            @firstMention = position
        end
        if not @lastMention or position > @lastMention
            @lastMention = position
        end
    end

    def replaceTemporariesWithRegisters(kind)
        if @kind == kind
            raise "Did not allocate register to temporary at #{codeOriginString}" unless @register
            @register
        else
            self
        end
    end

    def address?
        false
    end

    def label?
        false
    end

    def immediate?
        false
    end

    def register?
        true
    end
end

# Assign registers to temporaries, by finding which temporaries interfere
# with each other. Note that this relies on temporary live ranges not crossing
# basic block boundaries.

def assignRegistersToTemporaries(list, kind, registers)
    list.each_with_index {
        | node, index |
        node.filter(Tmp).uniq.each {
            | tmp |
            if tmp.kind == kind
                tmp.mention! index
            end
        }
    }

    freeRegisters = registers.dup
    list.each_with_index {
        | node, index |
        tmpList = node.filter(Tmp).uniq
        tmpList.each {
            | tmp |
            if tmp.kind == kind and tmp.firstMention == index
                raise "Could not allocate register to temporary at #{node.codeOriginString}" if freeRegisters.empty?
                tmp.register = freeRegisters.pop
            end
        }
        tmpList.each {
            | tmp |
            if tmp.kind == kind and tmp.lastMention == index
                freeRegisters.push tmp.register
                raise "Register allocation inconsistency at #{node.codeOriginString}" if freeRegisters.size > registers.size
            end
        }
    }

    list.map {
        | node |
        node.replaceTemporariesWithRegisters(kind)
    }
end


text:
import logging

# Default logger
fallbackLogger = logging.getLogger('large_image')
fallbackLogger.setLevel(logging.INFO)
fallbackLogHandler = logging.NullHandler()
fallbackLogHandler.setLevel(logging.NOTSET)
fallbackLogger.addHandler(fallbackLogHandler)

ConfigValues = {
    'logger': fallbackLogger,
    'logprint': fallbackLogger,

    # For tiles
    'cache_backend': None,  # 'python' or 'memcached'
    # 'python' cache can use 1/(val) of the available memory
    'cache_python_memory_portion': 32,
    # cache_memcached_url may be a list
    'cache_memcached_url': '127.0.0.1',
    'cache_memcached_username': None,
    'cache_memcached_password': None,

    # Generally, these keys are the form of "cache_<cacheName>_<key>"

    # For tilesources.  These are also limited by available file handles.
    # 'python' cache can use 1/(val) of the available memory based on a very
    # rough estimate of the amount of memory used by a tilesource
    'cache_tilesource_memory_portion': 8,
    # If >0, this is the maximum number of tilesources that will be cached
    'cache_tilesource_maximum': 0,

    'max_small_image_size': 4096,
}

def getConfig(key=None, default=None):
    """
    Get the config dictionary or a value from the cache config settings.

    :param key: if None, return the config dictionary.  Otherwise, return the
        value of the key if it is set or the default value if it is not.
    :param default: a value to return if a key is requested and not set.
    :returns: either the config dictionary or the value of a key.
    """
    if key is None:
        return ConfigValues
    return ConfigValues.get(key, default)

def setConfig(key, value):
    """
    Set a value in the config settings.

    :param key: the key to set.
    :param value: the value to store in the key.
    """
    curConfig = getConfig()
    if curConfig.get(key) is not value:
        curConfig[key] = value


text:
"""
    Formatter functions for operating system related status information.
"""

import flask_babel

from orchard.system_status.system import os as os_info

def current_logins(value: int) -> str:
    """
        Get a meaningful sentence describing how many users are currently logged in.

        :param value: The number of currently logged in users.
        :return: The number of logged in users as a correct text.
    """
    return flask_babel.ngettext('Currently, one user is logged in.',
                                'Currently, %(num)d users are logged in.',
                                num = value)

def gpu(value: os_info.gpu) -> str:
    """
        Get a meaningful text describing the current GPU firmware.

        :param value: The information on the GPU firmware.
        :return: A meaningful text describing the GPU firmware.
    """
    return flask_babel.gettext('%(hash)s of %(compile_time)s',
                               hash = value.hash,
                               compile_time = flask_babel.format_datetime(value.compile_time))

def kernel(value: os_info.kernel) -> str:
    """
        Get a meaningful text describing the current kernel version.

        :param value: The information on the kernel version.
        :return: A meaningful text describing the kernel.
    """
    return flask_babel.gettext('%(system)s %(version)s of %(compile_time)s',
                               system = value.system, version = value.version,
                               compile_time = flask_babel.format_datetime(value.compile_time))

def last_login(value: os_info.login) -> str:
    """
        Get a meaningful text describing the last login.

        :param value: The information of the last login to the system.
        :return: A meaningful text describing the last login.
    """
    return flask_babel.gettext('User "%(user)s" from %(host)s on %(date)s',
                               user = value.user, host = value.host,
                               date = flask_babel.format_datetime(value.login_time))


text:
export default function propertiesApply (elem, properties) {
  Object.keys(properties).forEach(function (name) {
    let prop = properties[name];
    prop.set && prop.set.call(elem, elem[name]);
  });
}


text:
package grpcclient

import (
	"fmt"

	log "github.com/golang/glog"
	"google.golang.org/grpc/grpclog"
)

// grpc doesn't return underlying errors. So, we have
// to rely on logs to know the root cause if a request
// fails. Using grpc's glogger is too spammy. So, we
// perform more selective logging using these functions.
func init() {
	grpclog.SetLoggerV2(&glogger{})
}

type glogger struct{}

func (g *glogger) Info(args ...interface{}) {
}

func (g *glogger) Infoln(args ...interface{}) {
}

func (g *glogger) Infof(format string, args ...interface{}) {
}

func (g *glogger) Warning(args ...interface{}) {
	log.WarningDepth(2, args...)
}

func (g *glogger) Warningln(args ...interface{}) {
	log.WarningDepth(2, fmt.Sprintln(args...))
}

func (g *glogger) Warningf(format string, args ...interface{}) {
	log.WarningDepth(2, fmt.Sprintf(format, args...))
}

func (g *glogger) Error(args ...interface{}) {
	log.ErrorDepth(2, args...)
}

func (g *glogger) Errorln(args ...interface{}) {
	log.ErrorDepth(2, fmt.Sprintln(args...))
}

func (g *glogger) Errorf(format string, args ...interface{}) {
	log.ErrorDepth(2, fmt.Sprintf(format, args...))
}

func (g *glogger) Fatal(args ...interface{}) {
	log.FatalDepth(2, args...)
}

func (g *glogger) Fatalln(args ...interface{}) {
	log.FatalDepth(2, fmt.Sprintln(args...))
}

func (g *glogger) Fatalf(format string, args ...interface{}) {
	log.FatalDepth(2, fmt.Sprintf(format, args...))
}

func (g *glogger) V(l int) bool {
	return bool(log.V(log.Level(l)))
}


text:
using NUnit.Framework;
using System;

[TestFixture]
public class DatabaseTests
{
    [Test]
    public void CtorShouldWorkWithCollection()
    {
        var database = new Database(new int[] { 1, 2, 3, 4, 5, 6 });

        Assert.AreEqual(6, database.Count());
    }

    [Test]
    public void CtorShouldWorkWithCollectionWithSixteenElements()
    {
        var database = new Database(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });

        Assert.AreEqual(16, database.Count());
    }

    [Test]
    public void CtorShouldWorkWithCollectionWithOneElement()
    {
        var database = new Database(new int[] { 1 });

        Assert.AreEqual(1, database.Count());
    }

    [Test]
    public void CtorShouldWorkWithCollectionWithZeroElement()
    {
        var database = new Database();

        Assert.AreEqual(0, database.Count());
    }

    [Test]
    public void CtorShouldNotAcceptMoreThan16Elements()
    {
        var array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };

        Assert.Throws<InvalidOperationException>(() => new Database(array));
    }

    [Test]
    public void CtorDoesntAcceptNullObject()
    {
        Assert.Throws<ArgumentNullException>(() => new Database(null));
    }

    [Test]
    public void AddMethodShouldAddOneElement()
    {
        var database = new Database();

        database.Add(2);

        Assert.AreEqual(1, database.Count());
    }

    [Test]
    public void AddMethodShouldAddManyElement()
    {
        var database = new Database();

        database.Add(2);
        database.Add(3);
        database.Add(4);
        database.Add(5);

        Assert.AreEqual(4, database.Count());
    }

    [Test]
    public void AddMethodShouldThrowExceptionWhenElementsInDatabaseAreEqualOrMoreThanCapacityOfDatabase()
    {
        var array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

        var database = new Database(array);

        Assert.Throws<InvalidOperationException>(() => database.Add(1));
    }

    [Test]
    public void AddMethodShouldAddElementAtNextFreeIndex()
    {
        var database = new Database();

        database.Add(1);
        database.Add(2);

        Assert.AreEqual(2, database.Count());
    }

    [Test]
    public void RemoveMethodShouldThrowExceptionIfArrayIsEmpty()
    {
        var database = new Database();

        Assert.Throws<InvalidOperationException>(() => database.Remove());
    }

    [Test]
    public void RemoveSingleElementOfCollection()
    {
        var database = new Database(new int[] { 1, 2, 3, 4, 5 });

        database.Remove();

        Assert.AreEqual(4, database.Count());
    }

    [Test]
    public void RemoveShouldRemoveElementOfLastIndex()
    {
        var database = new Database(new int[] { 1, 2, 3, 4, 5 });

        database.Remove();
        database.Remove();

        CollectionAssert.AreEqual(new int[] { 1, 2, 3 }, database.Fetch());
    }

    [Test]
    public void RemoveManyElementOfCollection()
    {
        var database = new Database(new int[] { 1, 2, 3, 4, 5 });

        database.Remove();
        database.Remove();
        database.Remove();

        Assert.AreEqual(2, database.Count());
    }

    [Test]
    public void CheckIfAddedElementAreLastInDatabaseCollection()
    {
        var database = new Database(new int[] { 1, 2 });

        database.Add(3);
        database.Add(4);

        CollectionAssert.AreEqual(new int[] { 1, 2, 3, 4 }, database.Fetch());
    }
}


text:
#ifndef CAF_DATA_PROCESSOR_HPP
#define CAF_DATA_PROCESSOR_HPP

#include <chrono>
#include <string>
#include <cstdint>
#include <cstddef> // size_t
#include <type_traits>

#include "caf/fwd.hpp"
#include "caf/atom.hpp"
#include "caf/error.hpp"
#include "caf/timestamp.hpp"
#include "caf/allowed_unsafe_message_type.hpp"

#include "caf/meta/annotation.hpp"
#include "caf/meta/save_callback.hpp"
#include "caf/meta/load_callback.hpp"

#include "caf/detail/type_list.hpp"
#include "caf/detail/apply_args.hpp"
#include "caf/detail/delegate_serialize.hpp"
#include "caf/detail/select_integer_type.hpp"

namespace caf {

/// A data processor translates an object into a format that can be
/// stored or vice versa. A data processor can be either in saving
/// or loading mode.
template <class Derived>
class data_processor {
public:
  // -- member types -----------------------------------------------------------

  /// Return type for `operator()`.
  using result_type = error;

  /// List of builtin types for data processors.
  using builtin_t =
    detail::type_list<
      int8_t,
      uint8_t,
      int16_t,
      uint16_t,
      int32_t,
      uint32_t,
      int64_t,
      uint64_t,
      float,
      double,
      long double,
      std::string,
      std::u16string,
      std::u32string
    >;

  /// List of builtin types for data processors as enum.
  enum builtin {
    i8_v,
    u8_v,
    i16_v,
    u16_v,
    i32_v,
    u32_v,
    i64_v,
    u64_v,
    float_v,
    double_v,
    ldouble_v,
    string8_v,
    string16_v,
    string32_v
  };

  // -- constructors, destructors, and assignment operators --------------------

  data_processor(const data_processor&) = delete;
  data_processor& operator=(const data_processor&) = delete;

  data_processor(execution_unit* ctx = nullptr) : context_(ctx) {
    // nop
  }

  virtual ~data_processor() {
    // nop
  }

  // -- pure virtual functions -------------------------------------------------

  /// Begins processing of an object. Saves the type information
  /// to the underlying storage when in saving mode, otherwise
  /// extracts them and sets both arguments accordingly.
  virtual error begin_object(uint16_t& typenr, std::string& name) = 0;

  /// Ends processing of an object.
  virtual error end_object() = 0;

  /// Begins processing of a sequence. Saves the size
  /// to the underlying storage when in saving mode, otherwise
  /// sets `num` accordingly.
  virtual error begin_sequence(size_t& num) = 0;

  /// Ends processing of a sequence.
  virtual error end_sequence() = 0;

  // -- getter -----------------------------------------------------------------

  /// Returns the actor system associated to this data processor.
  execution_unit* context() {
    return context_;
  }

  // -- apply functions --------------------------------------------------------

  /// Applies this processor to an arithmetic type.
  template <class T>
  typename std::enable_if<std::is_floating_point<T>::value, error>::type
  apply(T& x) {
    static constexpr auto tlindex = detail::tl_index_of<builtin_t, T>::value;
    static_assert(tlindex >= 0, "T not recognized as builtiln type");
    return apply_builtin(static_cast<builtin>(tlindex), &x);
  }

  template <class T>
  typename std::enable_if<
    std::is_integral<T>::value
    && !std::is_same<bool, T>::value,
    error
  >::type
  apply(T& x) {
    using type =
      typename detail::select_integer_type<
        static_cast<int>(sizeof(T)) * (std::is_signed<T>::value ? -1 : 1)
      >::type;
    static constexpr auto tlindex = detail::tl_index_of<builtin_t, type>::value;
    static_assert(tlindex >= 0, "T not recognized as builtiln type");
    return apply_builtin(static_cast<builtin>(tlindex), &x);
  }

  error apply(std::string& x) {
    return apply_builtin(string8_v, &x);
  }

  error apply(std::u16string& x) {
    return apply_builtin(string16_v, &x);
  }

  error apply(std::u32string& x) {
    return apply_builtin(string32_v, &x);
  }

  template <class D, atom_value V>
  static error apply_atom_constant(D& self, atom_constant<V>&) {
    static_assert(!D::writes_state, "cannot deserialize an atom_constant");
    auto x = V;
    return self.apply(x);
  }

  template <atom_value V>
  error apply(atom_constant<V>& x) {
    return apply_atom_constant(dref(), x);
  }

  /// Serializes enums using the underlying type
  /// if no user-defined serialization is defined.
  template <class T>
  typename std::enable_if<
    std::is_enum<T>::value
    && !detail::has_serialize<T>::value,
    error
  >::type
  apply(T& x) {
    using underlying = typename std::underlying_type<T>::type;
    struct {
      void operator()(T& lhs, underlying& rhs) const {
        lhs = static_cast<T>(rhs);
      }
      void operator()(underlying& lhs, T& rhs) const {
        lhs = static_cast<underlying>(rhs);
      }
    } assign;
    underlying tmp;
    return convert_apply(dref(), x, tmp, assign);
  }

  /// Applies this processor to an empty type.
  template <class T>
  typename std::enable_if<
    std::is_empty<T>::value && !detail::is_inspectable<Derived, T>::value,
    error
  >::type
  apply(T&) {
    return none;
  }

  error apply(bool& x) {
    struct {
      void operator()(bool& lhs, uint8_t& rhs) const {
        lhs = rhs != 0;
      }
      void operator()(uint8_t& lhs, bool& rhs) const {
        lhs = rhs ? 1 : 0;
      }
    } assign;
    uint8_t tmp;
    return convert_apply(dref(), x, tmp, assign);
  }

  template <class T>
  error consume_range(T& xs) {
    for (auto& x : xs) {
      using value_type = typename std::remove_const<
                           typename std::remove_reference<decltype(x)>::type
                         >::type;
      auto e = apply(const_cast<value_type&>(x));
      if (e)
        return e;
    }
    return none;
  }

  /// Converts each element in `xs` to `U` before calling `apply`.
  template <class U, class T>
  error consume_range_c(T& xs) {
    for (U x : xs) {
      auto e = apply(x);
      if (e)
        return e;
    }
    return none;
  }

  template <class T>
  error fill_range(T& xs, size_t num_elements) {
    auto insert_iter = std::inserter(xs, xs.end());
    for (size_t i = 0; i < num_elements; ++i) {
      typename std::remove_const<typename T::value_type>::type x;
      auto err = apply(x);
      if (err)
        return err;
      *insert_iter++ = std::move(x);
    }
    return none;
  }

  /// Loads elements from type `U` before inserting to `xs`.
  template <class U, class T>
  error fill_range_c(T& xs, size_t num_elements) {
    auto insert_iter = std::inserter(xs, xs.end());
    for (size_t i = 0; i < num_elements; ++i) {
      U x;
      auto err = apply(x);
      if (err)
        return err;
      *insert_iter++ = std::move(x);
    }
    return none;
  }
  // Applies this processor as Derived to `xs` in saving mode.
  template <class D, class T>
  static typename std::enable_if<
    D::reads_state && !detail::is_byte_sequence<T>::value,
    error
  >::type
  apply_sequence(D& self, T& xs) {
    auto s = xs.size();
    return error::eval([&] { return self.begin_sequence(s); },
                       [&] { return self.consume_range(xs); },
                       [&] { return self.end_sequence(); });
  }

  // Applies this processor as Derived to `xs` in loading mode.
  template <class D, class T>
  static typename std::enable_if<
    !D::reads_state && !detail::is_byte_sequence<T>::value,
    error
  >::type
  apply_sequence(D& self, T& xs) {
    size_t s;
    return error::eval([&] { return self.begin_sequence(s); },
                       [&] { return self.fill_range(xs, s); },
                       [&] { return self.end_sequence(); });
  }

  // Optimized saving for contiguous byte sequences.
  template <class D, class T>
  static typename std::enable_if<
    D::reads_state && detail::is_byte_sequence<T>::value,
    error
  >::type
  apply_sequence(D& self, T& xs) {
    auto s = xs.size();
    return error::eval([&] { return self.begin_sequence(s); },
                       [&] { return s > 0 ? self.apply_raw(xs.size(), &xs[0])
                                          : none; },
                       [&] { return self.end_sequence(); });
  }

  // Optimized loading for contiguous byte sequences.
  template <class D, class T>
  static typename std::enable_if<
    !D::reads_state && detail::is_byte_sequence<T>::value,
    error
  >::type
  apply_sequence(D& self, T& xs) {
    size_t s;
    return error::eval([&] { return self.begin_sequence(s); },
                       [&] { xs.resize(s);
                             return s > 0 ? self.apply_raw(s, &xs[0])
                                          : none; },
                       [&] { return self.end_sequence(); });
  }

  /// Applies this processor to a sequence of values.
  template <class T>
  typename std::enable_if<
    detail::is_iterable<T>::value
    && !detail::has_serialize<T>::value
    && !detail::is_inspectable<Derived, T>::value,
    error
  >::type
  apply(T& xs) {
    return apply_sequence(dref(), xs);
  }

  /// Applies this processor to an array.
  template <class T, size_t S>
  typename std::enable_if<detail::is_serializable<T>::value, error>::type
  apply(std::array<T, S>& xs) {
    return consume_range(xs);
  }

  /// Applies this processor to an array.
  template <class T, size_t S>
  typename std::enable_if<detail::is_serializable<T>::value, error>::type
  apply(T (&xs) [S]) {
    return consume_range(xs);
  }

  template <class F, class S>
  typename std::enable_if<
    detail::is_serializable<typename std::remove_const<F>::type>::value
    && detail::is_serializable<S>::value,
    error
  >::type
  apply(std::pair<F, S>& xs) {
    using t0 = typename std::remove_const<F>::type;
    // This cast allows the data processor to cope with
    // `pair<const K, V>` value types used by `std::map`.
    return error::eval([&] { return apply(const_cast<t0&>(xs.first)); },
                       [&] { return apply(xs.second); });
  }

  template <class... Ts>
  typename std::enable_if<
    detail::conjunction<
      detail::is_serializable<Ts>::value...
    >::value,
    error
  >::type
  apply(std::tuple<Ts...>& xs) {
    //apply_helper f{*this};
    return detail::apply_args(*this, detail::get_indices(xs), xs);
  }

  template <class T>
  typename std::enable_if<
    !std::is_empty<T>::value
    && detail::has_serialize<T>::value,
    error
  >::type
  apply(T& x) {
    // throws on error
    detail::delegate_serialize(dref(), x);
    return none;
  }

  template <class Rep, class Period>
  typename std::enable_if<std::is_integral<Rep>::value, error>::type
  apply(std::chrono::duration<Rep, Period>& x) {
    using duration_type = std::chrono::duration<Rep, Period>;
    // always save/store durations as int64_t to work around possibly
    // different integer types on different plattforms for standard typedefs
    struct {
      void operator()(duration_type& lhs, Rep& rhs) const {
        duration_type tmp{rhs};
        lhs = tmp;
      }
      void operator()(Rep& lhs, duration_type& rhs) const {
        lhs = rhs.count();
      }
    } assign;
    Rep tmp;
    return convert_apply(dref(), x, tmp, assign);
  }

  template <class Rep, class Period>
  typename std::enable_if<std::is_floating_point<Rep>::value, error>::type
  apply(std::chrono::duration<Rep, Period>& x) {
    using duration_type = std::chrono::duration<Rep, Period>;
    // always save/store floating point durations
    // as doubles for the same reason as above
    struct {
      void operator()(duration_type& lhs, double& rhs) const {
        duration_type tmp{rhs};
        lhs = tmp;
      }
      void operator()(double& lhs, duration_type& rhs) const {
        lhs = rhs.count();
      }
    } assign;
    double tmp;
    return convert_apply(dref(), x, tmp, assign);
  }

  template <class Duration>
  error apply(std::chrono::time_point<std::chrono::system_clock, Duration>& t) {
    if (Derived::reads_state) {
      auto dur = t.time_since_epoch();
      return apply(dur);
    }
    if (Derived::writes_state) {
      Duration dur;
      auto e = apply(dur);
      t = std::chrono::time_point<std::chrono::system_clock, Duration>{dur};
      return e;
    }
  }

  /// Applies this processor to a raw block of data of size `num_bytes`.
  virtual error apply_raw(size_t num_bytes, void* data) = 0;

  template <class T>
  typename std::enable_if<
    detail::is_inspectable<Derived, T>::value
      && !detail::has_serialize<T>::value,
    decltype(inspect(std::declval<Derived&>(), std::declval<T&>()))
  >::type
  apply(T& x) {
    return inspect(dref(), x);
  }

  // -- operator() -------------------------------------------------------------

  inline error operator()() {
    return none;
  }

  template <class F, class... Ts>
  error operator()(meta::save_callback_t<F> x, Ts&&... xs) {
    error e;
    if (Derived::reads_state)
      e = x.fun();
    return e ? e : (*this)(std::forward<Ts>(xs)...);
  }

  template <class F, class... Ts>
  error operator()(meta::load_callback_t<F> x, Ts&&... xs) {
    error e;
    if (Derived::writes_state)
      e = x.fun();
    return e ? e : (*this)(std::forward<Ts>(xs)...);
  }

  template <class... Ts>
  error operator()(const meta::annotation&, Ts&&... xs) {
    return (*this)(std::forward<Ts>(xs)...);
  }

  template <class T, class... Ts>
  typename std::enable_if<
    is_allowed_unsafe_message_type<T>::value,
    error
  >::type
  operator()(const T&, Ts&&... xs) {
    return (*this)(std::forward<Ts>(xs)...);
  }

  template <class T, class... Ts>
  typename std::enable_if<
    !meta::is_annotation<T>::value
    && !is_allowed_unsafe_message_type<T>::value,
    error
  >::type
  operator()(T&& x, Ts&&... xs) {
    static_assert(Derived::reads_state
                  || (!std::is_rvalue_reference<T&&>::value
                      && !std::is_const<
                             typename std::remove_reference<T>::type
                           >::value),
                  "a loading inspector requires mutable lvalue references");
    auto e = apply(deconst(x));
    return e ? e : (*this)(std::forward<Ts>(xs)...);
  }

protected:
  /// Applies this processor to a single builtin value.
  virtual error apply_builtin(builtin in_out_type, void* in_out) = 0;

private:
  template <class T>
  T& deconst(const T& x) {
    return const_cast<T&>(x);
  }

  template <class D, class T, class U, class F>
  static typename std::enable_if<D::reads_state, error>::type
  convert_apply(D& self, T& x, U& storage, F assign) {
    assign(storage, x);
    return self.apply(storage);
  }

  template <class D, class T, class U, class F>
  static typename std::enable_if<!D::reads_state, error>::type
  convert_apply(D& self, T& x, U& storage, F assign) {
    auto e = self.apply(storage);
    if (e)
      return e;
    assign(x, storage);
    return none;
  }

  // Returns a reference to the derived type.
  Derived& dref() {
    return *static_cast<Derived*>(this);
  }

  execution_unit* context_;
};

} // namespace caf

#endif // CAF_DATA_PROCESSOR_HPP


text:
PYTHON ?= python
NOSETESTS ?= nosetests
CTAGS ?= ctags

all: clean inplace test

clean-pyc:
	find . -name "*.pyc" | xargs rm -f

clean-so:
	find . -name "*.so" | xargs rm -f
	find . -name "*.pyd" | xargs rm -f

clean-build:
	rm -rf build

clean-ctags:
	rm -f tags

clean: clean-build clean-pyc clean-so clean-ctags

in: inplace # just a shortcut
inplace:
	$(PYTHON) setup.py build_ext -i

test: in
	rm -f .coverage
	$(NOSETESTS) bird

test-coverage:
	rm -rf coverage .coverage
	$(NOSETESTS) --with-coverage --cover-package=bird --cover-html --cover-html-dir=coverage

trailing-spaces:
	find . -name "*.py" | xargs perl -pi -e 's/[ \t]*$$//'

ctags:
	# make tags for symbol based navigation in emacs and vim
	# Install with: sudo apt-get install exuberant-ctags
	$(CTAGS) -R *

upload-pipy:
	python setup.py sdist bdist_egg register upload


text:
class Acme::Client::Resources::Challenges::DNS01 < Acme::Client::Resources::Challenges::Base
  CHALLENGE_TYPE = 'dns-01'.freeze
  RECORD_NAME = '_acme-challenge'.freeze
  RECORD_TYPE = 'TXT'.freeze
  DIGEST = OpenSSL::Digest::SHA256

  def record_name
    RECORD_NAME
  end

  def record_type
    RECORD_TYPE
  end

  def record_content
    Acme::Client::Util.urlsafe_base64(DIGEST.digest(key_authorization))
  end
end


text:
from __future__ import absolute_import
from datetime import date, datetime  # noqa: F401

from typing import List, Dict  # noqa: F401

from openapi_server.models.base_model_ import Model
from openapi_server.models.github_scmlinks import GithubScmlinks
from openapi_server import util

from openapi_server.models.github_scmlinks import GithubScmlinks  # noqa: E501

class GithubScm(Model):
    """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

    Do not edit the class manually.
    """

    def __init__(self, _class=None, links=None, credential_id=None, id=None, uri=None):  # noqa: E501
        """GithubScm - a model defined in OpenAPI

        :param _class: The _class of this GithubScm.  # noqa: E501
        :type _class: str
        :param links: The links of this GithubScm.  # noqa: E501
        :type links: GithubScmlinks
        :param credential_id: The credential_id of this GithubScm.  # noqa: E501
        :type credential_id: str
        :param id: The id of this GithubScm.  # noqa: E501
        :type id: str
        :param uri: The uri of this GithubScm.  # noqa: E501
        :type uri: str
        """
        self.openapi_types = {
            '_class': str,
            'links': GithubScmlinks,
            'credential_id': str,
            'id': str,
            'uri': str
        }

        self.attribute_map = {
            '_class': '_class',
            'links': '_links',
            'credential_id': 'credentialId',
            'id': 'id',
            'uri': 'uri'
        }

        self.__class = _class
        self._links = links
        self._credential_id = credential_id
        self._id = id
        self._uri = uri

    @classmethod
    def from_dict(cls, dikt) -> 'GithubScm':
        """Returns the dict as a model

        :param dikt: A dict.
        :type: dict
        :return: The GithubScm of this GithubScm.  # noqa: E501
        :rtype: GithubScm
        """
        return util.deserialize_model(dikt, cls)

    @property
    def _class(self):
        """Gets the _class of this GithubScm.

        :return: The _class of this GithubScm.
        :rtype: str
        """
        return self.__class

    @_class.setter
    def _class(self, _class):
        """Sets the _class of this GithubScm.

        :param _class: The _class of this GithubScm.
        :type _class: str
        """

        self.__class = _class

    @property
    def links(self):
        """Gets the links of this GithubScm.

        :return: The links of this GithubScm.
        :rtype: GithubScmlinks
        """
        return self._links

    @links.setter
    def links(self, links):
        """Sets the links of this GithubScm.

        :param links: The links of this GithubScm.
        :type links: GithubScmlinks
        """

        self._links = links

    @property
    def credential_id(self):
        """Gets the credential_id of this GithubScm.

        :return: The credential_id of this GithubScm.
        :rtype: str
        """
        return self._credential_id

    @credential_id.setter
    def credential_id(self, credential_id):
        """Sets the credential_id of this GithubScm.

        :param credential_id: The credential_id of this GithubScm.
        :type credential_id: str
        """

        self._credential_id = credential_id

    @property
    def id(self):
        """Gets the id of this GithubScm.

        :return: The id of this GithubScm.
        :rtype: str
        """
        return self._id

    @id.setter
    def id(self, id):
        """Sets the id of this GithubScm.

        :param id: The id of this GithubScm.
        :type id: str
        """

        self._id = id

    @property
    def uri(self):
        """Gets the uri of this GithubScm.

        :return: The uri of this GithubScm.
        :rtype: str
        """
        return self._uri

    @uri.setter
    def uri(self, uri):
        """Sets the uri of this GithubScm.

        :param uri: The uri of this GithubScm.
        :type uri: str
        """

        self._uri = uri


text:
namespace Ramble
{
	void ResourceManager::ReadAssetDB(const std::string& assetDBFilename)
	{
		std::ifstream file;

		file.open(assetDBFilename, std::ios::in);

		if(!file.good())
		{
			return;	//TODO: proper error message
		}

		std::string line;
		std::string token;

		while(!file.eof())
		{
			std::getline(file, line);
			std::stringstream stringy(line);

			if(std::getline(stringy, token, ','))
			{
				Asset asset;
				asset.hash = std::stoi(token);

				if(std::getline(stringy, token, ','))
				{
					asset.file = token;

					if(std::getline(stringy, token, ','))
					{
						if(token == "Music")
						{
							asset.assetType = AssetTypes::Music;
						}

						else if(token == "SoundEffect")
						{
							asset.assetType = AssetTypes::SoundEffect;
						}

						else if(token == "Sprite")
						{
							asset.assetType = AssetTypes::Sprite;
						}
					}
				}

				m_assets.push_back(asset);
			}
		}
	}
}


text:
package integration

import (
	"fmt"
	"os"
	"strings"
	"time"

	aggclient "github.com/m3db/m3/src/aggregator/client"
)

type conditionFn func() bool

func waitUntil(fn conditionFn, timeout time.Duration) bool {
	deadline := time.Now().Add(timeout)
	for time.Now().Before(deadline) {
		if fn() {
			return true
		}
		time.Sleep(10 * time.Millisecond)
	}
	return false
}

func getAggregatorClientTypeFromEnv() (aggclient.AggregatorClientType, error) {
	clientType := strings.ToLower(os.Getenv("TEST_AGGREGATOR_CLIENT_TYPE"))
	switch clientType {
	case "", "m3msg":
		return aggclient.M3MsgAggregatorClient, nil
	case "tcp":
		return aggclient.TCPAggregatorClient, nil
	default:
		return aggclient.AggregatorClientType(0), fmt.Errorf("unrecognized aggregator client type %v", clientType)
	}
}


text:
//= require utensils/canvas_util/_canvas_util

/**
 *  Converts a hex color value to canvas-friendly rgba. Original code from Robin W. Spencer (http://scaledinnovation.com).
 *  @return An rgba color string.
 *  @use    {@code CanvasUtil.hexToCanvasColor('#00ff00', 0.5);}
 */
utensils.CanvasUtil.hexToCanvasColor = function( hexColor, opacity ) {
  opacity = ( opacity != null ) ? opacity : "1.0";
  hexColor = hexColor.replace( "#", "" );
  var r = parseInt( hexColor.substring( 0, 2 ), 16 );
  var g = parseInt( hexColor.substring( 2, 4 ), 16 );
  var b = parseInt( hexColor.substring( 4, 6 ), 16 );
  return "rgba("+r+","+g+","+b+","+opacity+")";
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <TITLE>
        DOMPool (Apache JMeter API)
    </TITLE>

    <META NAME="keywords" CONTENT="org.apache.jmeter.protocol.http.util.DOMPool class">

    <LINK REL="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

        org.apache.jmeter.protocol.http.util

    Class DOMPool

java.lang.Object
  org.apache.jmeter.protocol.http.util.DOMPool

public final class DOMPool

extends Object

    The purpose of this class is to cache the DOM Documents in memory and by-pass
    parsing. For old systems or laptops, it's not practical to parse the XML
    documents every time. Therefore using a memory cache can reduce the CPU
    usage.

    For now this is a simple version to test the feasibility of caching. If it
    works, this class will be replaced with an Apache commons or something
    equivalent. If I was familiar with Apache Commons Pool, I would probably use
    it, but since I don't know the API, it is quicker for Proof of Concept to
    just write a dumb one. If the number documents in the pool exceed several
    hundred, it will take a long time for the lookup.

    Created on: Jun 17, 2003

            Method Summary

            static Document
        getDocument(Object key)

                      Return a document.

            static void
        putDocument(Object key,
            Object data)

                      Add an object to the cache.

        Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

            Method Detail

    getDocument

public static Document getDocument(Object key)

Return a document.

Parameters:

key -

Returns:

Document

    putDocument

public static void putDocument(Object key,
                               Object data)

Add an object to the cache.

Parameters:

key -

data -

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

Copyright © 1998-2009 Apache Software Foundation. All Rights Reserved.