text:
"""Tests for field serialization."""
from collections import namedtuple
import datetime as dt
import decimal

import pytest

from marshmallow import Schema, fields, utils
from marshmallow.exceptions import ValidationError
from marshmallow.compat import text_type, basestring

from tests.base import User, DummyModel, ALL_FIELDS

class DateTimeList:
    def __init__(self, dtimes):
        self.dtimes = dtimes

class IntegerList:
    def __init__(self, ints):
        self.ints = ints

class TestFieldSerialization:

    @pytest.fixture
    def user(self):
        return User("Foo", email="foo@bar.com", age=42)

    def test_default(self, user):
        field = fields.Field(default='nan')
        assert field.serialize('age', {}) == 'nan'

    @pytest.mark.parametrize(('value', 'expected'),
    [
        (42, float(42)),
        (0, float(0)),
        (None, None),
    ])
    def test_number(self, value, expected, user):
        field = fields.Number()
        user.age = value
        assert field.serialize('age', user) == expected

    def test_number_as_string(self, user):
        user.age = 42
        field = fields.Number(as_string=True)
        assert field.serialize('age', user) == str(float(user.age))

    def test_number_as_string_passed_none(self, user):
        user.age = None
        field = fields.Number(as_string=True, allow_none=True)
        assert field.serialize('age', user) is None

    def test_callable_default(self, user):
        field = fields.Field(default=lambda: 'nan')
        assert field.serialize('age', {}) == 'nan'

    def test_function_field(self, user):
        field = fields.Function(lambda obj: obj.name.upper())
        assert "FOO" == field.serialize("key", user)

    def test_function_field_passed_uncallable_object(self):
        with pytest.raises(ValueError):
            fields.Function('uncallable')

    def test_integer_field(self, user):
        field = fields.Integer()
        assert field.serialize('age', user) == 42

    def test_integer_as_string_field(self, user):
        field = fields.Integer(as_string=True)
        assert field.serialize('age', user) == '42'

    def test_integer_field_default(self, user):
        user.age = None
        field = fields.Integer(default=0)
        assert field.serialize('age', user) is None
        # missing
        assert field.serialize('age', {}) == 0

    def test_integer_field_default_set_to_none(self, user):
        user.age = None
        field = fields.Integer(default=None)
        assert field.serialize('age', user) is None

    def test_callable_field(self, user):
       field = fields.String()
       assert field.serialize('call_me', user) == 'This was called.'

    def test_decimal_field(self, user):
        user.m1 = 12
        user.m2 = '12.355'
        user.m3 = decimal.Decimal(1)
        user.m4 = None
        user.m5 = 'abc'
        user.m6 = [1, 2]

        field = fields.Decimal()
        assert isinstance(field.serialize('m1', user), decimal.Decimal)
        assert field.serialize('m1', user) == decimal.Decimal(12)
        assert isinstance(field.serialize('m2', user), decimal.Decimal)
        assert field.serialize('m2', user) == decimal.Decimal('12.355')
        assert isinstance(field.serialize('m3', user), decimal.Decimal)
        assert field.serialize('m3', user) == decimal.Decimal(1)
        assert field.serialize('m4', user) is None
        with pytest.raises(ValidationError):
            field.serialize('m5', user)
        with pytest.raises(ValidationError):
            field.serialize('m6', user)

        field = fields.Decimal(1)
        assert isinstance(field.serialize('m1', user), decimal.Decimal)
        assert field.serialize('m1', user) == decimal.Decimal(12)
        assert isinstance(field.serialize('m2', user), decimal.Decimal)
        assert field.serialize('m2', user) == decimal.Decimal('12.4')
        assert isinstance(field.serialize('m3', user), decimal.Decimal)
        assert field.serialize('m3', user) == decimal.Decimal(1)
        assert field.serialize('m4', user) is None
        with pytest.raises(ValidationError):
            field.serialize('m5', user)
        with pytest.raises(ValidationError):
            field.serialize('m6', user)

        field = fields.Decimal(1, decimal.ROUND_DOWN)
        assert isinstance(field.serialize('m1', user), decimal.Decimal)
        assert field.serialize('m1', user) == decimal.Decimal(12)
        assert isinstance(field.serialize('m2', user), decimal.Decimal)
        assert field.serialize('m2', user) == decimal.Decimal('12.3')
        assert isinstance(field.serialize('m3', user), decimal.Decimal)
        assert field.serialize('m3', user) == decimal.Decimal(1)
        assert field.serialize('m4', user) is None
        with pytest.raises(ValidationError):
            field.serialize('m5', user)
        with pytest.raises(ValidationError):
            field.serialize('m6', user)

    def test_decimal_field_string(self, user):
        user.m1 = 12
        user.m2 = '12.355'
        user.m3 = decimal.Decimal(1)
        user.m4 = None
        user.m5 = 'abc'
        user.m6 = [1, 2]

        field = fields.Decimal(as_string=True)
        assert isinstance(field.serialize('m1', user), basestring)
        assert field.serialize('m1', user) == '12'
        assert isinstance(field.serialize('m2', user), basestring)
        assert field.serialize('m2', user) == '12.355'
        assert isinstance(field.serialize('m3', user), basestring)
        assert field.serialize('m3', user) == '1'
        assert field.serialize('m4', user) is None
        with pytest.raises(ValidationError):
            field.serialize('m5', user)
        with pytest.raises(ValidationError):
            field.serialize('m6', user)

        field = fields.Decimal(1, as_string=True)
        assert isinstance(field.serialize('m1', user), basestring)
        assert field.serialize('m1', user) == '12.0'
        assert isinstance(field.serialize('m2', user), basestring)
        assert field.serialize('m2', user) == '12.4'
        assert isinstance(field.serialize('m3', user), basestring)
        assert field.serialize('m3', user) == '1.0'
        assert field.serialize('m4', user) is None
        with pytest.raises(ValidationError):
            field.serialize('m5', user)
        with pytest.raises(ValidationError):
            field.serialize('m6', user)

        field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True)
        assert isinstance(field.serialize('m1', user), basestring)
        assert field.serialize('m1', user) == '12.0'
        assert isinstance(field.serialize('m2', user), basestring)
        assert field.serialize('m2', user) == '12.3'
        assert isinstance(field.serialize('m3', user), basestring)
        assert field.serialize('m3', user) == '1.0'
        assert field.serialize('m4', user) is None
        with pytest.raises(ValidationError):
            field.serialize('m5', user)
        with pytest.raises(ValidationError):
            field.serialize('m6', user)

    def test_decimal_field_special_values(self, user):
        user.m1 = '-NaN'
        user.m2 = 'NaN'
        user.m3 = '-sNaN'
        user.m4 = 'sNaN'
        user.m5 = '-Infinity'
        user.m6 = 'Infinity'
        user.m7 = '-0'

        field = fields.Decimal(places=2, allow_nan=True)

        m1s = field.serialize('m1', user)
        assert isinstance(m1s, decimal.Decimal)
        assert m1s.is_qnan() and not m1s.is_signed()

        m2s = field.serialize('m2', user)
        assert isinstance(m2s, decimal.Decimal)
        assert m2s.is_qnan() and not m2s.is_signed()

        m3s = field.serialize('m3', user)
        assert isinstance(m3s, decimal.Decimal)
        assert m3s.is_qnan() and not m3s.is_signed()

        m4s = field.serialize('m4', user)
        assert isinstance(m4s, decimal.Decimal)
        assert m4s.is_qnan() and not m4s.is_signed()

        m5s = field.serialize('m5', user)
        assert isinstance(m5s, decimal.Decimal)
        assert m5s.is_infinite() and m5s.is_signed()

        m6s = field.serialize('m6', user)
        assert isinstance(m6s, decimal.Decimal)
        assert m6s.is_infinite() and not m6s.is_signed()

        m7s = field.serialize('m7', user)
        assert isinstance(m7s, decimal.Decimal)
        assert m7s.is_zero() and m7s.is_signed()

    def test_decimal_field_special_values_not_permitted(self, user):
        user.m1 = '-NaN'
        user.m2 = 'NaN'
        user.m3 = '-sNaN'
        user.m4 = 'sNaN'
        user.m5 = '-Infinity'
        user.m6 = 'Infinity'
        user.m7 = '-0'

        field = fields.Decimal(places=2)

        with pytest.raises(ValidationError):
            field.serialize('m1', user)
        with pytest.raises(ValidationError):
            field.serialize('m2', user)
        with pytest.raises(ValidationError):
            field.serialize('m3', user)
        with pytest.raises(ValidationError):
            field.serialize('m4', user)
        with pytest.raises(ValidationError):
            field.serialize('m5', user)
        with pytest.raises(ValidationError):
            field.serialize('m6', user)

        m7s = field.serialize('m7', user)
        assert isinstance(m7s, decimal.Decimal)
        assert m7s.is_zero() and m7s.is_signed()

    def test_boolean_field_serialization(self, user):
        field = fields.Boolean()

        user.truthy = 'non-falsy-ish'
        user.falsy = 'false'
        user.none = None

        assert field.serialize('truthy', user) == True
        assert field.serialize('falsy', user) == False
        assert field.serialize('none', user) == None

    def test_function_with_uncallable_param(self):
        with pytest.raises(ValueError):
            fields.Function("uncallable")

    def test_email_field_validates(self, user):
        user.email = 'bademail'
        field = fields.Email()
        with pytest.raises(ValidationError):
            field.serialize('email', user)

    def test_email_field_serialize_none(self, user):
        user.email = None
        field = fields.Email()
        assert field.serialize('email', user) is None

    def test_url_field_serialize_none(self, user):
        user.homepage = None
        field = fields.Url()
        assert field.serialize('homepage', user) is None

    def test_url_field_validates(self, user):
        user.homepage = 'badhomepage'
        field = fields.URL()
        with pytest.raises(ValidationError):
            field.serialize('homepage', user)

    def test_method_field_with_method_missing(self):
        class BadSerializer(Schema):
            bad_field = fields.Method('invalid')
        u = User('Foo')
        with pytest.raises(ValueError):
            BadSerializer().dump(u)

    def test_method_field_with_uncallable_attribute(self):
        class BadSerializer(Schema):
            foo = 'not callable'
            bad_field = fields.Method('foo')
        u = User('Foo')
        with pytest.raises(ValueError):
            BadSerializer().dump(u)

    def test_datetime_deserializes_to_iso_by_default(self, user):
        field = fields.DateTime()  # No format specified
        expected = utils.isoformat(user.created, localtime=False)
        assert field.serialize("created", user) == expected

    @pytest.mark.parametrize('fmt', ['rfc', 'rfc822'])
    def test_datetime_field_rfc822(self, fmt, user):
        field = fields.DateTime(format=fmt)
        expected = utils.rfcformat(user.created, localtime=False)
        assert field.serialize("created", user) == expected

    def test_localdatetime_rfc_field(self, user):
        field = fields.LocalDateTime(format='rfc')
        expected = utils.rfcformat(user.created, localtime=True)
        assert field.serialize("created", user) == expected

    @pytest.mark.parametrize('fmt', ['iso', 'iso8601'])
    def test_datetime_iso8601(self, fmt, user):
        field = fields.DateTime(format=fmt)
        expected = utils.isoformat(user.created, localtime=False)
        assert field.serialize("created", user) == expected

    def test_localdatetime_iso(self, user):
        field = fields.LocalDateTime(format="iso")
        expected = utils.isoformat(user.created, localtime=True)
        assert field.serialize("created", user) == expected

    def test_datetime_format(self, user):
        format = "%Y-%m-%d"
        field = fields.DateTime(format=format)
        assert field.serialize("created", user) == user.created.strftime(format)

    def test_string_field(self):
        field = fields.String()
        user = User(name=b'foo')
        assert field.serialize('name', user) == 'foo'
        field = fields.String(allow_none=True)
        user.name = None
        assert field.serialize('name', user) is None

    def test_formattedstring_field(self):
        field = fields.FormattedString('Hello {name}')
        user = User(name='Monty')
        assert field.serialize('name', user) == 'Hello Monty'

    def test_string_field_default_to_empty_string(self, user):
        field = fields.String(default='')
        assert field.serialize("notfound", {}) == ''

    def test_time_field(self, user):
        field = fields.Time()
        expected = user.time_registered.isoformat()[:12]
        assert field.serialize('time_registered', user) == expected

        user.time_registered = None
        assert field.serialize('time_registered', user) is None

    def test_date_field(self, user):
        field = fields.Date()
        assert field.serialize('birthdate', user) == user.birthdate.isoformat()

        user.birthdate = None
        assert field.serialize('birthdate', user) is None

    def test_timedelta_field(self, user):
        user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1)
        user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1)
        user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001)
        user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0)
        user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0)

        field = fields.TimeDelta(fields.TimeDelta.DAYS)
        assert field.serialize('d1', user) == 1
        field = fields.TimeDelta(fields.TimeDelta.SECONDS)
        assert field.serialize('d1', user) == 86401
        field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
        assert field.serialize('d1', user) == 86401000001

        field = fields.TimeDelta(fields.TimeDelta.DAYS)
        assert field.serialize('d2', user) == 1
        field = fields.TimeDelta(fields.TimeDelta.SECONDS)
        assert field.serialize('d2', user) == 86401
        field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
        assert field.serialize('d2', user) == 86401000001

        field = fields.TimeDelta(fields.TimeDelta.DAYS)
        assert field.serialize('d3', user) == 1
        field = fields.TimeDelta(fields.TimeDelta.SECONDS)
        assert field.serialize('d3', user) == 86401
        field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
        assert field.serialize('d3', user) == 86401000001

        field = fields.TimeDelta(fields.TimeDelta.DAYS)
        assert field.serialize('d4', user) == 0
        field = fields.TimeDelta(fields.TimeDelta.SECONDS)
        assert field.serialize('d4', user) == 0
        field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
        assert field.serialize('d4', user) == 0

        field = fields.TimeDelta(fields.TimeDelta.DAYS)
        assert field.serialize('d5', user) == -1
        field = fields.TimeDelta(fields.TimeDelta.SECONDS)
        assert field.serialize('d5', user) == -86400
        field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
        assert field.serialize('d5', user) == -86400000000

        user.d6 = None
        assert field.serialize('d6', user) is None

    def test_select_field(self, user):
        field = fields.Select(['male', 'female', 'transexual', 'asexual'])
        assert field.serialize("sex", user) == "male"
        invalid = User('foo', sex='alien')
        with pytest.raises(ValidationError):
            field.serialize('sex', invalid)

    def test_datetime_list_field(self):
        obj = DateTimeList([dt.datetime.utcnow(), dt.datetime.now()])
        field = fields.List(fields.DateTime)
        result = field.serialize('dtimes', obj)
        assert all([type(each) == str for each in result])

    def test_list_field_with_error(self):
        obj = DateTimeList(['invaliddate'])
        field = fields.List(fields.DateTime)
        with pytest.raises(ValidationError):
            field.serialize('dtimes', obj)

    def test_datetime_list_serialize_single_value(self):
        obj = DateTimeList(dt.datetime.utcnow())
        field = fields.List(fields.DateTime)
        result = field.serialize('dtimes', obj)
        assert len(result) == 1
        assert type(result[0]) == str

    def test_list_field_serialize_none_returns_none(self):
        obj = DateTimeList(None)
        field = fields.List(fields.DateTime)
        assert field.serialize('dtimes', obj) is None

    def test_list_field_respect_inner_attribute(self):
        now = dt.datetime.now()
        obj = DateTimeList([now])
        field = fields.List(fields.Int(attribute='day'))
        assert field.serialize('dtimes', obj) == [now.day]

    def test_list_field_respect_inner_attribute_single_value(self):
        now = dt.datetime.now()
        obj = DateTimeList(now)
        field = fields.List(fields.Int(attribute='day'))
        assert field.serialize('dtimes', obj) == [now.day]

    def test_list_field_work_with_generator_single_value(self):
        def custom_generator():
            yield dt.datetime.utcnow()
        obj = DateTimeList(custom_generator())
        field = fields.List(fields.DateTime)
        result = field.serialize('dtimes', obj)
        assert len(result) == 1

    def test_list_field_work_with_generators_multiple_values(self):
        def custom_generator():
            for dtime in [dt.datetime.utcnow(), dt.datetime.now()]:
                yield dtime
        obj = DateTimeList(custom_generator())
        field = fields.List(fields.DateTime)
        result = field.serialize('dtimes', obj)
        assert len(result) == 2

    def test_list_field_work_with_generators_error(self):
        def custom_generator():
            for dtime in [dt.datetime.utcnow(), "m", dt.datetime.now()]:
                yield dtime
        obj = DateTimeList(custom_generator())
        field = fields.List(fields.DateTime)
        with pytest.raises(ValidationError):
            field.serialize('dtimes', obj)

    def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement(self):
        def custom_generator():
            a = yield
            yield
        obj = DateTimeList(custom_generator())
        field = fields.List(fields.DateTime, allow_none=True)
        result = field.serialize('dtimes', obj)
        assert len(result) == 2
        assert result[0] is None
        assert result[1] is None

    def test_list_field_work_with_set(self):
        custom_set = set([1, 2, 3])
        obj = IntegerList(custom_set)
        field = fields.List(fields.Int)
        result = field.serialize("ints", obj)
        assert len(result) == 3
        assert 1 in result
        assert 2 in result
        assert 3 in result

    def test_list_field_work_with_custom_class_with_iterator_protocol(self):
        class IteratorSupportingClass:
            def __init__(self, iterable):
                self.iterable = iterable

            def __iter__(self):
                return iter(self.iterable)

        ints = IteratorSupportingClass([1, 2, 3])
        obj = IntegerList(ints)
        field = fields.List(fields.Int)
        result = field.serialize("ints", obj)
        assert len(result) == 3
        assert result[0] == 1
        assert result[1] == 2
        assert result[2] == 3

    def test_bad_list_field(self):
        class ASchema(Schema):
            id = fields.Int()
        with pytest.raises(ValueError):
            fields.List("string")
        with pytest.raises(ValueError) as excinfo:
            fields.List(ASchema)
        expected_msg = ('The type of the list elements must be a subclass '
                'of marshmallow.base.FieldABC')
        assert expected_msg in str(excinfo)

    def test_arbitrary_field(self, user):
        field = fields.Arbitrary()
        user.age = 12.3
        result = field.serialize('age', user)
        assert result == text_type(utils.float_to_decimal(user.age))

    def test_arbitrary_field_invalid_value(self, user):
        field = fields.Arbitrary()
        with pytest.raises(ValidationError):
            user.age = 'invalidvalue'
            field.serialize('age', user)

    def test_fixed_field(self, user):
        field = fields.Fixed(3)
        user.age = 42
        result = field.serialize('age', user)
        assert result == '42.000'

    def test_fixed_field_none(self, user):
        field = fields.Fixed()
        user.age = None
        assert field.serialize('age', user) is None

    def test_fixed_field_invalid_value(self, user):
        field = fields.Fixed()
        with pytest.raises(ValidationError):
            user.age = 'invalidvalue'
            field.serialize('age', user)

    def test_price_field(self, user):
        field = fields.Price()
        user.balance = 100
        assert field.serialize('balance', user) == '100.00'

    def test_price_field_none(self, user):
        field = fields.Price()
        user.balance = None
        assert field.serialize('balance', user) is None

    def test_serialize_does_not_apply_validators(self, user):
        field = fields.Field(validate=lambda x: False)
        # No validation error raised
        assert field.serialize('age', user) == user.age

    def test_query_select_field_func_key(self, user):
        user.du1 = DummyModel('a')
        user.du2 = DummyModel('b')
        user.du3 = DummyModel('c')
        user.du4 = DummyModel('d')
        query = lambda: [DummyModel(ch) for ch in 'abc']

        field = fields.QuerySelect(query, str)
        assert field.serialize('du1', user) == 'bar a'
        assert field.serialize('du2', user) == 'bar b'
        assert field.serialize('du3', user) == 'bar c'
        with pytest.raises(ValidationError):
            field.serialize('du4', user)

    def test_query_select_field_string_key(self, user):
        user.du1 = DummyModel('a')
        user.du2 = DummyModel('b')
        user.du3 = DummyModel('c')
        user.du4 = DummyModel('d')
        query = lambda: [DummyModel(ch) for ch in 'abc']

        field = fields.QuerySelect(query, 'foo')
        assert field.serialize('du1', user) == 'a'
        assert field.serialize('du2', user) == 'b'
        assert field.serialize('du3', user) == 'c'
        with pytest.raises(ValidationError):
            field.serialize('du4', user)

    def test_query_select_list_field_func_key(self, user):
        user.du1 = [DummyModel('a'), DummyModel('c'), DummyModel('b')]
        user.du2 = [DummyModel('d'), DummyModel('e'), DummyModel('e')]
        user.du3 = [DummyModel('a'), DummyModel('b'), DummyModel('f')]
        user.du4 = [DummyModel('a'), DummyModel('b'), DummyModel('b')]
        user.du5 = []
        query = lambda: [DummyModel(ch) for ch in 'abecde']

        field = fields.QuerySelectList(query, str)
        assert field.serialize('du1', user) == ['bar a', 'bar c', 'bar b']
        assert field.serialize('du2', user) == ['bar d', 'bar e', 'bar e']
        assert field.serialize('du5', user) == []
        with pytest.raises(ValidationError):
            field.serialize('du3', user)
        with pytest.raises(ValidationError):
            field.serialize('du4', user)

    def test_query_select_list_field_string_key(self, user):
        user.du1 = [DummyModel('a'), DummyModel('c'), DummyModel('b')]
        user.du2 = [DummyModel('d'), DummyModel('e'), DummyModel('e')]
        user.du3 = [DummyModel('a'), DummyModel('b'), DummyModel('f')]
        user.du4 = [DummyModel('a'), DummyModel('b'), DummyModel('b')]
        user.du5 = []
        query = lambda: [DummyModel(ch) for ch in 'abecde']

        field = fields.QuerySelectList(query, 'foo')
        assert field.serialize('du1', user) == ['a', 'c', 'b']
        assert field.serialize('du2', user) == ['d', 'e', 'e']
        assert field.serialize('du5', user) == []
        with pytest.raises(ValidationError):
            field.serialize('du3', user)
        with pytest.raises(ValidationError):
            field.serialize('du4', user)

    def test_constant_field_serialization(self, user):
        field = fields.Constant('something')
        assert field.serialize('whatever', user) == 'something'

    def test_constant_field_serialize_when_omitted(self):
        class MiniUserSchema(Schema):
            name = fields.Constant('bill')

        s = MiniUserSchema()
        assert s.dump({}).data['name'] == 'bill'

    @pytest.mark.parametrize('FieldClass', ALL_FIELDS)
    def test_all_fields_serialize_none_to_none(self, FieldClass):
        if FieldClass == fields.Enum:
            field = FieldClass(['bar', 'baz', None])
        elif FieldClass == fields.FormattedString:
            field = FieldClass('{foo}', allow_none=True)
        else:
            field = FieldClass(allow_none=True)

        res = field.serialize('foo', {'foo': None})
        if FieldClass == fields.FormattedString:
            assert res == 'None'
        else:
            assert res is None

def test_serializing_named_tuple():
    Point = namedtuple('Point', ['x', 'y'])

    field = fields.Field()

    p = Point(x=4, y=2)

    assert field.serialize('x', p) == 4

def test_serializing_named_tuple_with_meta():
    Point = namedtuple('Point', ['x', 'y'])
    p = Point(x=4, y=2)

    class PointSerializer(Schema):
        class Meta:
            fields = ('x', 'y')

    serialized = PointSerializer().dump(p)
    assert serialized.data['x'] == 4
    assert serialized.data['y'] == 2


text:
export * from './Clipboard';
export * from './Dimensions';
export * from './Geolocation';
export * from './Linking';
export * from './AsyncStorage';
export * from './Network';
export * from './UserPresence';
export * from './Accessibility';
export * from './Platform';
export * from './AppState';
export * from './Platform';

redpajama_set_name: RedPajamaGithub


text:
var CURRENT_VERSION = 89;

function mostrarLogCambios() {
    var div = recuadroBase();
    var divContenido = getDiv(CSS_CONTENIDO_RECUADRO);

    div.append(muestraSubtitulo(UI_DIALOGO_LOG_CAMBIOS_TITULO, true, true, [{texto:"X",delegado:cerrarLogCambios}]));
    divContenido.append($("#logCambios").html());
    div.append(divContenido);
    $("#contenidoResaltado").empty().append(div);
/*    $("#logCambios").dialog({
        modal: true,
        autoOpen: true,
        draggable: true,
        resizable: false,
        ////show: "puff",
        title: _l(UI_DIALOGO_LOG_CAMBIOS_TITULO),
        position: "center",
        closeOnEscape: true,
        width: ANCHO_DIALOGO,
        height: ALTO_DIALOGO,
        maxHeight: ALTO_DIALOGO
    });*/

    localStorage.ultimosCambiosVistos = CURRENT_VERSION;
}

function cerrarLogCambios() {
    $("#contenidoResaltado").empty();
}

function mostrarLicencia() {
    $("#licencia").dialog({
        modal: true,
        autoOpen: true,
        draggable: true,
        resizable: false,
        ////show: "puff",
        title: _l(UI_DIALOGO_LICENCIA_TITULO),
        position: "center",
        closeOnEscape: true,
        width: ANCHO_DIALOGO,
        height: ALTO_DIALOGO,
        maxHeight: ALTO_DIALOGO
    });
}


text:
<?php

namespace MYT\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{

//    public function getUserByUsername($username)
//    {
//        $qb = $this->createQueryBuilder('u');
//        $qb->add('select', 'user')
//           ->add('from',  'user u')
//           ->add('where', 'u.username = :username')
//           ->setParameter('username', $username);
//
//        return $qb->getQuery()->getResult();
//    }

    public function getUserByUsername($username)
    {
        $query = $this->getEntityManager()
            ->createQuery(
                'SELECT u FROM MakeYourTeamBundle:MyUser u WHERE u.username = :username'
            )->setParameter('username', $username);

        try {
            return $query->getSingleResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }

    }

}


text:
package com.mendeley.sdk.testUtils;

import android.text.TextUtils;

import com.mendeley.sdk.model.Annotation;
import com.mendeley.sdk.model.Document;
import com.mendeley.sdk.model.Education;
import com.mendeley.sdk.model.Employment;
import com.mendeley.sdk.model.File;
import com.mendeley.sdk.model.Folder;
import com.mendeley.sdk.model.Group;
import com.mendeley.sdk.model.Institution;
import com.mendeley.sdk.model.Person;
import com.mendeley.sdk.model.Profile;
import com.mendeley.sdk.model.ReadPosition;

import junit.framework.Assert;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * Class for asserting models in the tests
 */
public class AssertUtils {

    public static void assertDocuments(List<Document> expected, List<Document> actual) {
        Assert.assertEquals("Number of documents gotten", expected.size(), actual.size());

        for (int i = 0; i < expected.size(); i++) {
            assertDocument(expected.get(i), actual.get(i));
        }
    }

    public static void assertDocument(Document expected, Document actual) {
        Assert.assertEquals(expected.type, actual.type);
        Assert.assertEquals(expected.title, actual.title);
        Assert.assertEquals(expected.year, actual.year);
        Assert.assertEquals(expected.abstractString, actual.abstractString);
        Assert.assertEquals(expected.source, actual.source);
    }

    public static void assertPersons(List<Person> expected, List<Person> actual) {
        Assert.assertEquals("Number of persons gotten", expected.size(), actual.size());

        for (int i = 0; i < expected.size(); i++) {
            assertPerson(expected.get(i), actual.get(i));
        }
    }

    public static void assertPerson(Person expected, Person actual) {
        Assert.assertEquals(expected.firstName, actual.firstName);
        Assert.assertEquals(expected.lastName, actual.lastName);
    }

    public static void assertAnnotations(List<Annotation> expected, List<Annotation> actual) {
        Assert.assertEquals("Number of annotations gotten", expected.size(), actual.size());

        for (int i = 0; i < expected.size(); i++) {
            assertAnnotation(expected.get(i), actual.get(i));
        }
    }

    public static void assertAnnotation(Annotation expected, Annotation actual) {
        Assert.assertEquals(expected.type, actual.type);
        Assert.assertEquals(expected.text, actual.text);
        Assert.assertEquals(expected.documentId, actual.documentId);
        Assert.assertEquals(expected.fileHash, actual.fileHash);
    }

    public static void assertFiles(List<File> expected, List<File> actual) {
        Assert.assertEquals("Number of files gotten", expected.size(), actual.size());

        for (int i = 0; i < expected.size(); i++) {
            assertFile(expected.get(i), actual.get(i));
        }
    }

    public static void assertFile(File expected, File actual) {
        Assert.assertEquals(expected.documentId, actual.documentId);
        Assert.assertEquals(expected.mimeType, actual.mimeType);
    }

    public static void assertFolders(List<Folder> expected, List<Folder> actual) {
        Assert.assertEquals("Number of folders gotten", expected.size(), actual.size());

        for (int i = 0; i < expected.size(); i++) {
            assertFolder(expected.get(i), actual.get(i));
        }
    }

    public static void assertFolder(Folder expected, Folder actual) {
        Assert.assertEquals(expected.parentId, actual.parentId);
        Assert.assertEquals(expected.name, actual.name);
    }

    public static void assertGroup(Group expected, Group actual) {
        Assert.assertEquals(expected.id, actual.id);
        Assert.assertEquals(expected.name, actual.name);
    }

    public static void assertProfile(Profile expected, Profile actual) {
        if (!TextUtils.isEmpty(expected.id) && !TextUtils.isEmpty(actual.id)) {
            Assert.assertEquals(expected.id, actual.id);
        }
        Assert.assertEquals(expected.firstName, actual.firstName);
        Assert.assertEquals(expected.lastName, actual.lastName);
        Assert.assertEquals(expected.title, actual.title);
        Assert.assertEquals(expected.academicStatus, actual.academicStatus);
        assertInstitution(expected.institutionDetails, actual.institutionDetails);
        assertEmployments(expected.employment, actual.employment);
        assertEducations(expected.education, actual.education);
    }

    public static void assertProfilePhotos(List<Profile.Photo> expectedPhotos, List<Profile.Photo> actualPhotos) {
        Assert.assertEquals("number of photos", expectedPhotos.size(), actualPhotos.size());
        for (int i = 0; i < expectedPhotos.size(); i++) {
            assertProfilePhoto(expectedPhotos.get(i), actualPhotos.get(i));
        }
    }

    public static void assertProfilePhoto(Profile.Photo expectedPhoto, Profile.Photo actualPhoto) {
        Assert.assertEquals("is original photo", expectedPhoto.original, actualPhoto.original);
        Assert.assertEquals("photo url", expectedPhoto.url, actualPhoto.url);
        if (expectedPhoto.width != null) {
            Assert.assertEquals("photo width", actualPhoto.width, expectedPhoto.width);
        }
        if (expectedPhoto.height != null) {
            Assert.assertEquals("photo height", actualPhoto.height, expectedPhoto.height);
        }
    }

    public static void assertReadPositions(List<ReadPosition> expected, List<ReadPosition> actual) {
        Assert.assertEquals("Number of read positions gotten", expected.size(), actual.size());

        for (int i = 0; i < expected.size(); i++) {
            assertReadPosition(expected.get(i), actual.get(i));
        }
    }

    private static void assertReadPosition(ReadPosition expected, ReadPosition actual) {
        Assert.assertEquals(expected.fileId, actual.fileId);
        Assert.assertEquals(expected.page, actual.page);
        Assert.assertEquals(expected.verticalPosition, actual.verticalPosition);
        //cannot assert date as server ignores the posted date
    }

    public static void assertEmployments(List<Employment> expected, List<Employment> actual) {
        Assert.assertEquals("Number of employments gotten", expected.size(), actual.size());
        for (int i = 0; i < expected.size(); i++) {
            assertEmployment(expected.get(i), actual.get(i));
        }
    }

    public static void assertEducations(List<Education> expected, List<Education> actual) {
        Assert.assertEquals("Number of educations gotten", expected.size(), actual.size());
        for (int i = 0; i < expected.size(); i++) {
            assertEducation(expected.get(i), actual.get(i));
        }
    }

    public static void assertEmployment(Employment actual, Employment expected) {
        if (!TextUtils.isEmpty(expected.id) && !TextUtils.isEmpty(actual.id)) {
            Assert.assertEquals("Employment id", actual.id, expected.id);
        }
        Assert.assertEquals("Employment start date", actual.startDate, expected.startDate);
        Assert.assertEquals("Employment end date", actual.endDate, expected.endDate);
        Assert.assertEquals("Employment position", actual.position, expected.position);
        Assert.assertEquals("Employment website", actual.website, expected.website);
        Assert.assertEquals("Employment isMainEmployment", actual.isMainEmployment, expected.isMainEmployment);
        assertInstitution(actual.institution, expected.institution);
    }

    public static void assertEducation(Education actual, Education expected) {
        if (!TextUtils.isEmpty(expected.id) && !TextUtils.isEmpty(actual.id)) {
            Assert.assertEquals("Education id", actual.id, expected.id);
        }
        Assert.assertEquals("Education start date", actual.startDate, expected.startDate);
        Assert.assertEquals("Education end date", actual.endDate, expected.endDate);
        Assert.assertEquals("Education degree", actual.degree, expected.degree);
        Assert.assertEquals("Education website", actual.website, expected.website);
        assertInstitution(actual.institution, expected.institution);
    }

    public static void assertInstitution(Institution actual, Institution expected) {
        Assert.assertEquals("Institution id", actual.id, expected.id);
        Assert.assertEquals("Institution name", actual.name, expected.name);

        if (!TextUtils.isEmpty(expected.parentId) && !TextUtils.isEmpty(actual.parentId)) {
            Assert.assertEquals("Institution parentId", actual.parentId, expected.parentId);
        }
        if (!TextUtils.isEmpty(expected.city) && !TextUtils.isEmpty(actual.city)) {
            Assert.assertEquals("Institution end city", actual.city, expected.city);
        }
        if (!TextUtils.isEmpty(expected.country) && !TextUtils.isEmpty(actual.country)) {
            Assert.assertEquals("Institution country", actual.country, expected.country);
        }
        if (!TextUtils.isEmpty(expected.state) && !TextUtils.isEmpty(actual.state)) {
            Assert.assertEquals("Institution state", actual.state, expected.state);
        }
        if (!TextUtils.isEmpty(expected.profilerUrl) && !TextUtils.isEmpty(actual.profilerUrl)) {
            Assert.assertEquals("Institution profilerUrl", actual.profilerUrl, expected.profilerUrl);
        }
    }

    public static <T extends Object> void assertSameElementsInCollection(Collection<T> col1, Collection<T> col2, Comparator<T> comparator) {
        Assert.assertTrue(areSameElementsInCollection(col1, col2, comparator));
    }

    private static <T extends Object> boolean areSameElementsInCollection(Collection<T> col1, Collection<T> col2, Comparator<T> comparator) {
        if (col1.size() != col2.size()) {
            return false;
        }

        List<T> list1 = new ArrayList<T>(col1);
        Collections.sort(list1, comparator);

        List<T> list2 = new ArrayList<T>(col2);
        Collections.sort(list2, comparator);

        Iterator<T> i1 = list1.iterator(), i2 = list2.iterator();

        while (i1.hasNext() && i2.hasNext()) {
            if (comparator.compare(i1.next(), i2.next()) != 0) {
                return false;
            }
        }

        return true;
    }
}


text:
package org.drools.compiler.kie.builder.impl;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.kie.memorycompiler.resources.ResourceReader;

import static org.drools.core.util.IoUtils.readBytesFromInputStream;

public class DiskResourceReader implements ResourceReader {
    private final File root;

    private Map<String, Integer> filesHashing;

    public DiskResourceReader( final File pRoot ) {
        root = pRoot;
    }

    public boolean isAvailable( final String pResourceName ) {
        return new File(root, pResourceName).exists();
    }

    public byte[] getBytes( final String pResourceName ) {
        try {
            return readBytesFromInputStream(new FileInputStream(new File(root, pResourceName)));
        } catch(Exception e) {
            return null;
        }
    }

    public Collection<String> getFileNames() {
        List<String> list = new ArrayList();
        list(root, list);
        return list;
    }

    public void mark() {
        filesHashing = hashFiles();
    }

    public Collection<String> getModifiedResourcesSinceLastMark() {
        Set<String> modifiedResources = new HashSet<String>();
        Map<String, Integer> newHashing = hashFiles();
        for (Map.Entry<String, Integer> entry : newHashing.entrySet()) {
            Integer oldHashing = filesHashing.get(entry.getKey());
            if (oldHashing == null || !oldHashing.equals(entry.getValue())) {
                modifiedResources.add(entry.getKey());
            }
        }
        for (String oldFile : filesHashing.keySet()) {
            if (!newHashing.containsKey(oldFile)) {
                modifiedResources.add(oldFile);
            }
        }
        return modifiedResources;
    }

    private Map<String, Integer> hashFiles() {
        Map<String, Integer> hashing = new HashMap<String, Integer>();
        for (String fileName : getFileNames()) {
            byte[] bytes = getBytes( fileName );
            if ( bytes != null ) {
                hashing.put(fileName, Arrays.hashCode(bytes));
            }
        }
        return hashing;
    }

    /**
     * @deprecated
     */
    public String[] list() {
        final List<String> files = new ArrayList<String>();
        list(root, files);
        return files.toArray(new String[files.size()]);
    }

    /**
     * @deprecated
     */
    private void list( final File pFile, final List pFiles ) {
        if (pFile.isDirectory()) {
            final File[] directoryFiles = pFile.listFiles();
            for (int i = 0; i < directoryFiles.length; i++) {
                list(directoryFiles[i], pFiles);
            }
        } else {
            pFiles.add(pFile.getAbsolutePath().substring(root.getAbsolutePath().length()+1));
        }
    }

}


text:
__version__ = (0, 1, 0)

def short_version(version=None):
    """
    Return the short version number.

    For example: ``1.0.0``

    :param version: A tuple like ``(major, minor, micro, releaselevel)``.
        Default is :py:attr:`__version__`.
    :type version: tuple
    :rtype: str
    """
    v = version or __version__
    return '.'.join([str(x) for x in v[:3]])

def get_version(version=None):
    """
    Return the full version number, including rc, beta etc. tags.

    For example: ``2.0.0a1``

    :param version: A tuple like ``(major, minor, micro, releaselevel)``.
        Default is :py:attr:`__version__`.
    :type version: tuple
    :rtype: str
    """
    v = version or __version__
    if len(v) == 4:
        return '{0}{1}'.format(short_version(v), v[3])

    return short_version(v)

#: Library version number string.
version = get_version()

# Set default logging handler to avoid "No handler found" warnings.
import logging
from logging import NullHandler
logging.getLogger(__name__).addHandler(NullHandler())


text:
namespace value_store {

ValueStoreFactoryImpl::ValueStoreFactoryImpl(const base::FilePath& profile_path)
    : profile_path_(profile_path) {}

ValueStoreFactoryImpl::~ValueStoreFactoryImpl() = default;

base::FilePath ValueStoreFactoryImpl::GetDBPath(
    const base::FilePath& directory) const {
  DCHECK(!directory.empty());
  return profile_path_.Append(directory);
}

std::unique_ptr<ValueStore> ValueStoreFactoryImpl::CreateValueStore(
    const base::FilePath& directory,
    const std::string& uma_client_name) {
  return std::make_unique<LeveldbValueStore>(uma_client_name,
                                             GetDBPath(directory));
}

void ValueStoreFactoryImpl::DeleteValueStore(const base::FilePath& directory) {
  base::DeletePathRecursively(GetDBPath(directory));
}

bool ValueStoreFactoryImpl::HasValueStore(const base::FilePath& directory) {
  return base::DirectoryExists(GetDBPath(directory));
}

}  // namespace value_store


text:
FactoryGirl.define do
  factory :authentication do
    userid      "testuser"
    password    "secret"
    authtype    "default"
  end

  factory :authentication_status_error, :parent => :authentication do
    status      "Error"
    authtype    "bearer"
  end

  factory :authentication_ipmi, :parent => :authentication do
    authtype    "ipmi"
  end

  factory :authentication_ws, :parent => :authentication do
    authtype    "ws"
  end

  factory :authentication_ssh_keypair, :parent => :authentication, :class => 'ManageIQ::Providers::Openstack::InfraManager::AuthKeyPair' do
    authtype    "ssh_keypair"
    userid      "testuser"
    password    nil
    auth_key    'private_key_content'
  end

  factory :authentication_ssh_keypair_root, :parent => :authentication_ssh_keypair do
    userid      "root"
  end

  factory :authentication_ssh_keypair_without_key, :parent => :authentication_ssh_keypair do
    auth_key    nil
    status      "SomeMockedStatus"
  end

  factory :authentication_allow_all, :parent => :authentication, :class => "AuthenticationAllowAll" do
    authtype "AllowAllPasswordIdentityProvider"
  end

  factory :authentication_github, :parent => :authentication, :class => "AuthenticationGithub" do
    authtype "GitHubIdentityProvider"
    github_organizations ["github_organizations"]
  end

  factory :authentication_google, :parent => :authentication, :class => "AuthenticationGoogle" do
    authtype "GoogleIdentityProvider"
    google_hosted_domain "google_hosted_domain"
  end

  factory :authentication_htpasswd, :parent => :authentication, :class => "AuthenticationHtpasswd" do
    authtype "HTPasswdPasswordIdentityProvider"
    htpassd_users [{"htpassuser1" => "htpassword"}, {"htpassuser2" => "htpassword"}]
  end

  factory :authentication_ldap, :parent => :authentication, :class => "AuthenticationLdap" do
    authtype "LDAPPasswordIdentityProvider"
    ldap_id ["ldap_id"]
    ldap_email ["ldap_email"]
    ldap_name ["ldap_name"]
    ldap_preferred_user_name ["ldap_preferred_user_name"]
    ldap_bind_dn "ldap_bind_dn"
    ldap_insecure true
    ldap_url "ldap_url"
    certificate_authority "certificate_authority"
  end

  factory :authentication_open_id, :parent => :authentication, :class => "AuthenticationOpenId" do
    authtype "OpenIDIdentityProvider"
    open_id_sub_claim "open_id_sub_claim"
    open_id_user_info "open_id_user_info"
    open_id_authorization_endpoint "open_id_authorization_endpoint"
    open_id_token_endpoint "open_id_token_endpoint"
    open_id_extra_scopes ["open_id_extra_scopes"]
    open_id_extra_authorize_parameters "open_id_extra_authorize_parameters"
  end

  factory :authentication_request_header, :parent => :authentication, :class => "AuthenticationRequestHeader" do
    authtype "RequestHeaderIdentityProvider"
    request_header_challenge_url "request_header_challenge_url"
    request_header_login_url "request_header_login_url"
    request_header_headers ["request_header_headers"]
    request_header_preferred_username_headers ["request_header_preferred_username_headers"]
    request_header_name_headers ["request_header_name_headers"]
    request_header_email_headers ["request_header_email_headers"]
    certificate_authority "certificate_authority"
  end

  factory :authentication_redhat_metric, :parent => :authentication do
    authtype "metrics"
  end

  factory :automation_manager_authentication,
          :parent => :authentication,
          :class  => "ManageIQ::Providers::AutomationManager::Authentication"

  factory :embedded_automation_manager_authentication,
          :parent => :authentication,
          :class  => "ManageIQ::Providers::EmbeddedAutomationManager::Authentication"

  factory :ansible_cloud_credential,
          :parent => :automation_manager_authentication,
          :class  => "ManageIQ::Providers::AnsibleTower::AutomationManager::CloudCredential"

  factory :ansible_machine_credential,
          :parent => :automation_manager_authentication,
          :class  => "ManageIQ::Providers::AnsibleTower::AutomationManager::MachineCredential"

  factory :ansible_network_credential,
          :parent => :automation_manager_authentication,
          :class  => "ManageIQ::Providers::AnsibleTower::AutomationManager::NetworkCredential"

  factory :ansible_scm_credential,
          :parent => :automation_manager_authentication,
          :class  => "ManageIQ::Providers::AnsibleTower::AutomationManager::ScmCredential"

  factory :embedded_ansible_amazon_credential,
          :parent => :automation_manager_authentication,
          :class  => "ManageIQ::Providers::EmbeddedAnsible::AutomationManager::AmazonCredential"

  factory :embedded_ansible_machine_credential,
          :parent => :automation_manager_authentication,
          :class  => "ManageIQ::Providers::EmbeddedAnsible::AutomationManager::MachineCredential"

  factory :embedded_ansible_scm_credential,
          :parent => :automation_manager_authentication,
          :class  => "ManageIQ::Providers::EmbeddedAnsible::AutomationManager::ScmCredential"
end


text:
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using GitMind.Common.ThemeHandling;
using GitMind.Features.Diffing;
using GitMind.Features.Tags;
using GitMind.GitModel;
using GitMind.Utils.Git;
using GitMind.Utils.UI;
using IBranchService = GitMind.Features.Branches.IBranchService;
using ICommitsService = GitMind.Features.Commits.ICommitsService;

namespace GitMind.RepositoryViews
{
	internal class CommitViewModel : ViewModel
	{
		private readonly IBranchService branchService;
		private readonly IDiffService diffService;
		private readonly IThemeService themeService;
		private readonly IRepositoryCommands repositoryCommands;
		private readonly ICommitsService commitsService;
		private readonly ITagService tagService;

		private Commit commit;

		private int windowWidth;

		public CommitViewModel(
			IBranchService branchService,
			IDiffService diffService,
			IThemeService themeService,
			IRepositoryCommands repositoryCommands,
			ICommitsService commitsService,
			ITagService tagService)
		{
			this.branchService = branchService;
			this.diffService = diffService;
			this.themeService = themeService;
			this.repositoryCommands = repositoryCommands;
			this.commitsService = commitsService;
			this.tagService = tagService;
		}

		public int ZIndex => 400;
		public string Type => nameof(CommitViewModel);
		public string CommitId => Commit.RealCommitSha.Sha;
		public string ShortId => Commit.RealCommitSha.ShortSha;
		public string Author => Commit.Author;
		public string Date => Commit.AuthorDateText;
		public string Subject { get; private set; }
		//public string Tags { get; private set; }
		//public string Tickets => Commit.Tickets;
		public string BranchTips => Commit.BranchTips;
		public string CommitBranchText => $"Hide branch: {Commit.Branch.Name}";
		public string SwitchToBranchText => $"Switch to branch: {Commit.Branch.Name}";
		public string MergeBranchCommitText => $"Merge from this commit to branch: {Commit.Repository.CurrentBranch.Name}";
		public string PreviewMergeBranchCommitText => $"Preview merge from this commit to branch: {Commit.Repository.CurrentBranch.Name}";
		public string CommitBranchName => Commit.Branch.Name;
		public bool IsCurrent => Commit.IsCurrent;
		public bool IsUncommitted => Commit.IsUncommitted;
		public bool IsNotUncommitted => !Commit.IsUncommitted;
		public bool CanUncommit => UncommitCommand.CanExecute();
		public bool CanUndo => !Commit.IsUncommitted;
		public bool IsShown => BranchTips == null;
		public string BranchToolTip { get; set; }
		public bool CanMerge => Commit.Branch.IsCanBeMergeToOther;

		public int XPoint { get; set; }
		public int YPoint => IsEndPoint ? 4 : IsMergePoint ? 2 : 4;
		public int Size => IsEndPoint ? 8 : IsMergePoint ? 10 : 6;
		public Rect Rect { get; set; }
		public double Top => Rect.Top;
		public double Left => Rect.Left;
		public double Height => Rect.Height;
		public Brush SubjectBrush { get; set; }
		public Brush TagBrush { get; set; }
		public Brush TagBackgroundBrush { get; set; }
		public Brush TicketBrush { get; set; }
		public Brush TicketBackgroundBrush { get; set; }
		public Brush BranchTipBrush { get; set; }
		public bool HasDeleteTags => DeleteTagItems.Any();
		//public FontWeight SubjectWeight => Commit.CommitBranchName != null ? FontWeights.Bold : FontWeights.Normal;

		public string ToolTip { get; set; }
		public Brush Brush { get; set; }
		public FontStyle SubjectStyle => Commit.IsVirtual ? FontStyles.Italic : FontStyles.Normal;
		public Brush HoverBrush => themeService.Theme.HoverBrush;

		public ObservableCollection<LinkItem> Tickets { get; private set; }
		public ObservableCollection<LinkItem> Tags { get; private set; }

		public ObservableCollection<DeleteTagItem> DeleteTagItems { get; private set; }

		public double Width
		{
			get { return Get(); }
			set { Set(value - 2); }
		}

		public int GraphWidth
		{
			get { return Get(); }
			set { Set(value); }
		}

		public Brush BrushInner
		{
			get { return Get(); }
			set { Set(value); }
		}

		public int WindowWidth
		{
			get { return windowWidth; }
			set
			{
				if (windowWidth != value)
				{
					windowWidth = value;
					Width = windowWidth - 35;
				}
			}
		}

		public Command CommitCommand => AsyncCommand(() => commitsService.CommitChangesAsync());

		public Command ToggleDetailsCommand => Command(repositoryCommands.ToggleCommitDetails);
		public Command ShowCommitDiffCommand => Command(
			() => repositoryCommands.ShowDiff(
				Commit.IsVirtual && !Commit.IsUncommitted ? Commit.FirstParent : Commit));

		public Command SetCommitBranchCommand => Command(
			() => commitsService.EditCommitBranchAsync(Commit));
		public Command SwitchToCommitCommand => Command(
			() => branchService.SwitchToBranchCommitAsync(Commit),
			() => branchService.CanExecuteSwitchToBranchCommit(Commit));

		public Command SwitchToBranchCommand => Command(
			() => branchService.SwitchBranchAsync(Commit.Branch),
			() => branchService.CanExecuteSwitchBranch(Commit.Branch));

		public Command CreateBranchFromCommitCommand => Command(
			() => branchService.CreateBranchFromCommitAsync(Commit));

		public Command UndoUncommittedChangesCommand => AsyncCommand(
			() => commitsService.UndoUncommittedChangesAsync());

		public Command CleanWorkingFolderCommand => AsyncCommand(
			commitsService.CleanWorkingFolderAsync);

		public Command UncommitCommand => AsyncCommand(
		 () => commitsService.UnCommitAsync(Commit), () => commitsService.CanUnCommit(Commit));

		public Command UndoCommitCommand => AsyncCommand(
			() => commitsService.UndoCommitAsync(Commit), () => commitsService.CanUndoCommit(Commit));

		public Command MergeBranchCommitCommand => AsyncCommand(() => branchService.MergeBranchCommitAsync(Commit));

		public Command PreviewMergeCommitBranchCommand => AsyncCommand(
			() => diffService.ShowPreviewMergeDiffAsync(
				Commit.Repository.CurrentCommit.RealCommitSha, Commit.RealCommitSha));

		public Command AddTagCommitCommand => AsyncCommand(() => tagService.AddTagAsync(Commit.RealCommitSha));

		// Values used by other properties
		public Commit Commit
		{
			get => commit;
			set
			{
				commit = value;
				SetCommitValues();
			}
		}

		// If second parent is other branch (i.e. no a pull merge)
		// If commit is first commit in a branch (first parent is other branch)
		// If commit is tip commit, but not master
		public bool IsMergePoint =>
			(Commit.IsMergePoint && Commit.Branch != Commit.SecondParent.Branch)
			|| (Commit.HasFirstParent && Commit.Branch != Commit.FirstParent.Branch)
			|| (Commit == Commit.Branch.TipCommit && Commit.Branch.Name != BranchName.Master);

		public bool IsEndPoint =>
			(Commit.HasFirstParent && Commit.Branch != Commit.FirstParent.Branch)
			|| (Commit == Commit.Branch.TipCommit && Commit.Branch.Name != BranchName.Master);

		// Value used by merge and that determine if item is visible
		public BranchViewModel BranchViewModel { get; set; }
		public int RowIndex { get; set; }
		public int X => BranchViewModel?.X ?? -20;
		public int Y => Converters.ToY(RowIndex) + 10;

		public void SetDim()
		{
			SubjectBrush = themeService.Theme.DimBrush;
			TagBrush = themeService.Theme.DimBrush;
			TicketBackgroundBrush = themeService.Theme.BackgroundBrush;
			TicketBrush = themeService.Theme.DimBrush;
			TicketBackgroundBrush = themeService.Theme.BackgroundBrush;
			BranchTipBrush = themeService.Theme.DimBrush;

			Notify(nameof(SubjectBrush), nameof(TicketBrush), nameof(TagBrush), nameof(BranchTipBrush));
		}

		public void SetNormal(Brush subjectBrush)
		{
			SubjectBrush = subjectBrush;
			TagBrush = themeService.Theme.TagBrush;
			TagBackgroundBrush = themeService.Theme.TagBackgroundBrush;
			TicketBrush = themeService.Theme.TicketBrush;
			TicketBackgroundBrush = themeService.Theme.TicketBackgroundBrush;
			BranchTipBrush = themeService.Theme.BranchTipsBrush;

			Notify(nameof(SubjectBrush), nameof(TicketBrush), nameof(TagBrush), nameof(BranchTipBrush));
		}

		private void SetCommitValues()
		{
			ObservableCollection<LinkItem> issueItems = new ObservableCollection<LinkItem>();
			ObservableCollection<LinkItem> tagItems = new ObservableCollection<LinkItem>();
			ObservableCollection<DeleteTagItem> deleteTagItems = new ObservableCollection<DeleteTagItem>();

			Links subjectIssueLinks = commitsService.GetIssueLinks(Commit.Message);

			if (!string.IsNullOrEmpty(Commit.Tags))
			{
				var tags = Commit.Tags.Split(":".ToCharArray()).Where(n => !string.IsNullOrEmpty(n)).ToList();

				foreach (string tag in tags)
				{
					deleteTagItems.Add(new DeleteTagItem(tagService, tag));

					Links tagIssueLinks = commitsService.GetIssueLinks(tag);
					Links tagTagLinks = commitsService.GetTagLinks(tag);
					if (tagIssueLinks.AllLinks.Any())
					{
						tagIssueLinks.AllLinks.ForEach(link => issueItems.Add(new LinkItem(this, $"[{link.Text}]", link.Uri, link.LinkType)));
					}
					else if (tagTagLinks.AllLinks.Any())
					{
						tagTagLinks.AllLinks.ForEach(link => tagItems.Add(new LinkItem(this, $"[{link.Text}]", link.Uri, link.LinkType)));
					}
					else
					{
						tagItems.Add(new LinkItem(this, $"[{tag}]", null, LinkType.tag));
					}
				}
			}

			DeleteTagItems = deleteTagItems;
			Tags = tagItems;

			Subject = GetTextWithoutStart(Commit.Subject, subjectIssueLinks.TotalText);

			subjectIssueLinks.AllLinks.ForEach(link => issueItems.Add(new LinkItem(this, link.Text, link.Uri, link.LinkType)));

			Tickets = issueItems;
		}

		public override string ToString() => $"{ShortId} {Subject} {Date}";

		private static string GetTextWithoutStart(string text, string startText)
		{
			if ((text?.Length ?? 0) < (startText?.Length ?? 0))
			{
				return text;
			}

			if (text != null && startText != null && text.StartsWith(startText))
			{
				return text?.Substring(startText?.Length ?? 0);
			}

			return text;
		}
	}
}


text:
layout: post
title: "IntelliJ Rust Changelog #80"
date: 2018-08-06 14:52:51 +0300
---

## New Features

* Add `Needless lifetimes` inspection to check unnecessary lifetimes which can be removed.
See the corresponding clippy [inspection](https://github.com/rust-lang-nursery/rust-clippy/wiki#needless_lifetimes)

* Support method separators. You can enable this feature
via  `Preferences | Editor | General | Appearance | Show method separators` (by [@t-kameyama])

* Add `Assign to immutable` inspection
which annotates wrong assignments to element or field of the corresponding immutable array or struct

* Support `Inject Language` intention for rust string literals

* Implement new `Show expanded macro` and `Show recursively expanded macro` actions.
Now you can see how the plugin expands macros

* Validate package name while new project creation

* Implement `Goto definition` action for dependencies in `Cargo.toml`.
Now it navigates you to `lib.rs` of the corresponding crate

* Support `crate` keyword at the beginning of paths

* Allow attaching cargo project by directory with `Cargo.toml`

## Fixes

* Better completion for partial unknown types

* Fix false positive `Cannot borrow immutable local variable` annotation for index expressions

* Avoid UI freezes while typing string literals

* Don't reset run configuration working directory on each reopening `Edit configuration` window

* Correctly process empty groups while macro expansion

* Consider `self` and `Self` as identifiers in macro expansion

* Support parenthesized around bounds like `fn foo<T: (Bar)>(t: T)`

## Internal Improvements

* Update IDEA & CLion. Now 2018.2 platform is default for development

* Initial work on macro expansion in type and pattern context.
Note, name resolution and type inference are not supposed to work with such macros yet

[@t-kameyama]: https://github.com/t-kameyama


text:
<?php

namespace Dingo\Api\Tests\Http\Response\Format;

use Mockery;
use Dingo\Api\Http\Response;
use Illuminate\Http\Request;
use PHPUnit_Framework_TestCase;
use Illuminate\Support\MessageBag;
use Dingo\Api\Http\Response\Format\Jsonp;
use Dingo\Api\Tests\Stubs\EloquentModelStub;
use Illuminate\Database\Eloquent\Collection;

class JsonpTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $formatter = new Jsonp;
        $formatter->setRequest(Request::create('GET', '/', ['callback' => 'foo']));

        Response::setFormatters(['json' => $formatter]);
    }

    public function tearDown()
    {
        Mockery::close();

        Response::setFormatters([]);
    }

    public function testMorphingEloquentModel()
    {
        $response = (new Response(new EloquentModelStub))->morph();

        $this->assertSame('foo({"foo_bar":{"foo":"bar"}});', $response->getContent());
    }

    public function testMorphingEloquentCollection()
    {
        $response = (new Response(new Collection([new EloquentModelStub, new EloquentModelStub])))->morph();

        $this->assertSame('foo({"foo_bars":[{"foo":"bar"},{"foo":"bar"}]});', $response->getContent());
    }

    public function testMorphingEmptyEloquentCollection()
    {
        $response = (new Response(new Collection))->morph();

        $this->assertSame('foo([]);', $response->getContent());
    }

    public function testMorphingString()
    {
        $response = (new Response('foo'))->morph();

        $this->assertSame('foo', $response->getContent());
    }

    public function testMorphingArray()
    {
        $messages = new MessageBag(['foo' => 'bar']);

        $response = (new Response(['foo' => 'bar', 'baz' => $messages]))->morph();

        $this->assertSame('foo({"foo":"bar","baz":{"foo":["bar"]}});', $response->getContent());
    }

    public function testMorphingUnknownType()
    {
        $this->assertSame(1, (new Response(1))->morph()->getContent());
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/storagetransfer/v1/transfer.proto

namespace Google\Cloud\StorageTransfer\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request passed to GetTransferJob.
 *
 * Generated from protobuf message google.storagetransfer.v1.GetTransferJobRequest
 */
class GetTransferJobRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required.
     * The job to get.
     *
     * Generated from protobuf field string job_name = 1 [(.google.api.field_behavior) = REQUIRED];
     */
    private $job_name = '';
    /**
     * Required. The ID of the Google Cloud Platform Console project that owns the
     * job.
     *
     * Generated from protobuf field string project_id = 2 [(.google.api.field_behavior) = REQUIRED];
     */
    private $project_id = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $job_name
     *           Required.
     *           The job to get.
     *     @type string $project_id
     *           Required. The ID of the Google Cloud Platform Console project that owns the
     *           job.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Storagetransfer\V1\Transfer::initOnce();
        parent::__construct($data);
    }

    /**
     * Required.
     * The job to get.
     *
     * Generated from protobuf field string job_name = 1 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getJobName()
    {
        return $this->job_name;
    }

    /**
     * Required.
     * The job to get.
     *
     * Generated from protobuf field string job_name = 1 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setJobName($var)
    {
        GPBUtil::checkString($var, True);
        $this->job_name = $var;

        return $this;
    }

    /**
     * Required. The ID of the Google Cloud Platform Console project that owns the
     * job.
     *
     * Generated from protobuf field string project_id = 2 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getProjectId()
    {
        return $this->project_id;
    }

    /**
     * Required. The ID of the Google Cloud Platform Console project that owns the
     * job.
     *
     * Generated from protobuf field string project_id = 2 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setProjectId($var)
    {
        GPBUtil::checkString($var, True);
        $this->project_id = $var;

        return $this;
    }

}


text:
package net.firejack.platform.core.config.meta.expr;

public class FunctionExpression<T> implements IExpression<T> {

    private ExpressionFunctions function;
    private Object[] parameters;

    /**
     * @param function
     * @param parameters
     */
    public FunctionExpression(ExpressionFunctions function, Object[] parameters) {
        this.function = function;
        this.parameters = parameters;
    }

    @Override
    public T evaluate(IExpressionContext<T> context) throws ExpressionEvaluationException {
        IExpressionSupport<T> expressionSupport = context.getExpressionSupport();
        return expressionSupport.function(function, parameters);
    }
}


text:
DROP TABLE IF EXISTS `APP_USER`;
DROP TABLE IF EXISTS `MUSHROOM`;
DROP TABLE IF EXISTS `MUSHROOM_FIND`;
DROP TABLE IF EXISTS `RECIPE`;
DROP TABLE IF EXISTS `RECIPE_MUSHROOMS`;
DROP TABLE IF EXISTS `SPORE_COLOR`;
DROP TABLE IF EXISTS `CAP_SHAPE`;
DROP TABLE IF EXISTS `GILL_ATTATCHMENT`;
DROP TABLE IF EXISTS `SPORE_SURFACE`;


text:
enum {
  kMenuFormTableViewSectionItems = 0,
  kMenuFormTableViewSectionOther
};

@interface MenuFormViewController : FRCFormViewController {
  NSMutableSet *_selectedManagedObjects;
}

// Properties
@property(nonatomic, copy) NSString *titleKey;
@property(nonatomic, copy) NSString *userAdditionPlaceholderText;

@property(nonatomic, assign) BOOL allowMultipleSelections;
@property(nonatomic, assign) BOOL allowEmptySelection;
@property(nonatomic, assign) BOOL allowUserAdditions;

// Instance Methods
- (void)setSelectedManagedObjects:(NSSet *)selectedObjects;

@end


text:
<?php
/*

* Define class Modules Manager List

* Make sure you skip down to the end of this file, as there are a few

* lines of code that are very important.

*/
!defined('ABSPATH') and exit;
if (class_exists('aaModulesManger') != true) {
	class aaModulesManger
	{
		/*
		* Some required plugin information
		*/
		const VERSION = '1.0';

		/*
		* Store some helpers config
		*
		*/
		public $cfg = array();

		/*
		* Store some helpers config
		*/
		public $the_plugin = null;

		private $module_folder = '';
		private $module = '';

		private $settings = array();

		static protected $_instance;

		/**
	    * Singleton pattern
	    *
	    * @return Singleton instance
	    */
		static public function getInstance()
		{
			if (!self::$_instance) {
				self::$_instance = new self;
			}

			return self::$_instance;
		}

		/*
		* Required __construct() function that initalizes the AA-Team Framework
		*/
		public function __construct() //public function __construct($cfg)
		{
			global $psp;

			$this->the_plugin = $psp;
			$this->module_folder = $this->the_plugin->cfg['paths']['plugin_dir_url'] . 'modules/modules_manager/';
			$this->module = $this->the_plugin->cfg['modules']['modules_manager'];

			$this->settings = $this->the_plugin->getAllSettings( 'array', 'modules_manager' );

			$this->cfg = $this->the_plugin->cfg;
		}

		public function printListInterface()
		{
			$html   = array();

			$html[] = '

' . __('Loading', 'psp') . '

			';

			$html[] = '';

			$html[] = '
';

			$cc     = 0;

			$icon = array(
			    'Backlink_Builder'		=> 		'',
			    'capabilities'			=> 		'',
			    'Google_Analytics' 		=> 		'',
			    'Link_Builder'			=> 		'',
			    'Link_Redirect'			=> 		'',
			    'Minify'				=> 		'',
			    'Social_Stats'			=> 		'',
			    'W3C_HTMLValidator'		=> 		'',
			    'facebook_planner'		=> 		'',
			    'file_edit'				=> 		'',
			    'frontend'				=> 		'
                ',
			    'google_authorship'		=> 		'',
			    'google_pagespeed'		=> 		'',
			    'local_seo'				=> 		'',
			    'misc'					=> 		'',
			    'modules_manager'		=> 		'',
			    'monitor_404'			=> 		'',
			    'on_page_optimization'	=> 		'',
			    'remote_support'		=> 		'',
			    'rich_snippets'			=> 		'',
			    'seo_friendly_images'	=> 		'',
			    'serp'					=> 		'',
			    'server_status'			=> 		'',
			    'setup_backup'			=> 		'',
			    'sitemap'				=> 		'',
			    'tiny_compress'			=> 		'',
			    'title_meta_format'		=> 		'',
			    'dashboard'				=> 		''
			);

			foreach ($this->cfg['modules'] as $key => $value) {
				$module = $key;

				// Icon
				if ( !in_array($module, $this->cfg['core-modules'])
				&& !$this->the_plugin->capabilities_user_has_module($module) ) {
					continue 1;
				}

				$html[] = '
';
				$html[] = $icon[$key] != "" ? '
' . $icon[$key] . '
' : '';

				$html[] = 	'
' . $value[$key]['menu']['title'] . '
';

				// activate / deactivate plugin button
				if ($value['status'] == true) {
					if (!in_array($key, $this->cfg['core-modules'])) {
						$html[] = 'Deactivate';
					} else {
						$html[] = "" . __("Core Modules, can't be deactivated!", 'psp') . "";
					}
				} else {
					$html[] = '' . __('Activate', 'psp') . '';
				}

				$html[] = 	'' . ( __('read more', 'psp') ) . '';
				$html[] = 	'
' . (isset($value[$key]['description']) ? $value[$key]['description'] : '') . '
';
				$html[] = '
';
				$cc++;
			}

			$html[] = '

';
			$html[] = '
';

			return implode("\n", $html);
		}
	}
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"/>
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="format-detection" content="telephone=no">
		<meta name="apple-mobile-web-app-title" content="Barbell">

        <title>Barbell Configurator</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

		<link href="css/font.css" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="css/normalize.min.css">
        <link rel="stylesheet" href="css/main.css">

		<link rel="shortcut icon" href="favicon.ico" />

                	Barbell Configurator
                	Barbell Config
                	Barbell

settings

						Units

								<input type="radio" value="LB" data-bind="checkedValue: $data, checked: $root.weightUnit">

						Barbell Weight

								<input type="radio" value="LB" data-bind="checkedValue: $data, checked: $root.barbellWeight">

							Available Plates

									<input type="checkbox" value="LB" data-bind="checkedValue: $data, checked: available">

								<input class="max-plate-quantity" type="number" data-bind="visible: $root.maxPlatesVisible, value: total">

Set the maximum number of plates you can put on each side of the barbell

						Warmup Scheme

%

reps

									<input class="warmup-scheme-input warmup-percent" pattern="[0-9]*" name="warmupScheme[percent][]" data-bind="value: percent">
									<input class="warmup-scheme-input warmup-reps"    pattern="[0-9]*" name="warmupScheme[reps][]" data-bind="value: reps">

								<input type="button" value="+" class="button1 small-button" data-bind="click: addWarmupSet   , css: { hideSmallButton: warmupScheme().length > 4 }">
								<input type="button" value="–" class="button1 small-button" data-bind="click: removeWarmupSet, css: { hideSmallButton: warmupScheme().length < 2 }">

							<input type="checkbox" id="ignore-small-plates" class="single-checkbox ignore-small-plates" data-bind="checked: ignoreSmallPlates">

						Ignore small plates on warmup

							<input type="checkbox" id="prefer-fewer-plates" class="single-checkbox prefer-fewer-plates" data-bind="checked: preferFewerPlates">

							Prefer fewer plate changes on warmup
							Beta

							<input type="checkbox" id="multi-weight-mode" class="single-checkbox multi-weight-mode" data-bind="checked: multiWeightMode">

							Multi-weight input mode
							Enter multiple weights to appear on 1 row. Separate with * , + # ;

					<form class="weight-to-calculate-wrap config-wrap"  data-bind="submit: calculateSets">
						Weight
						<input id="weight-to-calculate" type="tel" data-bind="value: weightToCalculate, valueUpdate: ['input', 'afterkeyup'], hasFocus: isSelected" />

					</form>

	              				Working Weight:

 0">x  0">

										<span data-bind="visible: reps <= -10" class="reps work-reps">work

x

			              			<div class="plate-breakdown" data-bind="visible: displayWeight <= $root.barbellWeight">bar


text: export { default } from 'talentrh-components/components/application-menu';


text:
package br.ufg.cs.model;

import java.util.Date;
import java.util.Objects;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Classe responsável por conter o Objeto Fotos
 *
 * @author Bianca Raissa
 * @author José Sérgio
 * @author Rafhael Augusto
 * @date 30/06/2016 08:51:43
 * @version 1.0
 */
@XmlRootElement
public class Fotos {

    private Integer id;
    private Integer idEvento;
    private String nome;
    private String descricao;
    private Date dtFoto;
    private String foto;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getIdEvento() {
        return idEvento;
    }

    public void setIdEvento(Integer idEvento) {
        this.idEvento = idEvento;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Date getDtFoto() {
        return dtFoto;
    }

    public void setDtFoto(Date dtFoto) {
        this.dtFoto = dtFoto;
    }

    public String getFoto() {
        return foto;
    }

    public void setFoto(String foto) {
        this.foto = foto;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 59 * hash + Objects.hashCode(this.id);
        hash = 59 * hash + Objects.hashCode(this.idEvento);
        hash = 59 * hash + Objects.hashCode(this.nome);
        hash = 59 * hash + Objects.hashCode(this.descricao);
        hash = 59 * hash + Objects.hashCode(this.dtFoto);
        hash = 59 * hash + Objects.hashCode(this.foto);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Fotos other = (Fotos) obj;
        if (!Objects.equals(this.nome, other.nome)) {
            return false;
        }
        if (!Objects.equals(this.descricao, other.descricao)) {
            return false;
        }
        if (!Objects.equals(this.foto, other.foto)) {
            return false;
        }
        if (!Objects.equals(this.id, other.id)) {
            return false;
        }
        if (!Objects.equals(this.idEvento, other.idEvento)) {
            return false;
        }
        if (!Objects.equals(this.dtFoto, other.dtFoto)) {
            return false;
        }
        return true;
    }

}


text:
<!--
Thank you for pull request.
Below are a few things we ask you kindly to self-check before getting a review. Remove checks that are not relevant.
-->
Checklist
* [ ] Used a fork of the feedstock to propose changes
* [ ] Bumped the build number (if the version is unchanged)
* [ ] Reset the build number to `0` (if the version changed)
* [ ] [Re-rendered]( https://conda-forge.org/docs/conda_smithy.html#how-to-re-render ) with the latest `conda-smithy`
* [ ] Ensured the license file is being packaged.

<!--
Please note any issues this fixes using [closing keywords]( https://help.github.com/articles/closing-issues-using-keywords/ ):
-->

<!--
Please add any other relevant info below:
-->


text:
This directory contains tests and documentation to
validate service performance and stability under various
load/stress scenarios.

[Locust](http://locust.io) is the core load testing tool used to drive
requests thru an ECS deployment. [run_load_test.sh](run_load_test.sh) is
a wrapper around [Locust](http://locust.io) which is responsible for
parsing the load test's json configuration file, optionally spinning up
a local [ecservice.py](../../bin/ecservice.py) and launching
[analyze_load_test_tsv.py](analyze_load_test_tsv.py) to analyze the
results of the load test.
[load-test-config-for-travis.json](load-test-config-for-travis.json)
is an example load test configuration file.

```bash
>jq . load-test-config-for-travis.json
{
  "number_of_requests": 1000,
  "hatch_rate": 5,
  "concurrency": [
    10,
    15,
    20,
    25
  ]
}
>
```

[Locust](http://locust.io) (along with
a few other packages) aren't loaded by default when configuring the dev
environment using ```source cfg4dev```. Before running load tests you
need to pip install all the required packages.

```bash
>pip install --requirement requirements.txt
.
.
.
```

Here's an example of running a basic load test
using [load-test-config-for-travis.json](load-test-config-for-travis.json).

```bash
>tests/load/run_load_test.sh -v tests/load/load-test-config-for-travis.json
Started ECS - PID = 25608; config file '/tmp/tmp.H5e7xZFCoN'
Find locust log file @ '/tmp/tmp.nyG4LGQOtB' for 15 concurrency
Find locust output @ '/tmp/tmp.fS1xDEwLc5' for 15 concurrency
=======================================================================
2034 @ 16 from 2016-04-26 19:16:41.449000 to 2016-04-26 19:20:00.863000
=======================================================================
Request Type                 Ok Error         m        b      Min       50       60       70       80       90       95       99      Max
-----------------------------------------------------------------------------------------------------------------------------------------
Health-Check-Quick          515     0   -0.0027        6        4        5        5        6        7        9       10       14       24
Health-Check-Slow           234     0   -0.0585       82        6       21       36       71      119      264      325      468      693
NoOp                        257     0    0.0010        5        3        4        4        5        5        7       10       14       27
Tasks-Bad-Request-Body       72     0    0.0072        5        4        5        5        6        6        8        9       17       21
Tasks-Happy-Path            612     0   -0.2141     2197      647     2150     2297     2436     2595     2913     3149     4316     5171
Tasks-Image-Not-Found        86     0   -0.6782      969       30      764      857     1029     1330     1467     1612     1993     2015
Version                     258     0   -0.0012        5        3        5        5        5        6        7        9       14       25
=======================================================================
>
```
## Graphing Test Results

As described above, [run_load_test.sh](run_load_test.sh) runs a load
test and then [analyze_load_test_tsv.py](analyze_load_test_tsv.py)
analyzes the results of the load test.
By default [analyze_load_test_tsv.py](analyze_load_test_tsv.py)
generates the numeric results as illustrated above.
In addition to numeric results, [analyze_load_test_tsv.py](analyze_load_test_tsv.py)
can also generate a PDF document of graphs describing response times by
request type. To generate the graphs use the ```--graphs``` command
command line option with [analyze_load_test_tsv.py](analyze_load_test_tsv.py).

```bash
>analyze_load_test_tsv.py --help
Usage: analyze_load_test_tsv.py [options] <concurrency>

This utility analyzes load test results

Options:
  -h, --help       show this help message and exit
  --graphs=GRAPHS  pdf file name for graphs
>
```

Below is a sample of one of these pages and
[here](docs/25-sample-graphs.pdf) is a sample of a complete report.

![25-sample-graph.png](docs/25-sample-graph.png)

## Local & Cloud Deployments

By default ```run_load_test.sh``` spins up a local ECS deployment.
```run_load_test.sh``` can also be used to run a load tests against
an existing ECS deployment with the inclusion of the ```endpoint``` property
in the load test configuration document.
If the ECS deployment requires authentication the load test configuration
document should include the ```credentials``` property which points to a file
containing the output of ```ecsctl.sh creds```.

```bash
>cat ecsctl-sh-creds-output.txt
b35ec3fd96564323898920d282c18bb6:21023ce203851e7ec3eb1d25daf0fbcc
8d90c8aa5256454b974582c7f0c7fa76:5668c4e0d53901b26b2e4af6a7229f7d
731f1781575d430c9be46231fc7ad4c5:8e1a9ced90bd606bb5a1b3844b8f2299
1c78d19f3a2942a285c7091221808557:b4140392e719d0e7c6acd1e0e3bb1c12
cdf539dd1ba649e893950fa9f3de9f49:633ad1feaa40f2ecf1776b301e894340
>
```

```bash
>cat deployment.json
{
    "number_of_requests": 100,
    "hatch_rate": 5,
    "concurrency": [5],
    "endpoint": "https://api.ecs.cloudfeaster.com",
    "credentials": "ecsctl-sh-creds-output.txt"
}
```

```bash
>./run_load_test.sh -v deployment.json
Find locust log file @ '/tmp/tmp.aacQxEvsv1' for 5 concurrency
Find locust output @ '/tmp/tmp.fPFYvZEcCZ' for 5 concurrency
.
.
.
>
```

## Rate Limiting

Load tests are intented to stress an ECS deployment
and generate traffic that looks a lot like a DoS attack.
the typical ECS deployment has per node rate limiting rules in place
ie. nodes have defenses in place to protect themselves again DoS
or general abuse. so, if you're going to load test a real ECS deployment
then you'll want to significantly increase the rates. at this time the
only way to increase the rates is to configure them when the deployment is
being spun up. the ```deployment.json``` below illustrates how to set
these rates. take a look @ the ECS API docs for the default rates.

```bash
>cat deployment.json
{
    "docs_domain": "docs.ecs.cloudfeaster.com",
    "api_domain": "api.ecs.cloudfeaster.com",
    "docs_cert": "/vagrant/docs.ecs.cloudfeaster.com.ssl.bundle.crt",
    "docs_key": "/vagrant/docs.ecs.cloudfeaster.com.key",
    "api_cert": "/vagrant/api.ecs.cloudfeaster.com.ssl.bundle.crt",
    "api_key": "/vagrant/api.ecs.cloudfeaster.com.key",
    "api_credentials": "/vagrant/.htpasswd",
    "dh_parameter": "/vagrant/dhparam.pem",
    "api_rate_limiting": {
        "per_ip": {
            "rate_limit": "5000r/s",
            "conn_limit": "5000"
        },
        "per_key": {
            "rate_limit": "500r/s",
            "conn_limit": "500"
        }
    },
    "number_of_nodes": 1
}
>
```

## New Relic

[New Relic](http://newrelic.com/) is a great
[APM](https://en.wikipedia.org/wiki/Application_performance_management)
service that can be very useful for performance tunning.
Running ECS under the New Relic agent while ECS is servicing
requests from a load test generates lots of data for analysis.
ECS is written using [Tornado 4.3](http://www.tornadoweb.org/en/stable/)
and New Relic's support for Tornado has been spotty.
As of 30 Mar '16, [version 2.62.0.47 of New Relic's python agent](https://docs.newrelic.com/docs/agents/python-agent/hosting-mechanisms/introductory-tornado-4-support)
claims to have support for Tornado 4.3 but running ECS under this
agent generates stack traces - see [this](https://support.newrelic.com/tickets/190024) for details.
The New Relic support team have been awesome and are sorting out the problem.

* [newrelic.ini](newrelic.ini) was generated per the instructions
  outlined [here](https://pypi.python.org/pypi/newrelic) (pip install
  new relic and then ```newrelic-admin generate-config %LICENSE_KEY% newrelic.ini```)
  and [here](https://docs.newrelic.com/docs/agents/python-agent/hosting-mechanisms/introductory-tornado-4-support) (add ```feature_flag = tornado.instrumentation.r3```
  to [newrelic.ini](newrelic.ini))
* you'll need to replace ```%LICENSE_KEY%``` in [newrelic.ini](newrelic.ini)
  with your own license key
* use the following to run ECS under the New Relic agent
  ```NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program ecservice.py```


text:
using System;

namespace Guidelines.Core.Commands
{
	public interface IUpdateCommand<TDomain, out TId>
		where TDomain : IIdentifiable<TId>
	{
		TId Id { get; }
	}
}


text:
class Customer < ActiveRecord::Base
  belongs_to :user
  has_many :suits

  validates :rif, format: { with: /([V|E|G|J|P|N]{1}-\d{7,10})*/i , message: "El RIF o Cédula es inválido: Por favor ingresa uno válido. Formato: V-XXXXXXX" }
  validates :rif, :email, uniqueness: true

  scope :on, -> { where(status: true) }
end


text:
using System;
using System.Windows;
using System.Windows.Forms;
using MS.WindowsAPICodePack.Internal;

namespace GodLesZ.Library.Win7.Taskbar {
	internal sealed class TabbedThumbnailProxyWindow : Form, IDisposable {

		internal TabbedThumbnailProxyWindow(TabbedThumbnail preview) {
			TabbedThumbnail = preview;
			Size = new System.Drawing.Size(1, 1);

			if (!string.IsNullOrEmpty(preview.Title)) {
				Text = preview.Title;
			}

			if (preview.WindowsControl != null) {
				WindowsControl = preview.WindowsControl;
			}
		}

		internal TabbedThumbnail TabbedThumbnail { get; private set; }

		internal UIElement WindowsControl { get; private set; }

		internal IntPtr WindowToTellTaskbarAbout { get { return this.Handle; } }

		protected override void WndProc(ref Message m) {
			bool handled = false;

			if (this.TabbedThumbnail != null) {
				handled = TaskbarWindowManager.DispatchMessage(ref m, this.TabbedThumbnail.TaskbarWindow);
			}

			// If it's a WM_Destroy message, then also forward it to the base class (our native window)
			if ((m.Msg == (int)WindowMessage.Destroy) ||
			   (m.Msg == (int)WindowMessage.NCDestroy) ||
			   ((m.Msg == (int)WindowMessage.SystemCommand) && (((int)m.WParam) == TabbedThumbnailNativeMethods.ScClose))) {
				base.WndProc(ref m);
			} else if (!handled) { base.WndProc(ref m); }
		}

		#region IDisposable Members

		/// <summary>
		///
		/// </summary>
		~TabbedThumbnailProxyWindow() {
			Dispose(false);
		}

		/// <summary>
		/// Release the native objects.
		/// </summary>
		void IDisposable.Dispose() {
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected override void Dispose(bool disposing) {
			if (disposing) {
				// Dispose managed resources
				if (TabbedThumbnail != null) { TabbedThumbnail.Dispose(); }

				TabbedThumbnail = null;

				WindowsControl = null;
			}

			base.Dispose(disposing);
		}

		#endregion
	}
}


text:
<?php

namespace Controller\Admin;

use Controller\ControllerAbstract;
use Entity\Handicap;

class HandicapController extends ControllerAbstract {

    public function listAction() {

        $handicap = $this->app['handicap.repository']->findAll();

        return $this->render(
                'admin/handicap/handicap.html.twig',
                [
                    'handicap' => $handicap
                ]
        );
    }
        public function editAction($id = null)
    {
        if (is_null($id)) {
            $handicap = new Handicap();
        } else {
            $handicap= $this->app['handicap.repository']->find($id);

            if (is_null($handicap)) {
                $this->app->abort(404);
            }
        }

        $errors = [];

        if (!empty($_POST)) {
            $handicap->setName($_POST['name']);

            // contrôle des champs de formulaire
            if (empty($_POST['name'])) {
                $errors['name'] = 'L\'handicap est obligatoire';
            } elseif (strlen($_POST['name']) > 50) {
                $errors['name'] = 'L\'handicap ne doit pas dépasser 50 caractères';
            }

            if (empty($errors)) {
                $this->app['handicap.repository']->save($handicap);
                $this->addFlashMessage('L\'handicap est enregistrée');

                return $this->redirectRoute('admin_handicap');
            } else {
                $message = 'Le formulaire contient des erreurs';
                $message .= '
' . implode('
', $errors);
                $this->addFlashMessage($message, 'error');
            }
        }

        return $this->render(
            'admin/handicap/edit.html.twig',
            [
                'handicap' => $handicap
            ]
        );
    }

    public function deleteAction($id) {

        $handicap = $this->app['handicap.repository']->find($id);

        if (is_null($handicap)) {
            $this->app->abort(404);
        }

        $this->app['handicap.repository']->delete($handicap);
        $this->addFlashMessage('L\'handicap a été supprimé');

        return $this->redirectRoute('admin_handicap');
    }
}


text:
__author__ = 'fcanas'

import termhelper

class Reporter:
    """
    Responsible for displaying results and recording them to log files.
    """

    def __init__(self, warg=0):
        self.width = warg
        self.set_terminal_width(warg)  # default width of terminal

    templates = {
        'test': '[ {0:.<{2}}{1:.>{3}} ]',
        'set_tuples': '{0:.<{2}}{1:.>{3}}',
        'set_items': '{0:.<{1}}',
        'path_display': '[ {0:.<{1}}FAIL ]'
    }

    def report_test(self, test, items):
        """
        Report header for specification results.
        """
        template = self.templates['test']
        test_width = self.width - 4  # Test tuple is wrapped in [  ], which is 4 characters
        print template.format(test, len(items), 0, test_width - len(test), len(test))
        self.report_set(items)

    def report_set(self, entities):
        """
        Human-readable report for a set of unverified entities.
        """
        for item in sorted(entities):
            if type(item) is tuple:
                template = self.templates['set_tuples']
                tuple_padding = self.get_tuple_padding(item)
                print template.format(item[0], item[1], tuple_padding, len(item[1]))
            else:
                template = self.templates['set_items']
                print template.format(item, self.width)

    def set_terminal_width(self, warg=-1):
        """
        Overwrites default terminal width with the width of the current terminal window or the width arg passed
        in by user (if any and positive).
        """
        if warg <= 0:
            height, width = termhelper.terminal_height_width()
            self.width = max(width, 100)

    def get_tuple_padding(self, item):
        """
        Returns the proper length of padding for a tuple.
        The first item is allocated at least 30 characters of space.
        The second item is allocated up to 50 characters.
        """

        # Default padding, used when both items fit in their own allocated space without shifting the padding
        # and when a line break is unavoidable (default padding keeps the output more readable than no padding
        # in the case of a very short first item with a very long second item)

        tuple_padding = max(30, self.width - 50, len(item[0]) + 1)

        # If the combined length of the items is short enough to fit on one line, avoid a line break
        if len(item[0]) + len(item[1]) < self.width:

            # If the first item fills up its allocated space, pad by 1 character
            if len(item[0]) >= max(30, self.width - 50):
                tuple_padding = len(item[0]) + 1

            # If the second item is longer than its allocated space, shorten the padding to avoid a line break
            elif len(item[1]) > min(self.width - 30, 50):
                tuple_padding = self.width - len(item[1])

        return tuple_padding

    def display_paths(self, paths_dict):
        """
        Human readable output for displaying dependency paths.
        """
        def node_type(node):
            return " (type: {0})".format(str(node[1]))

        template = self.templates['path_display']

        for condition_id in paths_dict:
            for path_index, path in enumerate(list(paths_dict[condition_id])):
                tab = len(condition_id)
                for node_index, node in enumerate(path):
                    if node_index == 0:
                        if path_index == 0:
                            print template.format(condition_id + node_type(node), self.width - len('[ FAIL ]'))
                        else:
                            continue
                    else:
                        add_to_tab = 0
                        if type(node[0]) is tuple:
                            cid = node[0][0]
                            add_to_tab += len(cid)
                        else:
                            cid = node[0]
                            add_to_tab += len(cid)
                        if tab:
                            branch = '\--> depends on '
                            add_to_tab += len(branch)
                        else:
                            branch = ''

                        print " " * tab + branch + str(cid) + node_type(node)
                        tab += add_to_tab
            print