text:
package pattern

import (
	"bytes"
	"regexp"
	"strconv"
	"strings"
	"time"
)

func GlobToRegexString(glob string) string {
	var buffer bytes.Buffer
	r := strings.NewReader(glob)

	escape := false
	for {
		r, _, err := r.ReadRune()
		if err != nil {
			break
		}

		if escape {
			buffer.WriteRune(r)
			escape = false
			continue
		}

		if r == '\\' {
			buffer.WriteRune(r)
			escape = true
			continue
		}

		if r == '*' {
			buffer.WriteString(".*")
			continue
		}

		if r == '.' {
			buffer.WriteString("\\.")
			continue
		}

		buffer.WriteRune(r)
	}

	return buffer.String()
}

func StrToAge(t string, reference time.Time) (time.Time, error) {
	modifyPattern, err := regexp.Compile("^([+-]?[0-9]+)[\\s]*([a-zA-Z]+)$")
	if err != nil {
		return reference, err
	}

	if modifyPattern.MatchString(t) {
		submatches := modifyPattern.FindStringSubmatch(t)
		modifier, err := strconv.Atoi(submatches[1])
		if err != nil {
			return reference, err
		}

		// age must be negated
		modifier *= -1

		unit := strings.ToLower(submatches[2])

		if strings.HasPrefix(unit, "d") {
			return reference.AddDate(0, 0, modifier), nil
		}
		if strings.HasPrefix(unit, "w") {
			return reference.AddDate(0, 0, modifier*7), nil
		}
		if strings.HasPrefix(unit, "mon") {
			return reference.AddDate(0, modifier, 0), nil
		}
		if strings.HasPrefix(unit, "y") {
			return reference.AddDate(modifier, 0, 0), nil
		}

		if strings.HasPrefix(unit, "ns") {
			unit = "ns"
		} else if strings.HasPrefix(unit, "us") || strings.HasPrefix(unit, "µs") {
			unit = "us"
		} else if strings.HasPrefix(unit, "ms") {
			unit = "ms"
		} else if strings.HasPrefix(unit, "s") {
			unit = "s"
		} else if strings.HasPrefix(unit, "m") {
			unit = "m"
		} else if strings.HasPrefix(unit, "h") {
			unit = "h"
		}

		d, err := time.ParseDuration(strconv.Itoa(modifier) + unit)
		if err != nil {
			return reference, err
		}

		return reference.Add(d), nil
	}

	fixedPattern, err := regexp.Compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
	if fixedPattern.MatchString(t) {
		layout := "2006-01-02"
		return time.Parse(layout, t)
	}

	layout := "2006-01-02T15:04:05.000Z"
	return time.Parse(layout, t)
}

func StrToSize(sizeString string) (int64, error) {

	lower := strings.ToLower(sizeString)

	factor := int64(1)
	if strings.HasSuffix(lower, "k") {
		factor = 1024
		lower = strings.TrimSuffix(lower, "k")
	} else if strings.HasSuffix(lower, "m") {
		factor = 1024 * 1024
		lower = strings.TrimSuffix(lower, "m")
	} else if strings.HasSuffix(lower, "g") {
		factor = 1024 * 1024 * 1024
		lower = strings.TrimSuffix(lower, "g")
	} else if strings.HasSuffix(lower, "t") {
		factor = 1024 * 1024 * 1024 * 1024
		lower = strings.TrimSuffix(lower, "t")
	}

	ret, err := strconv.Atoi(lower)

	return int64(ret) * factor, err
}

func BuildMatchList(sourcePattern *regexp.Regexp, subject string) []string {
	list := make([]string, 0)
	sourcePattern.ReplaceAllStringFunc(subject, func(m string) string {
		parts := sourcePattern.FindStringSubmatch(m)
		i := 1
		for range parts[1:] {
			list = append(list, parts[i])
			i++

		}
		return m
	})
	return list
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;

namespace Bit.BlazorUI;

public partial class BitRadioButtonGroup
{
    private bool isComponentRendered;
    private bool isRequired;
    private BitRadioButtonOption? SelectedOption;
    private List<BitRadioButtonOption> AllOptions = new();

    /// <summary>
    /// Default value for RadioButtonGroup.
    /// </summary>
    [Parameter] public string? DefaultValue { get; set; }

    /// <summary>
    /// If true, an option must be selected in the RadioButtonGroup.
    /// </summary>
    [Parameter]
    public bool IsRequired
    {
        get => isRequired;
        set
        {
            isRequired = value;
            ClassBuilder.Reset();
        }
    }

    /// <summary>
    /// Descriptive label for the RadioButtonGroup.
    /// </summary>
    [Parameter] public string? Label { get; set; }

    /// <summary>
    /// ID of an element to use as the aria label for this RadioButtonGroup.
    /// </summary>
    [Parameter] public string AriaLabelledBy { get; set; } = string.Empty;

    /// <summary>
    /// Used to customize the label for the RadioButtonGroup.
    /// </summary>
    [Parameter] public RenderFragment? LabelFragment { get; set; }

    /// <summary>
    /// Name of RadioButtonGroup, this name is used to group each RadioButtonGroup into the same logical RadioButtonGroup
    /// </summary>
    [Parameter] public string Name { get; set; } = Guid.NewGuid().ToString();

    /// <summary>
    /// The content of RadioButtonGroup, common values are RadioButtonGroup component
    /// </summary>
    [Parameter] public RenderFragment? ChildContent { get; set; }

    /// <summary>
    /// Callback that is called when the value parameter is changed
    /// </summary>
    [Parameter] public EventCallback<string> OnValueChange { get; set; }

    public string LabelId { get; set; } = string.Empty;

    protected override string RootElementClass => "bit-rbg";

    protected override void RegisterComponentClasses()
    {
        ClassBuilder.Register(() => IsEnabled && IsRequired
                                   ? $"{RootElementClass}-required-{VisualClassRegistrar()}" : string.Empty);

        ClassBuilder.Register(() => ValueInvalid is true
                                   ? $"{RootElementClass}-invalid-{VisualClassRegistrar()}" : string.Empty);
    }

    protected override async Task OnInitializedAsync()
    {
        CurrentValue ??= DefaultValue;
        LabelId = $"RadioButtonGroupLabel{UniqueId}";
        OnValueChanging += HandleOnValueChanging;
        OnCurrentValueChanged += HandleOnCurrentValueChanged;

        await base.OnInitializedAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            isComponentRendered = true;
            if (AllOptions.Any(option => option.Value == Value) is false)
            {
                ResetValue();
                if (ValueHasBeenSet && ValueChanged.HasDelegate)
                {
                    await ValueChanged.InvokeAsync(Value);
                }
            }
        }

        await base.OnAfterRenderAsync(firstRender);
    }

    internal async Task SelectOption(BitRadioButtonOption option)
    {
        if (ValueHasBeenSet && ValueChanged.HasDelegate is false) return;

        SelectedOption?.SetState(false);
        option.SetState(true);

        SelectedOption = option;
        CurrentValue = option.Value;

        await OnValueChange.InvokeAsync(CurrentValue);
    }

    internal void RegisterOption(BitRadioButtonOption option)
    {
        if (option.Value.HasNoValue())
        {
            option.Value = AllOptions.Count.ToString(CultureInfo.InvariantCulture);
        }

        if (CurrentValue == option.Value)
        {
            option.SetState(true);
            SelectedOption = option;
        }

        AllOptions.Add(option);
    }

    internal void UnregisterOption(BitRadioButtonOption option)
    {
        AllOptions.Remove(option);
    }

    private void SelectOptionByKey(string? value)
    {
        var newOption = AllOptions.FirstOrDefault(i => i.Value == value);

        if (newOption is null || newOption == SelectedOption || newOption.IsEnabled is false)
        {
            _ = ValueChanged.InvokeAsync(Value);
            return;
        }

        _ = SelectOption(newOption);
    }

    private string GetAriaLabelledBy() => Label.HasValue() || LabelFragment is not null ? LabelId : AriaLabelledBy;

    private void HandleOnValueChanging(object? sender, ValueChangingEventArgs<string?> args)
    {
        if (isComponentRendered is false) return;

        var option = AllOptions.FirstOrDefault(i => i.Value == args.Value);
        if (option is not null)
        {
            SelectedOption?.SetState(false);
            option.SetState(true);
            SelectedOption = option;

            if (ValueHasBeenSet && ValueChanged.HasDelegate is false) return;

            _ = OnValueChange.InvokeAsync(args.Value);
        }
        else
        {
            args.ShouldChange = false;

            if (Value.HasNoValue())
            {
                SelectedOption?.SetState(false);
                SelectedOption = null;
            }

            if (ValueHasBeenSet && ValueChanged.HasDelegate is false) return;
            if (Value == args.Value) return;

            _ = ValueChanged.InvokeAsync(Value);
        }
    }

    private void HandleOnCurrentValueChanged(object? sender, EventArgs args)
    {
        SelectOptionByKey(CurrentValue);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            OnValueChanging -= HandleOnValueChanging;
            OnCurrentValueChanged -= HandleOnCurrentValueChanged;
        }

        base.Dispose(disposing);
    }

    /// <inheritdoc />
    protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out string result, [NotNullWhen(false)] out string? validationErrorMessage)
        => throw new NotSupportedException($"This component does not parse string inputs. Bind to the '{nameof(CurrentValue)}' property, not '{nameof(CurrentValueAsString)}'.");
}

redpajama_set_name: RedPajamaGithub


text:
#include "stdafx.h"
#include "r_dataset.h"
#include "tools.h"
#include "misc.h"
#include <Rdefines.h>

const char* dataset::class_name = "++dataset++";

SEXP dataset::open(SEXP rPath)
{
  std::wstring path;
  if (!tools::copy_to(rPath, path))
    return error_Ret("wrong path");

  //m_ipDataset.Attach(arcobject::open_dataset(path));
  m_dataset.reset(arcobject::open_dataset(path));
  if (m_dataset.get() == nullptr)
    return showError<true>("cannot open dataset");

  return tools::newVal(true);
}

SEXP dataset::get_type()
{
  const char* type_name = m_dataset->get_type();
  if (type_name == nullptr)
    return error_Ret("not a dataset");
  return tools::newVal(type_name);
}

const char* table::class_name = "++table++";

SEXP table::create_from(SEXP rHost, SEXP from)
{
  dataset* ds = rtl::getCObject<dataset>(from);
  if (ds)
  {
    if (rtl::createT<table>(rHost))
    {
      table* ts = rtl::getCObject<table>(rHost);
      //ts->m_ipDataset = ds->m_ipDataset;
      ts->m_dataset = ds->m_dataset;
    }
  }
  return rHost;
}

SEXP table::get_fields()
{
  //if (fix_table() == NULL)
  if (!m_dataset->is_table())
    return error_Ret("arc.table");
  auto ret =  arcobject::dataset_handle::get_fields(m_dataset.get());

  tools::protect pt;
  SEXP vect_type = pt.add(tools::newVal(ret.second));
  return tools::nameIt(vect_type, ret.first);
}

//SEXP table::select2(SEXP args)
SEXP table::select(SEXP fields, SEXP args)
{
  using namespace arcobject;
  //if (fix_table() == NULL)
  if (!m_dataset->is_table())
    return error_Ret("arc.table");

  SEXP selected = CAR(args);args = CDR(args);
  SEXP where_str = CAR(args);args = CDR(args);
  SEXP sr = CAR(args);args = CDR(args);

  std::vector<std::wstring> fld;
  if (!tools::copy_to(fields, fld))
    return error_Ret("'fields' should be string(s)");
  bool use_selection = true;
  tools::copy_to(selected, use_selection);

  if (fld.empty())
    return error_Ret("nothing to select");

  std::wstring where_clause;
  tools::copy_to(where_str, where_clause);

  std::pair<std::wstring, int> sp_ref;
  sp_ref.second = 0;
  if (!tools::copy_to(sr, sp_ref.second))
  {
    std::wstring wkt;
    if (tools::copy_to(sr, wkt))
    {
      struct eq
      {
        static bool op(const wchar_t &c) { return c == L'\''; }
      };
      std::replace_if(wkt.begin(), wkt.end(), eq::op, L'\"');
      sp_ref.first = wkt;
    }
  }

  std::vector<std::wstring> unique;
  for (const auto& it : fld)
    unique.push_back(tools::tolower(it));

  auto end = std::unique(unique.begin(), unique.end());
  auto new_size = std::distance(unique.begin(), end);
  unique.resize(new_size);

  auto cols = arcobject::dataset_handle::select(m_dataset.get(), unique, where_clause, use_selection, sp_ref);
  if (cols.empty())
    return showError<true>("COM error");

  tools::protect pt;
  std::vector<std::pair<SEXP, std::wstring>> unique_cols;
  for (dataset_handle::column_t* it : cols)
  {
    switch (it->t)
    {
      case dataset_handle::column_t::eInt:
        unique_cols.emplace_back(pt.add(tools::newVal(dataset_handle::column_t::get_ints(*it))), it->name);
      break;
      case dataset_handle::column_t::eDouble:
        unique_cols.emplace_back(pt.add(tools::newVal(dataset_handle::column_t::get_doubles(*it))), it->name);
      break;
      case dataset_handle::column_t::eString:
        unique_cols.emplace_back(pt.add(tools::newVal(dataset_handle::column_t::get_strings(*it))), it->name);
      break;
      case dataset_handle::column_t::eGeometry_point:
      {
        bool add_wkt = (!it->sr.first.empty() || it->sr.second != 0);
        auto& pts = dataset_handle::column_t::get_points(*it);
        tools::listGeneric xyzm((add_wkt ? 2 : 0) + 2 + (pts[2].empty() ? 0 : 1) + (pts[3].empty() ? 0 : 1));
        xyzm.push_back(pts[0], L"x"); pts[0].clear();
        xyzm.push_back(pts[1], L"y"); pts[1].clear();
        if (!pts[2].empty())
        {
          xyzm.push_back(pts[2], L"z");
          pts[2].clear();
        }
        if (!pts[3].empty())
        {
          xyzm.push_back(pts[3], L"m");
          pts[3].clear();
        }
        if (add_wkt)
        {
          xyzm.push_back(it->sr.first, L"WKT");
          xyzm.push_back(it->sr.second, L"WKID");
        }
        unique_cols.emplace_back(pt.add(xyzm.get()), it->name);
      } break;
      case dataset_handle::column_t::eGeometry_polyline:
      case dataset_handle::column_t::eGeometry_polygon:
      case dataset_handle::column_t::eGeometry_multipoint:
      {
        auto& geoms = dataset_handle::column_t::get_shapes(*it);
        bool add_wkt = (!it->sr.first.empty() || it->sr.second != 0);
        tools::listGeneric shapes(geoms.size() + add_wkt ? 2 : 0);
        std::wstring name;
        if (it->t == dataset_handle::column_t::eGeometry_polyline)
          name = L"Polyline";
        else if (it->t == dataset_handle::column_t::eGeometry_polygon)
          name = L"Polygon";
        else if (it->t == dataset_handle::column_t::eGeometry_multipoint)
          name = L"Multipoint";

        for (auto &g : geoms)
        {
          if (g.empty())
            shapes.push_back(R_NilValue, name);
          else
            shapes.push_back(g, name);
          g.clear();
        }
        if (add_wkt)
        {
          shapes.push_back(it->sr.first, L"WKT");
          shapes.push_back(it->sr.second, L"WKID");
        }
        unique_cols.emplace_back(pt.add(shapes.get()), it->name);
      }break;
      default:
        ATLASSERT(0);
        break;
    }
    delete it;
  }
  //use same reference for duplicated columns
  tools::listGeneric column_list(fld.size());
  ATLASSERT(unique_cols.size() == unique.size());
  if (unique_cols.size() == unique.size())
  {
    for(auto it = fld.begin(), end = fld.end(); it != end; ++it)
    {
      auto idx = std::distance(unique.begin(), std::find(unique.begin(), unique.end(), tools::tolower(*it)));
      column_list.push_back(unique_cols[idx].first, it->c_str());
    }
  }
  else
  {
    for(const auto &it : unique_cols)
      column_list.push_back(it.first, it.second.c_str());
  }
  return column_list.get();
}

/*SEXP table::select3(SEXP args)
{
  for(;args != R_NilValue; args = CDR(args))
  {
    const char *name = Rf_isNull(TAG(args)) ? "" : CHAR(PRINTNAME(TAG(args)));
    SEXP el = CAR(args);
    ATLTRACE("SEXP type:%s", Rf_type2char(TYPEOF(el)));
  }
  return R_NilValue;
}*/

const char* feature_class::class_name = "++feature_class++";
SEXP feature_class::create_from(SEXP rHost, SEXP from)
{
  dataset* ds = rtl::getCObject<dataset>(from);
  if (ds)
  {
    if (rtl::createT<feature_class>(rHost))
    {
      feature_class* pThis = rtl::getCObject<feature_class>(rHost);
      //pThis->m_ipDataset = ds->m_ipDataset;
      pThis->m_dataset = ds->m_dataset;
    }
  }
  return rHost;
}

SEXP feature_class::get_shape_info()
{
  //if (!fix_fc())
  if (!m_dataset->is_fc())
    return error_Ret("arc.feature");

  auto ret = arcobject::dataset_handle::get_shape_info(m_dataset.get());
  tools::listGeneric shape_attr(ret.size());
  for(auto &it : ret)
  {
    shape_attr.push_back(it.second, it.first);
    ::VariantClear(&it.second);
  }
  return shape_attr.get();
}

SEXP feature_class::get_extent()
{
  if (!m_dataset->is_fc())
    return error_Ret("arc.feature");
  return extent2r(arcobject::dataset_handle::get_extent(m_dataset.get()));
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding model 'EventDetails'
        db.create_table('zorna_eventdetails', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
            ('object_id', self.gf('django.db.models.fields.IntegerField')()),
            ('location', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
            ('free_busy', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('privacy', self.gf('django.db.models.fields.IntegerField')(default=0, max_length=1)),
        ))
        db.send_create_signal('calendars', ['EventDetails'])

        # Adding model 'ZornaCalendar'
        db.create_table('zorna_calendars', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(related_name='entity_content_type_calendars_zornacalendar_related', null=True, to=orm['contenttypes.ContentType'])),
            ('site', self.gf('django.db.models.fields.related.ForeignKey')(related_name='site_owner_calendars_zornacalendar_related', null=True, to=orm['sites.Site'])),
            ('owner', self.gf('django.db.models.fields.related.ForeignKey')(related_name='user_owner_calendars_zornacalendar_related', null=True, to=orm['auth.User'])),
            ('modifier', self.gf('django.db.models.fields.related.ForeignKey')(related_name='user_modifier_calendars_zornacalendar_related', null=True, to=orm['auth.User'])),
            ('time_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('time_updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, auto_now_add=True, blank=True)),
            ('enabled', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('calendar', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['schedule.Calendar'])),
            ('ct_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
            ('object_id', self.gf('django.db.models.fields.IntegerField')()),
        ))
        db.send_create_signal('calendars', ['ZornaCalendar'])

    def backwards(self, orm):

        # Deleting model 'EventDetails'
        db.delete_table('zorna_eventdetails')

        # Deleting model 'ZornaCalendar'
        db.delete_table('zorna_calendars')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'calendars.eventdetails': {
            'Meta': {'object_name': 'EventDetails', 'db_table': "'zorna_eventdetails'"},
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'free_busy': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'object_id': ('django.db.models.fields.IntegerField', [], {}),
            'privacy': ('django.db.models.fields.IntegerField', [], {'default': '0', 'max_length': '1'})
        },
        'calendars.zornacalendar': {
            'Meta': {'object_name': 'ZornaCalendar', 'db_table': "'zorna_calendars'"},
            'calendar': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['schedule.Calendar']"}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'entity_content_type_calendars_zornacalendar_related'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
            'ct_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modifier': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_modifier_calendars_zornacalendar_related'", 'null': 'True', 'to': "orm['auth.User']"}),
            'object_id': ('django.db.models.fields.IntegerField', [], {}),
            'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_owner_calendars_zornacalendar_related'", 'null': 'True', 'to': "orm['auth.User']"}),
            'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'site_owner_calendars_zornacalendar_related'", 'null': 'True', 'to': "orm['sites.Site']"}),
            'time_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'time_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'schedule.calendar': {
            'Meta': {'object_name': 'Calendar'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '200', 'db_index': 'True'})
        },
        'sites.site': {
            'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
            'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        }
    }

    complete_apps = ['calendars']


text:
package ca.uhn.fhir.rest.client;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.model.dstu2.resource.Conformance;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory;
import ca.uhn.fhir.rest.client.api.IHttpClient;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.rest.client.api.IRestfulClientFactory;
import ca.uhn.fhir.rest.client.impl.BaseClient;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
import ca.uhn.fhir.util.TestUtil;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;

public class RestfulClientFactoryDstu2Test {

	private static FhirContext ourCtx = FhirContext.forDstu2();

	/**
	 * See #518
	 */
	@SuppressWarnings({ "unchecked", "cast" })
	@Test
	public void testMissingCapabilityStatementDstu2() throws Exception {
		FhirContext ctx = mock(FhirContext.class);
		IRestfulClientFactory restfulClientFactory = mock(IRestfulClientFactory.class);
		IHttpClient httpClient = mock(IHttpClient.class);

		when(ctx.getResourceDefinition(Mockito.eq("CapabilityStatement"))).thenThrow(new DataFormatException());
		when(ctx.getResourceDefinition(Mockito.eq("Conformance"))).thenReturn(ourCtx.getResourceDefinition("Conformance"));
		when(ctx.getResourceDefinition(Conformance.class)).thenReturn(ourCtx.getResourceDefinition("Conformance"));
		when(ctx.getVersion()).thenReturn(FhirVersionEnum.DSTU2.getVersionImplementation());
		when(ctx.getRestfulClientFactory()).thenReturn(restfulClientFactory);

		when(restfulClientFactory.getHttpClient(nullable(StringBuilder.class), (Map<String, List<String>>)nullable(Map.class), nullable(String.class), nullable(RequestTypeEnum.class), nullable(List.class))).thenReturn(httpClient);

		IHttpRequest httpRequest = mock(IHttpRequest.class);
		when(httpClient.createGetRequest(any(FhirContext.class), nullable(EncodingEnum.class))).thenReturn(httpRequest);

		IHttpResponse httpResponse = mock(IHttpResponse.class);
		when(httpRequest.execute()).thenReturn(httpResponse);

		when(httpResponse.getStatus()).thenReturn(404);

		ApacheRestfulClientFactory cf = new ApacheRestfulClientFactory(ctx);
		IHttpClient client = mock(IHttpClient.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS));
		BaseClient baseClient = mock(BaseClient.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS));

		try {
			cf.validateServerBase("http://localhost:9999", client, baseClient);
			fail();
		} catch (ResourceNotFoundException e) {
			// ok
		}

	}

	@AfterAll
	public static void afterClassClearContext() {
		TestUtil.randomizeLocaleAndTimezone();
	}
}


text:
'use strict';
const path = require('path');
const fs = require('fs');
const _ = require('underscore.string');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const $$ = require('../utils/helpers');
const data = require('./strings');
const namingConvenions = require('../utils/namingConventions');
const conventions = Object.keys(namingConvenions);

const table = {
    title: 'utils/config/prompting.js :: filters and validation',
    intro: 'Whitespaces in inputs and filtered strings replaced with ■',
    head: {
        io: 'Input | Output\n----- | ------\n',
        fv: 'Input | Filtered | Valid\n----- | -------- | -----\n',
    }
};

function showWhitespaces (input) {
    let result;

    if (input === '') {
        result = '_blank_';
    } else {
        result = input.replace(/ /g, '■');
    }

    return result;
}

function putResult(result) {
    let str = '';
    result.forEach((item, index, arr) => {
        let ending = index === arr.length - 1 ? '\n' : ' | ';
        str += item + ending;
    });

    return str;
}

fs.writeFileSync('test/results/config-prompting.md', '', 'utf8');
fs.appendFileSync('test/results/config-prompting.md', '###' + table.title + '\n\n_' + table.intro + '_\n\n', 'utf8');

describe(table.title, () => {

    it('Filter and validate collection suffix', () => {

        let result = '#####Filter and validate collection suffix\n\n';
        result += table.head.fv;

        data.suffixes.forEach((suffix) => {
            let filtered = $$.filterName(null, suffix, 'collection-suffix');
            let validated = $$.validateName(null, filtered, 'collection-suffix');

            result += putResult([showWhitespaces(suffix), showWhitespaces(filtered), validated]);
        });

        fs.appendFileSync('test/results/config-prompting.md', result, 'utf8');
    });

    it('Filter and validate bem directory path', () => {
        let result = '#####Filter and validate bem directory path\n\n';
        result += table.head.fv;

        data.paths.forEach((p) => {
            let filtered = $$.filterName(null, p, 'path');
            let validated = $$.validatePath(filtered);

            result += putResult([showWhitespaces(p), showWhitespaces(filtered), validated]);
        });

        fs.appendFileSync('test/results/config-prompting.md', result, 'utf8');
    });

    it('Filter and validate custom extension input', () => {
        let result = '#####Filter and validate custom extension input\n\n';
        result += table.head.fv;

        data.extensions.forEach((ext) => {
            let filtered = $$.trim(ext, ' .');
            let validated = $$.isAlphanumeric(filtered);

            result += putResult([showWhitespaces(ext), showWhitespaces(filtered), validated]);
        });

        fs.appendFileSync('test/results/config-prompting.md', result, 'utf8');
    });

    it('Test dot() function', () => {
        let result = '#####Test dot() function\n\n';
        result += table.head.io;

        data.dot.forEach(input => {
            let output = $$.dot(input, 'ext');

            result += putResult([input, output]);
        });

        fs.appendFileSync('test/results/config-prompting.md', result, 'utf8');
    });

    it('Filter and validate \"root\" styles file', () => {

        conventions.forEach((convention) => {
            let result = '#####Filter and validate "root" styles file for \"' + convention + '\" convention\n\n';
            result += table.head.fv;

            data.filenames.forEach((filename) => {
                let dotted = $$.dot(filename, 'ext');
                let filtered = $$.filterName(convention, dotted.replace(/\.ext$/, ''), 'root');
                filtered = $$.dot(filtered, 'ext');
                let validated = $$.validateName(convention, filtered.replace(/\.ext$/, ''), 'root');

                result += putResult([showWhitespaces(filename), showWhitespaces(filtered), validated]);
            });

            fs.appendFileSync('test/results/config-prompting.md', result, 'utf8');
        });
    });

});


text:
/**
 * Defines {@link org.apache.beam.sdk.options.PipelineOptions} for configuring pipeline execution
 * for Amazon Web Services components.
 */
@Experimental(Kind.SOURCE_SINK)
package org.apache.beam.sdk.io.aws2.options;

import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;


text:
<?php
declare(strict_types=1);

namespace TSwiackiewicz\AwesomeApp\SharedKernel\User\Exception;

use TSwiackiewicz\DDD\Event\Event;

/**
 * Class RuntimeException
 * @package TSwiackiewicz\AwesomeApp\SharedKernel\User\Exception
 */
class RuntimeException extends \RuntimeException
{
    private const INVALID_HANDLED_EVENT_ERROR_CODE = 1234;

    /**
     * @param Event $handledEvent
     * @param string $expectedEventType
     * @return RuntimeException
     */
    public static function invalidHandledEventType(
        Event $handledEvent,
        string $expectedEventType
    ): RuntimeException
    {
        return new static(
            sprintf(
                'Invalid handled event type - expected: %s, given: %s',
                $expectedEventType,
                get_class($handledEvent)
            ),
            self::INVALID_HANDLED_EVENT_ERROR_CODE
        );
    }
}


text:
CREATE OR REPLACE function FN_IS_FIRST_S2S_SUBMISSION
	   (as_proposal_number in osp$eps_proposal.proposal_number%type)
	RETURN smallint
is
 ret_code      number := NULL;
 row_count     number;
begin
  SELECT count(*)
  INTO row_count
    FROM OSP$S2S_APPLICATION
   WHERE PROPOSAl_NUMBER = as_proposal_number;
 IF (row_count > 0) THEN
  ret_code := 0;
 ELSE
  ret_code := 1;
 END IF;
 RETURN (ret_code);
end;
/


text:
<bill session="110" type="hr" number="983" updated="2009-01-09T09:54:56-05:00">
	<status><calendar date="1202945460" datetime="2008-02-13T19:31:00-05:00" /></status>

	<introduced date="1202878800" datetime="2008-02-13"/>
	<titles>
		<title type="official" as="introduced">Waiving a requirement of clause 6(a) of rule XIII with respect to consideration of certain resolutions reported from the Committee on Rules and providing for consideration of motions to suspend the rules.</title>
	</titles>
	<sponsor id="412224"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1202945460" datetime="2008-02-13T19:31:00-05:00"><text>The House Committee on Rules reported an original measure, H. Rept. 110-527, by Mr. Arcuri.</text></action>
		<action date="1202945460" datetime="2008-02-13T19:31:00-05:00"><text>Waiving a requirement of clause 6(a) of rule XIII with respect to consideration of certain resolutions reported from the Committee on Rules and providing for consideration of motions to suspend the rules.</text></action>
		<calendar date="1202945460" datetime="2008-02-13T19:31:00-05:00" ><text>Placed on the House Calendar, Calendar No. 189.</text></calendar>
		<action date="1204174320" datetime="2008-02-27T12:52:00-05:00"><text>Pursuant to the provisions of H. Res. 1001, H. Res. 983 is laid on the table.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	2/13/2008--Reported to House without amendment. Makes it in order at any time on the legislative day of Thursday, February 14, 2008, for the Speaker to entertain motions that the House suspend the rules relating to a bill addressing foreign intelligence surveillance.<br/>
	</summary>
</bill>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using CryptoPriceProxy.ResponseTypes;
using ServiceStack.Common.Web;
using ServiceStack.ServiceClient.Web;

namespace CryptoPriceProxy.Clients
{
    /// <summary>
    /// Bitcoin price client, default data comes from public MtGox API in USD
    /// http://data.mtgox.com/api/1/BTCUSD/ticker
    /// </summary>
    public class BitcoinPriceClient : ICoinPriceClient
    {
        readonly JsonServiceClient client = new JsonServiceClient("http://data.mtgox.com");

        public CoinPrice GetLatest()
        {
            CoinPrice result;
            MtGoxDto dto;

            try
            {
                dto = client.Get<MtGoxDto>("/api/1/BTCUSD/ticker");
            }
            catch (Exception e)
            {
                throw new HttpError("Failed to get latest price", e);
            }

            if (dto == null)
            {
                throw new Exception("HTTP server responded without any data");
            }
            try
            {
                result = dto.Response.ToCoinPrice();
            }
            catch (Exception e)
            {
                throw new SerializationException("Failed to serialize to 'CoinPrice'", e);
            }
            return result;
        }
    }
}


text:
package com.dumu.housego.view;

public interface ICheckPhoneRegistView {
	void CheckSuccess(String info);

	void CheckFail(String errorMessage);
}


text:
// coding: utf-8
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
/*
 * WARNING: This file is generated automatically, do not edit!
 * Please modify the corresponding *.in file instead and rebuild this file.
 */
// ----------------------------------------------------------------------------

#include <avr/interrupt.h>
#include "timer_e0.hpp"

#ifdef TCE0

void
xpcc::atxmega::TimerE0::setTimerCommand(uint8_t command, bool clear)
{
	if (clear) {
		TCE0_CTRLFCLR = command;
	}
	else {
		TCE0_CTRLFSET = command;
	}
}

// specific configuration combinations
void
xpcc::atxmega::TimerE0::setMsTimer(uint8_t interval)
{
	setClockSource(TC_CLKSEL_DIV64_gc);
	setOverflowInterrupt(TC_OVFINTLVL_MED_gc);
	TCE0_PER = (interval * F_CPU) / 64000l;
}

#endif	// TCE0


text:
import PLATFORM = require( './index' );

// TESTS //

// The variable is a string...
{
	// tslint:disable-next-line:no-unused-expression
	PLATFORM; // $ExpectType string
}


text:
namespace rapid {
namespace fetch {
const char Gripper::kGripperAction[] = "gripper_controller/gripper_action";
const double Gripper::kClosedPosition = 0;
const double Gripper::kOpenedPosition = 0.115;

Gripper::Gripper() : client_(kGripperAction, true) {
  if (client_.waitForServer(ros::Duration(5.0))) {
    ROS_ERROR("Gripper server \"%s\" may not be connected.", kGripperAction);
  }
}

bool Gripper::Close(double max_effort) {
  control_msgs::GripperCommandGoal goal;
  goal.command.position = kClosedPosition;
  goal.command.max_effort = max_effort;
  client_.sendGoal(goal);
  return client_.waitForResult(ros::Duration(5.0));
}

bool Gripper::Open(double max_effort) {
  control_msgs::GripperCommandGoal goal;
  goal.command.position = kOpenedPosition;
  goal.command.max_effort = max_effort;
  client_.sendGoal(goal);
  return client_.waitForResult(ros::Duration(5.0));
}
}  // namespace fetch
}  // namespace rapid


text:
#ifndef __GTK_FILE_CHOOSER_WIDGET_H__
#define __GTK_FILE_CHOOSER_WIDGET_H__

#include "gtkfilechooser.h"
#include <gtk/gtkvbox.h>

G_BEGIN_DECLS

#define GTK_TYPE_FILE_CHOOSER_WIDGET             (gtk_file_chooser_widget_get_type ())
#define GTK_FILE_CHOOSER_WIDGET(obj)             (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_FILE_CHOOSER_WIDGET, GtkFileChooserWidget))
#define GTK_FILE_CHOOSER_WIDGET_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_FILE_CHOOSER_WIDGET, GtkFileChooserWidgetClass))
#define GTK_IS_FILE_CHOOSER_WIDGET(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_FILE_CHOOSER_WIDGET))
#define GTK_IS_FILE_CHOOSER_WIDGET_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FILE_CHOOSER_WIDGET))
#define GTK_FILE_CHOOSER_WIDGET_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_FILE_CHOOSER_WIDGET, GtkFileChooserWidgetClass))

typedef struct _GtkFileChooserWidget      GtkFileChooserWidget;
typedef struct _GtkFileChooserWidgetClass GtkFileChooserWidgetClass;

typedef struct _GtkFileChooserWidgetPrivate GtkFileChooserWidgetPrivate;

struct _GtkFileChooserWidgetClass
{
  GtkVBoxClass parent_class;
};

struct _GtkFileChooserWidget
{
  GtkVBox parent_instance;

  GtkFileChooserWidgetPrivate *priv;
};

GType      gtk_file_chooser_widget_get_type         (void);
GtkWidget *gtk_file_chooser_widget_new              (GtkFileChooserAction  action);
GtkWidget *gtk_file_chooser_widget_new_with_backend (GtkFileChooserAction  action,
						     const gchar          *backend);
G_END_DECLS

#endif /* __GTK_FILE_CHOOSER_WIDGET_H__ */


text:
'use strict';

var localConnection;
var remoteConnection;
var sendChannel;
var receiveChannel;
var pcConstraint;
var megsToSend = document.querySelector('input#megsToSend');
var sendButton = document.querySelector('button#sendTheData');
var orderedCheckbox = document.querySelector('input#ordered');
var sendProgress = document.querySelector('progress#sendProgress');
var receiveProgress = document.querySelector('progress#receiveProgress');

var receivedSize = 0;
var bytesToSend = 0;

var bitrateMax = 0;

sendButton.onclick = createConnection;

function createConnection() {
  var servers = null;
  pcConstraint = null;

  bytesToSend = megsToSend.value * 1024 * 1024;

  // Add localConnection to global scope to make it visible from the browser console.
  window.localConnection = localConnection = new RTCPeerConnection(servers,
      pcConstraint);
  trace('Created local peer connection object localConnection');

  var dataChannelParams = {ordered: false};
  if (orderedCheckbox.checked) {
    dataChannelParams.ordered = true;
  }

  sendChannel = localConnection.createDataChannel(
      'sendDataChannel', dataChannelParams);
  sendChannel.binaryType = 'arraybuffer';
  trace('Created send data channel');

  sendChannel.onopen = onSendChannelStateChange;
  sendChannel.onclose = onSendChannelStateChange;
  localConnection.onicecandidate = iceCallback1;

  localConnection.createOffer(gotDescription1, onCreateSessionDescriptionError);

  // Add remoteConnection to global scope to make it visible from the browser console.
  window.remoteConnection = remoteConnection = new RTCPeerConnection(servers,
      pcConstraint);
  trace('Created remote peer connection object remoteConnection');

  remoteConnection.onicecandidate = iceCallback2;
  remoteConnection.ondatachannel = receiveChannelCallback;
}

function onCreateSessionDescriptionError(error) {
  trace('Failed to create session description: ' + error.toString());
}

function randomAsciiString(length) {
  var result = '';
  for (var i = 0; i < length; i++) {
    // Visible ASCII chars are between 33 and 126.
    result += String.fromCharCode(33 + Math.random() * 93);
  }
  return result;
}

function sendGeneratedData() {
  sendProgress.max = bytesToSend;
  receiveProgress.max = sendProgress.max;
  sendProgress.value = 0;
  receiveProgress.value = 0;

  var chunkSize = 16384;
  var stringToSendRepeatedly = randomAsciiString(chunkSize);
  var sendAllData = function() {
    // Try to queue up a bunch of data and back off when the channel starts to
    // fill up. We don't setTimeout after each send since this lowers our
    // throughput quite a bit (setTimeout(fn, 0) can take hundreds of milli-
    // seconds to execute).
    while (sendProgress.value < sendProgress.max) {
      if (sendChannel.bufferedAmount > 5 * chunkSize) {
        setTimeout(sendAllData, 250);
        return;
      }
      sendProgress.value += chunkSize;
      sendChannel.send(stringToSendRepeatedly);
    }
  };
  setTimeout(sendAllData, 0);
}

function closeDataChannels() {
  trace('Closing data channels');
  sendChannel.close();
  trace('Closed data channel with label: ' + sendChannel.label);
  receiveChannel.close();
  trace('Closed data channel with label: ' + receiveChannel.label);
  localConnection.close();
  remoteConnection.close();
  localConnection = null;
  remoteConnection = null;
  trace('Closed peer connections');
}

function gotDescription1(desc) {
  localConnection.setLocalDescription(desc);
  trace('Offer from localConnection \n' + desc.sdp);
  remoteConnection.setRemoteDescription(desc);
  remoteConnection.createAnswer(gotDescription2,
      onCreateSessionDescriptionError);
}

function gotDescription2(desc) {
  remoteConnection.setLocalDescription(desc);
  trace('Answer from remoteConnection \n' + desc.sdp);
  localConnection.setRemoteDescription(desc);
}

function iceCallback1(event) {
  trace('local ice callback');
  if (event.candidate) {
    remoteConnection.addIceCandidate(event.candidate,
        onAddIceCandidateSuccess, onAddIceCandidateError);
    trace('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function iceCallback2(event) {
  trace('remote ice callback');
  if (event.candidate) {
    localConnection.addIceCandidate(event.candidate,
        onAddIceCandidateSuccess, onAddIceCandidateError);
    trace('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess() {
  trace('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  trace('Failed to add Ice Candidate: ' + error.toString());
}

function receiveChannelCallback(event) {
  trace('Receive Channel Callback');
  receiveChannel = event.channel;
  receiveChannel.binaryType = 'arraybuffer';
  receiveChannel.onmessage = onReceiveMessageCallback;

  receivedSize = 0;
  bitrateMax = 0;
}

function onReceiveMessageCallback(event) {
  receivedSize += event.data.length;
  receiveProgress.value = receivedSize;

  if (receivedSize === bytesToSend) {
    closeDataChannels();
  }
}

function onSendChannelStateChange() {
  var readyState = sendChannel.readyState;
  trace('Send channel state is: ' + readyState);
  if (readyState === 'open') {
    sendGeneratedData();
  }
}


text:
<?php

namespace Perimeter\RateLimiter\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * RateLimitMeter
 *
 * Doctrine2 Entity for RateLimit Meters
 *
 * @ORM\Entity
 * @ORM\Table(name="rate_limit_meter",uniqueConstraints={@ORM\UniqueConstraint(name="meter_id_idx", columns={"meter_id"})})
 */
class RateLimitMeter
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     **/
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     **/
    public $meter_id;

    /**
     * @ORM\Column(type="integer")
     **/
    public $warn_threshold;

    /**
     * @ORM\Column(type="integer")
     **/
    public $limit_threshold;

    /**
     * @ORM\Column(type="boolean")
     **/
    public $should_warn = true;

    /**
     * @ORM\Column(type="boolean")
     **/
    public $should_limit = false;

    /**
     * @ORM\Column(type="boolean")
     **/
    public $num_tokens = 1;

    /**
     * @ORM\Column(type="integer", nullable=true)
     **/
    public $throttle_ms = 0;

    public function getId()
    {
        return $this->id;
    }

    public function fromArray($array)
    {
        foreach ($array as $key => $value) {
            $this->$key = $value;
        }
    }

    public function toArray()
    {
        return array(
            'id'              => $this->id,
            'meter_id'        => $this->meter_id,
            'warn_threshold'  => $this->warn_threshold,
            'limit_threshold' => $this->limit_threshold,
            'should_warn'     => $this->should_warn,
            'should_limit'    => $this->should_limit,
            'num_tokens'      => $this->num_tokens,
            'throttle_ms'     => $this->throttle_ms,
        );
    }
}


text:
import {Injector, bind, Binding} from "angular2/src/core/di";
import {DEFAULT_PIPES} from 'angular2/src/core/pipes';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
import {Reflector, reflector} from 'angular2/src/core/reflection/reflection';
import {Parser, Lexer} from 'angular2/src/core/change_detection/change_detection';
import {
  EventManager,
  DomEventsPlugin,
  EVENT_MANAGER_PLUGINS
} from 'angular2/src/core/render/dom/events/event_manager';
import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {KeyEventsPlugin} from 'angular2/src/core/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/core/render/dom/events/hammer_gestures';
import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view_pool';
import {Renderer} from 'angular2/src/core/render/api';
import {AppRootUrl} from 'angular2/src/core/compiler/app_root_url';
import {DomRenderer, DomRenderer_, DOCUMENT} from 'angular2/src/core/render/render';
import {APP_ID_RANDOM_BINDING} from 'angular2/src/core/application_tokens';
import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';
import {
  DomElementSchemaRegistry
} from 'angular2/src/core/compiler/schema/dom_element_schema_registry';
import {
  SharedStylesHost,
  DomSharedStylesHost
} from 'angular2/src/core/render/dom/shared_styles_host';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {AppViewManager, AppViewManager_} from 'angular2/src/core/linker/view_manager';
import {AppViewManagerUtils} from 'angular2/src/core/linker/view_manager_utils';
import {AppViewListener} from 'angular2/src/core/linker/view_listener';
import {ViewResolver} from 'angular2/src/core/linker/view_resolver';
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
import {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
import {
  DynamicComponentLoader,
  DynamicComponentLoader_
} from 'angular2/src/core/linker/dynamic_component_loader';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {Testability} from 'angular2/src/core/testability/testability';
import {XHR} from 'angular2/src/core/compiler/xhr';
import {XHRImpl} from 'angular2/src/core/compiler/xhr_impl';
import {Serializer} from 'angular2/src/web_workers/shared/serializer';
import {ON_WEB_WORKER} from 'angular2/src/web_workers/shared/api';
import {RenderProtoViewRefStore} from 'angular2/src/web_workers/shared/render_proto_view_ref_store';
import {
  RenderViewWithFragmentsStore
} from 'angular2/src/web_workers/shared/render_view_with_fragments_store';
import {AnchorBasedAppRootUrl} from 'angular2/src/core/compiler/anchor_based_app_root_url';
import {WebWorkerApplication} from 'angular2/src/web_workers/ui/impl';
import {MessageBus} from 'angular2/src/web_workers/shared/message_bus';
import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer';
import {MessageBasedXHRImpl} from 'angular2/src/web_workers/ui/xhr_impl';
import {WebWorkerSetup} from 'angular2/src/web_workers/ui/setup';
import {
  ServiceMessageBrokerFactory,
  ServiceMessageBrokerFactory_
} from 'angular2/src/web_workers/shared/service_message_broker';
import {
  ClientMessageBrokerFactory,
  ClientMessageBrokerFactory_
} from 'angular2/src/web_workers/shared/client_message_broker';

var _rootInjector: Injector;

// Contains everything that is safe to share between applications.
var _rootBindings = [bind(Reflector).toValue(reflector)];

// TODO: This code is nearly identical to core/application. There should be a way to only write it
// once
function _injectorBindings(): any[] {
  return [
    bind(DOCUMENT)
        .toValue(DOM.defaultDoc()),
    EventManager,
    new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
    new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
    new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
    bind(DomRenderer).toClass(DomRenderer_),
    bind(Renderer).toAlias(DomRenderer),
    APP_ID_RANDOM_BINDING,
    DomSharedStylesHost,
    bind(SharedStylesHost).toAlias(DomSharedStylesHost),
    Serializer,
    bind(ON_WEB_WORKER).toValue(false),
    bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()),
    RenderViewWithFragmentsStore,
    RenderProtoViewRefStore,
    AppViewPool,
    bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
    bind(AppViewManager).toClass(AppViewManager_),
    AppViewManagerUtils,
    AppViewListener,
    ProtoViewFactory,
    ViewResolver,
    DEFAULT_PIPES,
    DirectiveResolver,
    Parser,
    Lexer,
    bind(ExceptionHandler).toFactory(() => new ExceptionHandler(DOM), []),
    bind(XHR).toValue(new XHRImpl()),
    UrlResolver,
    bind(DynamicComponentLoader).toClass(DynamicComponentLoader_),
    Testability,
    AnchorBasedAppRootUrl,
    bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
    WebWorkerApplication,
    WebWorkerSetup,
    MessageBasedXHRImpl,
    MessageBasedRenderer,
    bind(ServiceMessageBrokerFactory).toClass(ServiceMessageBrokerFactory_),
    bind(ClientMessageBrokerFactory).toClass(ClientMessageBrokerFactory_),
    BrowserDetails,
    AnimationBuilder,
  ];
}

export function createInjector(zone: NgZone, bus: MessageBus): Injector {
  BrowserDomAdapter.makeCurrent();
  _rootBindings.push(bind(NgZone).toValue(zone));
  _rootBindings.push(bind(MessageBus).toValue(bus));
  var injector: Injector = Injector.resolveAndCreate(_rootBindings);
  return injector.resolveAndCreateChild(_injectorBindings());
}


text:
package backend

import (
	"fmt"
	"hash/crc32"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path"
	"sync"
	"sync/atomic"
	"time"

	"github.com/boltdb/bolt"
)

var (
	defaultBatchLimit    = 10000
	defaultBatchInterval = 100 * time.Millisecond

	defragLimit = 10000

	// InitialMmapSize is the initial size of the mmapped region. Setting this larger than
	// the potential max db size can prevent writer from blocking reader.
	// This only works for linux.
	InitialMmapSize = int64(10 * 1024 * 1024 * 1024)
)

type Backend interface {
	BatchTx() BatchTx
	Snapshot() Snapshot
	Hash() (uint32, error)
	// Size returns the current size of the backend.
	Size() int64
	Defrag() error
	ForceCommit()
	Close() error
}

type Snapshot interface {
	// Size gets the size of the snapshot.
	Size() int64
	// WriteTo writes the snapshot into the given writer.
	WriteTo(w io.Writer) (n int64, err error)
	// Close closes the snapshot.
	Close() error
}

type backend struct {
	// size and commits are used with atomic operations so they must be
	// 64-bit aligned, otherwise 32-bit tests will crash

	// size is the number of bytes in the backend
	size int64
	// commits counts number of commits since start
	commits int64

	mu sync.RWMutex
	db *bolt.DB

	batchInterval time.Duration
	batchLimit    int
	batchTx       *batchTx

	stopc chan struct{}
	donec chan struct{}
}

func New(path string, d time.Duration, limit int) Backend {
	return newBackend(path, d, limit)
}

func NewDefaultBackend(path string) Backend {
	return newBackend(path, defaultBatchInterval, defaultBatchLimit)
}

func newBackend(path string, d time.Duration, limit int) *backend {
	db, err := bolt.Open(path, 0600, boltOpenOptions)
	if err != nil {
		log.Panicf("backend: cannot open database at %s (%v)", path, err)
	}

	b := &backend{
		db: db,

		batchInterval: d,
		batchLimit:    limit,

		stopc: make(chan struct{}),
		donec: make(chan struct{}),
	}
	b.batchTx = newBatchTx(b)
	go b.run()
	return b
}

// BatchTx returns the current batch tx in coalescer. The tx can be used for read and
// write operations. The write result can be retrieved within the same tx immediately.
// The write result is isolated with other txs until the current one get committed.
func (b *backend) BatchTx() BatchTx {
	return b.batchTx
}

// ForceCommit forces the current batching tx to commit.
func (b *backend) ForceCommit() {
	b.batchTx.Commit()
}

func (b *backend) Snapshot() Snapshot {
	b.batchTx.Commit()

	b.mu.RLock()
	defer b.mu.RUnlock()
	tx, err := b.db.Begin(false)
	if err != nil {
		log.Fatalf("backend: cannot begin tx (%s)", err)
	}
	return &snapshot{tx}
}

func (b *backend) Hash() (uint32, error) {
	h := crc32.New(crc32.MakeTable(crc32.Castagnoli))

	b.mu.RLock()
	defer b.mu.RUnlock()
	err := b.db.View(func(tx *bolt.Tx) error {
		c := tx.Cursor()
		for next, _ := c.First(); next != nil; next, _ = c.Next() {
			b := tx.Bucket(next)
			if b == nil {
				return fmt.Errorf("cannot get hash of bucket %s", string(next))
			}
			h.Write(next)
			b.ForEach(func(k, v []byte) error {
				h.Write(k)
				h.Write(v)
				return nil
			})
		}
		return nil
	})

	if err != nil {
		return 0, err
	}

	return h.Sum32(), nil
}

func (b *backend) Size() int64 {
	return atomic.LoadInt64(&b.size)
}

func (b *backend) run() {
	defer close(b.donec)

	for {
		select {
		case <-time.After(b.batchInterval):
		case <-b.stopc:
			b.batchTx.CommitAndStop()
			return
		}
		b.batchTx.Commit()
	}
}

func (b *backend) Close() error {
	close(b.stopc)
	<-b.donec
	return b.db.Close()
}

// Commits returns total number of commits since start
func (b *backend) Commits() int64 {
	return atomic.LoadInt64(&b.commits)
}

func (b *backend) Defrag() error {
	// TODO: make this non-blocking?
	// lock batchTx to ensure nobody is using previous tx, and then
	// close previous ongoing tx.
	b.batchTx.Lock()
	defer b.batchTx.Unlock()

	// lock database after lock tx to avoid deadlock.
	b.mu.Lock()
	defer b.mu.Unlock()

	b.batchTx.commit(true)
	b.batchTx.tx = nil

	tmpdb, err := bolt.Open(b.db.Path()+".tmp", 0600, boltOpenOptions)
	if err != nil {
		return err
	}

	err = defragdb(b.db, tmpdb, defragLimit)

	if err != nil {
		tmpdb.Close()
		os.RemoveAll(tmpdb.Path())
		return err
	}

	dbp := b.db.Path()
	tdbp := tmpdb.Path()

	err = b.db.Close()
	if err != nil {
		log.Fatalf("backend: cannot close database (%s)", err)
	}
	err = tmpdb.Close()
	if err != nil {
		log.Fatalf("backend: cannot close database (%s)", err)
	}
	err = os.Rename(tdbp, dbp)
	if err != nil {
		log.Fatalf("backend: cannot rename database (%s)", err)
	}

	b.db, err = bolt.Open(dbp, 0600, boltOpenOptions)
	if err != nil {
		log.Panicf("backend: cannot open database at %s (%v)", dbp, err)
	}
	b.batchTx.tx, err = b.db.Begin(true)
	if err != nil {
		log.Fatalf("backend: cannot begin tx (%s)", err)
	}

	return nil
}

func defragdb(odb, tmpdb *bolt.DB, limit int) error {
	// open a tx on tmpdb for writes
	tmptx, err := tmpdb.Begin(true)
	if err != nil {
		return err
	}

	// open a tx on old db for read
	tx, err := odb.Begin(false)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	c := tx.Cursor()

	count := 0
	for next, _ := c.First(); next != nil; next, _ = c.Next() {
		b := tx.Bucket(next)
		if b == nil {
			return fmt.Errorf("backend: cannot defrag bucket %s", string(next))
		}

		tmpb, berr := tmptx.CreateBucketIfNotExists(next)
		if berr != nil {
			return berr
		}

		b.ForEach(func(k, v []byte) error {
			count++
			if count > limit {
				err = tmptx.Commit()
				if err != nil {
					return err
				}
				tmptx, err = tmpdb.Begin(true)
				if err != nil {
					return err
				}
				tmpb = tmptx.Bucket(next)
			}
			err = tmpb.Put(k, v)
			if err != nil {
				return err
			}
			return nil
		})
	}

	return tmptx.Commit()
}

// NewTmpBackend creates a backend implementation for testing.
func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
	dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
	if err != nil {
		log.Fatal(err)
	}
	tmpPath := path.Join(dir, "database")
	return newBackend(tmpPath, batchInterval, batchLimit), tmpPath
}

func NewDefaultTmpBackend() (*backend, string) {
	return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
}

type snapshot struct {
	*bolt.Tx
}

func (s *snapshot) Close() error { return s.Tx.Rollback() }


text:
package org.knowm.yank;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import java.util.List;
import java.util.Properties;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/** @author timmolter */
public class SnakeCaseTest2 {

  @BeforeClass
  public static void setUpDB() {

    Properties dbProps = PropertiesUtils.getPropertiesFromClasspath("HSQL_DB.properties");

    Yank.setupDefaultConnectionPool(dbProps);
  }

  @AfterClass
  public static void tearDownDB() {

    Yank.releaseDefaultConnectionPool();
  }

  @Test
  public void test0() {

    String sql = "CREATE TABLE TEST0 (spotfix_id BIGINT NULL)";
    Yank.execute(sql, null);

    Test0Bean test0Bean = new Test0Bean();
    test0Bean.setSpotfix_id(87L);
    Object[] params = new Object[] {test0Bean.getSpotfix_id()};
    String SQL = "INSERT INTO TEST0 (spotfix_id) VALUES (?)";
    int numInserted = Yank.execute(SQL, params);
    //    System.out.println("numInserted: " + numInserted);
    assertThat(numInserted, equalTo(1));

    SQL = "SELECT * FROM TEST0";
    List<Test0Bean> testBeans = Yank.queryBeanList(SQL, Test0Bean.class, null);
    //    System.out.println(testBeans.get(0).toString());
    assertThat(testBeans.get(0).getSpotfix_id(), equalTo(87L));
  }

  public static class Test0Bean {

    private long spotfix_id;

    /** @return the spotfix_id */
    public long getSpotfix_id() {
      return spotfix_id;
    }

    /** @param spotfix_id the spotfix_id to set */
    public void setSpotfix_id(long spotfix_id) {
      this.spotfix_id = spotfix_id;
    }

    @Override
    public String toString() {
      return "Test0Bean [spotfix_id=" + spotfix_id + "]";
    }
  }
}


text:
PGRAPH: 2d/3d graphics and compute engine
=========================================

Contents:

.. toctree::
   :titlesonly:

   intro
   m2mf
   2d/index
   nv01/index
   riva/index
   tnt/index
   celsius/index
   kelvin/index
   rankine/index
   curie/index
   tesla/index
   fermi/index
   kepler/index


text:
// @ts-check

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	h = include('tests/helpers').default;

/**
 * Starts a test
 *
 * @param {Playwright.Page} page
 * @param {!Object} params
 * @returns {!Promise<void>}
 */
module.exports = async (page, params) => {
	await h.utils.setup(page, params.context);

	let
		ctx;

	const check = async (val) => {
		expect(await page.evaluate(() => globalThis.tVal)).toBe(val);
	};

	describe('updateOn', () => {
		beforeEach(async () => {
			await h.utils.reloadAndWaitForIdle(page);
			ctx = await h.component.waitForComponent(page, '#dummy-component');
		});

		it('executes a handler on event emitting', async () => {
			await ctx.evaluate((ctx) => {
				ctx.directives.updateOn.add(ctx.$el, {
					emitter: ctx.selfEmitter,
					event: 'foo',
					handler: () => globalThis.tVal = true
				}, ctx);

				ctx.emit('foo');
			});

			await check(true);
		});

		it('executes a handler on field changing', async () => {
			await ctx.evaluate((ctx) => {
				ctx.directives.updateOn.add(ctx.$el, {
					emitter: 'testField',
					handler: () => globalThis.tVal = true
				}, ctx);

				ctx.testField = 2;
			});

			await check(true);
		});

		it('executes a handler on promise resolving', async () => {
			await ctx.evaluate((ctx) => {
				globalThis.tVal = 0;

				/** @type {Function} */
				let pRes;

				ctx.directives.updateOn.add(ctx.$el, {
					emitter: new Promise((res) => pRes = res),
					single: true,
					handler: () => globalThis.tVal++,
					errorHandler: () => globalThis.tVal--
				}, ctx);

				pRes();
			});

			await check(1);
		});

		it('executes a handler once with the `single` option', async () => {
			await ctx.evaluate((ctx) => {
				globalThis.tVal = 0;

				ctx.directives.updateOn.add(ctx.$el, {
					emitter: ctx.selfEmitter,
					event: 'foo',
					single: true,
					handler: () => globalThis.tVal++
				}, ctx);

				ctx.emit('foo');
				ctx.emit('foo');
			});

			await check(1);
		});

		it('executes an error handler if the promise was rejected', async () => {
			await ctx.evaluate((ctx) => {
				globalThis.tVal = 0;

				/** @type {Function} */
				let pRej;

				ctx.directives.updateOn.add(ctx.$el, {
					emitter: new Promise((res, rej) => pRej = rej),
					single: true,
					handler: () => globalThis.tVal++,
					errorHandler: () => globalThis.tVal--
				}, ctx);

				pRej();
			});

			await check(-1);
		});

		it('provides arguments into the handler', async () => {
			await ctx.evaluate((ctx) => {
				ctx.directives.updateOn.add(ctx.$el, {
					emitter: ctx.selfEmitter,
					event: 'foo',
					handler: (el, ctx, val) => globalThis.tVal = val
				}, ctx);

				ctx.emit('foo', 1);
			});

			await check(1);
		});

		it('invokes the `remove` method', async () => {
			await ctx.evaluate((ctx) => {
				ctx.directives.updateOn.add(ctx.$el, {
					emitter: ctx.selfEmitter,
					event: 'foo',
					handler: (el, val) => globalThis.tVal = val
				}, ctx);

				ctx.directives.updateOn.remove(ctx.$el, ctx);
				ctx.emit('foo', 1);
			});

			await check(undefined);
		});
	});
};


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using DonorDatabase.Models;

namespace DonorDatabase.Controllers
{
    public class LOVTypeController : ApiController
    {
        private donordatabaseEntities db = new donordatabaseEntities();

        // GET api/LOVType
        [Authorize]
        public IEnumerable<LOVType> GetLOVType()
        {
            return db.LOVTypes.AsEnumerable();
        }

        // GET api/LOVType/5
        public LOVType GetLOVType(int id)
        {
            var items = db.LOVTypes.Include(p => p.LOVs);
            LOVType item = items.Where(p => p.LOVTypeID == id).FirstOrDefault();
            if (item == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return item;
        }

        // PUT api/LOVType/5
        [Authorize]
        public HttpResponseMessage PutLOVType(int id, LOVType item)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != item.LOVTypeID)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(item).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/LOVType
        [Authorize]
        public HttpResponseMessage PostLOVType(LOVType item)
        {
            if (ModelState.IsValid)
            {
                db.LOVTypes.Add(item);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, item);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = item.LOVTypeID }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        // DELETE api/LOVType/5
        [Authorize]
        public HttpResponseMessage DeleteLOVType(int id)
        {
            LOVType item = db.LOVTypes.Find(id);
            if (item == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.LOVTypes.Remove(item);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, item);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


text:
Ext.ux.FilteredDataView = Ext.extend(Ext.DataView,{
    itemSelector: '.item',
    emptyText: '
No Recent Events
',
    loadingText: 'Loading',

    // override this method to pick which
    // records are allowed
    collect: function(record){
        return true;
    },

    sort: false,

    collectData: function(records,idx){
        var rs = [];
        for (var i=0; i < records.length; i++) {
            if(this.collect(records[i]))
                rs.push( records[i].data );
        }
        if(this.sort)
            rs.sort(this.sort);
        return rs;
    },

    onUpdate: function(ds, record) {
        // standard onUpdate fails so just refresh everything for now
        this.refresh();
    },

    initComponent: function(){
        // better errors
        if(!this.store)
            throw new Error("No store attached to DataView");
        if(!this.tpl)
            throw new Error("No tpl assigned to DataView");
        // super
        Ext.ux.FilteredDataView.superclass.initComponent.apply(this, arguments);
    }

});

Ext.ux.DatumView = Ext.extend(Ext.ux.FilteredDataView,{
    // faster collectData for single
    collectData: function(records,idx){
        for (var i=0; i < records.length; i++) {
            if(records[i].internalId===this.internalId)
                return [records[i].data];
        }
        return [];
    },
    initComponent: function(){
        // check we have a record id
        // we use internalId so that unsynced records can be used
        if(this.record)
            this.internalId = this.record.internalId;
        if(!this.internalId)
            throw new Error('you must supply a record or internalId property');
        // super
        Ext.ux.DatumView.superclass.initComponent.apply(this, arguments);
    }
});


text:
import FeatureNameStatistics from 'goog:proto.featureStatistics.FeatureNameStatistics';
import Histogram from 'goog:proto.featureStatistics.Histogram';

import * as fsg from '../feature_statistics_generator';

const {expect} = chai;

describe('generateStats', () => {
  it('handles null data', () => {
    const stats = fsg.generateStats();
    expect(stats.getNumExamples()).to.equal(0);
  });

  it('picks dominant data type', () => {
    const items: fsg.DataPoint[] = [];
    const numItem: fsg.DataPoint = {};
    numItem['f1'] = 1;
    items.push(numItem);
    for (let i = 0; i < 5; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = 'string';
      items.push(item);
    }

    const stats = fsg.generateStats(items);
    const feature = stats.getFeaturesList()![0];
    expect(feature.getType()).to.equal(FeatureNameStatistics.Type.STRING);
    expect(feature.getNumStats()).to.not.be.null;
  });

  it('detects integers', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 5; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = i;
      items.push(item);
    }

    const stats = fsg.generateStats(items);
    const feature = stats.getFeaturesList()![0];
    expect(feature.getType()).to.equal(FeatureNameStatistics.Type.INT);
  });

  it('detects floats', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 5; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = i;
      items.push(item);
    }
    const floatItem: fsg.DataPoint = {};
    floatItem['f1'] = 1.1;
    items.push(floatItem);
    const stats = fsg.generateStats(items);
    const feature = stats.getFeaturesList()![0];
    expect(feature.getType()).to.equal(FeatureNameStatistics.Type.FLOAT);
  });

  it('handles data', () => {
    const items: fsg.DataPoint[] = [];
    const item: fsg.DataPoint = {};
    item['f1'] = 1;
    item['f2'] = 'hello';
    items.push(item);
    const stats = fsg.generateStats(items);
    expect(stats.getNumExamples()).to.equal(1);
  });

  it('handles data with missing entries', () => {
    const items: fsg.DataPoint[] = [];
    const item: fsg.DataPoint = {};
    item['f1'] = 1;
    items.push(item);
    const item2: fsg.DataPoint = {};
    item2['f2'] = 'hello';
    items.push(item2);
    const stats = fsg.generateStats(items);
    expect(stats.getNumExamples()).to.equal(2);
  });

  it('handles numeric data', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 500; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = i;
      items.push(item);
    }
    const item: fsg.DataPoint = {};
    item['f1'] = 0;
    items.push(item);
    const stats = fsg.generateStats(items);
    expect(stats.getNumExamples()).to.equal(501);

    const numStats = stats.getFeaturesList()![0].getNumStats()!;
    expect(numStats.getMin()).to.equal(0);
    expect(numStats.getMax()).to.equal(499);
    expect(numStats.getMean()).to.be.within(249.001, 249.003);
    expect(numStats.getStdDev()).to.be.within(144.766, 144.768);
    expect(numStats.getMedian()).to.be.within(248.99, 249.01);
    expect(numStats.getNumZeros()).to.equal(2);

    expect(numStats.getHistogramsList().length).to.equal(2);
    expect(numStats.getHistogramsList()![0].getType())
      .to.equal(Histogram.HistogramType.STANDARD);
    let hist = numStats.getHistogramsList()![0].getBucketsList()!;
    expect(hist.length).to.equal(10);
    expect(hist[0].getSampleCount()).to.equal(51);
    expect(hist[0].getLowValue()).to.equal(0);
    expect(hist[0].getHighValue()).to.equal(49.9);
    expect(hist[9].getSampleCount()).to.equal(50);
    expect(hist[9].getLowValue()).to.be.within(449.099, 449.101);
    expect(hist[9].getHighValue()).to.equal(499);

    expect(numStats.getHistogramsList()![1].getType())
      .to.equal(Histogram.HistogramType.QUANTILES);
    hist = numStats.getHistogramsList()![1].getBucketsList()!;
    expect(hist.length).to.equal(10);
    expect(hist[0].getSampleCount()).to.equal(50.1);
    expect(hist[0].getLowValue()).to.equal(0);
    expect(hist[0].getHighValue()).to.equal(49);
    expect(hist[9].getSampleCount()).to.equal(50.1);
    expect(hist[9].getLowValue()).to.equal(449);
    expect(hist[9].getHighValue()).to.equal(499);
  });

  it('handles inf values', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 500; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = i;
      items.push(item);
    }
    const item: fsg.DataPoint = {};
    item['f1'] = Infinity;
    items.push(item);
    const item2: fsg.DataPoint = {};
    item2['f1'] = -Infinity;
    items.push(item2);
    const stats = fsg.generateStats(items);
    expect(stats.getNumExamples()).to.equal(502);

    const numStats = stats.getFeaturesList()![0].getNumStats()!;
    expect(numStats.getMin()).to.equal(-Infinity);
    expect(numStats.getMax()).to.equal(Infinity);
    expect(numStats.getMean()).to.be.NaN;
    expect(numStats.getStdDev()).to.be.NaN;

    expect(numStats.getHistogramsList().length).to.equal(2);
    expect(numStats.getHistogramsList()![0].getType())
      .to.equal(Histogram.HistogramType.STANDARD);
    const hist = numStats.getHistogramsList()![0].getBucketsList()!;
    expect(hist.length).to.equal(10);
    expect(hist[0].getLowValue()).to.equal(-Infinity);
    expect(hist[0].getSampleCount()).to.equal(51);
    expect(hist[9].getHighValue()).to.equal(Infinity);
    expect(hist[9].getSampleCount()).to.equal(51);
  });

  it('calculates correct quantiles', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 50; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = i;
      items.push(item);
      const itemConst: fsg.DataPoint = {};
      itemConst['f1'] = 100;
      items.push(itemConst);
    }
    const stats = fsg.generateStats(items);
    expect(stats.getNumExamples()).to.equal(100);
    const numStats = stats.getFeaturesList()![0].getNumStats()!;

    expect(numStats.getHistogramsList()![1].getType())
      .to.equal(Histogram.HistogramType.QUANTILES);
    const hist = numStats.getHistogramsList()![1].getBucketsList()!;
    expect(hist.length).to.equal(10);
    expect(hist[0].getSampleCount()).to.equal(10);
    expect(hist[0].getLowValue()).to.equal(0);
    expect(hist[0].getHighValue()).to.equal(9.9);
    expect(hist[9].getSampleCount()).to.equal(10);
    expect(hist[9].getLowValue()).to.equal(100);
    expect(hist[9].getHighValue()).to.equal(100);
  });

  it('handles string data', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 500; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = i % 2 === 0 ? 'popular' : i < 150 ? 'third' : 'second';
      items.push(item);
    }
    const stats = fsg.generateStats(items);
    expect(stats.getNumExamples()).to.equal(500);

    const stringStats = stats.getFeaturesList()![0].getStringStats()!;
    expect(stringStats.getUnique()).to.equal(3);
    expect(stringStats.getAvgLength()).to.equal(6.35);
    const topVals = stringStats.getTopValuesList()!;
    expect(topVals.length).to.equal(1);
    expect(topVals[0].getValue()).to.equal('popular');
    expect(topVals[0].getFrequency()).to.equal(250);

    const hist = stringStats.getRankHistogram()!.getBucketsList()!;
    expect(hist.length).to.equal(3);
    expect(hist[0].getSampleCount()).to.equal(250);
    expect(hist[0].getLabel()).to.equal('popular');
    expect(hist[0].getLowRank()).to.equal(0);
    expect(hist[0].getHighRank()).to.equal(0);
    expect(hist[2].getSampleCount()).to.equal(75);
    expect(hist[2].getLowRank()).to.equal(2);
    expect(hist[2].getHighRank()).to.equal(2);
  });

  it('generates correct common stats for strings', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 10; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = 'test';
      items.push(item);
    }
    const missingItem: fsg.DataPoint = {};
    missingItem['f2'] = 'f1 is missing';
    items.push(missingItem);

    const stats = fsg.generateStats(items);
    let common = stats.getFeaturesList()![0].getStringStats()!.getCommonStats()!;
    expect(common.getMinNumValues()).to.equal(1);
    expect(common.getMaxNumValues()).to.equal(1);
    expect(common.getAvgNumValues()).to.equal(1);
    expect(common.getNumMissing()).to.equal(1);
    expect(common.getNumNonMissing()).to.equal(10);
    expect(common.getNumValuesHistogram()!.getType())
      .to.equal(Histogram.HistogramType.QUANTILES);
    const hist = common.getNumValuesHistogram()!.getBucketsList()!;
    expect(hist.length).to.equal(10);
    expect(hist[0].getSampleCount()).to.equal(1);
    expect(hist[0].getLowValue()).to.equal(1);
    expect(hist[0].getHighValue()).to.equal(1);
    expect(hist[9].getSampleCount()).to.equal(1);
    expect(hist[9].getLowValue()).to.equal(1);
    expect(hist[9].getHighValue()).to.equal(1);

    common = stats.getFeaturesList()![1].getStringStats()!.getCommonStats()!;
    expect(common.getNumMissing()).to.equal(10);
    expect(common.getNumNonMissing()).to.equal(1);
  });

  it('generates correct common stats for nums', () => {
    const items: fsg.DataPoint[] = [];
    for (let i = 0; i < 10; ++i) {
      const item: fsg.DataPoint = {};
      item['f1'] = 1;
      items.push(item);
    }
    const missingItem: fsg.DataPoint = {};
    missingItem['f2'] = 2;
    items.push(missingItem);

    const stats = fsg.generateStats(items);
    let common = stats.getFeaturesList()![0].getNumStats()!.getCommonStats()!;
    expect(common.getMinNumValues()).to.equal(1);
    expect(common.getMaxNumValues()).to.equal(1);
    expect(common.getAvgNumValues()).to.equal(1);
    expect(common.getNumMissing()).to.equal(1);
    expect(common.getNumNonMissing()).to.equal(10);
    expect(common.getNumValuesHistogram()!.getType())
      .to.equal(Histogram.HistogramType.QUANTILES);
    const hist = common.getNumValuesHistogram()!.getBucketsList()!;
    expect(hist.length).to.equal(10);
    expect(hist[0].getSampleCount()).to.equal(1);
    expect(hist[0].getLowValue()).to.equal(1);
    expect(hist[0].getHighValue()).to.equal(1);
    expect(hist[9].getSampleCount()).to.equal(1);
    expect(hist[9].getLowValue()).to.equal(1);
    expect(hist[9].getHighValue()).to.equal(1);

    common = stats.getFeaturesList()![1].getNumStats()!.getCommonStats()!;
    expect(common.getNumMissing()).to.equal(10);
    expect(common.getNumNonMissing()).to.equal(1);
  });
});

describe('getStatsProto', () => {
  it('handles empty array', () => {
    const stats = fsg.getStatsProto([]);
    expect(stats.getDatasetsList().length).to.equal(0);
  });

  it('handles multiple datasets', () => {
    const items1: fsg.DataPoint[] = [];
    const item1: fsg.DataPoint = {};
    item1['f1'] = 1;
    items1.push(item1);
    const items2: fsg.DataPoint[] = [];
    const item2: fsg.DataPoint = {};
    item2['f1'] = 1;
    items2.push(item2);
    const stats = fsg.getStatsProto([
      {data: items1, name: 'train'},
      {data: items2, name: 'test'}]);
    const list = stats.getDatasetsList();
    expect(list.length).to.equal(2);
    expect(list[0].getName()).to.equal('train');
    expect(list[1].getName()).to.equal('test');
  });
});


text:
package edu.iu.grid.oim.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.divrep.DivRepRoot;

import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.lib.StaticConfig;

import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.db.ServiceGroupModel;
import edu.iu.grid.oim.model.db.SiteModel;
import edu.iu.grid.oim.model.db.record.ServiceGroupRecord;
import edu.iu.grid.oim.view.BootBreadCrumbView;
import edu.iu.grid.oim.view.BootMenuView;
import edu.iu.grid.oim.view.BootPage;
import edu.iu.grid.oim.view.BreadCrumbView;
import edu.iu.grid.oim.view.ContentView;
import edu.iu.grid.oim.view.DivRepWrapper;
import edu.iu.grid.oim.view.HtmlView;
import edu.iu.grid.oim.view.MenuView;
import edu.iu.grid.oim.view.Page;
import edu.iu.grid.oim.view.SideContentView;

import edu.iu.grid.oim.view.divrep.form.ResourceGroupFormDE;
import edu.iu.grid.oim.view.divrep.form.ServiceGroupFormDE;
import edu.iu.grid.oim.view.divrep.form.SiteFormDE;

public class ServiceGroupEditServlet extends ServletBase implements Servlet {
	private static final long serialVersionUID = 1L;
	static Logger log = Logger.getLogger(ServiceGroupEditServlet.class);
	private String parent_page = "servicegroup";

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		UserContext context = new UserContext(request);
		Authorization auth = context.getAuthorization();
		auth.check("admin");

		ServiceGroupRecord rec;
		String title;

		try {
			//if site_id is provided then we are doing update, otherwise do new.
			String id_str = request.getParameter("id");
			if(id_str != null) {
				//pull record to update
				int id = Integer.parseInt(id_str);
				ServiceGroupModel model = new ServiceGroupModel(context);
				ServiceGroupRecord keyrec = new ServiceGroupRecord();
				keyrec.id = id;
				rec = model.get(keyrec);
				title = "Update "+rec.name;
			} else {
				rec = new ServiceGroupRecord();
				title = "New";
			}

			ServiceGroupFormDE form = new ServiceGroupFormDE(context, rec, parent_page);

			//put the form in a view and display
			ContentView contentview = new ContentView(context);
			//contentview.add(new HtmlView("<h1>"+title+"</h1>"));
			contentview.add(new DivRepWrapper(form));

			//setup crumbs
			BootBreadCrumbView bread_crumb = new BootBreadCrumbView();
			bread_crumb.addCrumb("Administration",  "admin");
			bread_crumb.addCrumb("Service Group",  parent_page);
			bread_crumb.addCrumb(title, null);
			contentview.setBreadCrumb(bread_crumb);

			BootPage page = new BootPage(context, new BootMenuView(context, "admin"), contentview, createSideView());

			page.render(response.getWriter());
		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

	private SideContentView createSideView()
	{
		SideContentView view = new SideContentView();
		//view.add("TODO", new HtmlView("Whatever"));
		return view;
	}
}


text:
//------------------------------------------------------------------------------
// Copyright (c) 2017 John D. Haughton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//------------------------------------------------------------------------------

#ifndef TRM_FRAME_H
#define TRM_FRAME_H

#include <cassert>
#include <cstdarg>

#include "STB/Fifo.h"

#include "PLT/Event.h"

#include "GUI/Font/Teletext.h"
#include "GUI/Frame.h"
#include "GUI/Bitmap.h"

#include "TRM/AnsiImpl.h"
#include "TRM/Device.h"

namespace TRM {

static const unsigned MIN_FONT_WIDTH  = 6;
static const unsigned MIN_FONT_HEIGHT = 8;

//! Terminal device using GUI::Frame back-end
template <unsigned WIDTH, unsigned HEIGHT>
class Frame
   : public Device
   , private AnsiImpl<WIDTH/MIN_FONT_WIDTH, HEIGHT/MIN_FONT_HEIGHT>
{
private:
   using Impl = AnsiImpl<WIDTH / MIN_FONT_WIDTH, HEIGHT / MIN_FONT_HEIGHT>;

   static const unsigned DEFAULT_BG_COL = 0;
   static const unsigned DEFAULT_FG_COL = 1;
   static const uint8_t  RGB_NRM        = 0xC0;

   GUI::Frame            frame;
   const GUI::Font*      font{};
   unsigned              border{0};
   unsigned              line_space{0};
   GUI::Vector           org;
   STB::Colour           default_bg_col{STB::BLACK};
   STB::Colour           default_fg_col{STB::WHITE};
   bool                  draw_cursor{true};
   unsigned              timeout_ms{0};
   unsigned              sleep_ms{0};
   GUI::Bitmap           sleep_image{};
   STB::Fifo<uint8_t, 6> response;
   bool                  shift{false};
   bool                  caps_lock{false};

   STB::Colour convertCol256ToRGB(uint8_t col, bool bg)
   {
      switch(col)
      {
      case  0: return STB::BLACK;
      case  1: return STB::RGB(RGB_NRM,       0,       0);
      case  2: return STB::RGB(      0, RGB_NRM,       0);
      case  3: return STB::RGB(RGB_NRM, RGB_NRM,       0);
      case  4: return STB::RGB(      0,       0, RGB_NRM);
      case  5: return STB::RGB(RGB_NRM,       0, RGB_NRM);
      case  6: return STB::RGB(      0, RGB_NRM, RGB_NRM);
      case  7: return STB::RGB(RGB_NRM, RGB_NRM, RGB_NRM);
      case  8: return bg ? default_bg_col : default_fg_col;
      case  9: return STB::RED;
      case 10: return STB::GREEN;
      case 11: return STB::YELLOW;
      case 12: return STB::BLUE;
      case 13: return STB::MAGENTA;
      case 14: return STB::CYAN;
      case 15: return STB::WHITE;

      default:
         if(col < 232)
         {
            col -= 16;
            uint8_t blu = (col % 6) * 51;
            col /= 6;
            uint8_t grn = (col % 6) * 51;
            col /= 6;
            uint8_t red = (col % 6) * 51;
            return STB::RGB(red, blu, grn);
         }
         else
         {
            col -= 232;
            uint8_t lvl = col * 11;
            return STB::GREY(lvl);
         }
      }
   }

   void screenSave(bool on)
   {
      frame.clear(default_bg_col);

      if (on)
      {
         if (sleep_image.getWidth() != 0)
         {
            frame.drawImage(sleep_image,
                            0, 0,
                            frame.getWidth(), frame.getHeight(),
                            0, 0);
         }
         PLT::Event::setTimer(0);
      }
      else
      {
         this->redraw();
         PLT::Event::setTimer(timeout_ms != 0 ? timeout_ms : sleep_ms);
      }

      frame.refresh();
   }

   // Implement AnsiImpl

   virtual void renderChar(unsigned            c,
                           unsigned            r,
                           uint8_t             ch,
                           typename Impl::Attr at) override
   {
      STB::Colour fg, bg;

      if(at.isInvert())
      {
         fg = convertCol256ToRGB(at.getBgCol(), /* bg */ true);
         bg = convertCol256ToRGB(at.getFgCol(), /* bg */ false);
      }
      else
      {
         fg = convertCol256ToRGB(at.getFgCol(), /* bg */ false);
         bg = convertCol256ToRGB(at.getBgCol(), /* bg */ true);
      }

      unsigned x = org.x + (c - 1) * font->getWidth();
      unsigned y = org.y + (r - 1) * (font->getHeight() + line_space);

      frame.fillRect(bg, x, y, x + font->getWidth(), y + font->getHeight() + line_space);

      frame.drawChar(fg, bg, x, y + line_space, font, ch);

      if(at.isBold())
      {
         frame.drawChar(fg, bg, x + 1, y + line_space, font, ch);
      }

      // TODO use an italic font for italics
      if(at.isUnderline() || at.isItalic())
      {
         frame.drawLine(fg, x, y + font->getHeight() - 1, x + font->getWidth(),
                        y + font->getHeight() - 1);
      }
   }

   virtual void returnString(const char* s) override
   {
      while(*s)
      {
         assert(!response.full());
         uint8_t ch = *s++;
         response.push(ch);
      }
   }

   uint8_t shiftChar(uint8_t ch)
   {
      if ((ch >= 'a') && (ch <= 'z'))
      {
         return ch - 'a' + 'A';
      }

      // TODO configurable to actual keyboard
      switch(ch)
      {
      case '1': return '!';
      case '2': return '@';
      case '3': return '#';
      case '4': return '$';
      case '5': return '%';
      case '6': return '^';
      case '7': return '&';
      case '8': return '*';
      case '9': return '(';
      case '0': return ')';
      case '-': return '_';
      case '=': return '+';
      case '[': return '{';
      case ']': return '}';
      case ';': return ':';
      case '\'': return '"';
      case '\\': return '|';
      case '`': return '~';
      case ',': return '<';
      case '.': return '>';
      case '/': return '?';

      case PLT::UP:   return PLT::PAGE_UP;
      case PLT::DOWN: return PLT::PAGE_DOWN;
      }

      return ch;
   }

   uint8_t getInput()
   {
      uint8_t ch{};

      if(!response.empty())
      {
         ch = response.back();
         response.pop();
         return ch;
      }

      PLT::Event::setTimer(timeout_ms != 0 ? timeout_ms : sleep_ms);

      bool screen_save{false};

      while(true)
      {
         PLT::Event::Message event;
         PLT::Event::Type    type = PLT::Event::wait(event);

         if (screen_save)
         {
            screenSave(/* on */false);
            screen_save = false;
         }
         else if(type == PLT::Event::QUIT)
         {
            ch = PLT::QUIT;
            break;
         }
         else if(type == PLT::Event::TIMER)
         {
            if(timeout_ms != 0)
            {
               ch = PLT::TIMEOUT;
               break;
            }

            screenSave(/* on */true);
            screen_save = true;
         }
         else if(type == PLT::Event::KEY_DOWN)
         {
            if((event.code == PLT::KeyCode::LSHIFT) ||
               (event.code == PLT::KeyCode::RSHIFT))
            {
               shift = true;
            }
            else if(event.code == PLT::KeyCode::CAPSLOCK)
            {
               caps_lock = !caps_lock;
            }
            else if((event.code == PLT::KeyCode::LCTRL) ||
                    (event.code == PLT::KeyCode::LALT)  ||
                    (event.code == PLT::KeyCode::LCMD)  ||
                    (event.code == PLT::KeyCode::RCMD)  ||
                    (event.code == PLT::KeyCode::RALT))
            {
                // Ignore these keys for now
            }
            else
            {
               if (shift || caps_lock)
               {
                  event.code = shiftChar(event.code);
               }

               if(this->isEchoEnabled() && (event.code < 0x80))
               {
                  this->ansiWrite(event.code);
               }

               ch = event.code;
               break;
            }
         }
         else if(type == PLT::Event::KEY_UP)
         {
            if((event.code == PLT::KeyCode::LSHIFT) ||
               (event.code == PLT::KeyCode::RSHIFT))
            {
               shift = false;
            }
         }
      }

      PLT::Event::setTimer(0);

      return ch;
   }

   void initLayout()
   {
      unsigned cols = (WIDTH - 2 * border) / font->getWidth();
      unsigned rows = (HEIGHT - 2 * border) / (font->getHeight() + line_space);

      this->resize(cols, rows);

      org.x = (WIDTH - (cols * font->getWidth())) / 2;
      org.y = border;

      frame.clear(default_bg_col);
   }

public:
   Frame(const char* title_)
      : frame(title_, WIDTH, HEIGHT)
      , font(&GUI::font_teletext15)
      , border(0)
      , line_space(0)
   {
      initLayout();
   }

   ~Frame() { frame.refresh(); }

   void setFont(const GUI::Font& font_)
   {
      font = &font_;
      initLayout();
   }

   // implement PLT::Device

   virtual int ioctl(unsigned request, ...) override
   {
      int     status = -1;
      va_list ap;

      va_start(ap, request);

      switch(request)
      {
      case IOCTL_TERM_ICANON:
         (void)va_arg(ap, int);
         status = 0;
         break;

      case IOCTL_TERM_ECHO:
         this->setEcho(va_arg(ap, int) != 0);
         status = 0;
         break;

      case IOCTL_TERM_PALETTE:
      {
         unsigned    col = va_arg(ap, unsigned);
         STB::Colour rgb = va_arg(ap, unsigned);
              if (col == DEFAULT_BG_COL) { default_bg_col = rgb; }
         else if (col == DEFAULT_FG_COL) { default_fg_col = rgb; }
         initLayout();
         status = 0;
      }
      break;

      case IOCTL_TERM_BORDER:
         border = va_arg(ap, unsigned);
         initLayout();
         status = 0;
         break;

      case IOCTL_TERM_LINE_SPACE:
         line_space = va_arg(ap, unsigned);
         initLayout();
         status = 0;
         break;

      case IOCTL_TERM_FONT_SIZE:
      {
         unsigned font_size = va_arg(ap, unsigned);

              if (font_size >= 18)  { setFont(GUI::font_teletext18); }
         else if (font_size >= 15)  { setFont(GUI::font_teletext15); }
         else if (font_size >= 12)  { setFont(GUI::font_teletext12); }
         else                       { setFont(GUI::font_teletext9);  }

         initLayout();
         status = 0;
      }
      break;

      case IOCTL_TERM_TIMEOUT_MS:
         timeout_ms = va_arg(ap, unsigned);
         status     = 0;
         break;

      case IOCTL_TERM_COLOURS:
         status = 256;
         break;

      case IOCTL_TERM_FONTS:
         status = 1;
         break;

      case IOCTL_TERM_CURSOR:
         draw_cursor = va_arg(ap, int) != 0;
         status = 0;
         break;

      case IOCTL_TERM_SLEEP:
         sleep_ms = va_arg(ap, unsigned) * 1000;
         status = 0;
         break;

      case IOCTL_TERM_SLEEP_IMAGE:
         if (sleep_image.readFromFile(va_arg(ap, const char*)))
         {
            status = 0;
         }
         break;

      default:
         break;
      }

      va_end(ap);

      return status;
   }

   virtual int write(const void* buffer, size_t n) override
   {
      const uint8_t* ptr = static_cast<const uint8_t*>(buffer);

      while(n--)
      {
         uint8_t ch = *ptr++;
         this->ansiWrite(ch);
      }

      return n;
   }

   virtual int read(void* buffer_, size_t n) override
   {
      uint8_t* buffer = static_cast<uint8_t*>(buffer_);

      size_t i;

      for(i = 0; i < n; i++)
      {
         if (draw_cursor) this->drawCursor(Impl::Cursor::BLOCK);
         frame.refresh();

         uint8_t ch = getInput();

         switch(ch)
         {
         case PLT::QUIT:
            this->drawCursor(Impl::Cursor::OFF);
            return -1;

         case PLT::TIMEOUT:
            this->drawCursor(Impl::Cursor::OFF);
            return 0;

         default:
            break;
         }

         buffer[i] = ch;
         if (draw_cursor) this->drawCursor(Impl::Cursor::OFF);
      }

      return i;
   }

   using Device::read;
   using Device::write;
};

} // namespace TRM

#endif // TRM_FRAME_H


text:
class CreateColorSchemeColors < ActiveRecord::Migration[5.1]
  def change
    create_table :color_scheme_colors do |t|
      t.integer :color_scheme_id
      t.integer :color_id

      t.timestamps
    end
  end
end


text:
module ActsAsArchival

  VERSION = "2.1.0".freeze

end


text:
import styles from './Header.css';
import Wrapper from './Wrapper';

import CSSModules from 'react-css-modules';
import { Link } from 'react-router'
import React from 'react';

export default CSSModules(class Header extends React.Component {
    render() {
        return (
            <header styleName='header'>
                <Wrapper>
                    <Link styleName='logoLink' to={'/'}>
                        <img src="/logo.png" width="45" height="39" alt="FlexiMaps"/>
                    </Link>
                </Wrapper>
            </header>
        );
    }
}, styles);