text:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>

<title>UTEST_Func</title>
<meta name='robots' content='noindex,nofollow' />
<meta name='generator' content='GLOBAL-6.5.2' />
<meta http-equiv='Content-Style-Type' content='text/css' />
<link rel='stylesheet' type='text/css' href='../style.css' />

UTEST_Func        886 test/test.c    static char* test_run(const UTEST_Func* test_list, _UWORD num)
UTEST_Func        900 test/test.c        UTEST_Func f;
UTEST_Func        336 test/test.h    static char* test_run(const UTEST_Func* test_list, _UWORD num);
UTEST_Func        338 test/test.h    static const UTEST_Func test_basic_drivers_[] = {
UTEST_Func        344 test/test.h    static const UTEST_Func test_drivers_[] = {
UTEST_Func        370 test/test.h    static const UTEST_Func test_modules_[] = {


text:
<?php

declare(strict_types=1);

namespace Scheb\TwoFactorBundle\Security\TwoFactor\Csrf;

use Scheb\TwoFactorBundle\Security\Http\ParameterBagUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;

class CsrfTokenValidator
{
    /**
     * @var CsrfTokenManagerInterface
     */
    private $csrfTokenGenerator;

    /**
     * @var array
     */
    private $options;

    public function __construct(CsrfTokenManagerInterface $csrfTokenGenerator, array $options)
    {
        $this->csrfTokenGenerator = $csrfTokenGenerator;
        $this->options = $options;
    }

    public function hasValidCsrfToken(Request $request): bool
    {
        $tokenValue = ParameterBagUtils::getRequestParameterValue($request, $this->options['csrf_parameter']);
        $token = new CsrfToken($this->options['csrf_token_id'], $tokenValue);
        if (!$this->csrfTokenGenerator->isTokenValid($token)) {
            return false;
        }

        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Melanchall.DryWetMidi.Common;

namespace Melanchall.DryWetMidi.MusicTheory
{
    /// <summary>
    /// Represents a musical scale.
    /// </summary>
    public sealed class Scale
    {
        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="Scale"/> with the
        /// specified intervals and root note.
        /// </summary>
        /// <param name="intervals">Intervals between adjacent notes of the scale.</param>
        /// <param name="rootNote">Root note (tonic) of the scale.</param>
        /// <exception cref="ArgumentNullException"><paramref name="intervals"/> is <c>null</c>.</exception>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="rootNote"/> specified an
        /// invalid value.</exception>
        public Scale(IEnumerable<Interval> intervals, NoteName rootNote)
        {
            ThrowIfArgument.IsNull(nameof(intervals), intervals);
            ThrowIfArgument.IsInvalidEnumValue(nameof(rootNote), rootNote);

            Intervals = intervals;
            RootNote = rootNote;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets inetrvals between adjacent notes of the current <see cref="Scale"/>.
        /// </summary>
        public IEnumerable<Interval> Intervals { get; }

        /// <summary>
        /// Gets root note (tonic) of the current <see cref="Scale"/>.
        /// </summary>
        public NoteName RootNote { get; }

        #endregion

        #region Methods

        /// <summary>
        /// Converts the string representation of a musical scale to its <see cref="Scale"/>
        /// equivalent. A return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="input">A string containing a scale to convert.</param>
        /// <param name="scale">When this method returns, contains the <see cref="Scale"/>
        /// equivalent of the musical scale contained in <paramref name="input"/>, if the conversion succeeded,
        /// or <c>null</c> if the conversion failed. The conversion fails if the <paramref name="input"/> is <c>null</c> or
        /// <see cref="string.Empty"/>, or is not of the correct format. This parameter is passed uninitialized;
        /// any value originally supplied in result will be overwritten.</param>
        /// <returns><c>true</c> if <paramref name="input"/> was converted successfully; otherwise, <c>false</c>.</returns>
        public static bool TryParse(string input, out Scale scale)
        {
            return ParsingUtilities.TryParse(input, ScaleParser.TryParse, out scale);
        }

        /// <summary>
        /// Converts the string representation of a musical scale to its <see cref="Scale"/> equivalent.
        /// </summary>
        /// <param name="input">A string containing a scale to convert.</param>
        /// <returns>A <see cref="Scale"/> equivalent to the musical scale contained in <paramref name="input"/>.</returns>
        /// <exception cref="ArgumentException"><paramref name="input"/> is <c>null</c> or contains white-spaces only.</exception>
        /// <exception cref="FormatException"><paramref name="input"/> has invalid format.</exception>
        public static Scale Parse(string input)
        {
            return ParsingUtilities.Parse<Scale>(input, ScaleParser.TryParse);
        }

        #endregion

        #region Operators

        /// <summary>
        /// Determines if two <see cref="Scale"/> objects are equal.
        /// </summary>
        /// <param name="scale1">The first <see cref="Scale"/> to compare.</param>
        /// <param name="scale2">The second <see cref="Scale"/> to compare.</param>
        /// <returns><c>true</c> if the scales are equal, <c>false</c> otherwise.</returns>
        public static bool operator ==(Scale scale1, Scale scale2)
        {
            if (ReferenceEquals(scale1, scale2))
                return true;

            if (ReferenceEquals(null, scale1) || ReferenceEquals(null, scale2))
                return false;

            return scale1.RootNote == scale2.RootNote &&
                   scale1.Intervals.SequenceEqual(scale2.Intervals);
        }

        /// <summary>
        /// Determines if two <see cref="Scale"/> objects are not equal.
        /// </summary>
        /// <param name="scale1">The first <see cref="Scale"/> to compare.</param>
        /// <param name="scale2">The second <see cref="Scale"/> to compare.</param>
        /// <returns><c>false</c> if the scales are equal, <c>true</c> otherwise.</returns>
        public static bool operator !=(Scale scale1, Scale scale2)
        {
            return !(scale1 == scale2);
        }

        #endregion

        #region Overrides

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            return $"{RootNote} {string.Join(" ", Intervals)}";
        }

        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        /// <param name="obj">The object to compare with the current object.</param>
        /// <returns><c>true</c> if the specified object is equal to the current object; otherwise, <c>false</c>.</returns>
        public override bool Equals(object obj)
        {
            return this == (obj as Scale);
        }

        /// <summary>
        /// Serves as the default hash function.
        /// </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            unchecked
            {
                var result = 17;
                result = result * 23 + RootNote.GetHashCode();
                result = result * 23 + Intervals.GetHashCode();
                return result;
            }
        }

        #endregion
    }
}


text:
require('babel-polyfill');
require('./dist-seed/seed.bundle.js');


text:
author: slowe
categories: Information
comments: false
date: 2006-01-24T14:21:33Z
slug: gsx-upgrade-much-smoother-this-time
tags:
- CentOS
- Linux
- Networking
- RedHat
- Virtualization
- VMware
- Windows
title: GSX Upgrade Much Smoother This Time
url: /2006/01/24/gsx-upgrade-much-smoother-this-time/
wordpress_id: 166
---

Earlier today I completed another [GSX Server](http://www.vmware.com/products/gsx/) upgrade (from version 2.5 to version 3.2.1) for a customer, and fortunately this upgrade was much smoother than [the last GSX Server upgrade][1].

No BSODs (Blue Screens of Death) this time during the uninstallation, and the previous version uninstalled itself cleanly. The installation of the new version went quickly and smoothly, and in practically no time we were booting up "legacy" VMs under the new version of GSX Server.

As with the previous upgrade, those VMs running Red Hat Linux 9.0 detected "new" hardware (specifically, a "new" network card and a "new" SCSI card; ironically, they are exactly the same virtual hardware as before) and seamlessly migrated over the configuration without any issues whatsoever.

Unfortunately, I was dismayed to find that a VM running CentOS 4.2 did not maintain the network configuration while setting up this "new" hardware, so I had to go back in and re-enter the network settings. This was only a minor inconvenience, as the network reconfiguration was quick and easy. It's also nice to note that the [time synchronization problems with CentOS 4.2][2] appear to have resolved themselves now under the new version of GSX Server. (Note that even after [the changes that mostly resolved the NTPd problems][3], time was still slightly off and lots of NTPd messages were being logged; even those issues have disappeared as well.)

The network reconfiguration on a VM running Windows Server 2003, on the other hand, was _not_ quick and easy. As before, the network configuration simply disappeared during the discovery of "new" hardware. In the last upgrade for this customer, the only Windows-based VM we had to work with was an older Windows 2000-based server. I had hoped that the problems we'd seen with that server would be resolved in Windows Server 2003.

Not so. The VMware Tools installation removed the driver and installed a new driver, so even if the network configuration had made it through the "new hardware" discovery process, it would have been hosed at that point. Eventually, after a couple of different reboots, I finally had the Windows server up and running with its original network configuration again. If there is one area I've found so far that VMware really needs to work on, it's this one.

[1]: {{< relref "2006-01-10-gsx-server-upgrade-woes.md" >}}
[2]: {{< relref "2005-12-19-ntpd-on-centos-42.md" >}}
[3]: {{< relref "2005-12-23-centos-ntpd-problem-mostly-resolved.md" >}}


text:
import * as jQuery from 'jquery';
import * as alfnavigator from 'alfnavigator';
import 'css!database/database';
import welcomeHtml from 'text!database/database.html';
import 'underscore';

export class DatabaseView extends alfnavigator.BaseContentView{
	constructor(args){
		super({html: _.template(welcomeHtml)(args.controller.model), controller: args.controller});
	}
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--Created: Sun Feb 07 16:42:13 PST 2021--><!--By: regxmllib build 52f8ec992adbcba8bd18d9b06508c69a1e9c459b--><!--See: https://github.com/sandflow/regxmllib--><Extension xmlns="http://www.smpte-ra.org/schemas/2001-1b/2013/metadict">
<SchemeID>urn:uuid:cd2b0b47-3e39-5fd0-7fe3-e4a2f08cc8ae</SchemeID>
<SchemeURI>http://www.smpte-ra.org/reg/395/2014/13/1/amwa/as_common</SchemeURI>
<MetaDefinitions>
<ClassDefinition>
<Identification>urn:smpte:ul:060e2b34.027f0101.0d010701.01010100</Identification>
<Symbol>DM_Segmentation_Framework</Symbol>
<Description>Segmentation metadata framework</Description>
<Name>DM_Segmentation_Framework</Name>
<ParentClass>urn:smpte:ul:060e2b34.027f0101.0d010401.00000000</ParentClass>
<IsConcrete>false</IsConcrete>
</ClassDefinition>
</MetaDefinitions>
</Extension>


text:
from datetime import date, datetime
from decimal import Decimal
from calendar import monthrange
import re
import stripe

from django import forms
from django.apps import apps
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
from django.db.models import get_model
from django.conf import settings

from django_conference import settings as conf_settings
from django_conference.models import (Meeting, Paper, Session, SessionCadre,
    RegistrationDonation, Registration, RegistrationExtra,
    RegistrationGuest, RegistrationOption, PaperPresenter)

class SessionsWidget(forms.CheckboxSelectMultiple):
    """
    Widget for representing all the sessions associated with a certain
    time slot. Sessions titles are displayed in a list, with complete details
    on the session below the title.
    """
    def render(self, name, value, attrs=None, choices=()):
        if value is None:
            value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        values = set([force_unicode(v) for v in value])
        # since all the sessions have the same time slot,
        # use the first in the list to get the description
        session = Session.objects.get(pk=self.choices[0][1])
        description = session.get_time_slot_string()
        expand_img = '' % (
            settings.STATIC_URL)
        output = [u"""

%s %s

""" % (expand_img, description)]
        for (i, choice) in enumerate(self.choices):
            session_id = choice[0]
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
            session = Session.objects.get(pk=session_id)
            cb = forms.CheckboxInput(final_attrs,
                check_test=lambda v: v in values)
            rendered_cb = cb.render(name, unicode(session_id))
            output.append(u"""

%s%s

"""
                % (rendered_cb, unicode(session)))
            cadre_dict = {
                'Chair': session.chairs,
                'Organizer': session.organizers,
                'Commentator': session.commentators,
            }
            for desc, cadre in cadre_dict.items():
                if not cadre.count():
                    continue
                if cadre.count() == 1:
                    cadre_name = unicode(cadre.all()[0])
                    output.append(u'%s: %s
' % (desc, cadre_name))
                elif cadre.count() > 1:
                    output.append(u'%ss:
' % desc)
                    output.extend([u'
%s
' %
                        unicode(o) for o in cadre.all()])
                    output.append(u'
')
            if session.papers:
                output.append(u"""
                            %s Papers

""" % expand_img)
                output.extend([u'
%s, %s
' %
                    (unicode(p), p.get_presenter())
                    for p in session.papers.all()])
                output.append(u'
')
            output.append(u"""

""")
        output.append(u"""

""")
        return mark_safe(u'\n'.join(output))

class MeetingSessions(forms.Form):
    """
    Form for selecting meeting sessions. All fields are dynamically generated
    by querying for the sessions associated with a given meeting.
    """
    def __init__(self, meeting, *args, **kwargs):
        super(MeetingSessions, self).__init__(*args, **kwargs)
        self.meeting = meeting
        self.set_session_fields()

    def set_session_fields(self):
        # adds multi-select fields for choosing which sessions to attend,
        # with one field for each (start_time, stop_time) combo
        meeting_sessions = self.meeting.sessions.filter(accepted=True)
        time_slots = (meeting_sessions.filter(accepted=1).distinct()
                        .values_list("start_time", "stop_time")
                        .order_by('start_time', 'stop_time'))
        for i, time_slot in enumerate(time_slots):
            sessions = meeting_sessions.filter(start_time=time_slot[0],
                stop_time=time_slot[1])
            choices = [(s.pk, s.pk) for s in sessions]
            field_name = "sessions_%i" % i
            self.fields[field_name] = forms.MultipleChoiceField(label="",
                choices=choices, required=False, widget=SessionsWidget)

    def get_sessions(self):
        clean = self.clean()
        # go through and split off session-related values into a separate list,
        # since they have to be combined together
        sessions = []
        for item in clean.keys():
            if item.startswith("sessions_"):
                if clean[item]:
                    sessions.append(clean[item])
                clean.pop(item)
        # flatten list
        sessions = sum(sessions, [])
        return [Session.objects.get(pk=int(x)) for x in sessions]

class MeetingRegister(forms.Form):
    """
    Main form for meeting registrations.
    """
    type = forms.ChoiceField(choices=[], required=True,
        label="Registration Type")
    guest_first_name = forms.CharField(required=False, max_length=45)
    guest_last_name = forms.CharField(required=False, max_length=45)
    special_needs = forms.CharField(required=False, widget=forms.Textarea)

    def __init__(self, meeting, *args, **kwargs):
        super(MeetingRegister, self).__init__(*args, **kwargs)
        self.meeting = meeting
        self.set_type_field()

    def set_type_field(self):
        """
        Generate list of available registration type (e.g. HSS Member, student)
        based on current date and deadlines associated with the meeting.
        """
        early_reg_passed = date.today() > self.meeting.early_reg_deadline
        TYPES = [("", "Please select")] + \
                [(x.id, x.option_name+"\t$"+
                  str(x.regular_price if early_reg_passed else x.early_price))
                 for x in self.meeting.regoptions.filter(admin_only=False)]
        self.fields['type'].choices = TYPES

    def get_guest(self):
        """
        Returns unsaved RegistrationGuest object if user entered something
        for the guest_first_name field, else returns None.
        """
        clean = self.clean()
        if not clean.get('guest_first_name'):
            return None
        return RegistrationGuest(first_name=clean['guest_first_name'],
            last_name=clean['guest_last_name'])

    def get_registration(self, registrant):
        """
        Returns unsaved Registration object corresponding to cleaned form data
        and the given registrant.
        """
        clean = self.clean()
        user_model = apps.get_model(conf_settings.DJANGO_CONFERENCE_USER_MODEL)
        reg_username = conf_settings.DJANGO_CONFERENCE_ONLINE_REG_USERNAME
        entered_by = user_model.objects.get_by_natural_key(reg_username)
        kwargs = {
            'meeting': self.meeting,
            'type': RegistrationOption.objects.get(id=clean['type']),
            'special_needs': clean.get('special_needs', ''),
            'date_entered': datetime.today(),
            'payment_type': 'cc',
            'registrant': registrant,
            'entered_by': entered_by,
        }
        return Registration(**kwargs)

class MeetingExtras(forms.Form):
    """
    Form for fixed-price meeting extra (e.g. abstracts). All fields are
    dynamically generated from the MeetingExtra model.
    """
    def __init__(self, meeting, *args, **kwargs):
        super(MeetingExtras, self).__init__(*args, **kwargs)
        self.meeting = meeting
        extras = meeting.extras.filter(admin_only=False)
        for extra in extras:
            field = extra.extra_type
            if extra.max_quantity == 1:
                self.fields[field.name] = forms.BooleanField(required=False,
                    label=field.label, help_text=extra.help_text)
            else:
                self.fields[field.name] = forms.IntegerField(required=False,
                    initial=0, min_value=0, max_value=extra.max_quantity,
                    label=field.label, help_text=extra.help_text)

    def get_extras(self, registrant):
        """
        Returns list of RegistrationExtra objects
        """
        clean = self.clean()
        extras = []
        for name, qty in clean.items():
            if qty is True:
                qty = 1
            if not qty:
                continue
            extra = self.meeting.extras.get(extra_type__name=name)
            price = None
            reg_extra = RegistrationExtra(extra=extra, quantity=qty,
                price=price)
            extras.append(reg_extra)
        return extras

class MeetingDonations(forms.Form):
    """
    Form for donations that registrants can make. All fields are
    dynamically generated from the MeetingDonation model.
    """
    def __init__(self, meeting, *args, **kwargs):
        super(MeetingDonations, self).__init__(*args, **kwargs)
        self.meeting = meeting
        donations = meeting.donations.all()
        for donation in donations:
            field = donation.donate_type
            self.fields[field.name] = forms.DecimalField(required=False,
                widget = self.MoneyWidget(), decimal_places=2,
                min_value=Decimal("0.0"), max_digits=6,
                label=field.label, help_text=donation.help_text, initial=0)

    class MoneyWidget(forms.TextInput):
        def render(self, *args, **kwargs):
            return '$' + super(self.__class__, self).render(*args, **kwargs)

    def get_donations(self):
        """
        Returns list of RegistrationDonation objects
        """
        clean = self.clean()
        donations = []
        for name, total in clean.items():
            if not total:
                continue
            total = Decimal(total)
            donate_type = self.meeting.donations.get(donate_type__name=name)
            donation = RegistrationDonation(total=total,
                donate_type=donate_type)
            donations.append(donation)
        return donations

class SessionCadreForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        """
        Special form for the SessionCadre model that accepts a "optional"
        keyword, which indicates that validation should only happen
        if the user enters something in
        """
        optional = kwargs.pop('optional', True)
        super(SessionCadreForm, self).__init__(*args, **kwargs)
        if optional:
            for f in self.fields.values():
                f.required = False

    def has_entered_info(self):
        data = self.cleaned_data
        return any([data.get('first_name'), data.get('last_name'),
            data.get('mi'), data.get('email'), data.get('institution')])

    def clean(self):
        clean = super(SessionCadreForm, self).clean()
        if self.has_entered_info():
            #i.e. User Entered Some Data
            #lets ensure all necessary data is present
            if not all([clean.get('first_name'), clean.get('last_name'),
                clean.get('email'), clean.get('institution')]):
                err = "Please fill in all the first name, last name, email,"+\
                      " and institution fields for this person."
                raise forms.ValidationError(err)
        return clean

    class Meta:
        model = SessionCadre
        fields = ["first_name", "mi", "last_name", "gender", "type", "email",
            "institution"]

class AbstractForm(forms.ModelForm):
    """
    Base form for models that contain abstracts
    """
    def __init__(self, *args, **kwargs):
        super(AbstractForm, self).__init__(*args, **kwargs)
        max_words = conf_settings.DJANGO_CONFERENCE_ABSTRACT_MAX_WORDS
        if max_words > 0:
            self.fields['abstract'].help_text = "%i words maximum" % max_words

    def clean_abstract(self):
        data = self.cleaned_data['abstract']
        num_words = len(data.split())
        max_words = conf_settings.DJANGO_CONFERENCE_ABSTRACT_MAX_WORDS
        if num_words > max_words:
            message = "Abstract can contain a maximum of %i words. "+\
                      "You supplied %i words."
            raise forms.ValidationError(message % (max_words, num_words))
        return data

class PaperPresenterForm(forms.ModelForm):
    header = "Presenter Information"
    class Meta:
        model = PaperPresenter
        fields = ['first_name', 'last_name', 'email', 'gender', 'birth_year',
            'status', 'time_periods', 'regions', 'subjects']

class PaperForm(AbstractForm):
    header = "Paper/Poster Information"

    class Meta:
        model = Paper
        exclude = ['creation_time', 'submitter', 'presenter', 'accepted', 'sessions']

    def save(self, submitter, presenter=None, commit=True):
        self.instance.submitter = submitter
        if presenter:
            self.instance.presenter = presenter
        return super(PaperForm, self).save(commit)

class SessionForm(AbstractForm):
    NUM_PAPERS_RANGE = [(x, x) for x in range(3, 11)]
    num_papers = forms.ChoiceField(choices=NUM_PAPERS_RANGE, required=True,
        label="Paper Abstracts")

    class Meta:
        model = Session
        fields = ['title', 'abstract', 'notes', 'num_papers']

    def save(self, meeting, submitter, commit=True):
        self.instance.meeting = meeting
        self.instance.submitter = submitter
        return super(SessionForm, self).save(commit)

class StripeTextInput(forms.TextInput):
    """
    This is a version of forms.widgets.TextInput that doesn't render the input
    with the "name" or "value" attributes. We don't want to have the "name"
    attribute because that will cause CC details to be POSTed to us when the
    form is submitted.
    """
    def __init__(self, stripe_field_name, attrs=None):
        self.stripe_field_name = stripe_field_name
        super(StripeTextInput, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        extra = {'type': self.input_type, 'data-stripe': self.stripe_field_name}
        final_attrs = self.build_attrs(attrs, **extra)
        return mark_safe(u'<input%s />' % forms.utils.flatatt(final_attrs))

class StripeSelect(forms.Select):
    """
    Same as StripeTextInput, except for <select>s
    """
    def __init__(self, stripe_field_name, attrs=None):
        self.stripe_field_name = stripe_field_name
        super(StripeSelect, self).__init__(attrs)

    def render(self, name, value, attrs=None, choices=()):
        extra = {'data-stripe': self.stripe_field_name}
        final_attrs = self.build_attrs(attrs, **extra)
        output = [u'<select%s>' % forms.utils.flatatt(final_attrs)]
        output.append(self.render_options(choices, []))
        output.append(u'</select>')
        return mark_safe(u'\n'.join(output))

class CCExpWidget(forms.MultiWidget):
    """ Widget containing two select boxes for selecting the month and year"""
    def decompress(self, value):
        return [value.month, value.year] if value else [None, None]

    def format_output(self, rendered_widgets):
        html = u' / '.join(rendered_widgets)
        return u'%s' % html

class CCExpField(forms.MultiValueField):
    EXP_MONTH = [(str(x).rjust(2, "0"), x) for x in xrange(1, 13)]
    EXP_YEAR = [(x, x) for x in xrange(date.today().year,
                                       date.today().year + 15)]

    def __init__(self, *args, **kwargs):
        fields = (
            forms.ChoiceField(choices=self.EXP_MONTH,
                widget=StripeSelect('exp-month')),
            forms.ChoiceField(choices=self.EXP_YEAR,
                widget=StripeSelect('exp-year')),
        )
        super(CCExpField, self).__init__(fields, *args, **kwargs)
        self.widget = CCExpWidget(widgets =
            [fields[0].widget, fields[1].widget])

class StripePaymentForm(forms.Form):
    number = forms.IntegerField(label="Card Number",
        widget=StripeTextInput('number'))
    name = forms.CharField(label="Card Holder Name", max_length=60,
        widget=StripeTextInput('name'))
    expiration = CCExpField(label="Expiration")
    cvc = forms.CharField(label="CVC Number", max_length=4,
        widget=StripeTextInput('cvs'))

class StripeProcessPayment:
    def __init__(self, payment_data):
        self.last_error = ''
        self.payment_data = payment_data

    def is_valid(self):
        result = self.process_payment()
        if not result:
            email = conf_settings.DJANGO_CONFERENCE_CONTACT_EMAIL
            error = u"""
                We encountered an error while processing your credit card.
                Please contact %s for assistance.
            """
            self.last_error = mark_safe(error % (email, email))
            return False
        elif result != 'success':
            self.last_error = u'We encountered the following error while '+\
                u'processing your credit card: '+result
            return False
        return True

    def process_payment(self):
        if conf_settings.DJANGO_CONFERENCE_DISABLE_PAYMENT_PROCESSING:
            return 'success'
        if not self.payment_data or 'stripeToken' not in self.payment_data:
            return False
        stripe.api_key = conf_settings.DJANGO_CONFERENCE_STRIPE_SECRET_KEY
        two_places = Decimal('0.01')
        total_rounded = self.payment_data['total'].quantize(two_places)
        total_cents = str(total_rounded).replace('.', '')
        # Create the charge on Stripe's servers - this will charge the user's card
        try:
            charge = stripe.Charge.create(
                currency="usd",
                amount=total_cents,
                card=self.payment_data['stripeToken'],
                description=self.payment_data['description'],
            )
            return 'success'
        except stripe.CardError, e:
          # The card has been declined
            return unicode(e)


text:
BGFRI
=====

product page not found


text:
import React, { PropTypes } from 'react';

function EpisodesListItem(props) {
  let rowClass;
  let Icon;
  if ((new Date(props.episode.airstamp)) > (new Date())) {
    rowClass = 'info';
    Icon = 'glyphicon glyphicon-eye-open';
  } else if (props.episode.episode === 1 || props.episode.season === 1) {
    rowClass = 'success';
    Icon = 'glyphicon glyphicon-eye-close';
  } else {
    Icon = 'glyphicon glyphicon-eye-open';
    rowClass = '';
  }

  return (

      {props.episode.episode}

      {props.episode.name}
      {new Date(props.episode.airstamp).toLocaleDateString()}

  );
}

EpisodesListItem.propTypes = {};

export default EpisodesListItem;


text:
package com.webuml.importer.git.infrastructure;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.webuml.importer.domain.projectmodel.Project;

public class ProjectResource extends Project {

  @JsonIgnore
  String _links;

  public ProjectResource() {
  }

  public String get_links() {
    return _links;
  }

  public void set_links(String _links) {
    this._links = _links;
  }
}


text:
package com.twelvemonkeys.imageio.plugins.bmp;

import com.twelvemonkeys.imageio.spi.ImageWriterSpiBase;

import javax.imageio.ImageTypeSpecifier;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.spi.ServiceRegistry;
import java.awt.image.BufferedImage;
import java.util.Locale;

import static com.twelvemonkeys.imageio.util.IIOUtil.lookupProviderByName;

/**
 * BMPImageWriterSpi
 */
public final class BMPImageWriterSpi extends ImageWriterSpiBase {
    public BMPImageWriterSpi() {
        super(new BMPProviderInfo());
    }

    @Override
    public void onRegistration(ServiceRegistry registry, Class<?> category) {
        // Make sure we register BEHIND the built-in BMP writer
        ImageWriterSpi sunSpi = lookupProviderByName(registry, "com.sun.imageio.plugins.bmp.BMPImageWriterSpi", ImageWriterSpi.class);

        if (sunSpi != null && sunSpi.getVendorName() != null) {
            registry.setOrdering((Class<ImageWriterSpi>) category, sunSpi, this);
        }
    }

    @Override
    public boolean canEncodeImage(final ImageTypeSpecifier type) {
        // TODO: Support more types, as time permits.
        return type.getBufferedImageType() == BufferedImage.TYPE_4BYTE_ABGR;
    }

    @Override
    public BMPImageWriter createWriterInstance(final Object extension) {
        return new BMPImageWriter(this);
    }

    @Override
    public String getDescription(final Locale locale) {
        return "Windows Device Independent Bitmap Format (BMP) Writer";
    }
}


text:
import request from "supertest";
import { assert } from "chai";
import * as helper from "./helper";
import { Done } from "mocha";
const app = helper.postcodesioApplication();

describe("Outcodes routes", () => {
  before(async function () {
    this.timeout(0);
    await helper.clearPostcodeDb();
    await helper.seedPostcodeDb();
  });

  after(async () => helper.clearPostcodeDb);

  describe("GET /outcodes/:outcode", function () {
    const testOutcode = "AB10";
    it("should return correct geolocation data for a given outcode", function (done: Done) {
      const path = ["/outcodes/", encodeURI(testOutcode)].join("");
      request(app)
        .get(path)
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(200)
        .end(function (error, response) {
          if (error) return done(error);
          assert.equal(response.body.status, 200);
          assert.equal(response.body.result.outcode, testOutcode);
          assert.isUndefined(response.body.result.id);
          assert.isUndefined(response.body.result.location);
          helper.isOutcodeObject(response.body.result);
          done();
        });
    });
    it("should be case insensitive", function (done: Done) {
      const path = ["/outcodes/", encodeURI(testOutcode.toLowerCase())].join(
        ""
      );
      request(app)
        .get(path)
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(200)
        .end(function (error, response) {
          if (error) return done(error);
          assert.equal(response.body.status, 200);
          assert.equal(response.body.result.outcode, testOutcode);
          helper.isOutcodeObject(response.body.result);
          done();
        });
    });
    it("should be space insensitive", function (done: Done) {
      const path = ["/outcodes/", encodeURI(testOutcode + "   ")].join("");
      request(app)
        .get(path)
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(200)
        .end(function (error, response) {
          if (error) return done(error);
          assert.equal(response.body.status, 200);
          assert.equal(response.body.result.outcode, testOutcode);
          helper.isOutcodeObject(response.body.result);
          done();
        });
    });
    it("should return 404 for an outcode which does not exist", function (done: Done) {
      const path = ["/outcodes/", encodeURI("DEFINITELYBOGUS")].join("");
      request(app)
        .get(path)
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(404)
        .end(function (error, response) {
          if (error) return done(error);
          assert.equal(response.body.status, 404);
          assert.isUndefined(response.body.result);
          assert.equal(response.body.error, "Outcode not found");
          done();
        });
    });
    it("should respond to options", function (done: Done) {
      const path = ["/outcodes/", encodeURI(testOutcode)].join("");
      request(app)
        .options(path)
        .expect(204)
        .end(function (error, response) {
          if (error) done(error);
          helper.validCorsOptions(response);
          done();
        });
    });
  });
  describe("GET /outcodes", function () {
    let loc: any, uri: string;

    beforeEach(function () {
      uri = "/outcodes";
      loc = {
        longitude: -2.09301393644196,
        latitude: 57.1392691975667,
      };
    });

    it("returns a list of nearby postcodes", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lon: loc.longitude,
          lat: loc.latitude,
        })
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(200)
        .end(function (error, response) {
          if (error) return done(error);
          assert.isArray(response.body.result);
          assert.isTrue(response.body.result.length > 0);
          response.body.result.forEach(function (outcode: any) {
            helper.isOutcodeObject(outcode);
          });
          done();
        });
    });
    it("accepts full spelling of longitude and latitude", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          longitude: loc.longitude,
          latitude: loc.latitude,
        })
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(200)
        .end(function (error, response) {
          if (error) return done(error);
          assert.isArray(response.body.result);
          assert.isTrue(response.body.result.length > 0);
          response.body.result.forEach(function (outcode: any) {
            helper.isOutcodeObject(outcode);
          });
          done();
        });
    });
    it("returns 400 if longitude is missing", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          latitude: loc.latitude,
        })
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(400)
        .end(function (error, response) {
          if (error) return done(error);
          assert.equal(response.body.status, 400);
          done();
        });
    });
    it("returns 400 if latitude is missing", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          longitude: loc.longitude,
        })
        .expect("Content-Type", /json/)
        .expect(helper.allowsCORS)
        .expect(400)
        .end(function (error, response) {
          if (error) return done(error);
          assert.equal(response.body.status, 400);
          done();
        });
    });
    it("is sensitive to distance query", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lon: loc.longitude,
          lat: loc.latitude,
        })
        .expect(200)
        .end(function (error, firstResponse) {
          if (error) return done(error);
          request(app)
            .get(uri)
            .query({
              lon: loc.longitude,
              lat: loc.latitude,
              radius: 25000,
            })
            .expect(200)
            .end(function (error, secondResponse) {
              if (error) return done(error);
              assert.isTrue(
                secondResponse.body.result.length >=
                  firstResponse.body.result.length
              );
              done();
            });
        });
    });
    it("is sensitive to limit query", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lon: loc.longitude,
          lat: loc.latitude,
          limit: 1,
        })
        .expect(200)
        .end(function (error, response) {
          if (error) return done(error);
          assert.equal(response.body.result.length, 1);
          done();
        });
    });
    it("returns a 400 error if invalid longitude", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lon: "BOGUS",
          lat: loc.latitude,
        })
        .expect(400)
        .end(function (error, response) {
          if (error) return done(error);
          done();
        });
    });
    it("returns a 400 error if invalid latitude", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lon: loc.longitude,
          lat: "BOGUS",
        })
        .expect(400)
        .end(function (error, response) {
          if (error) return done(error);
          done();
        });
    });
    it("returns a 400 error if invalid limit", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lon: loc.longitude,
          lat: loc.latitude,
          limit: "BOGUS",
        })
        .expect(400)
        .end(function (error, response) {
          if (error) return done(error);
          done();
        });
    });
    it("returns a 400 error if invalid distance", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lon: loc.longitude,
          lat: loc.latitude,
          radius: "BOGUS",
        })
        .expect(400)
        .end(function (error, response) {
          if (error) return done(error);
          done();
        });
    });
    it("returns null if no outcodes nearby", function (done: Done) {
      request(app)
        .get(uri)
        .query({
          lat: 0,
          lon: 0,
        })
        .expect(200)
        .end(function (error, response) {
          if (error) done(error);
          assert.isNull(response.body.result);
          done();
        });
    });
    it("responds to options", function (done: Done) {
      request(app)
        .options(uri)
        .expect(204)
        .end(function (error, response) {
          if (error) done(error);
          helper.validCorsOptions(response);
          done();
        });
    });
  });
});


text:
package edu.tamu.tcat.dex.rest.v1;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import edu.tamu.tcat.trc.entries.common.DateDescription;
import edu.tamu.tcat.trc.entries.types.biblio.AuthorList;
import edu.tamu.tcat.trc.entries.types.biblio.AuthorReference;
import edu.tamu.tcat.trc.entries.types.biblio.Edition;
import edu.tamu.tcat.trc.entries.types.biblio.PublicationInfo;
import edu.tamu.tcat.trc.entries.types.biblio.Title;
import edu.tamu.tcat.trc.entries.types.biblio.TitleDefinition;
import edu.tamu.tcat.trc.entries.types.biblio.Work;
import edu.tamu.tcat.trc.entries.types.bio.Person;
import edu.tamu.tcat.trc.entries.types.bio.PersonName;

public class RepoAdapter
{
   private static final Logger logger = Logger.getLogger(RepoAdapter.class.getName());

   public static RestApiV1.Manuscript toManuscriptDTO(Work work)
   {
      Objects.requireNonNull(work);

      RestApiV1.Manuscript dto = new RestApiV1.Manuscript();

      dto.id = work.getId();
      dto.title = getTitle(work.getTitle());
      dto.links = work.getSummary();

      AuthorList authorList = work.getAuthors();
      AuthorReference authorReference = authorList == null || authorList.size() == 0 ? null : authorList.get(0);
      dto.author = getName(authorReference);

      return dto;
   }

   public static RestApiV1.Play toPlayDTO(Work work)
   {
      Objects.requireNonNull(work);

      RestApiV1.Play dto = new RestApiV1.Play();

      dto.id = work.getId();
      dto.title = getTitle(work.getTitle());

      for (AuthorReference ref : work.getAuthors())
      {
         if (ref == null)
         {
            continue;
         }

         dto.playwrights.add(toDTO(ref));
      }

      return dto;
   }

   public static RestApiV1.Playwright toPlaywrightDTO(Person person)
   {
      Objects.requireNonNull(person);

      RestApiV1.Playwright dto = new RestApiV1.Playwright();

      dto.id = person.getId();

      dto.names = Stream.concat(Stream.of(person.getCanonicalName()), person.getAlternativeNames().stream())
            .map(RepoAdapter::getName)
            .collect(Collectors.toList());

      return dto;
   }

   public static RestApiV1.Character toCharacterDTO(Person person)
   {
      RestApiV1.Character dto = new RestApiV1.Character();

      dto.id = person.getId();
      dto.name = getName(person.getCanonicalName());

      // TODO: dto.plays

      return dto;
   }

   private static RestApiV1.PlaywrightReference toDTO(AuthorReference ref)
   {
      RestApiV1.PlaywrightReference dto = new RestApiV1.PlaywrightReference();

      dto.id = ref.getId();
      dto.name = getName(ref);

      return dto;
   }

   public static RestApiV1.PlayBibEntry toPlayBibEntryDTO(Work work)
   {
      RestApiV1.PlayBibEntry dto = new RestApiV1.PlayBibEntry();

      dto.id = work.getId();
      dto.title = getTitle(work.getTitle());
      dto.playwrights = getAuthors(work.getAuthors());
      dto.playwrights.addAll(getAuthors(work.getOtherAuthors()));

      dto.editions = work.getEditions().stream()
            .map(RepoAdapter::toEditionBibEntryDTO)
            .collect(Collectors.toList());

      return dto;
   }

   public static RestApiV1.EditionBibEntry toEditionBibEntryDTO(Edition edition)
   {
      RestApiV1.EditionBibEntry dto = new RestApiV1.EditionBibEntry();

      dto.id = edition.getId();
      dto.editors = getAuthors(edition.getAuthors());
      dto.editors.addAll(getAuthors(edition.getOtherAuthors()));

      Collection<Title> titles = edition.getTitles();
      if (titles != null && !titles.isEmpty())
      {
         dto.title = getTitle(titles.iterator().next());
      }

      PublicationInfo publicationInfo = edition.getPublicationInfo();
      if (publicationInfo != null)
      {
         DateDescription publicationDate = publicationInfo.getPublicationDate();
         if (publicationDate != null)
         {
            dto.date = publicationDate.getDescription();
         }
      }

      String summary = edition.getSummary();
      if (summary != null)
      {
         try {
            dto.link = new URI(summary);
         }
         catch (URISyntaxException e) {
            logger.log(Level.WARNING, "Unable to parse URI on edition [" + edition.getId() + "].", e);
         }
      }

      return dto;
   }

   private static String getTitle(TitleDefinition titleDefinition)
   {
      if (titleDefinition == null)
      {
         return "";
      }

      return getTitle(titleDefinition.get("canonical"));
   }

   private static String getTitle(Title title)
   {
      if (title == null)
      {
         return "";
      }

      String titleString = title.getFullTitle();
      return titleString == null ? "" : titleString;
   }

   private static String getName(AuthorReference ref)
   {
      if (ref == null)
      {
         return "";
      }

      String firstName = ref.getFirstName();
      String firstNameTrimmed = firstName == null ? "" : firstName.trim();

      String lastName = ref.getLastName();
      String lastNameTrimmed = lastName == null ? "" : lastName.trim();

      return (firstNameTrimmed + " " + lastNameTrimmed).trim();
   }

   private static String getName(PersonName name)
   {
      if (name == null)
      {
         return "";
      }

      // prefer display name
      String displayName = name.getDisplayName();
      if (displayName != null && !displayName.isEmpty())
      {
         return displayName;
      }

      // fall back to construction from name parts
      List<String> nameParts = Arrays.asList(
            name.getTitle(),
            name.getGivenName(),
            name.getMiddleName(),
            name.getFamilyName(),
            name.getSuffix()
      );

      StringJoiner nameJoiner = new StringJoiner(" ");
      nameJoiner.setEmptyValue("");
      nameParts.stream()
            .filter(Objects::nonNull)
            .forEach(nameJoiner::add);

      return nameJoiner.toString().replaceAll("\\w+", " ");
   }

   private static List<String> getAuthors(List<AuthorReference> authorList)
   {
      return authorList.stream()
            .map(RepoAdapter::getName)
            .collect(Collectors.toList());
   }

   private static List<String> getAuthors(AuthorList authorList)
   {
      List<String> authors = new ArrayList<>(authorList.size());
      authorList.forEach(ar -> authors.add(getName(ar)));
      return authors;
   }
}


text:
package cz.kea.web.components.dataproviders;

import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

import com.vaadin.data.provider.AbstractBackEndDataProvider;
import com.vaadin.data.provider.Query;
import cz.kea.api.model.Identifiable;
import cz.kea.api.services.BaseService;
import cz.kea.api.utils.Filter;
import cz.kea.api.utils.Order;
import cz.kea.web.components.converters.OrderConverter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Jakub Jaros (jakub.jaros@ibacz.eu)
 */
public abstract class BaseDataProvider<T extends Identifiable<ID>, ID extends Serializable> extends AbstractBackEndDataProvider<T, Map<Filter, Object>> {

    protected final Logger log = LogManager.getFormatterLogger(getClass());

    @Autowired
    protected OrderConverter orderConverter;

    @Override
    protected Stream<T> fetchFromBackEnd(Query<T, Map<Filter, Object>> query) {
        log.trace("Fetching from back end.");

        Optional<Map<Filter, Object>> optionalFilter = query.getFilter();
        Map<Filter, Object> filter = optionalFilter.orElse(Collections.emptyMap());
        Order[] orders = orderConverter.convert(query.getSortOrders());
        if (orders.length > 0) {
            return getService().findAll(filter, query.getOffset(), query.getLimit(), orders).getItems().stream();
        } else {
            return getService().findAll(filter, query.getOffset(), query.getLimit()).getItems().stream();
        }
    }

    @Override
    protected int sizeInBackEnd(Query<T, Map<Filter, Object>> query) {
        log.trace("Getting size from back end.");

        Optional<Map<Filter, Object>> optionalFilter = query.getFilter();
        Map<Filter, Object> filter = optionalFilter.orElse(Collections.emptyMap());
        return (int) getService().count(filter);
    }

    protected abstract BaseService<T, ID> getService();
}


text:
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/scatterlist.h>
#include <linux/kfifo.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_host.h>

#include "iscsi_iser.h"

/* Register user buffer memory and initialize passive rdma
 *  dto descriptor. Total data size is stored in
 *  iser_task->data[ISER_DIR_IN].data_len
 */
static int iser_prepare_read_cmd(struct iscsi_task *task,
				 unsigned int edtl)

{
	struct iscsi_iser_task *iser_task = task->dd_data;
	struct iser_regd_buf *regd_buf;
	int err;
	struct iser_hdr *hdr = &iser_task->desc.iser_header;
	struct iser_data_buf *buf_in = &iser_task->data[ISER_DIR_IN];

	err = iser_dma_map_task_data(iser_task,
				     buf_in,
				     ISER_DIR_IN,
				     DMA_FROM_DEVICE);
	if (err)
		return err;

	if (edtl > iser_task->data[ISER_DIR_IN].data_len) {
		iser_err("Total data length: %ld, less than EDTL: "
			 "%d, in READ cmd BHS itt: %d, conn: 0x%p\n",
			 iser_task->data[ISER_DIR_IN].data_len, edtl,
			 task->itt, iser_task->iser_conn);
		return -EINVAL;
	}

	err = iser_reg_rdma_mem(iser_task,ISER_DIR_IN);
	if (err) {
		iser_err("Failed to set up Data-IN RDMA\n");
		return err;
	}
	regd_buf = &iser_task->rdma_regd[ISER_DIR_IN];

	hdr->flags    |= ISER_RSV;
	hdr->read_stag = cpu_to_be32(regd_buf->reg.rkey);
	hdr->read_va   = cpu_to_be64(regd_buf->reg.va);

	iser_dbg("Cmd itt:%d READ tags RKEY:%#.4X VA:%#llX\n",
		 task->itt, regd_buf->reg.rkey,
		 (unsigned long long)regd_buf->reg.va);

	return 0;
}

/* Register user buffer memory and initialize passive rdma
 *  dto descriptor. Total data size is stored in
 *  task->data[ISER_DIR_OUT].data_len
 */
static int
iser_prepare_write_cmd(struct iscsi_task *task,
		       unsigned int imm_sz,
		       unsigned int unsol_sz,
		       unsigned int edtl)
{
	struct iscsi_iser_task *iser_task = task->dd_data;
	struct iser_regd_buf *regd_buf;
	int err;
	struct iser_hdr *hdr = &iser_task->desc.iser_header;
	struct iser_data_buf *buf_out = &iser_task->data[ISER_DIR_OUT];
	struct ib_sge *tx_dsg = &iser_task->desc.tx_sg[1];

	err = iser_dma_map_task_data(iser_task,
				     buf_out,
				     ISER_DIR_OUT,
				     DMA_TO_DEVICE);
	if (err)
		return err;

	if (edtl > iser_task->data[ISER_DIR_OUT].data_len) {
		iser_err("Total data length: %ld, less than EDTL: %d, "
			 "in WRITE cmd BHS itt: %d, conn: 0x%p\n",
			 iser_task->data[ISER_DIR_OUT].data_len,
			 edtl, task->itt, task->conn);
		return -EINVAL;
	}

	err = iser_reg_rdma_mem(iser_task,ISER_DIR_OUT);
	if (err != 0) {
		iser_err("Failed to register write cmd RDMA mem\n");
		return err;
	}

	regd_buf = &iser_task->rdma_regd[ISER_DIR_OUT];

	if (unsol_sz < edtl) {
		hdr->flags     |= ISER_WSV;
		hdr->write_stag = cpu_to_be32(regd_buf->reg.rkey);
		hdr->write_va   = cpu_to_be64(regd_buf->reg.va + unsol_sz);

		iser_dbg("Cmd itt:%d, WRITE tags, RKEY:%#.4X "
			 "VA:%#llX + unsol:%d\n",
			 task->itt, regd_buf->reg.rkey,
			 (unsigned long long)regd_buf->reg.va, unsol_sz);
	}

	if (imm_sz > 0) {
		iser_dbg("Cmd itt:%d, WRITE, adding imm.data sz: %d\n",
			 task->itt, imm_sz);
		tx_dsg->addr   = regd_buf->reg.va;
		tx_dsg->length = imm_sz;
		tx_dsg->lkey   = regd_buf->reg.lkey;
		iser_task->desc.num_sge = 2;
	}

	return 0;
}

/* creates a new tx descriptor and adds header regd buffer */
static void iser_create_send_desc(struct iser_conn	*ib_conn,
				  struct iser_tx_desc	*tx_desc)
{
	struct iser_device *device = ib_conn->device;

	ib_dma_sync_single_for_cpu(device->ib_device,
		tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE);

	memset(&tx_desc->iser_header, 0, sizeof(struct iser_hdr));
	tx_desc->iser_header.flags = ISER_VER;

	tx_desc->num_sge = 1;

	if (tx_desc->tx_sg[0].lkey != device->mr->lkey) {
		tx_desc->tx_sg[0].lkey = device->mr->lkey;
		iser_dbg("sdesc %p lkey mismatch, fixing\n", tx_desc);
	}
}

static int iser_alloc_rx_descriptors(struct iser_conn *ib_conn)
{
	int i, j;
	u64 dma_addr;
	struct iser_rx_desc *rx_desc;
	struct ib_sge       *rx_sg;
	struct iser_device  *device = ib_conn->device;

	ib_conn->rx_descs = kmalloc(ISER_QP_MAX_RECV_DTOS *
				sizeof(struct iser_rx_desc), GFP_KERNEL);
	if (!ib_conn->rx_descs)
		goto rx_desc_alloc_fail;

	rx_desc = ib_conn->rx_descs;

	for (i = 0; i < ISER_QP_MAX_RECV_DTOS; i++, rx_desc++)  {
		dma_addr = ib_dma_map_single(device->ib_device, (void *)rx_desc,
					ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE);
		if (ib_dma_mapping_error(device->ib_device, dma_addr))
			goto rx_desc_dma_map_failed;

		rx_desc->dma_addr = dma_addr;

		rx_sg = &rx_desc->rx_sg;
		rx_sg->addr   = rx_desc->dma_addr;
		rx_sg->length = ISER_RX_PAYLOAD_SIZE;
		rx_sg->lkey   = device->mr->lkey;
	}

	ib_conn->rx_desc_head = 0;
	return 0;

rx_desc_dma_map_failed:
	rx_desc = ib_conn->rx_descs;
	for (j = 0; j < i; j++, rx_desc++)
		ib_dma_unmap_single(device->ib_device, rx_desc->dma_addr,
			ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE);
	kfree(ib_conn->rx_descs);
	ib_conn->rx_descs = NULL;
rx_desc_alloc_fail:
	iser_err("failed allocating rx descriptors / data buffers\n");
	return -ENOMEM;
}

void iser_free_rx_descriptors(struct iser_conn *ib_conn)
{
	int i;
	struct iser_rx_desc *rx_desc;
	struct iser_device *device = ib_conn->device;

	if (ib_conn->login_buf) {
		ib_dma_unmap_single(device->ib_device, ib_conn->login_dma,
			ISER_RX_LOGIN_SIZE, DMA_FROM_DEVICE);
		kfree(ib_conn->login_buf);
	}

	if (!ib_conn->rx_descs)
		return;

	rx_desc = ib_conn->rx_descs;
	for (i = 0; i < ISER_QP_MAX_RECV_DTOS; i++, rx_desc++)
		ib_dma_unmap_single(device->ib_device, rx_desc->dma_addr,
			ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE);
	kfree(ib_conn->rx_descs);
}

/**
 *  iser_conn_set_full_featured_mode - (iSER API)
 */
int iser_conn_set_full_featured_mode(struct iscsi_conn *conn)
{
	struct iscsi_iser_conn *iser_conn = conn->dd_data;

	iser_dbg("Initially post: %d\n", ISER_MIN_POSTED_RX);

	/* Check that there is no posted recv or send buffers left - */
	/* they must be consumed during the login phase */
	BUG_ON(iser_conn->ib_conn->post_recv_buf_count != 0);
	BUG_ON(atomic_read(&iser_conn->ib_conn->post_send_buf_count) != 0);

	if (iser_alloc_rx_descriptors(iser_conn->ib_conn))
		return -ENOMEM;

	/* Initial post receive buffers */
	if (iser_post_recvm(iser_conn->ib_conn, ISER_MIN_POSTED_RX))
		return -ENOMEM;

	return 0;
}

/**
 * iser_send_command - send command PDU
 */
int iser_send_command(struct iscsi_conn *conn,
		      struct iscsi_task *task)
{
	struct iscsi_iser_conn *iser_conn = conn->dd_data;
	struct iscsi_iser_task *iser_task = task->dd_data;
	unsigned long edtl;
	int err;
	struct iser_data_buf *data_buf;
	struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)task->hdr;
	struct scsi_cmnd *sc  =  task->sc;
	struct iser_tx_desc *tx_desc = &iser_task->desc;

	edtl = ntohl(hdr->data_length);

	/* build the tx desc regd header and add it to the tx desc dto */
	tx_desc->type = ISCSI_TX_SCSI_COMMAND;
	iser_create_send_desc(iser_conn->ib_conn, tx_desc);

	if (hdr->flags & ISCSI_FLAG_CMD_READ)
		data_buf = &iser_task->data[ISER_DIR_IN];
	else
		data_buf = &iser_task->data[ISER_DIR_OUT];

	if (scsi_sg_count(sc)) { /* using a scatter list */
		data_buf->buf  = scsi_sglist(sc);
		data_buf->size = scsi_sg_count(sc);
	}

	data_buf->data_len = scsi_bufflen(sc);

	if (hdr->flags & ISCSI_FLAG_CMD_READ) {
		err = iser_prepare_read_cmd(task, edtl);
		if (err)
			goto send_command_error;
	}
	if (hdr->flags & ISCSI_FLAG_CMD_WRITE) {
		err = iser_prepare_write_cmd(task,
					     task->imm_count,
				             task->imm_count +
					     task->unsol_r2t.data_length,
					     edtl);
		if (err)
			goto send_command_error;
	}

	iser_task->status = ISER_TASK_STATUS_STARTED;

	err = iser_post_send(iser_conn->ib_conn, tx_desc);
	if (!err)
		return 0;

send_command_error:
	iser_err("conn %p failed task->itt %d err %d\n",conn, task->itt, err);
	return err;
}

/**
 * iser_send_data_out - send data out PDU
 */
int iser_send_data_out(struct iscsi_conn *conn,
		       struct iscsi_task *task,
		       struct iscsi_data *hdr)
{
	struct iscsi_iser_conn *iser_conn = conn->dd_data;
	struct iscsi_iser_task *iser_task = task->dd_data;
	struct iser_tx_desc *tx_desc = NULL;
	struct iser_regd_buf *regd_buf;
	unsigned long buf_offset;
	unsigned long data_seg_len;
	uint32_t itt;
	int err = 0;
	struct ib_sge *tx_dsg;

	itt = (__force uint32_t)hdr->itt;
	data_seg_len = ntoh24(hdr->dlength);
	buf_offset   = ntohl(hdr->offset);

	iser_dbg("%s itt %d dseg_len %d offset %d\n",
		 __func__,(int)itt,(int)data_seg_len,(int)buf_offset);

	tx_desc = kmem_cache_zalloc(ig.desc_cache, GFP_ATOMIC);
	if (tx_desc == NULL) {
		iser_err("Failed to alloc desc for post dataout\n");
		return -ENOMEM;
	}

	tx_desc->type = ISCSI_TX_DATAOUT;
	tx_desc->iser_header.flags = ISER_VER;
	memcpy(&tx_desc->iscsi_header, hdr, sizeof(struct iscsi_hdr));

	/* build the tx desc */
	iser_initialize_task_headers(task, tx_desc);

	regd_buf = &iser_task->rdma_regd[ISER_DIR_OUT];
	tx_dsg = &tx_desc->tx_sg[1];
	tx_dsg->addr    = regd_buf->reg.va + buf_offset;
	tx_dsg->length  = data_seg_len;
	tx_dsg->lkey    = regd_buf->reg.lkey;
	tx_desc->num_sge = 2;

	if (buf_offset + data_seg_len > iser_task->data[ISER_DIR_OUT].data_len) {
		iser_err("Offset:%ld & DSL:%ld in Data-Out "
			 "inconsistent with total len:%ld, itt:%d\n",
			 buf_offset, data_seg_len,
			 iser_task->data[ISER_DIR_OUT].data_len, itt);
		err = -EINVAL;
		goto send_data_out_error;
	}
	iser_dbg("data-out itt: %d, offset: %ld, sz: %ld\n",
		 itt, buf_offset, data_seg_len);

	err = iser_post_send(iser_conn->ib_conn, tx_desc);
	if (!err)
		return 0;

send_data_out_error:
	kmem_cache_free(ig.desc_cache, tx_desc);
	iser_err("conn %p failed err %d\n",conn, err);
	return err;
}

int iser_send_control(struct iscsi_conn *conn,
		      struct iscsi_task *task)
{
	struct iscsi_iser_conn *iser_conn = conn->dd_data;
	struct iscsi_iser_task *iser_task = task->dd_data;
	struct iser_tx_desc *mdesc = &iser_task->desc;
	unsigned long data_seg_len;
	int err = 0;
	struct iser_device *device;

	/* build the tx desc regd header and add it to the tx desc dto */
	mdesc->type = ISCSI_TX_CONTROL;
	iser_create_send_desc(iser_conn->ib_conn, mdesc);

	device = iser_conn->ib_conn->device;

	data_seg_len = ntoh24(task->hdr->dlength);

	if (data_seg_len > 0) {
		struct ib_sge *tx_dsg = &mdesc->tx_sg[1];
		if (task != conn->login_task) {
			iser_err("data present on non login task!!!\n");
			goto send_control_error;
		}
		memcpy(iser_conn->ib_conn->login_buf, task->data,
							task->data_count);
		tx_dsg->addr    = iser_conn->ib_conn->login_dma;
		tx_dsg->length  = task->data_count;
		tx_dsg->lkey    = device->mr->lkey;
		mdesc->num_sge = 2;
	}

	if (task == conn->login_task) {
		err = iser_post_recvl(iser_conn->ib_conn);
		if (err)
			goto send_control_error;
	}

	err = iser_post_send(iser_conn->ib_conn, mdesc);
	if (!err)
		return 0;

send_control_error:
	iser_err("conn %p failed err %d\n",conn, err);
	return err;
}

/**
 * iser_rcv_dto_completion - recv DTO completion
 */
void iser_rcv_completion(struct iser_rx_desc *rx_desc,
			 unsigned long rx_xfer_len,
			 struct iser_conn *ib_conn)
{
	struct iscsi_iser_conn *conn = ib_conn->iser_conn;
	struct iscsi_hdr *hdr;
	u64 rx_dma;
	int rx_buflen, outstanding, count, err;

	/* differentiate between login to all other PDUs */
	if ((char *)rx_desc == ib_conn->login_buf) {
		rx_dma = ib_conn->login_dma;
		rx_buflen = ISER_RX_LOGIN_SIZE;
	} else {
		rx_dma = rx_desc->dma_addr;
		rx_buflen = ISER_RX_PAYLOAD_SIZE;
	}

	ib_dma_sync_single_for_cpu(ib_conn->device->ib_device, rx_dma,
			rx_buflen, DMA_FROM_DEVICE);

	hdr = &rx_desc->iscsi_header;

	iser_dbg("op 0x%x itt 0x%x dlen %d\n", hdr->opcode,
			hdr->itt, (int)(rx_xfer_len - ISER_HEADERS_LEN));

	iscsi_iser_recv(conn->iscsi_conn, hdr,
		rx_desc->data, rx_xfer_len - ISER_HEADERS_LEN);

	ib_dma_sync_single_for_device(ib_conn->device->ib_device, rx_dma,
			rx_buflen, DMA_FROM_DEVICE);

	/* decrementing conn->post_recv_buf_count only --after-- freeing the   *
	 * task eliminates the need to worry on tasks which are completed in   *
	 * parallel to the execution of iser_conn_term. So the code that waits *
	 * for the posted rx bufs refcount to become zero handles everything   */
	conn->ib_conn->post_recv_buf_count--;

	if (rx_dma == ib_conn->login_dma)
		return;

	outstanding = ib_conn->post_recv_buf_count;
	if (outstanding + ISER_MIN_POSTED_RX <= ISER_QP_MAX_RECV_DTOS) {
		count = min(ISER_QP_MAX_RECV_DTOS - outstanding,
						ISER_MIN_POSTED_RX);
		err = iser_post_recvm(ib_conn, count);
		if (err)
			iser_err("posting %d rx bufs err %d\n", count, err);
	}
}

void iser_snd_completion(struct iser_tx_desc *tx_desc,
			struct iser_conn *ib_conn)
{
	struct iscsi_task *task;
	struct iser_device *device = ib_conn->device;

	if (tx_desc->type == ISCSI_TX_DATAOUT) {
		ib_dma_unmap_single(device->ib_device, tx_desc->dma_addr,
					ISER_HEADERS_LEN, DMA_TO_DEVICE);
		kmem_cache_free(ig.desc_cache, tx_desc);
	}

	atomic_dec(&ib_conn->post_send_buf_count);

	if (tx_desc->type == ISCSI_TX_CONTROL) {
		/* this arithmetic is legal by libiscsi dd_data allocation */
		task = (void *) ((long)(void *)tx_desc -
				  sizeof(struct iscsi_task));
		if (task->hdr->itt == RESERVED_ITT)
			iscsi_put_task(task);
	}
}

void iser_task_rdma_init(struct iscsi_iser_task *iser_task)

{
	iser_task->status = ISER_TASK_STATUS_INIT;

	iser_task->dir[ISER_DIR_IN] = 0;
	iser_task->dir[ISER_DIR_OUT] = 0;

	iser_task->data[ISER_DIR_IN].data_len  = 0;
	iser_task->data[ISER_DIR_OUT].data_len = 0;

	memset(&iser_task->rdma_regd[ISER_DIR_IN], 0,
	       sizeof(struct iser_regd_buf));
	memset(&iser_task->rdma_regd[ISER_DIR_OUT], 0,
	       sizeof(struct iser_regd_buf));
}

void iser_task_rdma_finalize(struct iscsi_iser_task *iser_task)
{
	int is_rdma_aligned = 1;
	struct iser_regd_buf *regd;

	/* if we were reading, copy back to unaligned sglist,
	 * anyway dma_unmap and free the copy
	 */
	if (iser_task->data_copy[ISER_DIR_IN].copy_buf != NULL) {
		is_rdma_aligned = 0;
		iser_finalize_rdma_unaligned_sg(iser_task, ISER_DIR_IN);
	}
	if (iser_task->data_copy[ISER_DIR_OUT].copy_buf != NULL) {
		is_rdma_aligned = 0;
		iser_finalize_rdma_unaligned_sg(iser_task, ISER_DIR_OUT);
	}

	if (iser_task->dir[ISER_DIR_IN]) {
		regd = &iser_task->rdma_regd[ISER_DIR_IN];
		if (regd->reg.is_fmr)
			iser_unreg_mem(&regd->reg);
	}

	if (iser_task->dir[ISER_DIR_OUT]) {
		regd = &iser_task->rdma_regd[ISER_DIR_OUT];
		if (regd->reg.is_fmr)
			iser_unreg_mem(&regd->reg);
	}

       /* if the data was unaligned, it was already unmapped and then copied */
       if (is_rdma_aligned)
		iser_dma_unmap_task_data(iser_task);
}


text:
package org.apache.samza.metrics.reporter;

import java.util.Map;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class TestMetricsSnapshot {
  private static final MetricsHeader METRICS_HEADER =
      new MetricsHeader("job", "id", "container", "container-id", Optional.of("epoch-123"), "source", "1.2", "3.4",
          "a.b.c", 100, 10);
  private static final Metrics METRICS =
      new Metrics(ImmutableMap.of("group0", ImmutableMap.of("a", "b"), "group1", ImmutableMap.of("c", "d")));

  @Test
  public void testGetAsMap() {
    MetricsSnapshot metricsSnapshot = new MetricsSnapshot(METRICS_HEADER, METRICS);
    Map<String, Object> expected = ImmutableMap.of("header", METRICS_HEADER.getAsMap(), "metrics", METRICS.getAsMap());
    assertEquals(expected, metricsSnapshot.getAsMap());
  }

  @Test
  public void testFromMap() {
    Map<String, Map<String, Object>> map =
        ImmutableMap.of("header", ImmutableMap.copyOf(METRICS_HEADER.getAsMap()), "metrics",
            ImmutableMap.copyOf((Map<String, Object>) (Map<?, ?>) METRICS.getAsMap()));
    MetricsSnapshot expected = new MetricsSnapshot(METRICS_HEADER, METRICS);
    assertEquals(expected, MetricsSnapshot.fromMap(map));
  }
}


text:
describe("metric.BodyWeight", function(): void {
  var expect = chai.expect;
  var m: metric.IMetric;

  beforeEach(function(): void {
    var $injector = angular.injector(["ng", "dosenApp"]);
    var wikipedia = $injector.get("wikipedia");
    m = new metric.BodyWeight(wikipedia);
  });

  it("should get a metric", function(done: MochaDone): void {
    this.timeout(5000);
    m.getMetric("ペリカン").then(function(mi: metric.IMetricItem): void {
    	try {
        expect(mi).to.have.property("name").and.equal("体重");
        expect(mi).to.have.property("text").and.equal("11キログラム");
        expect(mi).to.have.property("value").and.equal(11);
        done();
      } catch (e) {
        done(e);
      }
    });
  });

  it("should get some value for invalid text", function(done: MochaDone): void {
    this.timeout(5000);
    m.getMetric("ストリング").then(function(mi: metric.IMetricItem): void {
    	try {
        expect(mi).to.have.property("name").and.equal("体重");
        expect(mi).to.have.property("text");
        expect(mi).to.have.property("value").and.equal(0);
        done();
      } catch (e) {
        done(e);
      }
    });
  });
});


text:
package com.javacreed.api.swing.common.text;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;

public class DocumentAdapter implements DocumentListener {

  public static <T extends JTextComponent> T wrap(final T textComponent, final TextChangedListener listener) {
    textComponent.getDocument().addDocumentListener(new TextChangedAdapter(listener));
    return textComponent;
  }

  @Override
  public void changedUpdate(final DocumentEvent e) {
    updated(e);
  }

  @Override
  public void insertUpdate(final DocumentEvent e) {
    updated(e);
  }

  @Override
  public void removeUpdate(final DocumentEvent e) {
    updated(e);
  }

  public void updated(final DocumentEvent e) {}

}


text:
<?php

declare(strict_types=1);

namespace MarcusJaschen\Collmex\Exception;

class InvalidTypeIdentifierException extends \Exception
{
}


text:
// ---------------------------------------------------------------------------
// Copyright (C) 2005 Microsoft Corporation All Rights Reserved
// ---------------------------------------------------------------------------

using System.CodeDom;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Workflow.Activities.Common;
using System.Workflow.ComponentModel.Compiler;

namespace System.Workflow.Activities.Rules
{
    public enum RuleAttributeTarget
    {
        Parameter,
        This
    }

    public abstract class RuleAttribute : Attribute
    {
        internal abstract bool Validate(RuleValidation validation, MemberInfo member, Type contextType, ParameterInfo[] parameters);
        internal abstract void Analyze(RuleAnalysis analysis, MemberInfo member, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions);
    }

    public abstract class RuleReadWriteAttribute : RuleAttribute
    {
        private RuleAttributeTarget attributeTarget;
        private string attributePath;

        protected RuleReadWriteAttribute(string path, RuleAttributeTarget target)
        {
            this.attributeTarget = target;
            this.attributePath = path;
        }

        public string Path
        {
            get { return attributePath; }
        }

        public RuleAttributeTarget Target
        {
            get { return attributeTarget; }
        }

        internal override bool Validate(RuleValidation validation, MemberInfo member, Type contextType, ParameterInfo[] parameters)
        {
            ValidationError error = null;
            string message = null;

            if (string.IsNullOrEmpty(attributePath))
            {
                // It is allowed to pass null or the empty string to [RuleRead] or [RuleWrite].  This
                // is how you indicate that a method or property has no dependencies or side effects.
                return true;
            }

            bool valid = true;

            string[] parts = attributePath.Split('/');

            // Check the first part.

            string firstPart = parts[0];
            int startOfRelativePortion = 0;
            if (attributeTarget == RuleAttributeTarget.This)
            {
                // When target is "This", the path is allowed to start with the token "this".  It is
                // then skipped for the rest of the validation, and the contextType remains what it
                // was when passed in.
                if (firstPart == "this")
                    ++startOfRelativePortion;
            }
            else
            {
                // When target is "Parameter", the path must start with the name of a parameter.
                bool found = false;
                for (int p = 0; p < parameters.Length; ++p)
                {
                    ParameterInfo param = parameters[p];
                    if (param.Name == firstPart)
                    {
                        found = true;

                        // The context type is the parameter type.
                        contextType = param.ParameterType;
                        break;
                    }
                }

                if (!found)
                {
                    message = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleAttributeParameter, firstPart, member.Name);
                    error = new ValidationError(message, ErrorNumbers.Error_InvalidRuleAttributeParameter);
                    error.UserData[RuleUserDataKeys.ErrorObject] = this;
                    validation.AddError(error);
                    return false;
                }

                ++startOfRelativePortion;
            }

            int numParts = parts.Length;

            // Check the last part.  The last part is allowed to be empty, or "*".

            string lastPart = parts[numParts - 1];
            if (string.IsNullOrEmpty(lastPart) || lastPart == "*")
                numParts -= 1;

            // Check the rest of the parts.

            Type currentType = contextType;
            for (int i = startOfRelativePortion; i < numParts; ++i)
            {
                // Can't have embedded "*" wildcards.
                if (parts[i] == "*")
                {
                    // The "*" occurred in the middle of the path, which is a no-no.
                    error = new ValidationError(Messages.InvalidWildCardInPathQualifier, ErrorNumbers.Error_InvalidWildCardInPathQualifier);
                    error.UserData[RuleUserDataKeys.ErrorObject] = this;
                    validation.AddError(error);
                    valid = false;
                    break;
                }

                // Skip array types.
                while (currentType.IsArray)
                    currentType = currentType.GetElementType();

                // Make sure the member exists in the current type.
                BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
                if (validation.AllowInternalMembers(currentType))
                    bindingFlags |= BindingFlags.NonPublic;

                FieldInfo field = currentType.GetField(parts[i], bindingFlags);
                if (field != null)
                {
                    currentType = field.FieldType;
                }
                else
                {
                    PropertyInfo property = currentType.GetProperty(parts[i], bindingFlags);
                    if (property != null)
                    {
                        currentType = property.PropertyType;
                    }
                    else
                    {
                        message = string.Format(CultureInfo.CurrentCulture, Messages.UpdateUnknownFieldOrProperty, parts[i]);
                        error = new ValidationError(message, ErrorNumbers.Error_UnknownFieldOrProperty);
                        error.UserData[RuleUserDataKeys.ErrorObject] = this;
                        validation.AddError(error);
                        valid = false;
                        break;
                    }
                }
            }

            return valid;
        }

        internal void AnalyzeReadWrite(RuleAnalysis analysis, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions)
        {
            if (string.IsNullOrEmpty(attributePath))
            {
                // If the suffix is null or empty, this means the RuleAttributeTarget has no dependencies.
                if (attributeTarget == RuleAttributeTarget.This)
                {
                    // The target object has no dependencies.
                    attributedExpressions.Add(targetExpression);
                }
                else if (attributeTarget == RuleAttributeTarget.Parameter)
                {
                    // ALL arguments have no dependencies.
                    for (int i = 0; i < argumentExpressions.Count; ++i)
                        attributedExpressions.Add(argumentExpressions[i]);
                }
            }
            else
            {
                string suffix = attributePath;

                bool isRead = !analysis.ForWrites;
                bool isWrite = analysis.ForWrites;

                if (attributeTarget == RuleAttributeTarget.This)
                {
                    // Target is "This", so perform the analysis on the target expression.

                    // Remove the optional "this/" token if present.
                    string optionalPrefix = "this/";
                    if (suffix.StartsWith(optionalPrefix, StringComparison.Ordinal))
                        suffix = suffix.Substring(optionalPrefix.Length);

                    RuleExpressionWalker.AnalyzeUsage(analysis, targetExpression, isRead, isWrite, new RulePathQualifier(suffix, targetQualifier));
                    attributedExpressions.Add(targetExpression);
                }
                else if (attributeTarget == RuleAttributeTarget.Parameter)
                {
                    string paramName = null;

                    int firstSlash = suffix.IndexOf('/');
                    if (firstSlash >= 0)
                    {
                        paramName = suffix.Substring(0, firstSlash);
                        suffix = suffix.Substring(firstSlash + 1);
                    }
                    else
                    {
                        paramName = suffix;
                        suffix = null;
                    }

                    // Find the ParameterInfo that corresponds to this attribute path.
                    ParameterInfo param = Array.Find<ParameterInfo>(parameters,
                                                                    delegate(ParameterInfo p) { return p.Name == paramName; });
                    if (param != null)
                    {
                        RulePathQualifier qualifier = string.IsNullOrEmpty(suffix) ? null : new RulePathQualifier(suffix, null);

                        // 99.9% of the time, the parameter usage attribute only applies to one argument.  However,
                        // if this attribute corresponds to the last parameter, then just assume that all the trailing
                        // arguments correspond.  (In other words, if the caller passed more arguments then there
                        // are parameters, we assume it was a params array.)
                        //
                        // Usually this loop will only execute once.
                        int end = param.Position + 1;
                        if (param.Position == parameters.Length - 1)
                            end = argumentExpressions.Count;

                        for (int i = param.Position; i < end; ++i)
                        {
                            CodeExpression argExpr = argumentExpressions[i];
                            RuleExpressionWalker.AnalyzeUsage(analysis, argExpr, isRead, isWrite, qualifier);
                            attributedExpressions.Add(argExpr);
                        }
                    }
                }
            }
        }
    }

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = true)]
    public sealed class RuleReadAttribute : RuleReadWriteAttribute
    {
        public RuleReadAttribute(string path, RuleAttributeTarget target)
            : base(path, target)
        {
        }

        public RuleReadAttribute(string path)
            : base(path, RuleAttributeTarget.This)
        {
        }

        internal override void Analyze(RuleAnalysis analysis, MemberInfo member, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions)
        {
            // A RuleRead attribute is only applicable if we're analyzing for reads.
            if (analysis.ForWrites)
                return;

            base.AnalyzeReadWrite(analysis, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions);
        }
    }

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = true)]
    public sealed class RuleWriteAttribute : RuleReadWriteAttribute
    {
        public RuleWriteAttribute(string path, RuleAttributeTarget target)
            : base(path, target)
        {
        }

        public RuleWriteAttribute(string path)
            : base(path, RuleAttributeTarget.This)
        {
        }

        internal override void Analyze(RuleAnalysis analysis, MemberInfo member, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions)
        {
            // A RuleWrite attribute is only applicable if we're analyzing for writes.
            if (!analysis.ForWrites)
                return;

            base.AnalyzeReadWrite(analysis, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions);
        }
    }

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = true)]
    public sealed class RuleInvokeAttribute : RuleAttribute
    {
        private string methodInvoked;

        public RuleInvokeAttribute(string methodInvoked)
        {
            this.methodInvoked = methodInvoked;
        }

        public string MethodInvoked
        {
            get { return methodInvoked; }
        }

        internal override bool Validate(RuleValidation validation, MemberInfo member, Type contextType, ParameterInfo[] parameters)
        {
            Stack<MemberInfo> methodStack = new Stack<MemberInfo>();
            methodStack.Push(member);

            bool result = ValidateInvokeAttribute(validation, member, contextType, methodStack);

            methodStack.Pop();

            return result;
        }

        private bool ValidateInvokeAttribute(RuleValidation validation, MemberInfo member, Type contextType, Stack<MemberInfo> methodStack)
        {
            string message;
            ValidationError error;

            if (string.IsNullOrEmpty(methodInvoked))
            {
                // Invoked method or property name was null or empty.
                message = string.Format(CultureInfo.CurrentCulture, Messages.AttributeMethodNotFound, member.Name, this.GetType().Name, Messages.NullValue);
                error = new ValidationError(message, ErrorNumbers.Warning_RuleAttributeNoMatch, true);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validation.AddError(error);
                return false;
            }

            bool valid = true;

            // Go through all the methods and properties on the target context,
            // looking for all the ones that match the name on the attribute.
            MemberInfo[] members = contextType.GetMember(methodInvoked, MemberTypes.Method | MemberTypes.Property, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

            if (members == null || members.Length == 0)
            {
                // Invoked method or property didn't exist.
                message = string.Format(CultureInfo.CurrentCulture, Messages.AttributeMethodNotFound, member.Name, this.GetType().Name, methodInvoked);
                error = new ValidationError(message, ErrorNumbers.Warning_RuleAttributeNoMatch, true);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validation.AddError(error);
                valid = false;
            }
            else
            {
                for (int i = 0; i < members.Length; ++i)
                {
                    MemberInfo mi = members[i];
                    if (!methodStack.Contains(mi)) // Prevent recursion
                    {
                        methodStack.Push(mi);

                        object[] attrs = mi.GetCustomAttributes(typeof(RuleAttribute), true);
                        if (attrs != null && attrs.Length != 0)
                        {
                            foreach (RuleAttribute invokedRuleAttr in attrs)
                            {
                                if (invokedRuleAttr is RuleReadWriteAttribute readWriteAttr)
                                {
                                    // This read/write attribute may not specify a target of "Parameter", since
                                    // we can't map from the invoker's parameters to the invokee's parameters.
                                    if (readWriteAttr.Target == RuleAttributeTarget.Parameter)
                                    {
                                        message = string.Format(CultureInfo.CurrentCulture, Messages.InvokeAttrRefersToParameterAttribute, mi.Name);
                                        error = new ValidationError(message, ErrorNumbers.Error_InvokeAttrRefersToParameterAttribute, true);
                                        error.UserData[RuleUserDataKeys.ErrorObject] = this;
                                        validation.AddError(error);
                                        valid = false;
                                    }
                                    else
                                    {
                                        // Validate the read/write attribute normally.
                                        readWriteAttr.Validate(validation, mi, contextType, null);
                                    }
                                }
                                else
                                {
                                    RuleInvokeAttribute invokeAttr = (RuleInvokeAttribute)invokedRuleAttr;
                                    invokeAttr.ValidateInvokeAttribute(validation, mi, contextType, methodStack);
                                }
                            }
                        }

                        methodStack.Pop();
                    }
                }
            }

            return valid;
        }

        internal override void Analyze(RuleAnalysis analysis, MemberInfo member, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions)
        {
            Stack<MemberInfo> methodStack = new Stack<MemberInfo>();
            methodStack.Push(member);

            AnalyzeInvokeAttribute(analysis, member.DeclaringType, methodStack, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions);

            methodStack.Pop();
        }

        private void AnalyzeInvokeAttribute(RuleAnalysis analysis, Type contextType, Stack<MemberInfo> methodStack, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions)
        {
            // Go through all the methods and properties on the target context,
            // looking for all the ones that match the name on the attribute.
            MemberInfo[] members = contextType.GetMember(methodInvoked, MemberTypes.Method | MemberTypes.Property, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

            for (int m = 0; m < members.Length; ++m)
            {
                MemberInfo mi = members[m];
                if (!methodStack.Contains(mi)) // Prevent recursion
                {
                    methodStack.Push(mi);

                    object[] attrs = mi.GetCustomAttributes(typeof(RuleAttribute), true);
                    if (attrs != null && attrs.Length != 0)
                    {
                        RuleAttribute[] ruleAttrs = (RuleAttribute[])attrs;
                        for (int i = 0; i < ruleAttrs.Length; ++i)
                        {
                            RuleAttribute ruleAttr = ruleAttrs[i];

                            if (ruleAttr is RuleReadWriteAttribute readWriteAttr)
                            {
                                // Just analyze the read/write attribute normally.
                                readWriteAttr.Analyze(analysis, mi, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions);
                            }
                            else
                            {
                                RuleInvokeAttribute invokeAttr = (RuleInvokeAttribute)ruleAttr;
                                invokeAttr.AnalyzeInvokeAttribute(analysis, contextType, methodStack, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions);
                            }
                        }
                    }

                    methodStack.Pop();
                }
            }
        }
    }
}


text:
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\nauth.proto\x12\x06\x61uthpb\"5\n\x04User\x12\x0c\n\x04name\x18\x01 \x01(\x0c\x12\x10\n\x08password\x18\x02 \x01(\x0c\x12\r\n\x05roles\x18\x03 \x03(\t\"\x83\x01\n\nPermission\x12)\n\x08permType\x18\x01 \x01(\x0e\x32\x17.authpb.Permission.Type\x12\x0b\n\x03key\x18\x02 \x01(\x0c\x12\x11\n\trange_end\x18\x03 \x01(\x0c\"*\n\x04Type\x12\x08\n\x04READ\x10\x00\x12\t\n\x05WRITE\x10\x01\x12\r\n\tREADWRITE\x10\x02\"?\n\x04Role\x12\x0c\n\x04name\x18\x01 \x01(\x0c\x12)\n\rkeyPermission\x18\x02 \x03(\x0b\x32\x12.authpb.PermissionB\x15\n\x11io.etcd.jetcd.apiP\x01\x62\x06proto3')

_USER = DESCRIPTOR.message_types_by_name['User']
_PERMISSION = DESCRIPTOR.message_types_by_name['Permission']
_ROLE = DESCRIPTOR.message_types_by_name['Role']
_PERMISSION_TYPE = _PERMISSION.enum_types_by_name['Type']
User = _reflection.GeneratedProtocolMessageType('User', (_message.Message,), {
  'DESCRIPTOR' : _USER,
  '__module__' : 'auth_pb2'
  # @@protoc_insertion_point(class_scope:authpb.User)
  })
_sym_db.RegisterMessage(User)

Permission = _reflection.GeneratedProtocolMessageType('Permission', (_message.Message,), {
  'DESCRIPTOR' : _PERMISSION,
  '__module__' : 'auth_pb2'
  # @@protoc_insertion_point(class_scope:authpb.Permission)
  })
_sym_db.RegisterMessage(Permission)

Role = _reflection.GeneratedProtocolMessageType('Role', (_message.Message,), {
  'DESCRIPTOR' : _ROLE,
  '__module__' : 'auth_pb2'
  # @@protoc_insertion_point(class_scope:authpb.Role)
  })
_sym_db.RegisterMessage(Role)

if _descriptor._USE_C_DESCRIPTORS == False:

  DESCRIPTOR._options = None
  DESCRIPTOR._serialized_options = b'\n\021io.etcd.jetcd.apiP\001'
  _USER._serialized_start=22
  _USER._serialized_end=75
  _PERMISSION._serialized_start=78
  _PERMISSION._serialized_end=209
  _PERMISSION_TYPE._serialized_start=167
  _PERMISSION_TYPE._serialized_end=209
  _ROLE._serialized_start=211
  _ROLE._serialized_end=274
# @@protoc_insertion_point(module_scope)


text:
require 'spec_helper'

module EWayClient
  RSpec.describe SendTransactionRequest, type: %i[virtus] do

    it "inherits from BaseRequest" do
      expect(described_class < BaseRequest).to be true
    end

    describe "attributes" do
      subject { described_class }
      it { is_expected.to have_attribute(:agent_code, String) }
      it { is_expected.to have_attribute(:username, String) }
      it { is_expected.to have_attribute(:password, String) }
      it { is_expected.to have_attribute(:transaction_id, String) }
      it { is_expected.to have_attribute(:transaction_date, Time) }
      it { is_expected.to have_attribute(:degit_code, String) }
      it { is_expected.to have_attribute(:transaction_amount, Integer) }
      it { is_expected.to have_attribute(:sett_amount, Integer) }
      it { is_expected.to have_attribute(:transaction_currency, String) }
      it { is_expected.to have_attribute(:sett_currency, String) }
      it { is_expected.to have_attribute(:sett_conversion_rate, Float) }
      it { is_expected.to have_attribute(:paymentmode, String) }
      it { is_expected.to have_attribute(:sender_name, String) }
      it { is_expected.to have_attribute(:sender_address, String) }
      it { is_expected.to have_attribute(:sender_district, String) }
      it { is_expected.to have_attribute(:sender_city, String) }
      it { is_expected.to have_attribute(:sender_country, String) }
      it { is_expected.to have_attribute(:sender_question, String) }
      it { is_expected.to have_attribute(:sender_answer, String) }
      it { is_expected.to have_attribute(:receiver_name, String) }
      it { is_expected.to have_attribute(:receiver_address, String) }
      it { is_expected.to have_attribute(:receiver_wards, String) }
      it { is_expected.to have_attribute(:receiver_district, String) }
      it { is_expected.to have_attribute(:receiver_city, String) }
      it { is_expected.to have_attribute(:receiver_phone, String) }
      it { is_expected.to have_attribute(:hours_receive, String) }
      it { is_expected.to have_attribute(:bank_id, String) }
      it { is_expected.to have_attribute(:bank_account_number, String) }
      it { is_expected.to have_attribute(:transaction_message, String) }
      it { is_expected.to have_attribute(:transaction_key, String) }
      it { is_expected.to have_attribute(:bankbranch_name, String) }
      it { is_expected.to have_attribute(:bankbranch_address, String) }
      it { is_expected.to have_attribute(:secret, String) }
    end

    describe "#transaction_key" do
      let(:expected_hash) do
        Digest::MD5.hexdigest([50_000, "FT", "99999"].join)
      end
      let(:request) do
        described_class.new(
          transaction_amount: 50_000,
          paymentmode: "FT",
          secret: "99999",
        )
      end

      it "is the md5 hash of the transaction amount, paymentmode, and secret" do
        expect(request.transaction_key).to eq expected_hash
      end
    end

    describe "#transaction_date" do
      let(:request) { described_class.new(transaction_date: transaction_date) }
      subject { request.transaction_date }
      before do
        Timecop.freeze
      end

      context "no date is set" do
        let(:transaction_date) { nil }
        it { is_expected.to be_nil }
      end

      context "date is set" do
        let(:transaction_date) { Time.now }
        let(:expected_time) do
          Time.now.in_time_zone("Bangkok").strftime("%m/%d/%Y %H:%M:%S")
        end
        it { is_expected.to eq expected_time }
      end
    end

  end
end


text:
FROM php:apache

RUN a2enmod rewrite

RUN apt-get update \
&& apt-get install curl php5-cli git -y \
&& curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

RUN rm -rf /var/lib/apt/lists/*

RUN mkdir -p /var/lib/http-echo/data && chmod -R 777 /var/lib/http-echo

VOLUME /var/lib/http-echo/data/

COPY ./ /var/www/html/

RUN composer update


text:
REPO_SCRIPTS_PATH=$(dirname $(readlink -f $0))
AVAILABLE_REPOSITORY_NAMES="alpine apache oracle jenkins pypi"

usage() {

    echo -e "usage: update.sh <action> | <repo-name>\n"
    echo "Available actions:"
    echo " - usage"
    echo " - all"
    echo
    echo "Available repository names:"
    echo " - alpine"
    echo " - apache"
    echo " - sonatype"
    echo " - oracle"
    echo " - jenkins"
    echo " - pypi"
    echo
}

precheck() {

    ACTION=${1:-}
    REPOS_PATH=${2:-}

    if [ -z "${ACTION}" ] || [ "${ACTION}" = "usage" ]
    then
        usage; exit 0
    elif [ "${ACTION}" = "all" ]
    then
        all; exit 0
    elif [[ ! ${AVAILABLE_REPOSITORY_NAMES} =~ (^|[[:space:]])"${ACTION}"($|[[:space:]]) ]]
    then
        echo "[ERROR] Unknown repository name or action: ${ACTION}"
        exit 1
    fi

    if [ -z ${REPOS_PATH} ] && [ ! -d ${REPOS_PATH} ]
    then
        echo "[ERROR] Repository path is not specified or does not exist"
        exit 1
    fi

    for repo in ${AVAILABLE_REPOSITORY_NAMES}
    do
        if [ ! -d ${REPOS_PATH%%/}/${repo} ]
        then
            echo "[WARNING] The repository path does not exist," ${REPOS_PATH%%/}/${repo}
            mkdir -p ${REPOS_PATH%%/}/${repo}
            echo "[INFO] The repository path was created," ${REPOS_PATH%%/}/${repo}
        fi
    done
}

alpine() {

    precheck alpine $@
    echo "[INFO] Update Alpine repository"
	ALPINE_REPO_PATH=${REPOS_PATH} ${REPO_SCRIPTS_PATH%%/}/alpine/update.sh all
}

apache() {

    precheck apache $@
    echo "[INFO] Update Apache repository"
	APACHE_REPO_PATH=${REPOS_PATH} ${REPO_SCRIPTS_PATH%%/}/apache/update.sh
}

jenkins() {

    precheck jenkins $@
    echo "[INFO] Update Jenkins repository"
    JENKINS_REPO_PATH=${REPOS_PATH%%/}/jenkins/ \
        ${REPO_SCRIPTS_PATH%%/}/jenkins/update.sh jenkins_by_list ${REPO_SCRIPTS_PATH%%/}/etc/jenkins.versions
    echo "[INFO] Update Jenkins plugins"
    JENKINS_REPO_PATH=${REPOS_PATH%%/}/jenkins/ \
        ${REPO_SCRIPTS_PATH%%/}/jenkins/update.sh plugins_by_list ${REPO_SCRIPTS_PATH%%/}/etc/jenkins.plugins

}

sonatype() {

    precheck oracle $@
    echo "[INFO] Update Sonatype repository"
    SONATYPE_REPO_PATH=${REPOS_PATH%%/}/sonatype/ ${REPO_SCRIPTS_PATH%%/}/sonatype/update.sh
}

oracle() {

    precheck oracle $@
    echo "[INFO] Update Oracle Java repository"
    ORACLE_REPO_PATH=${REPOS_PATH%%/}/oracle/ \
        ${REPO_SCRIPTS_PATH%%/}/oracle/update.sh all
}

pypi() {

    precheck pypi $@
    echo "[INFO] Update Python packages repository"
    ${REPO_SCRIPTS_PATH%%/}/pypi/update.sh \
        ${REPO_SCRIPTS_PATH%%/}/pypi/pypi-mirror.py \
        ${REPO_SCRIPTS_PATH%%/}/etc/pypi-packages.json \
        ${REPOS_PATH%%/}/pypi/
}

all() {

    precheck all $@
    alpine $@
    apache $@
    jenkins $@
    oracle $@
    pypi $@
}

$@


text:
class ActiveForm < ActiveRecord::Base
  def self.columns()
    @columns ||= []
  end

  def self.column(name, sql_type = nil, default = nil, null = true)
    columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
  end
end