text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _class, _temp;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _keyboardArrowUp = require('../svg-icons/hardware/keyboard-arrow-up');

var _keyboardArrowUp2 = _interopRequireDefault(_keyboardArrowUp);

var _keyboardArrowDown = require('../svg-icons/hardware/keyboard-arrow-down');

var _keyboardArrowDown2 = _interopRequireDefault(_keyboardArrowDown);

var _IconButton = require('../IconButton');

var _IconButton2 = _interopRequireDefault(_IconButton);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function getStyles() {
  return {
    root: {
      top: 0,
      bottom: 0,
      right: 4,
      margin: 'auto',
      position: 'absolute'
    }
  };
}

var CardExpandable = (_temp = _class = function (_Component) {
  (0, _inherits3.default)(CardExpandable, _Component);

  function CardExpandable() {
    (0, _classCallCheck3.default)(this, CardExpandable);
    return (0, _possibleConstructorReturn3.default)(this, _Component.apply(this, arguments));
  }

  CardExpandable.prototype.render = function render() {
    var styles = getStyles(this.props, this.context);

    return _react2.default.createElement(
      _IconButton2.default,
      {
        style: (0, _assign2.default)(styles.root, this.props.style),
        onTouchTap: this.props.onExpanding,
        iconStyle: this.props.iconStyle
      },
      this.props.expanded ? this.props.openIcon : this.props.closeIcon
    );
  };

  return CardExpandable;
}(_react.Component), _class.propTypes = {
  closeIcon: _propTypes2.default.node,
  expanded: _propTypes2.default.bool,
  iconStyle: _propTypes2.default.object,
  onExpanding: _propTypes2.default.func.isRequired,
  openIcon: _propTypes2.default.node,
  style: _propTypes2.default.object
}, _class.contextTypes = {
  muiTheme: _propTypes2.default.object.isRequired
}, _class.defaultProps = {
  closeIcon: _react2.default.createElement(_keyboardArrowDown2.default, null),
  openIcon: _react2.default.createElement(_keyboardArrowUp2.default, null)
}, _temp);
exports.default = CardExpandable;


text:
<bill session="115" type="hr" number="417" updated="2017-09-18T22:15:11Z">
  <state datetime="2017-06-27">REFERRED</state>
  <status>
    <introduced datetime="2017-06-27"/>
  </status>
  <introduced datetime="2017-06-27"/>
  <titles>
    <title type="official" as="introduced">Expressing the sense of the House of Representatives regarding the importance of civic education and civic involvement programs in the elementary and secondary schools of the United States.</title>
    <title type="display">Expressing the sense of the House of Representatives regarding the importance of civic education and civic involvement programs in the elementary and secondary schools of the United States.</title>
  </titles>
  <sponsor bioguide_id="R000593"/>
  <cosponsors/>
  <actions>
    <action datetime="2017-06-27">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-06-27" state="REFERRED">
      <text>Referred to the House Committee on Education and the Workforce.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSED" name="House Education and the Workforce" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Education"/>
    <term name="Academic performance and assessments"/>
    <term name="Constitution and constitutional amendments"/>
    <term name="Elementary and secondary education"/>
    <term name="National and community service"/>
    <term name="Public participation and lobbying"/>
    <term name="Teaching, teachers, curricula"/>
    <term name="U.S. history"/>
  </subjects>
  <amendments/>
  <summary date="2017-06-27T04:00:00Z" status="Introduced in House">Expresses the sense of the House of Representatives regarding the importance of civic education and civic involvement programs in schools.  Encourages schools to test high school seniors about basic civic knowledge and to promote civic participation, democratic engagement, and social service.</summary>
  <committee-reports/>
</bill>

redpajama_set_name: RedPajamaGithub


text:
#if !defined(XALAN_AVT_HEADER_GUARD)
#define XALAN_AVT_HEADER_GUARD

// Base include file.  Must be first.
#include <xalanc/XSLT/XSLTDefinitions.hpp>

#include <xalanc/XalanDOM/XalanDOMString.hpp>

namespace XERCES_CPP_NAMESPACE
{
    class Locator;
}

namespace XALAN_CPP_NAMESPACE {

typedef xercesc::Locator  LocatorType;
using xercesc::Locator;

class AVTPart;
class PrefixResolver;
class XPathExecutionContext;
class XalanNode;
class StringTokenizer;
class StylesheetConstructionContext;

/**
 * Class to hold an Attribute Value Template.
 */
class AVT
{
public:

    typedef std::size_t     size_type;

    /**
     * Construct an Attribute Value Template(AVT) by parsing the string, and
     * either constructing a vector of AVTParts, or simply hold on to the
     * string if the AVT is simple.
     *
     * @param constructionContext context for construction of AVT
     * @param locator         the Locator for the AVT.  May be null.
     * @param name                name of AVT
     * @param stringedValue       string value to parse
     * @param resolver            resolver for namespace resolution
     */
    AVT(
            StylesheetConstructionContext&  constructionContext,
            const Locator*                  locator,
            const XalanDOMChar*             name,
            const XalanDOMChar*             stringedValue,
            const PrefixResolver&           resolver);

    virtual
    ~AVT();

    /**
     * Retrieve the name of the Attribute Value Template
     *
     * @return name of AVT
     */
    const XalanDOMString&
    getName() const
    {
        return m_name;
    }

    /**
     * Append the value to the buffer.
     *
     * @param buf              buffer to write into
     * @param contextNode      current context node
     * @param prefixResolver   prefix resolver to use
     * @param executionContext execution context
     */
    void
    evaluate(
            XalanDOMString&         buf,
            XalanNode*              contextNode,
            const PrefixResolver&   prefixResolver,
            XPathExecutionContext&  executionContext) const
    {
        if(m_simpleString != 0)
        {
            buf.assign(m_simpleString, m_simpleStringLength);
        }
        else
        {
            doEvaluate(buf, contextNode, prefixResolver, executionContext);
        }
    }

    /**
     * Append the value to the buffer.
     *
     * @param buf              buffer to write into
     * @param prefixResolver   prefix resolver to use
     * @param executionContext execution context
     */
    void
    evaluate(
            XalanDOMString&         buf,
            const PrefixResolver&   prefixResolver,
            XPathExecutionContext&  executionContext) const
    {
        if(m_simpleString != 0)
        {
            buf.assign(m_simpleString, m_simpleStringLength);
        }
        else
        {
            doEvaluate(buf, prefixResolver, executionContext);
        }
    }

private:

    void
    doEvaluate(
            XalanDOMString&         buf,
            const PrefixResolver&   prefixResolver,
            XPathExecutionContext&  executionContext) const;

    void
    doEvaluate(
            XalanDOMString&         buf,
            XalanNode*              contextNode,
            const PrefixResolver&   prefixResolver,
            XPathExecutionContext&  executionContext) const;

    void
    nextToken(
            StylesheetConstructionContext&  constructionContext,
            const Locator*                  locator,
            StringTokenizer&                tokenizer,
            XalanDOMString&                 token);

    // not implemented
    AVT(const AVT&);

    AVT&
    operator=(const AVT&);

    bool
    operator==(const AVT&) const;

    // Data members...
    const AVTPart**                 m_parts;

    size_type                       m_partsSize;

    const XalanDOMChar*             m_simpleString;

    XalanDOMString::size_type       m_simpleStringLength;

    const XalanDOMString&           m_name;

    static const XalanDOMString     s_emptyString;
};

}

#endif  // XALAN_AVT_HEADER_GUARD


text:
@interface Pinoccio : NSObject

-(void)generateTokenWithEmail:(NSString *)email password:(NSString *)password withCompletion:(void (^)(NSString *, BOOL))block;
-(void)troopWithToken:(NSString *)token withCompletion:(void (^)(id, BOOL))block;
@end


text:
import datetime
import json
import unittest

from django import forms
from django.core import exceptions, serializers
from django.db import connection
from django.db.models import F
from django.test import TestCase, override_settings
from django.utils import timezone

from . import PostgreSQLTestCase
from .models import RangeLookupsModel, RangesModel

try:
    from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange
    from django.contrib.postgres import fields as pg_fields, forms as pg_forms
    from django.contrib.postgres.validators import (
        RangeMaxValueValidator, RangeMinValueValidator,
    )
except ImportError:
    pass

def skipUnlessPG92(test):
    try:
        PG_VERSION = connection.pg_version
    except AttributeError:
        PG_VERSION = 0
    if PG_VERSION < 90200:
        return unittest.skip('PostgreSQL >= 9.2 required')(test)
    return test

@skipUnlessPG92
class TestSaveLoad(TestCase):

    def test_all_fields(self):
        now = timezone.now()
        instance = RangesModel(
            ints=NumericRange(0, 10),
            bigints=NumericRange(10, 20),
            floats=NumericRange(20, 30),
            timestamps=DateTimeTZRange(now - datetime.timedelta(hours=1), now),
            dates=DateRange(now.date() - datetime.timedelta(days=1), now.date()),
        )
        instance.save()
        loaded = RangesModel.objects.get()
        self.assertEqual(instance.ints, loaded.ints)
        self.assertEqual(instance.bigints, loaded.bigints)
        self.assertEqual(instance.floats, loaded.floats)
        self.assertEqual(instance.timestamps, loaded.timestamps)
        self.assertEqual(instance.dates, loaded.dates)

    def test_range_object(self):
        r = NumericRange(0, 10)
        instance = RangesModel(ints=r)
        instance.save()
        loaded = RangesModel.objects.get()
        self.assertEqual(r, loaded.ints)

    def test_tuple(self):
        instance = RangesModel(ints=(0, 10))
        instance.save()
        loaded = RangesModel.objects.get()
        self.assertEqual(NumericRange(0, 10), loaded.ints)

    def test_range_object_boundaries(self):
        r = NumericRange(0, 10, '[]')
        instance = RangesModel(floats=r)
        instance.save()
        loaded = RangesModel.objects.get()
        self.assertEqual(r, loaded.floats)
        self.assertTrue(10 in loaded.floats)

    def test_unbounded(self):
        r = NumericRange(None, None, '()')
        instance = RangesModel(floats=r)
        instance.save()
        loaded = RangesModel.objects.get()
        self.assertEqual(r, loaded.floats)

    def test_empty(self):
        r = NumericRange(empty=True)
        instance = RangesModel(ints=r)
        instance.save()
        loaded = RangesModel.objects.get()
        self.assertEqual(r, loaded.ints)

    def test_null(self):
        instance = RangesModel(ints=None)
        instance.save()
        loaded = RangesModel.objects.get()
        self.assertIsNone(loaded.ints)

@skipUnlessPG92
class TestQuerying(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.objs = [
            RangesModel.objects.create(ints=NumericRange(0, 10)),
            RangesModel.objects.create(ints=NumericRange(5, 15)),
            RangesModel.objects.create(ints=NumericRange(None, 0)),
            RangesModel.objects.create(ints=NumericRange(empty=True)),
            RangesModel.objects.create(ints=None),
        ]

    def test_exact(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__exact=NumericRange(0, 10)),
            [self.objs[0]],
        )

    def test_isnull(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__isnull=True),
            [self.objs[4]],
        )

    def test_isempty(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__isempty=True),
            [self.objs[3]],
        )

    def test_contains(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__contains=8),
            [self.objs[0], self.objs[1]],
        )

    def test_contains_range(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__contains=NumericRange(3, 8)),
            [self.objs[0]],
        )

    def test_contained_by(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__contained_by=NumericRange(0, 20)),
            [self.objs[0], self.objs[1], self.objs[3]],
        )

    def test_overlap(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__overlap=NumericRange(3, 8)),
            [self.objs[0], self.objs[1]],
        )

    def test_fully_lt(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__fully_lt=NumericRange(5, 10)),
            [self.objs[2]],
        )

    def test_fully_gt(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__fully_gt=NumericRange(5, 10)),
            [],
        )

    def test_not_lt(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__not_lt=NumericRange(5, 10)),
            [self.objs[1]],
        )

    def test_not_gt(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__not_gt=NumericRange(5, 10)),
            [self.objs[0], self.objs[2]],
        )

    def test_adjacent_to(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__adjacent_to=NumericRange(0, 5)),
            [self.objs[1], self.objs[2]],
        )

    def test_startswith(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__startswith=0),
            [self.objs[0]],
        )

    def test_endswith(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__endswith=0),
            [self.objs[2]],
        )

    def test_startswith_chaining(self):
        self.assertSequenceEqual(
            RangesModel.objects.filter(ints__startswith__gte=0),
            [self.objs[0], self.objs[1]],
        )

@skipUnlessPG92
class TestQueryingWithRanges(TestCase):
    def test_date_range(self):
        objs = [
            RangeLookupsModel.objects.create(date='2015-01-01'),
            RangeLookupsModel.objects.create(date='2015-05-05'),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.filter(date__contained_by=DateRange('2015-01-01', '2015-05-04')),
            [objs[0]],
        )

    def test_date_range_datetime_field(self):
        objs = [
            RangeLookupsModel.objects.create(timestamp='2015-01-01'),
            RangeLookupsModel.objects.create(timestamp='2015-05-05'),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.filter(timestamp__date__contained_by=DateRange('2015-01-01', '2015-05-04')),
            [objs[0]],
        )

    def test_datetime_range(self):
        objs = [
            RangeLookupsModel.objects.create(timestamp='2015-01-01T09:00:00'),
            RangeLookupsModel.objects.create(timestamp='2015-05-05T17:00:00'),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.filter(
                timestamp__contained_by=DateTimeTZRange('2015-01-01T09:00', '2015-05-04T23:55')
            ),
            [objs[0]],
        )

    def test_integer_range(self):
        objs = [
            RangeLookupsModel.objects.create(integer=5),
            RangeLookupsModel.objects.create(integer=99),
            RangeLookupsModel.objects.create(integer=-1),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.filter(integer__contained_by=NumericRange(1, 98)),
            [objs[0]]
        )

    def test_biginteger_range(self):
        objs = [
            RangeLookupsModel.objects.create(big_integer=5),
            RangeLookupsModel.objects.create(big_integer=99),
            RangeLookupsModel.objects.create(big_integer=-1),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.filter(big_integer__contained_by=NumericRange(1, 98)),
            [objs[0]]
        )

    def test_float_range(self):
        objs = [
            RangeLookupsModel.objects.create(float=5),
            RangeLookupsModel.objects.create(float=99),
            RangeLookupsModel.objects.create(float=-1),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.filter(float__contained_by=NumericRange(1, 98)),
            [objs[0]]
        )

    def test_f_ranges(self):
        parent = RangesModel.objects.create(floats=NumericRange(0, 10))
        objs = [
            RangeLookupsModel.objects.create(float=5, parent=parent),
            RangeLookupsModel.objects.create(float=99, parent=parent),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.filter(float__contained_by=F('parent__floats')),
            [objs[0]]
        )

    def test_exclude(self):
        objs = [
            RangeLookupsModel.objects.create(float=5),
            RangeLookupsModel.objects.create(float=99),
            RangeLookupsModel.objects.create(float=-1),
        ]
        self.assertSequenceEqual(
            RangeLookupsModel.objects.exclude(float__contained_by=NumericRange(0, 100)),
            [objs[2]]
        )

@skipUnlessPG92
class TestSerialization(TestCase):
    test_data = (
        '[{"fields": {"ints": "{\\"upper\\": \\"10\\", \\"lower\\": \\"0\\", '
        '\\"bounds\\": \\"[)\\"}", "floats": "{\\"empty\\": true}", '
        '"bigints": null, "timestamps": "{\\"upper\\": \\"2014-02-02T12:12:12+00:00\\", '
        '\\"lower\\": \\"2014-01-01T00:00:00+00:00\\", \\"bounds\\": \\"[)\\"}", '
        '"dates": "{\\"upper\\": \\"2014-02-02\\", \\"lower\\": \\"2014-01-01\\", \\"bounds\\": \\"[)\\"}" }, '
        '"model": "postgres_tests.rangesmodel", "pk": null}]'
    )

    lower_date = datetime.date(2014, 1, 1)
    upper_date = datetime.date(2014, 2, 2)
    lower_dt = datetime.datetime(2014, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
    upper_dt = datetime.datetime(2014, 2, 2, 12, 12, 12, tzinfo=timezone.utc)

    def test_dumping(self):
        instance = RangesModel(ints=NumericRange(0, 10), floats=NumericRange(empty=True),
            timestamps=DateTimeTZRange(self.lower_dt, self.upper_dt),
            dates=DateRange(self.lower_date, self.upper_date))
        data = serializers.serialize('json', [instance])
        dumped = json.loads(data)
        for field in ('ints', 'dates', 'timestamps'):
            dumped[0]['fields'][field] = json.loads(dumped[0]['fields'][field])
        check = json.loads(self.test_data)
        for field in ('ints', 'dates', 'timestamps'):
            check[0]['fields'][field] = json.loads(check[0]['fields'][field])
        self.assertEqual(dumped, check)

    def test_loading(self):
        instance = list(serializers.deserialize('json', self.test_data))[0].object
        self.assertEqual(instance.ints, NumericRange(0, 10))
        self.assertEqual(instance.floats, NumericRange(empty=True))
        self.assertEqual(instance.bigints, None)
        self.assertEqual(instance.dates, DateRange(self.lower_date, self.upper_date))
        self.assertEqual(instance.timestamps, DateTimeTZRange(self.lower_dt, self.upper_dt))

class TestValidators(PostgreSQLTestCase):

    def test_max(self):
        validator = RangeMaxValueValidator(5)
        validator(NumericRange(0, 5))
        with self.assertRaises(exceptions.ValidationError) as cm:
            validator(NumericRange(0, 10))
        self.assertEqual(cm.exception.messages[0], 'Ensure that this range is completely less than or equal to 5.')
        self.assertEqual(cm.exception.code, 'max_value')

    def test_min(self):
        validator = RangeMinValueValidator(5)
        validator(NumericRange(10, 15))
        with self.assertRaises(exceptions.ValidationError) as cm:
            validator(NumericRange(0, 10))
        self.assertEqual(cm.exception.messages[0], 'Ensure that this range is completely greater than or equal to 5.')
        self.assertEqual(cm.exception.code, 'min_value')

class TestFormField(PostgreSQLTestCase):

    def test_valid_integer(self):
        field = pg_forms.IntegerRangeField()
        value = field.clean(['1', '2'])
        self.assertEqual(value, NumericRange(1, 2))

    def test_valid_floats(self):
        field = pg_forms.FloatRangeField()
        value = field.clean(['1.12345', '2.001'])
        self.assertEqual(value, NumericRange(1.12345, 2.001))

    def test_valid_timestamps(self):
        field = pg_forms.DateTimeRangeField()
        value = field.clean(['01/01/2014 00:00:00', '02/02/2014 12:12:12'])
        lower = datetime.datetime(2014, 1, 1, 0, 0, 0)
        upper = datetime.datetime(2014, 2, 2, 12, 12, 12)
        self.assertEqual(value, DateTimeTZRange(lower, upper))

    def test_valid_dates(self):
        field = pg_forms.DateRangeField()
        value = field.clean(['01/01/2014', '02/02/2014'])
        lower = datetime.date(2014, 1, 1)
        upper = datetime.date(2014, 2, 2)
        self.assertEqual(value, DateRange(lower, upper))

    def test_using_split_datetime_widget(self):
        class SplitDateTimeRangeField(pg_forms.DateTimeRangeField):
            base_field = forms.SplitDateTimeField

        class SplitForm(forms.Form):
            field = SplitDateTimeRangeField()

        form = SplitForm()
        self.assertHTMLEqual(str(form), '''

                Field:

                    <input id="id_field_0_0" name="field_0_0" type="text" />
                    <input id="id_field_0_1" name="field_0_1" type="text" />
                    <input id="id_field_1_0" name="field_1_0" type="text" />
                    <input id="id_field_1_1" name="field_1_1" type="text" />

        ''')
        form = SplitForm({
            'field_0_0': '01/01/2014',
            'field_0_1': '00:00:00',
            'field_1_0': '02/02/2014',
            'field_1_1': '12:12:12',
        })
        self.assertTrue(form.is_valid())
        lower = datetime.datetime(2014, 1, 1, 0, 0, 0)
        upper = datetime.datetime(2014, 2, 2, 12, 12, 12)
        self.assertEqual(form.cleaned_data['field'], DateTimeTZRange(lower, upper))

    def test_none(self):
        field = pg_forms.IntegerRangeField(required=False)
        value = field.clean(['', ''])
        self.assertEqual(value, None)

    def test_rendering(self):
        class RangeForm(forms.Form):
            ints = pg_forms.IntegerRangeField()

        self.assertHTMLEqual(str(RangeForm()), '''

            Ints:

                <input id="id_ints_0" name="ints_0" type="number" />
                <input id="id_ints_1" name="ints_1" type="number" />

        ''')

    def test_integer_lower_bound_higher(self):
        field = pg_forms.IntegerRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['10', '2'])
        self.assertEqual(cm.exception.messages[0], 'The start of the range must not exceed the end of the range.')
        self.assertEqual(cm.exception.code, 'bound_ordering')

    def test_integer_open(self):
        field = pg_forms.IntegerRangeField()
        value = field.clean(['', '0'])
        self.assertEqual(value, NumericRange(None, 0))

    def test_integer_incorrect_data_type(self):
        field = pg_forms.IntegerRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('1')
        self.assertEqual(cm.exception.messages[0], 'Enter two whole numbers.')
        self.assertEqual(cm.exception.code, 'invalid')

    def test_integer_invalid_lower(self):
        field = pg_forms.IntegerRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['a', '2'])
        self.assertEqual(cm.exception.messages[0], 'Enter a whole number.')

    def test_integer_invalid_upper(self):
        field = pg_forms.IntegerRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['1', 'b'])
        self.assertEqual(cm.exception.messages[0], 'Enter a whole number.')

    def test_integer_required(self):
        field = pg_forms.IntegerRangeField(required=True)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['', ''])
        self.assertEqual(cm.exception.messages[0], 'This field is required.')
        value = field.clean([1, ''])
        self.assertEqual(value, NumericRange(1, None))

    def test_float_lower_bound_higher(self):
        field = pg_forms.FloatRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['1.8', '1.6'])
        self.assertEqual(cm.exception.messages[0], 'The start of the range must not exceed the end of the range.')
        self.assertEqual(cm.exception.code, 'bound_ordering')

    def test_float_open(self):
        field = pg_forms.FloatRangeField()
        value = field.clean(['', '3.1415926'])
        self.assertEqual(value, NumericRange(None, 3.1415926))

    def test_float_incorrect_data_type(self):
        field = pg_forms.FloatRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('1.6')
        self.assertEqual(cm.exception.messages[0], 'Enter two numbers.')
        self.assertEqual(cm.exception.code, 'invalid')

    def test_float_invalid_lower(self):
        field = pg_forms.FloatRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['a', '3.1415926'])
        self.assertEqual(cm.exception.messages[0], 'Enter a number.')

    def test_float_invalid_upper(self):
        field = pg_forms.FloatRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['1.61803399', 'b'])
        self.assertEqual(cm.exception.messages[0], 'Enter a number.')

    def test_float_required(self):
        field = pg_forms.FloatRangeField(required=True)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['', ''])
        self.assertEqual(cm.exception.messages[0], 'This field is required.')
        value = field.clean(['1.61803399', ''])
        self.assertEqual(value, NumericRange(1.61803399, None))

    def test_date_lower_bound_higher(self):
        field = pg_forms.DateRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['2013-04-09', '1976-04-16'])
        self.assertEqual(cm.exception.messages[0], 'The start of the range must not exceed the end of the range.')
        self.assertEqual(cm.exception.code, 'bound_ordering')

    def test_date_open(self):
        field = pg_forms.DateRangeField()
        value = field.clean(['', '2013-04-09'])
        self.assertEqual(value, DateRange(None, datetime.date(2013, 4, 9)))

    def test_date_incorrect_data_type(self):
        field = pg_forms.DateRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('1')
        self.assertEqual(cm.exception.messages[0], 'Enter two valid dates.')
        self.assertEqual(cm.exception.code, 'invalid')

    def test_date_invalid_lower(self):
        field = pg_forms.DateRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['a', '2013-04-09'])
        self.assertEqual(cm.exception.messages[0], 'Enter a valid date.')

    def test_date_invalid_upper(self):
        field = pg_forms.DateRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['2013-04-09', 'b'])
        self.assertEqual(cm.exception.messages[0], 'Enter a valid date.')

    def test_date_required(self):
        field = pg_forms.DateRangeField(required=True)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['', ''])
        self.assertEqual(cm.exception.messages[0], 'This field is required.')
        value = field.clean(['1976-04-16', ''])
        self.assertEqual(value, DateRange(datetime.date(1976, 4, 16), None))

    def test_datetime_lower_bound_higher(self):
        field = pg_forms.DateTimeRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['2006-10-25 14:59', '2006-10-25 14:58'])
        self.assertEqual(cm.exception.messages[0], 'The start of the range must not exceed the end of the range.')
        self.assertEqual(cm.exception.code, 'bound_ordering')

    def test_datetime_open(self):
        field = pg_forms.DateTimeRangeField()
        value = field.clean(['', '2013-04-09 11:45'])
        self.assertEqual(value, DateTimeTZRange(None, datetime.datetime(2013, 4, 9, 11, 45)))

    def test_datetime_incorrect_data_type(self):
        field = pg_forms.DateTimeRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('2013-04-09 11:45')
        self.assertEqual(cm.exception.messages[0], 'Enter two valid date/times.')
        self.assertEqual(cm.exception.code, 'invalid')

    def test_datetime_invalid_lower(self):
        field = pg_forms.DateTimeRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['45', '2013-04-09 11:45'])
        self.assertEqual(cm.exception.messages[0], 'Enter a valid date/time.')

    def test_datetime_invalid_upper(self):
        field = pg_forms.DateTimeRangeField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['2013-04-09 11:45', 'sweet pickles'])
        self.assertEqual(cm.exception.messages[0], 'Enter a valid date/time.')

    def test_datetime_required(self):
        field = pg_forms.DateTimeRangeField(required=True)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['', ''])
        self.assertEqual(cm.exception.messages[0], 'This field is required.')
        value = field.clean(['2013-04-09 11:45', ''])
        self.assertEqual(value, DateTimeTZRange(datetime.datetime(2013, 4, 9, 11, 45), None))

    @override_settings(USE_TZ=True, TIME_ZONE='Africa/Johannesburg')
    def test_datetime_prepare_value(self):
        field = pg_forms.DateTimeRangeField()
        value = field.prepare_value(
            DateTimeTZRange(datetime.datetime(2015, 5, 22, 16, 6, 33, tzinfo=timezone.utc), None)
        )
        self.assertEqual(value, [datetime.datetime(2015, 5, 22, 18, 6, 33), None])

    def test_model_field_formfield_integer(self):
        model_field = pg_fields.IntegerRangeField()
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, pg_forms.IntegerRangeField)

    def test_model_field_formfield_biginteger(self):
        model_field = pg_fields.BigIntegerRangeField()
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, pg_forms.IntegerRangeField)

    def test_model_field_formfield_float(self):
        model_field = pg_fields.FloatRangeField()
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, pg_forms.FloatRangeField)

    def test_model_field_formfield_date(self):
        model_field = pg_fields.DateRangeField()
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, pg_forms.DateRangeField)

    def test_model_field_formfield_datetime(self):
        model_field = pg_fields.DateTimeRangeField()
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, pg_forms.DateTimeRangeField)

class TestWidget(PostgreSQLTestCase):
    def test_range_widget(self):
        f = pg_forms.ranges.DateTimeRangeField()
        self.assertHTMLEqual(
            f.widget.render('datetimerange', ''),
            '<input type="text" name="datetimerange_0" /><input type="text" name="datetimerange_1" />'
        )
        self.assertHTMLEqual(
            f.widget.render('datetimerange', None),
            '<input type="text" name="datetimerange_0" /><input type="text" name="datetimerange_1" />'
        )
        dt_range = DateTimeTZRange(
            datetime.datetime(2006, 1, 10, 7, 30),
            datetime.datetime(2006, 2, 12, 9, 50)
        )
        self.assertHTMLEqual(
            f.widget.render('datetimerange', dt_range),
            '<input type="text" name="datetimerange_0" value="2006-01-10 07:30:00" />'
            '<input type="text" name="datetimerange_1" value="2006-02-12 09:50:00" />'
        )


text: A Golang [UNDER CONSTRUCTION] Automation Server


text:
This project provides a Node.js package for accessing the Azure PAS. Right now it supports:
- **Node.js version: 6.x.x or higher**

## How to Install

```bash
npm install azure-arm-datafactory
```

## How to Use

### Authentication, client creation and listing factories as an example

 ```javascript
 var msRestAzure = require('ms-rest-azure');
 var DataFactoryManagementClient = require("azure-arm-datafactory");

 // Interactive Login
 // It provides a url and code that needs to be copied and pasted in a browser and authenticated over there. If successful,
 // the user will get a DeviceTokenCredentials object.
 msRestAzure.interactiveLogin(function(err, credentials) {
  let client = new DataFactoryManagementClient(credentials, 'your-subscription-id');
  client.factories.list().then((factories) => {
    console.log('List of factories:');
    console.dir(factories, {depth: null, colors: true});
   });
  }).catch((err) => {
   console.log('An error ocurred');
   console.dir(err, {depth: null, colors: true});
  });
});
```

## Related projects

- [Microsoft Azure SDK for Node.js](https://github.com/Azure/azure-sdk-for-node)


text:
import basicserial

from yamllint import linter
from yamllint.config import YamlLintConfig

from .base import Tool, Issue, AccessIssue, UnknownIssue

class YamlLintIssue(Issue):
    tool = 'yamllint'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.pylint_type = 'E' if self.code == 'syntax' else 'C'

class YamlLintTool(Tool):
    """
    The yamllint tool, as its name implies, is a linter for YAML files.
    """

    @classmethod
    def get_default_config(cls):
        config = Tool.get_default_config()
        config['filters'] = [
            r'\.yaml$',
            r'\.yml$',
        ]
        return config

    @classmethod
    def get_all_codes(cls):
        codes = [
            ('syntax', 'YAML syntax error'),
        ]

        cfg = YamlLintConfig('extends: default')
        codes += [
            (rule, rule)
            for rule in cfg.rules
        ]

        return codes

    def make_config(self):
        cfg = {
            'extends': 'default',
            'rules': {},
        }

        rules = [
            rule
            for rule, _ in self.get_all_codes()
            if rule != 'syntax'
        ]
        for rule in rules:
            if rule in self.config['disabled']:
                cfg['rules'][rule] = 'disable'
            elif rule in self.config['options']:
                cfg['rules'][rule] = self.config['options'][rule]

        return YamlLintConfig(basicserial.to_yaml(cfg))

    def execute(self, finder):
        issues = []
        cfg = self.make_config()

        for filepath in finder.files(self.config['filters']):
            try:
                problems = linter.run(
                    finder.read_file(filepath),
                    cfg,
                    filepath=filepath,
                )
            except Exception as exc:  # pylint: disable=broad-except
                issues.append(self.make_issue(exc, filepath))
            else:
                issues += [
                    self.make_issue(problem, filepath)
                    for problem in problems
                    if not (
                        'syntax' in self.config['disabled']
                        and not problem.rule  # noqa: W503
                    )
                ]
        return issues

    def make_issue(self, problem, filename):
        if isinstance(problem, linter.LintProblem):
            return YamlLintIssue(
                problem.rule or 'syntax',
                problem.desc,
                filename,
                problem.line,
                problem.column,
            )

        if isinstance(problem, EnvironmentError):
            return AccessIssue(problem, filename)

        return UnknownIssue(problem, filename)


text:
void InitHistograms(AliDielectron *die, Int_t cutDefinition);

void SetupEventCuts(AliDielectron *die, Int_t cutDefinition);
void SetupTrackCuts(AliDielectron *die, Int_t cutDefinition);
void SetupV0Cuts(   AliDielectron *die, Int_t cutDefinition);
void SetupPairCuts( AliDielectron *die, Int_t cutDefinition);

void ConfigEvtPlane(AliDielectron *die, Int_t cutDefinition);
void SetEtaCorrection(AliDielectron *die);

TString names=("NANO");
enum { kNANO=0 };

TObjArray *arrNames=names.Tokenize(";");
const Int_t nDie=arrNames->GetEntries();

Bool_t  isESD     = kTRUE;
TString periodLHC = "";
TString list  = gSystem->Getenv("LIST");

AliDielectron* ConfigLMEE_nano_PbPb2015(Int_t cutDefinition, Bool_t hasMC=kFALSE, TString period="")
{
  //
  // Setup the instance of AliDielectron
  //

  periodLHC = period;
  printf("this is -%s- filtering \n",periodLHC.Data());

  //ESD handler?
  isESD=(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()->IsA()==AliESDInputHandler::Class());

  // task name
  TString name=Form("%02d",cutDefinition);
  if (cutDefinition<arrNames->GetEntriesFast())  name=arrNames->At(cutDefinition)->GetName();
  printf(" Adding %s%s config %s for %s \n",(isESD?"ESD":"AOD"),(hasMC?" MC":""),name.Data(),list.Data());

  // init AliDielectron
  AliDielectron *die = new AliDielectron(Form("%s",name.Data()), Form("%s",name.Data()));
  die->SetHasMC(hasMC);

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv CUTS vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  SetupEventCuts(die,cutDefinition);
  SetupTrackCuts(die,cutDefinition);
  // SetupV0Cuts(die,cutDefinition);   // switch off for nanoAODs??
  // SetupPairCuts(die,cutDefinition);

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv MISC vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  // PID eta correction
  //SetEtaCorrection(die); //no eta corrction
  // prefilter settings
  //  if(hasMC)
  die->SetNoPairing();
  //  else die->SetPreFilterUnlikeOnly();
  //die->SetPreFilterAllSigns();

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv OUTPUT vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  // histogram setup
  InitHistograms(die,cutDefinition);

  // cut QA
  die->SetCutQA();

  return die;
}

//______________________________________________________________________________________
void SetupEventCuts(AliDielectron *die, Int_t cutDefinition)
{
  //
  // Setup the event cuts
  //

  AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","eventCuts");
  if(!isESD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
  eventCuts->SetRequireVertex();
  eventCuts->SetMinVtxContributors(1);
  eventCuts->SetVertexZ(-10.,+10.);
  eventCuts->SetCentralityRange(10., 50., kTRUE);
  eventCuts->Print();
  die->GetEventFilter().AddCuts(eventCuts);

}

//______________________________________________________________________________________
void SetupTrackCuts(AliDielectron *die, Int_t cutDefinition)
{
  //
  // Setup the track cuts
  //

  Bool_t hasMC=die->GetHasMC();

  // Quality cuts
  AliDielectronCutGroup* cuts = new AliDielectronCutGroup("cuts","cuts",AliDielectronCutGroup::kCompAND);
  die->GetTrackFilter().AddCuts(cuts);

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv FILTER CUTS vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  // AOD track filter (needs to be first cut to speed up)
  AliDielectronTrackCuts *trkFilter = new AliDielectronTrackCuts("TrkFilter","TrkFilter");
  // trkFilter->SetAODFilterBit(AliDielectronTrackCuts::kTPCqual);
  trkFilter->SetAODFilterBit(AliDielectronTrackCuts::kTPCqualSPDany);
  //  trkFilter->SetMinNCrossedRowsOverFindable(0.6);

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv TRACK CUTS vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  AliDielectronVarCuts *varCuts   = new AliDielectronVarCuts("VarCuts","VarCuts");
  AliDielectronTrackCuts *trkCuts = new AliDielectronTrackCuts("TrkCuts","TrkCuts");
  // specific cuts
  varCuts->AddCut(AliDielectronVarManager::kPt,           0.38, 5.);
  varCuts->AddCut(AliDielectronVarManager::kEta,         -0.8,   0.8);
  // if(periodLHC.Contains("LHC11h"))
  //   varCuts->AddCut(AliDielectronVarManager::kTPCclsSegments,7.,   8.0);
  varCuts->AddCut(AliDielectronVarManager::kNclsTPC,     70.0, 160.0);
  trkCuts->SetITSclusterCut(AliDielectronTrackCuts::kOneOf, 3); // SPD any

  // standard cuts
  varCuts->AddCut(AliDielectronVarManager::kImpactParXY, -1.0,   1.0);
  varCuts->AddCut(AliDielectronVarManager::kImpactParZ,  -3.0,   3.0);
  varCuts->AddCut(AliDielectronVarManager::kTPCchi2Cl,    0.0,   4.0);
  varCuts->AddCut(AliDielectronVarManager::kKinkIndex0,   0.);
  trkCuts->SetRequireITSRefit(kTRUE);
  trkCuts->SetRequireTPCRefit(kTRUE);

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv PID CUTS vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  //AliDielectronVarCuts *pidVarCuts = new AliDielectronVarCuts("varPIDCuts","varPIDCuts");
    AliDielectronPID *pidCuts        = new AliDielectronPID("PIDCuts","PIDCuts");
  // TOF inclusion
  //  pidVarCuts->AddCut(AliDielectronVarManager::kTOFbeta,      0.2,   0.9, kTRUE);
    pidCuts->AddCut(AliDielectronPID::kTOF,AliPID::kElectron,-3.0.,3.0,0.,0.,kFALSE, AliDielectronPID::kIfAvailable);
  // TPC inclusion
    pidCuts->AddCut(AliDielectronPID::kTPC,AliPID::kElectron,-3.5.,3.5);
    pidCuts->AddCut(AliDielectronPID::kTPC,AliPID::kPion,-100.,3.0,0.,0.,kTRUE);
  //  pidCuts->AddCut(AliDielectronPID::kTPC,AliPID::kProton,-100.,3.5,0.,0.,kTRUE);

  // PID cuts via varcuts to cut on the signal and not on nsigma
  //pidVarCuts->AddCut(AliDielectronVarManager::kTPCsignal,      75.,   77., kTRUE);

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv MC PID CUTS vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  AliDielectronVarCuts *pidCutsMC = new AliDielectronVarCuts("PIDCutsMC","PIDCutsMC");
  pidCutsMC->SetCutType(AliDielectronVarCuts::kAny);
  pidCutsMC->SetCutOnMCtruth(kTRUE);
  pidCutsMC->AddCut(AliDielectronVarManager::kPdgCode, -11., -11.);
  pidCutsMC->AddCut(AliDielectronVarManager::kPdgCode, +11., +11.);

  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv TENDER CUTS vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  // exclude conversion electrons selected by the tender
  AliDielectronTrackCuts *noconv=new AliDielectronTrackCuts("noConv","noConv");
  noconv->SetV0DaughterCut(AliPID::kElectron,kTRUE);

  // activate the cut sets (order might be CPU timewise important)
  if(hasMC) {
    //    cuts->AddCut(pidCutsMC);
  }
  else {
    if(!isESD) cuts->AddCut(trkFilter);
    cuts->AddCut(varCuts);
    cuts->AddCut(trkCuts);
    cuts->AddCut(pidCuts);
    //cuts->AddCut(pidVarCuts);
    //cuts->AddCut(noconv);
  }
  cuts->Print();

}

//______________________________________________________________________________________
void SetupV0Cuts(AliDielectron *die, Int_t cutDefinition)
{
  //
  // Setup the V0 cuts
  //

  // Quality cuts (add the gamma filter to the cut group)
  TIter next(die->GetTrackFilter().GetCuts());
  AliAnalysisCuts *cuts;
  while((cuts = (AliAnalysisCuts*)next())) {
    if(cuts->IsA() == AliDielectronCutGroup::Class())  break;
  }

  AliDielectronV0Cuts *gammaV0Cuts = new AliDielectronV0Cuts("IsGamma","IsGamma");
  gammaV0Cuts->SetPdgCodes(22,11,11);
  gammaV0Cuts->SetDefaultPID(16);
  gammaV0Cuts->AddCut(AliDielectronVarManager::kCosPointingAngle, TMath::Cos(0.02),   1.0, kFALSE);
  gammaV0Cuts->AddCut(AliDielectronVarManager::kChi2NDF,                       0.0,  10.0, kFALSE);
  gammaV0Cuts->AddCut(AliDielectronVarManager::kLegDist,                       0.0,   0.25, kFALSE);
  gammaV0Cuts->AddCut(AliDielectronVarManager::kR,                             3.0,  90.0, kFALSE);
  gammaV0Cuts->AddCut(AliDielectronVarManager::kPsiPair,                       0.0,   0.05, kFALSE);
  gammaV0Cuts->AddCut(AliDielectronVarManager::kM,                             0.0,   0.05, kFALSE);
  //  gammaV0Cuts->AddCut(AliDielectronVarManager::kOpeningAngle,              0.0,   0.1, kFALSE);
  gammaV0Cuts->AddCut(AliDielectronVarManager::kArmPt,                         0.0,   0.05, kFALSE);
  //  gammaV0Cuts->AddCut(AliDielectronVarManager::kArmAlpha,                     -0.35,  0.35, kFALSE); // not sure if it works as expected
  gammaV0Cuts->SetExcludeTracks(kTRUE);
  gammaV0Cuts->Print();

 //  const Double_t |cutAlphaG| < 0.35; &&  const Double_t cutQTG < 0.05;
 //  const Double_t |cutAlphaG2|[2] = {0.6, 0.8}; &&  const Double_t cutQTG2 < 0.04;

  if(cuts)
    ((AliDielectronCutGroup*)cuts)->AddCut(gammaV0Cuts);
  else
    die->GetTrackFilter().AddCuts(gammaV0Cuts);
}

//______________________________________________________________________________________
void SetupPairCuts(AliDielectron *die, Int_t cutDefinition)
{
  //
  // Setup the pair cuts
  //

  // conversion rejection
  Double_t gCut=0.05;
  AliDielectronVarCuts *gammaCuts = new AliDielectronVarCuts("GammaCuts","GammaCuts");
  gammaCuts->AddCut(AliDielectronVarManager::kM,            0.0,   gCut);
  //  die->GetPairPreFilter().AddCuts(gammaCuts);

  // rapidity selection
  Double_t yCut=0.9;
  AliDielectronVarCuts *rapCut=new AliDielectronVarCuts(Form("|Y|<%.1f",yCut),Form("|Y|<%.1f",yCut));
  rapCut->AddCut(AliDielectronVarManager::kY,-1.*yCut,yCut);
  die->GetPairFilter().AddCuts(rapCut);

}

//______________________________________________________________________________________
void InitHistograms(AliDielectron *die, Int_t cutDefinition)
{
  //
  // Initialise the histograms
  //
  Bool_t hasMC=die->GetHasMC();

  //Setup histogram Manager
  AliDielectronHistos *histos=new AliDielectronHistos(die->GetName(),die->GetTitle());

  //add histograms to event class
  histos->AddClass("Event");
  histos->UserHistogram("Event","","", 100, 0.0, 100.0,   AliDielectronVarManager::kCentralityNew);
  histos->UserHistogram("Event","","", 300,-15., +15.0,   AliDielectronVarManager::kZvPrim);
  histos->AddClass("Track_ev1+");
  histos->UserHistogram("Track_ev1+","","", 1000, 0., 10.,   AliDielectronVarManager::kPt);
  histos->AddClass("Track_ev1-");
  histos->UserHistogram("Track_ev1-","","", 1000, 0., 10.,   AliDielectronVarManager::kPt);
  // candidates monitoring
  histos->UserProfile("Event","","", AliDielectronVarManager::kTracks, 100,0,100., AliDielectronVarManager::kCentralityNew);
  histos->UserProfile("Event","","", AliDielectronVarManager::kPairs,  100,0,100., AliDielectronVarManager::kCentralityNew);

  die->SetHistogramManager(histos);
}

//______________________________________________________________________________________
void SetEtaCorrection(AliDielectron *die) {

  if (AliDielectronPID::GetCentroidCorrFunction()) return;

  TF2 *fCntrdCorr=0x0;
  TF1 *fWdthCorr=0x0;
  /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv DATA vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
  if( !die->GetHasMC() ) {
    // 2-dimensional eta correction for the centroid of electron sigmas
    fCntrdCorr = new TF2("fCntrdCorr", "[0] + [1]*y + [2]*y*y + [3]*TMath::Power(y,3) + [4]*TMath::Power(y,4) + [5]*TMath::Power(y,5) + [6]*TMath::Power(y,6) + [7]*x",
			 //0.0, 3000.0, -0.9, +0.9); // Nacc
			 0.0,   90.0, -0.9, +0.9); // centrality
    //  fCntrdCorr->SetParameters(0.723106, 0.23958, -6.31221, -0.687976, 15.912, 0.579609, -11.6901, -0.000354381); // Nacc
    fCntrdCorr->SetParameters(+0.149002, +0.214644 , -6.034930, -0.529588, +14.97902, +0.402640, -10.890027, +0.011248); // centrality
    // 1-dimensional eta correction for the width of electron sigmas
    // fWdthCorr = new TF1("fWdthCorr", "pol2", 0.0, 3000.0);     // Nacc
    // fWdthCorr->SetParameters(1.06108, 0.000217804,-5.80291e-08);
    fWdthCorr = new TF1("fWdthCorr", "pol2", 0.0, 90.0);       // centrality
    fWdthCorr->SetParameters(+1.290755, -0.005261, +0.000021);
  }
  else  {
    /* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv MONTE CARLO vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
    // 2-dimensional eta correction for the centroid of electron sigmas
    fCntrdCorr = new TF2("fCntrdCorr", "[0] + [1]*y + [2]*y*y + [3]*TMath::Power(y,3) + [4]*TMath::Power(y,4) + [5]*TMath::Power(y,5) + [6]*TMath::Power(y,6) + [7]*x",
			      0.0, 3000.0, -0.9, +0.9);
    fCntrdCorr->SetParameters(+0.378611, -0.070831, -3.076778, +0.121977, +8.576097, +0.113009, -5.001368, -0.000181);

    // 1-dimensional eta correction for the width of electron sigmas
    fWdthCorr = new TF1("fWdthCorr", "pol1", 0.0, 3000.0);
    fWdthCorr->SetParameters(+0.881894, +0.000053);
  }

  // apply corrections
  // AliDielectronPID::SetCentroidCorrFunction(fCntrdCorr,AliDielectronVarManager::kNacc,AliDielectronVarManager::kEta);
  // AliDielectronPID::SetWidthCorrFunction(fWdthCorr,AliDielectronVarManager::kNacc);
  AliDielectronPID::SetCentroidCorrFunction(fCntrdCorr,AliDielectronVarManager::kCentralityNew,AliDielectronVarManager::kEta);
  AliDielectronPID::SetWidthCorrFunction(fWdthCorr,AliDielectronVarManager::kCentralityNew);

}


text:
title: Granting Access to Developers
book: portal
chapter: 8
---

## Introduction

Since [Developers][developers] are a type of [Consumer](/0.13.x/getting-started/adding-consumers/), plugins and auth credentials can be similarly applied to them. In this section we will learn how Developers can get access to your routes and services by managing their credentials.

## How to Manage Your Developer Credentials

As a Developer, once you are [approved](/enterprise/{{page.kong_version}}/developer-portal/managing-developers/#developers-statuses), you can login to the Dev Portal Dashboard and [create](#creating-a-credential), [update](#updating-a-credential), or [delete](#deleting-a-credential) credentials. The credential options available will be based on which authentication plugins the Kong admin has enabled.

Current plugins supported:

- [ACL](/plugins/acl/)
- [Basic Authentication](/plugins/key-authentication/)
- [Key Authentication](/plugins/key-authentication/)
- [OAuth 2.0](/plugins/basic-authentication/)
- [HMAC Signature Authentication](/plugins/hmac-authentication/)
- [JWT](/plugins/jwt/)

> Note: This refers to Developer API credentials, not authentication for access to the Developer Portal. Learn more about which authentication plugins are supported by the Developer Portal on the [Authentication](/enterprise/0.33-x/developer-portal/configuration/authentication) page.

<video width="100%" autoplay loop controls>
  <source src="https://konghq.com/wp-content/uploads/2018/05/May-16-2018-15-44-26_.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

### Creating a Credential

In the Dev Portal Dashboard, click "Create API Credential". Select the Authentication plugin from the dropdown inside the modal window and fill out the form. Click "Create API Credential" inside the modal and you should see a confirmation that the credential was successfully created.

### Updating a Credential

In the Dev Portal Dashboard, find the credential you wish to edit. Click "Edit". Edit the form inside the modal window with updated information, then click "Edit API Credential". You should see a confirmation that the credential was successfully saved.

### Deleting a Credential

> WARNING: This is a destructive action. Deleting a credential means that all applications or services using this credential will no longer have access.

In the Dev Portal Dashboard, find the credential you wish to delete. Click the trash icon <svg data-v-1421dd7e="" width="14" height="16" xmlns="http://www.w3.org/2000/svg"><path data-v-1421dd7e="" d="M3 3V2c0-1.1045695.8954305-2 2-2h4c1.1045695 0 2 .8954305 2 2v1h2c.5522847 0 1 .4477153 1 1v1H0V4c0-.5522847.4477152-1 1-1h2zm2 0V2h4v1H5zM1 6h2v8h8V6h2v8c0 1.1045695-.8954305 2-2 2H3c-1.1045695 0-2-.8954305-2-2V6zm5 0v7c-.5522847 0-1-.4477153-1-1V7c0-.5522847.4477153-1 1-1zm2 0c.5522847 0 1 .4477153 1 1v5c0 .5522847-.4477153 1-1 1V6z" fill="#BFBFBF" fill-rule="evenodd"></path></svg>. In the confirmation modal, click "Delete API Credential" to delete. You should see a confirmation that the credential was successfully deleted.

[developers]: /enterprise/{{page.kong_version}}/developer-portal/glossary/#types-of-humans

Next: [File Management ›]({{page.book.next}})


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 67(4): 909 (1975)

#### Original name
Sebacina cremea McNabb, 1969

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8" />

    <link rel='stylesheet' href='https://cdn.wilddog.com/app/wildchat/0.6.0/wildchat.min.css' />


text:
package ca.loobo.restbot.reader.legacy;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runners.model.InitializationError;
import org.springframework.core.io.FileSystemResource;

import ca.loobo.restbot.Case;
import ca.loobo.restbot.Context;
import ca.loobo.restbot.reader.ResourceReader;
import ca.loobo.restbot.reader.legacy.LegacyExcelReader;

public class LegacyExcelReaderTest {

	//@Test
	public void test() throws InitializationError {
		Context ctx = new Context();
		ctx.setHost("test");
		ResourceReader rr = new LegacyExcelReader();
		rr.read(ctx, new FileSystemResource("resources/TQA_catalogRestApi_v5.4.xlsx"));
		rr.readProperties(ctx, new FileSystemResource("resources/TQA_catalogRestApi_v5.4_environmentParams.txt"));

		assertEquals(465, ctx.getCases().size());
		int i=0;
		for(Case c : ctx.getCases()) {
			System.err.println("handled " + ++i);
			try {
			c.getResponseTemplate();
			}catch(Exception e) {
				System.err.println(e.getMessage());
			}
		}
	}
}


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

<title>ca.ualberta.cmput301f13t13.storyhoard.local Class Hierarchy</title>
<meta name="date" content="2013-12-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Hierarchy For Package ca.ualberta.cmput301f13t13.storyhoard.local

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

ca.ualberta.cmput301f13t13.storyhoard.local.BogoPicGen

ca.ualberta.cmput301f13t13.storyhoard.local.DBContract

ca.ualberta.cmput301f13t13.storyhoard.local.DBContract.ChapterTable

ca.ualberta.cmput301f13t13.storyhoard.local.DBContract.ChoiceTable

ca.ualberta.cmput301f13t13.storyhoard.local.DBContract.MediaTable

ca.ualberta.cmput301f13t13.storyhoard.local.DBContract.StoryTable

SQLiteOpenHelper

ca.ualberta.cmput301f13t13.storyhoard.local.DBHelper

ca.ualberta.cmput301f13t13.storyhoard.local.StoringManager<A>

ca.ualberta.cmput301f13t13.storyhoard.local.ChapterManager

ca.ualberta.cmput301f13t13.storyhoard.local.ChoiceManager

ca.ualberta.cmput301f13t13.storyhoard.local.MediaManager

ca.ualberta.cmput301f13t13.storyhoard.local.StoryManager

ca.ualberta.cmput301f13t13.storyhoard.local.Syncher

ca.ualberta.cmput301f13t13.storyhoard.local.Utilities

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes


text:
package com.amazonaws.internal;

import java.io.IOException;
import java.io.InputStream;

import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.util.AWSRequestMetrics;

/**
 * Record input stream read time into {@link AWSRequestMetrics} under metric type
 * HttpSocketReadTime;
 */
public class MetricsInputStream extends DelegateInputStream {

    private AWSRequestMetrics metrics;

    public MetricsInputStream(InputStream in) {
        super(in);
    }

    public void setMetrics(AWSRequestMetrics metrics) {
        this.metrics = metrics;
    }

    /**
     * {@inheritDoc}
     * Record the read time into the metrics.
     */
    @Override
    public int read() throws IOException {
        if (metrics != null) {
            metrics.startEvent(Field.HttpSocketReadTime);
        }
        try {
            return in.read();
        } finally {
            if (metrics != null) {
                metrics.endEvent(Field.HttpSocketReadTime);
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * Record the read time into the metrics.
     */
    @Override
    public int read(byte b[]) throws IOException {
        if (metrics != null) {
            metrics.startEvent(Field.HttpSocketReadTime);
        }
        try {
            return in.read(b);
        } finally {
            if (metrics != null) {
                metrics.endEvent(Field.HttpSocketReadTime);
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * Record the read time into the metrics.
     */
    @Override
    public int read(byte b[], int off, int len) throws IOException {
        if (metrics != null) {
            metrics.startEvent(Field.HttpSocketReadTime);
        }
        try {
            return in.read(b, off, len);
        } finally {
            if (metrics != null) {
                metrics.endEvent(Field.HttpSocketReadTime);
            }
        }
    }
}


text:
package home.library.entities.loc;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the home.library.entities.loc package.
 * <p>An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _Mods_QNAME = new QName("http://www.loc.gov/mods/v3", "mods");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: home.library.entities.loc
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link OriginInfoType }
     *
     */
    public OriginInfoType createOriginInfoType() {
        return new OriginInfoType();
    }

    /**
     * Create an instance of {@link LibraryOfCongressBook }
     *
     */
    public LibraryOfCongressBook createModsType() {
        return new LibraryOfCongressBook();
    }

    /**
     * Create an instance of {@link DateIssuedType }
     *
     */
    public DateIssuedType createDateIssuedType() {
        return new DateIssuedType();
    }

    /**
     * Create an instance of {@link LanguageTermType }
     *
     */
    public LanguageTermType createLanguageTermType() {
        return new LanguageTermType();
    }

    /**
     * Create an instance of {@link RecordContentSourceType }
     *
     */
    public RecordContentSourceType createRecordContentSourceType() {
        return new RecordContentSourceType();
    }

    /**
     * Create an instance of {@link FormType }
     *
     */
    public FormType createFormType() {
        return new FormType();
    }

    /**
     * Create an instance of {@link LanguageType }
     *
     */
    public LanguageType createLanguageType() {
        return new LanguageType();
    }

    /**
     * Create an instance of {@link ClassificationType }
     *
     */
    public ClassificationType createClassificationType() {
        return new ClassificationType();
    }

    /**
     * Create an instance of {@link LocationType }
     *
     */
    public LocationType createLocationType() {
        return new LocationType();
    }

    /**
     * Create an instance of {@link RecordChangeDateType }
     *
     */
    public RecordChangeDateType createRecordChangeDateType() {
        return new RecordChangeDateType();
    }

    /**
     * Create an instance of {@link IdentifierType }
     *
     */
    public IdentifierType createIdentifierType() {
        return new IdentifierType();
    }

    /**
     * Create an instance of {@link TagType }
     *
     */
    public TagType createSubjectType() {
        return new TagType();
    }

    /**
     * Create an instance of {@link TitleInfoType }
     *
     */
    public TitleInfoType createTitleInfoType() {
        return new TitleInfoType();
    }

    /**
     * Create an instance of {@link RecordInfoType }
     *
     */
    public RecordInfoType createRecordInfoType() {
        return new RecordInfoType();
    }

    /**
     * Create an instance of {@link RecordCreationDateType }
     *
     */
    public RecordCreationDateType createRecordCreationDateType() {
        return new RecordCreationDateType();
    }

    /**
     * Create an instance of {@link NameType }
     *
     */
    public NameType createNameType() {
        return new NameType();
    }

    /**
     * Create an instance of {@link PhysicalDescriptionType }
     *
     */
    public PhysicalDescriptionType createPhysicalDescriptionType() {
        return new PhysicalDescriptionType();
    }

    /**
     * Create an instance of {@link PlaceType }
     *
     */
    public PlaceType createPlaceType() {
        return new PlaceType();
    }

    /**
     * Create an instance of {@link NoteType }
     *
     */
    public NoteType createNoteType() {
        return new NoteType();
    }

    /**
     * Create an instance of {@link UrlType }
     *
     */
    public UrlType createUrlType() {
        return new UrlType();
    }

    /**
     * Create an instance of {@link RelatedItemType }
     *
     */
    public RelatedItemType createRelatedItemType() {
        return new RelatedItemType();
    }

    /**
     * Create an instance of {@link PlaceTermType }
     *
     */
    public PlaceTermType createPlaceTermType() {
        return new PlaceTermType();
    }

    /**
     * Create an instance of {@link OriginInfoType.DateIssued }
     *
     */
    public OriginInfoType.DateIssued createOriginInfoTypeDateIssued() {
        return new OriginInfoType.DateIssued();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link LibraryOfCongressBook }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://www.loc.gov/mods/v3", name = "mods")
    public JAXBElement<LibraryOfCongressBook> createMods(LibraryOfCongressBook value) {
        return new JAXBElement<LibraryOfCongressBook>(_Mods_QNAME, LibraryOfCongressBook.class, null, value);
    }

}


text:
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"image"
	"image/png"
	"io/ioutil"
	"log"

	"github.com/gitchander/gofra/palgen"
	"github.com/gitchander/gofra/utils/random"
)

func main() {
	size := image.Point{512, 64}
	m := NewRGBASize(size)

	var p palgen.Params
	palgen.RandParams(random.NewRandNow(), &p)
	printJSON(p)

	palgen.DrawPalette(m, p)

	err := SaveImagePNG("palette.png", m)
	checkError(err)
}

func checkError(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func printJSON(v interface{}) {
	data, err := json.MarshalIndent(v, "", "\t")
	checkError(err)
	fmt.Printf("%s\n", data)
}

func NewRGBASize(size image.Point) *image.RGBA {
	r := image.Rectangle{Max: size}
	return image.NewRGBA(r)
}

func SaveImagePNG(filename string, m image.Image) error {
	var buf bytes.Buffer
	err := png.Encode(&buf, m)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(filename, buf.Bytes(), 0666)
}


text:
package org.apache.zeppelin.influxdb;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.util.Iterator;

import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.interpreter.InterpreterUtils;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Pong;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

/**
 * InfluxDB interpreter for Zeppelin.
 */
public class InfluxDBInterpreter extends Interpreter {
  private static final Logger LOGGER = LoggerFactory.getLogger(InfluxDBInterpreter.class);

  private static final char WHITESPACE = ' ';
  private static final char NEWLINE = '\n';
  private static final char TAB = '\t';
  private static final String EMPTY_COLUMN_VALUE = "";
  private static final String TABLE_MAGIC_TAG = "%table ";

  static {
    Interpreter.register("influxdb", InfluxDBInterpreter.class.getName());
  }

  public InfluxDBInterpreter(Properties property) {
    super(property);
  }

  @Override
  public void open() {
    for (Map.Entry<Object, Object> e : property.entrySet()) {
      String key = e.getKey().toString();
      String value = (e.getValue() == null) ? "" : e.getValue().toString();
      LOGGER.debug("Property: key: {}, value: {}", key, value);
    }
  }

  @Override
  public InterpreterResult interpret(String cmd, InterpreterContext interpreterContext) {
    LOGGER.info("Run influxDB command '{}'", cmd);

    StringBuilder msg = new StringBuilder();
    try {
      InfluxDB idb = InfluxDBFactory.connect(property.getProperty("default.url"),
          property.getProperty("default.user"), property.getProperty("default.password"));

      QueryResult query = idb.query(new Query(cmd, property.getProperty("default.database")));

      if (query.hasError()) {
        LOGGER.error("InfluxDB Query Error ", query.getError());
        msg.append(query.getError());
      } else {
        msg.append(TABLE_MAGIC_TAG);
        List<QueryResult.Result> results = query.getResults();
        LOGGER.debug("InfluxDB Query result '{}'", results.toString());
        QueryResult.Series data = results.get(0).getSeries().get(0);
        Iterator<String> columns = data.getColumns().iterator();
        Iterator<List<Object>> rows = data.getValues().iterator();
        while (columns.hasNext()) {
          msg.append(sanitize(columns.next()));
          if (columns.hasNext()) {
            msg.append(TAB);
          } else {
            msg.append(NEWLINE);
          }
        }
        while (rows.hasNext()) {
          Iterator<Object> row = rows.next().iterator();
          while (row.hasNext()) {
            Object elem = row.next();
            elem = (elem != null) ? elem : "";
            msg.append(sanitize(elem.toString()));
            if (row.hasNext()) {
              msg.append(TAB);
            } else {
              msg.append(NEWLINE);
            }
          }
        }
      }
    } catch (Exception e) {
      LOGGER.error("Error ", e);
      msg = new StringBuilder();
      msg.append(e);
    }
    return new InterpreterResult(Code.SUCCESS, msg.toString());
  }

  @Override
  public FormType getFormType() {
    return FormType.SIMPLE;
  }

  @Override
  public int getProgress(InterpreterContext context) {
    return 0;
  }

  @Override
  public Scheduler getScheduler() {
    return SchedulerFactory.singleton().createOrGetParallelScheduler(
        InfluxDBInterpreter.class.getName() + this.hashCode(), 5);
  }

  @Override
  public List<InterpreterCompletion> completion(String buf, int cursor) {
    return null;
  }

  @Override
  public void cancel(InterpreterContext context) {}

  @Override
  public void close() {}

  /**
 * For %table response replace Tab and Newline characters from the content.
 */
  private String sanitize(String str) {
    if (str == null) {
      return EMPTY_COLUMN_VALUE;
    }
    return str.replace(TAB, WHITESPACE).replace(NEWLINE, WHITESPACE);
  }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package lair.models;

import java.util.Objects;

/**
 *
 * @author dkottmann
 */
public class PluginId {

    private String tool;
    private String id;

    public PluginId() {
        this.tool = Constants.TOOL;
        this.id = "";
    }

    /**
     * @return the tool
     */
    public String getTool() {
        return tool;
    }

    /**
     * @param tool the tool to set
     */
    public void setTool(String tool) {
        this.tool = tool;
    }

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 67 * hash + Objects.hashCode(this.tool);
        hash = 67 * hash + Objects.hashCode(this.id);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PluginId other = (PluginId) obj;
        if (!Objects.equals(this.tool, other.tool)) {
            return false;
        }
        if (!Objects.equals(this.id, other.id)) {
            return false;
        }
        return true;
    }
}


text:
package com.ajlopez.ajlisp.forms;

import com.ajlopez.ajlisp.Environment;
import com.ajlopez.ajlisp.IForm;
import com.ajlopez.ajlisp.List;
import com.ajlopez.ajlisp.Machine;

public class MClosure implements IForm {
	private Environment closure;
	private IForm form;

	public MClosure(Environment closure, IForm form) {
		this.closure = closure;
		this.form = form;
	}

	public Object evaluate(Environment environment, List arguments) {
		return Machine.evaluate(environment, this.form.evaluate(this.closure, arguments));
	}
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2016 Couchbase, Inc
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#pragma once

#include "config.h"

#include <atomic>
#include <climits>
#include <list>
#include <string>

#include "ep_engine.h"
#include "locks.h"
#include "syncobject.h"
#include "atomicqueue.h"
#include "connmap.h"
#include "dcp/consumer.h"
#include "dcp/producer.h"

class DcpConnMap : public ConnMap {

public:

    DcpConnMap(EventuallyPersistentEngine &engine);

    /**
     * Find or build a dcp connection for the given cookie and with
     * the given name.
     */
    DcpProducer *newProducer(const void* cookie, const std::string &name,
                             bool notifyOnly);

    /**
     * Create a new consumer and add it in the list of TapConnections
     * @param e the engine
     * @param c the cookie representing the client
     * @return Pointer to the new dcp connection
     */
    DcpConsumer *newConsumer(const void* cookie, const std::string &name);

    void notifyVBConnections(uint16_t vbid, uint64_t bySeqno);

    void notifyBackfillManagerTasks();

    void removeVBConnections(connection_t &conn);

    /**
     * Close outbound (active) streams for a vbucket whenever a state
     * change is detected. In case of failovers, close inbound (passive)
     * streams as well.
     *
     * @param vbucket the vbucket id
     * @param state the new state of the vbucket
     * @closeInboundStreams bool flag indicating failover
     */
    void vbucketStateChanged(uint16_t vbucket, vbucket_state_t state,
                             bool closeInboundStreams = true);

    void shutdownAllConnections();

    /**
     * Handles the slow stream with the specified name.
     * Returns true if the stream dropped its cursors on the
     * checkpoint.
     */
    bool handleSlowStream(uint16_t vbid, const std::string &name);

    void disconnect(const void *cookie);

    void manageConnections();

    bool canAddBackfillToActiveQ();

    void decrNumActiveSnoozingBackfills();

    void updateMaxActiveSnoozingBackfills(size_t maxDataSize);

    uint16_t getNumActiveSnoozingBackfills () {
        SpinLockHolder lh(&numBackfillsLock);
        return numActiveSnoozingBackfills;
    }

    uint16_t getMaxActiveSnoozingBackfills () {
        SpinLockHolder lh(&numBackfillsLock);
        return maxActiveSnoozingBackfills;
    }

    ENGINE_ERROR_CODE addPassiveStream(ConnHandler& conn, uint32_t opaque,
                                       uint16_t vbucket, uint32_t flags);

    /* Use this only for any quick direct stats from DcpConnMap. To collect
       individual conn stats from conn lists please use ConnStatBuilder */
    void addStats(ADD_STAT add_stat, const void *c);

    /* Updates the minimum compression ratio to be achieved for docs by
     * all the producers, which will be in effect if the producer side
     * value compression is enabled */
    void updateMinCompressionRatioForProducers(float value);

    float getMinCompressionRatio();

protected:
    /*
     * deadConnections is protected (as opposed to private) because
     * of the module test ep-engine_dead_connections_test
     */
    std::list<connection_t> deadConnections;

private:

    bool isPassiveStreamConnected_UNLOCKED(uint16_t vbucket);

    void disconnect_UNLOCKED(const void *cookie);

    void closeAllStreams_UNLOCKED();

    void cancelAllTasks_UNLOCKED();

    SpinLock numBackfillsLock;
    /* Db file memory */
    static const uint32_t dbFileMem;
    uint16_t numActiveSnoozingBackfills;
    uint16_t maxActiveSnoozingBackfills;
    /* Max num of backfills we want to have irrespective of memory */
    static const uint16_t numBackfillsThreshold;
    /* Max percentage of memory we want backfills to occupy */
    static const uint8_t numBackfillsMemThreshold;

    std::atomic<float> minCompressionRatioForProducer;

    /* Total memory used by all DCP consumer buffers */
    std::atomic<size_t> aggrDcpConsumerBufferSize;

};


text:
package com.github.xsavikx.android.screencast.ui.interaction;

import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;

import javax.swing.SwingUtilities;

import com.github.xsavikx.android.screencast.api.command.executor.CommandExecutor;
import com.github.xsavikx.android.screencast.api.command.factory.AdbInputCommandFactory;
import com.github.xsavikx.android.screencast.api.injector.Injector;
import com.github.xsavikx.android.screencast.spring.config.ApplicationContextProvider;
import com.github.xsavikx.android.screencast.ui.JPanelScreen;

public class MouseActionAdapter extends MouseAdapter {
  private CommandExecutor commandExecutor;
  private final JPanelScreen jp;
  private Injector injector;
  private int dragFromX = -1;

  private int dragFromY = -1;
  private long timeFromPress = -1;
  private final static long ONE_SECOND = 1000L;

  public MouseActionAdapter(JPanelScreen jPanelScreen) {
    this.jp = jPanelScreen;
  }

  public MouseActionAdapter(JPanelScreen jPanelScreen, Injector injector) {
    this(jPanelScreen);
    this.injector = injector;
  }

  @Override
  public void mouseClicked(MouseEvent e) {
    if (injector != null && e.getButton() == MouseEvent.BUTTON3) {
      injector.screencapture.toogleOrientation();
      e.consume();
      return;
    }
    final Point p2 = jp.getRawPoint(e.getPoint());
    if (p2.x > 0 && p2.y > 0) {
      SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
          getCommandExecutor().execute(AdbInputCommandFactory.getTapCommand(p2.x, p2.y));

        }
      });
    }
  }

  @Override
  public void mouseDragged(MouseEvent e) {
    if (dragFromX == -1 && dragFromY == -1) {
      Point p2 = jp.getRawPoint(e.getPoint());
      dragFromX = p2.x;
      dragFromY = p2.y;
      timeFromPress = System.currentTimeMillis();
    }
  }

  @Override
  public void mouseReleased(MouseEvent e) {
    if (timeFromPress >= ONE_SECOND) {
      final Point p2 = jp.getRawPoint(e.getPoint());
      final int xFrom = dragFromX;
      final int yFrom = dragFromY;
      final int xTo = p2.x;
      final int yTo = p2.y;
      SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
          getCommandExecutor().execute(AdbInputCommandFactory.getSwipeCommand(xFrom, yFrom, xTo, yTo));
        }
      });
      dragFromX = -1;
      dragFromY = -1;
      timeFromPress = -1;
    }
  }

  @Override
  public void mouseWheelMoved(MouseWheelEvent arg0) {
    // if (JFrameMain.this.injector == null)
    // return;
    // JFrameMain.this.injector.injectTrackball(arg0.getWheelRotation() < 0 ?
    // -1f : 1f);
  }

  private CommandExecutor getCommandExecutor() {
    if (commandExecutor == null) {
      commandExecutor = ApplicationContextProvider.getApplicationContext().getBean(CommandExecutor.class);
    }
    return commandExecutor;
  }
}