text:
module ActiveList
  # Manage data query
  class Generator
    # Generate select code for the table taking all parameters in account
    def select_data_code(options = {})
      paginate = (options.key?(:paginate) ? options[:paginate] : @table.paginate?)
      # Check order
      unless @table.options.keys.include?(:order)
        columns = @table.table_columns
        @table.options[:order] = (columns.any? ? columns.first.name.to_sym : { id: :desc })
      end

      class_name = @table.model.name
      class_name = "(controller_name != '#{class_name.tableize}' ? controller_name.to_s.classify.constantize : #{class_name})" if collection?

      # Find data
      query_code = class_name.to_s
      query_code << scope_code if scope_code
      query_code << ".select(#{select_code})" if select_code
      query_code << ".from(#{from_code})" if from_code
      query_code << ".where(#{conditions_code})" unless @table.options[:conditions].blank?
      query_code << ".joins(#{@table.options[:joins].inspect})" unless @table.options[:joins].blank?
      unless includes_reflections.empty?
        expr = includes_reflections.inspect[1..-2]
        query_code << ".includes(#{expr})"
        query_code << ".references(#{expr})"
      end

      code = ''
      code << "#{query_code}\n"

      code << if @table.options[:count].present?
                "#{var_name(:count)} = #{query_code}.count(#{@table.options[:count].inspect})\n"
              else
                "#{var_name(:count)} = #{query_code}.count\n"
              end
      query_code << ".group(#{@table.options[:group].inspect})" unless @table.options[:group].blank?
      query_code << ".reorder(#{var_name(:order)})"

      if paginate
        code << "#{var_name(:limit)}  = (#{var_name(:params)}[:per_page] || 25).to_i\n"

        code << "if params[:page]\n"
        code << "  #{var_name(:page)} = (#{var_name(:params)}[:page] || 1).to_i\n"
        code << "elsif params['#{table.name}-id'] and #{var_name(:index)} = #{query_code}.pluck(:id).index(params['#{table.name}-id'].to_i)\n"
        # Find page of request element
        code << "  #{var_name(:page)} = (#{var_name(:index)}.to_f / #{var_name(:limit)}).floor + 1\n"
        code << "else\n"
        code << "  #{var_name(:page)} = 1\n"
        code << "end\n"
        code << "#{var_name(:page)}   = 1 if #{var_name(:page)} < 1\n"

        code << "#{var_name(:offset)} = (#{var_name(:page)} - 1) * #{var_name(:limit)}\n"
        code << "#{var_name(:last)}   = (#{var_name(:count)}.to_f / #{var_name(:limit)}).ceil.to_i\n"
        code << "#{var_name(:last)}   = 1 if #{var_name(:last)} < 1\n"

        code << "return #{view_method_name}(options.merge(page: 1)) if 1 > #{var_name(:page)}\n"
        code << "return #{view_method_name}(options.merge(page: #{var_name(:last)})) if #{var_name(:page)} > #{var_name(:last)}\n"
        query_code << ".offset(#{var_name(:offset)})"
        query_code << ".limit(#{var_name(:limit)})"
      end

      code << "#{records_variable_name} = #{query_code} || {}\n"
      code
    end

    protected

    # Compute includes Hash
    def includes_reflections
      hash = []
      @table.columns.each do |column|
        hash << column.reflection.name if column.respond_to?(:reflection)
      end
      hash
    end

    def scope_code
      return nil unless scopes = @table.options[:scope]
      scopes = [scopes].flatten
      code = ''
      scopes.each do |scope|
        code << ".#{scope}"
      end
      code
    end

    # Generate the code from a conditions option
    def conditions_code
      conditions = @table.options[:conditions]
      code = ''
      case conditions
      when Array
        case conditions[0]
        when String # SQL
          code << '[' + conditions.first.inspect
          code << conditions[1..-1].collect { |p| ', ' + sanitize_condition(p) }.join if conditions.size > 1
          code << ']'
        when Symbol # Method
          raise 'What?' # Amazingly explicit.
        # code << conditions.first.to_s + '('
        # code << conditions[1..-1].collect { |p| sanitize_condition(p) }.join(', ') if conditions.size > 1
        # code << ')'
        else
          raise ArgumentError, 'First element of an Array can only be String or Symbol.'
        end
      when Hash # SQL
        code << '{' + conditions.collect { |key, value| key.to_s + ': ' + sanitize_condition(value) }.join(',') + '}'
      when Symbol # Method
        code << conditions.to_s + '(options)'
      when CodeString
        code << '(' + conditions.gsub(/\s*\n\s*/, ';') + ')'
      when String
        code << conditions.inspect
      else
        raise ArgumentError, "Unsupported type for conditions: #{conditions.inspect}"
      end
      code
    end

    def from_code
      return nil unless @table.options[:from]
      from = @table.options[:from]
      code = ''
      code << '(' + from.gsub(/\s*\n\s*/, ';') + ')'
      code
    end

    def select_code
      return nil unless @table.options[:distinct] || @table.options[:select]
      code = ''
      code << 'DISTINCT ' if @table.options[:distinct]
      if @table.options[:select]
        # code << @table.options[:select].collect { |k, v| ", #{k[0].to_s + '.' + k[1].to_s} AS #{v}" }.join
        code << @table.options[:select].collect do |k, v|
          c = if k.is_a? Array
                k[0].to_s + '.' + k[1].to_s
              else
                k
              end
          c += " AS #{v}" unless v.blank?
          c
        end.join(', ')
      else
        code << "#{@table.model.table_name}.*"
      end
      ("'" + code + "'").c
    end

    def sanitize_condition(value)
      # if value.is_a? Array
      #   # if value.size==1 and value[0].is_a? String
      #   #   value[0].to_s
      #   # else
      #   value.inspect
      #   # end
      # elsif value.is_a? CodeString
      #   value.inspect
      # elsif value.is_a? String
      #   '"' + value.gsub('"', '\"') + '"'
      # els
      if [Date, DateTime].include? value.class
        '"' + value.to_formatted_s(:db) + '"'
      elsif value.is_a? NilClass
        'nil'
      else
        value.inspect
      end
    end
  end
end


text:
/**
 * История комманд.
 *
 * @author dew1983@mail.ru <Suvorov Andrey M.>
 */

Ext.define(
	'FBEditor.command.HistoryCommand',
	{
		singleton: true,
		alternateClassName: 'FBEditor.HistoryCommand',

		/**
		 * @private
		 * @property {Ext.util.MixedCollection} Коллекция комманд.
		 */
		commands: null,

		/**
		 * @private
		 * @property {Number} Указывает на текущую команду в истории.
		 * Первая команда имеет индекс 0.
		 */
		currentIndex: -1,

		/**
		 * Инициализирует историю команд.
		 */
		init: function ()
		{
			var me = this;

			me.commands = new Ext.util.MixedCollection();
		},

		/**
		 * Добавляет в историю комманду.
		 * @param {FBEditor.command.InterfaceCommand} command Комманда.
		 */
		add: function (command)
		{
			var me = this,
				currentIndex;

			currentIndex = me.currentIndex;
			me.commands.add(currentIndex, command);
			currentIndex++;
			me.currentIndex = currentIndex;
		}
	}
);

redpajama_set_name: RedPajamaGithub


text:
export interface DatepickerDialogClosed extends Pick<DatepickerDialog, 'value'> {
  opened: boolean;
}
export type DatepickerDialogOpened = DatepickerDialogClosed & DatepickerFirstUpdated;

import '@material/mwc-button/mwc-button.js';
import { css, html, LitElement, property, query } from 'lit-element';

import type { WeekNumberType } from 'nodemod/dist/calendar/calendar_typing.js';
import { datepickerVariables } from './common-styles.js';
import type {
  DatepickerFirstUpdated,
  DatepickerValueUpdated,
  FocusTrap,
  HTMLElementPart,
  StartView,
} from './custom_typings.js';
import { KEY_CODES_MAP } from './custom_typings.js';
import type { Datepicker } from './datepicker.js';
import { animateElement } from './helpers/animate-element.js';
import { dispatchCustomEvent } from './helpers/dispatch-custom-event.js';
import { getResolvedDate } from './helpers/get-resolved-date.js';
import { getResolvedLocale } from './helpers/get-resolved-locale.js';
import { setFocusTrap } from './helpers/set-focus-trap.js';
import { toFormattedDateString } from './helpers/to-formatted-date-string.js';

export class DatepickerDialog extends LitElement {
  static get styles() {
    // tslint:disable: max-line-length
    return [
      datepickerVariables,
      css`
      :host {
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;

        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        z-index: var(--app-datepicker-dialog-z-index, 24);
        -webkit-tap-highlight-color: rgba(0,0,0,0);
      }

      .scrim,
      .content-container {
        pointer-events: auto;
      }

      .scrim {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: var(--app-datepicker-dialog-scrim-bg-color, rgba(0, 0, 0, .55));
        visibility: hidden;
        z-index: 22;
      }

      .content-container {
        position: absolute;
        top: 50%;
        left: 50%;
        max-width: 100%;
        max-height: 100%;
        background-color: var(--app-datepicker-bg-color, #fff);
        transform: translate3d(-50%, -50%, 0);
        border-radius: var(--app-datepicker-dialog-border-radius, 8px);
        will-change: transform, opacity;
        overflow: hidden;
        visibility: hidden;
        opacity: 0;
        z-index: 23;
        box-shadow: 0 24px 38px 3px rgba(0, 0, 0, 0.14),
                    0 9px 46px 8px rgba(0, 0, 0, 0.12),
                    0 11px 15px -7px rgba(0, 0, 0, 0.4);
      }

      .datepicker {
        --app-datepicker-border-top-left-radius: 8px;
        --app-datepicker-border-top-right-radius: 8px;
      }

      .actions-container {
        display: flex;
        align-items: center;
        justify-content: flex-end;

        margin: 0;
        padding: 12px;
        background-color: inherit;
        --mdc-theme-primary: var(--app-datepicker-accent-color, #1a73e8);
      }

      mwc-button[dialog-confirm] {
        margin: 0 0 0 8px;
      }

      .clear {
        margin: 0 auto 0 0;
      }

      /**
       * NOTE: IE11-only fix via CSS hack.
       * Visit https://bit.ly/2DEUNZu|CSS for more relevant browsers' hacks.
       */
      @media screen and (-ms-high-contrast: none) {
        mwc-button[dialog-dismiss] {
          min-width: 10ch;
        }
      }
      `,
    ];
    // tslint:enable: max-line-length
  }

  @property({ type: Number, reflect: true })
  public firstDayOfWeek: number = 0;

  @property({ type: Boolean, reflect: true })
  public showWeekNumber: boolean = false;

  @property({ type: String, reflect: true })
  public weekNumberType: WeekNumberType = 'first-4-day-week';

  @property({ type: Boolean, reflect: true })
  public landscape: boolean = false;

  @property({ type: String, reflect: true })
  public startView: StartView = 'calendar';

  @property({ type: String, reflect: true })
  public min?: string;

  @property({ type: String, reflect: true })
  public max?: string;

  @property({ type: String })
  public value: string = toFormattedDateString(getResolvedDate());

  @property({ type: String })
  public locale: string = getResolvedLocale();

  @property({ type: String })
  public disabledDays: string = '';

  @property({ type: String })
  public disabledDates?: string;

  @property({ type: String })
  public weekLabel: string = 'Wk';

  @property({ type: Number })
  public dragRatio: number = .15;

  @property({ type: String })
  public clearLabel: string = 'clear';

  @property({ type: String })
  public dismissLabel: string = 'cancel';

  @property({ type: String })
  public confirmLabel: string = 'set';

  @property({ type: Boolean })
  public noFocusTrap: boolean = false;

  @property({ type: Boolean })
  public alwaysResetValue: boolean = false;

  @query('.content-container')
  private _contentContainer?: HTMLDivElement;

  @query('mwc-button[dialog-confirm]')
  private _dialogConfirm?: HTMLElement;

  private _hasNativeWebAnimation: boolean = 'animate' in HTMLElement.prototype;
  private _focusable?: HTMLElement;
  private _focusTrap?: FocusTrap;
  private _opened: boolean = false;

  public async open(): Promise<void> {
    await this.updateComplete;

    if (this._opened) return;

    this.removeAttribute('aria-hidden');
    this.style.display = 'block';
    this._opened = true;

    if (this.alwaysResetValue && this._datepicker) this._datepicker.value = this.value;

    await this.requestUpdate();

    const contentContainer = this._contentContainer!;

    this._scrim!.style.visibility = contentContainer.style.visibility = 'visible';

    await animateElement(contentContainer, {
      hasNativeWebAnimation: this._hasNativeWebAnimation,
      keyframes: [
        { opacity: '0' },
        { opacity: '1' },
      ],
    });

    contentContainer.style.opacity = '1';

    const focusable = this._focusable!;

    if (!this.noFocusTrap) {
      this._focusTrap = setFocusTrap(this, [focusable, this._dialogConfirm!])!;
    }

    focusable.focus();

    dispatchCustomEvent<DatepickerDialogOpened>(this, 'datepicker-dialog-opened', {
      firstFocusableElement: focusable,
      opened: true,
      value: this.value,
    });
  }

  public async close(): Promise<void> {
    await this.updateComplete;

    if (!this._opened) return;

    this._opened = false;
    this._scrim!.style.visibility = '';

    const contentContainer = this._contentContainer!;

    await animateElement(contentContainer, {
      hasNativeWebAnimation: this._hasNativeWebAnimation,
      keyframes: [
        { opacity: '1' },
        { opacity: '0' },
      ],
    });

    contentContainer.style.opacity =
    contentContainer.style.visibility = '';

    this.setAttribute('aria-hidden', 'true');
    this.style.display = 'none';

    if (!this.noFocusTrap) this._focusTrap!.disconnect();

    dispatchCustomEvent<DatepickerDialogClosed>(
      this, 'datepicker-dialog-closed', { opened: false, value: this.value });
  }

  protected shouldUpdate() {
    return !this.hasAttribute('aria-hidden');
  }

  protected firstUpdated() {
    this.setAttribute('role', 'dialog');
    this.setAttribute('aria-label', 'datepicker');
    this.setAttribute('aria-modal', 'true');
    this.setAttribute('aria-hidden', 'true');
    this.addEventListener('keyup', (ev: KeyboardEvent) => {
      if (ev.keyCode === KEY_CODES_MAP.ESCAPE) this.close();
    });

    dispatchCustomEvent<DatepickerFirstUpdated>(this, 'datepicker-dialog-first-updated', {
      value: this.value,
      firstFocusableElement: this._focusable!,
    });
  }

  // tslint:disable-next-line: function-name
  protected _getUpdateComplete() {
    const datepicker = this._datepicker;

    return (
      datepicker ? datepicker.updateComplete : Promise.resolve()
    ).then(() => super._getUpdateComplete());
  }

  protected render() {
    return html`

    ${this._opened ? html`

    <app-datepicker class="datepicker"
      .min="${this.min}"
      .max="${this.max}"
      .firstDayOfWeek="${this.firstDayOfWeek}"
      .showWeekNumber="${this.showWeekNumber}"
      .weekNumberType="${this.weekNumberType}"
      .disabledDays="${this.disabledDays}"
      .disabledDates="${this.disabledDates}"
      .landscape="${this.landscape}"
      .locale="${this.locale}"
      .startView="${this.startView}"
      .value="${this.value}"
      .weekLabel="${this.weekLabel}"
      .dragRatio="${this.dragRatio}"
      @datepicker-first-updated="${this._setFocusable}"
      @datepicker-value-updated="${this._updateWithKey}"></app-datepicker>

        <mwc-button class="clear" part="clear" @click="${this._setToday}">${this.clearLabel}</mwc-button>

        <mwc-button part="dismiss" dialog-dismiss @click="${this.close}">${this.dismissLabel}</mwc-button>
        <mwc-button part="confirm" dialog-confirm @click="${this._update}">${this.confirmLabel}</mwc-button>

` : null}
    `;
  }

  private _padStart(val: number) {
    return `0${val}`.slice(-2);
  }

  private _setToday() {
    const today = getResolvedDate();
    const fy = today.getFullYear();
    const m = today.getMonth();
    const d = today.getDate();

    this._datepicker!.value = [`${fy}`].concat([1 + m, d].map(this._padStart)).join('-');
  }

  private _updateValue() {
    this.value = this._datepicker!.value;
  }

  private _update() {
    this._updateValue();

    return this.close();
  }

  private _updateWithKey(ev: CustomEvent<DatepickerValueUpdated>) {
    const { isKeypress, keyCode } = ev.detail;

    if (!isKeypress || keyCode !== KEY_CODES_MAP.ENTER && keyCode !== KEY_CODES_MAP.SPACE) return;

    return this._update();
  }

  private _setFocusable(ev: CustomEvent<DatepickerFirstUpdated>) {
    this._focusable = ev.detail && ev.detail.firstFocusableElement;
    this._updateValue();
  }

  private get _datepicker() {
    return this.shadowRoot!.querySelector<Datepicker>('.datepicker');
  }

  private get _scrim() {
    return this.shadowRoot!.querySelector<HTMLDivElement>('.scrim');
  }

}

declare global {
  // #region HTML element type extension
  interface HTMLElement {
    part: HTMLElementPart;
  }
  // #endregion HTML element type extension

  interface HTMLElementEventMap {
    'datepicker-dialog-closed': CustomEvent<DatepickerDialogClosed>;
    'datepicker-dialog-first-updated': CustomEvent<DatepickerFirstUpdated>;
    'datepicker-dialog-opened': CustomEvent<DatepickerDialogOpened>;
  }
}


text:
package notable

import (
	"bytes"
	"fmt"
	"os"
	"regexp"
	"text/template"
	"time"
)

type Variables struct {
	Today           string
	NotesByCategory []CategoryNotes
}

type CategoryNotes struct {
	Name  string
	Notes []Note
}

func (categoryNotes *CategoryNotes) Title() string {
	count := len(categoryNotes.Notes)
	announcements := pluralize(count, "Announcement")

	return fmt.Sprintf("#%s — %s", categoryNotes.Name, announcements)
}

func Email() string {
	var html bytes.Buffer

	notesTemplate, err := template.ParseFiles("template.html")
	check(err)

	today := time.Now().Add(-8 * time.Hour).Format("Monday, January 2, 2006")
	variables := Variables{today, notesByCategory()}
	err = notesTemplate.Execute(&html, variables)
	check(err)

	autolinkRegexp := regexp.MustCompile(`([^"])(\b([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))`)
	return autolinkRegexp.ReplaceAllString(html.String(), "$1$2")
}

func SendEmail() {
	subject := pluralize(len(Notes()), "Notable Announcement")
	if os.Getenv("POSTMARK_API_KEY") != "" {
		sendViaPostmark(subject, Email())
	} else {
		sendViaMandrill(subject, Email())
	}
}

func notesByCategory() []CategoryNotes {
	var category string
	grouped := make(map[string]*CategoryNotes, 0)

	for _, note := range Notes() {
		category = note.Category

		if _, found := grouped[category]; !found {
			grouped[category] = &CategoryNotes{Name: category, Notes: make([]Note, 0)}
		}

		grouped[category].Notes = append(grouped[category].Notes, note)
	}

	categoryNotes := make([]CategoryNotes, 0)

	for _, value := range grouped {
		categoryNotes = append(categoryNotes, *value)
	}

	return categoryNotes
}

func pluralize(count int, singularForm string) string {
	pluralForm := fmt.Sprintf("%s%s", singularForm, "s")

	if count == 1 {
		return fmt.Sprintf("1 %s", singularForm)
	} else {
		return fmt.Sprintf("%d %s", count, pluralForm)
	}
}


text:
package de.mirkosertic.bytecoder.core;

public abstract class BytecodeInstruction {

    private final BytecodeOpcodeAddress opcodeAddress;

    public BytecodeInstruction(final BytecodeOpcodeAddress aOpcodeAddress) {
        opcodeAddress = aOpcodeAddress;
    }

    public BytecodeOpcodeAddress getOpcodeAddress() {
        return opcodeAddress;
    }

    public BytecodeOpcodeAddress[] getPotentialJumpTargets() {
        return new BytecodeOpcodeAddress[0];
    }

    public boolean isJumpSource() {
        return false;
    }
}


text:
define(function (require) {

    var $ = require('jquery');
    var $q = require('q');
    var $auth = require('common/auth');
    var $route = require('common/route');
    var $messageHandler = require('common/messagehandler');
    var $event = require('common/event');

    function XhrParser(xhrObj) {
        var xhr = xhrObj;
        this.getError = function (context) {
            return {
                context: context,
                statusCode: xhr.status,
                message: xhr.statusText,
	            //authorizationFailed: false
                authorizationFailed: (xhr.readyState === 0 && xhr.status === 0) || xhr.status === 401
            }
        }
    }

    function Failure(deferred, url) {
        var d = deferred;
        var context = url;
        this.func = function (xhr) {
            var error = new XhrParser(xhr).getError(context);

            if (error.authorizationFailed) {
	            if(!$route.isLoginPage()) {
		            $route.storePage();
                    $route.gotoLoginPage();
	            }
            }
            else if (error.statusCode === 404)
            {
	            // noop
            }
            else{
	            console.error(error);
                $messageHandler.showError("Infelizmente houve uma falha na comunicação.");
            }

            d.reject(error);
        }
    }

    function HttpConfiguration(config) {

	    this.authRequired = config ? config : {authRequired: true};
        this.contentType = 'application/json'
    }

	function RequestInterceptor( config){

		this.intercept = function (xhr, obj) {
			$event.emitEvent('loading-started');
			if (config.authRequired) {
				$auth.applyAuth(xhr);
			}
		}

	}

    function ResponseInterceptor(deferred) {

        var _deferred = deferred;

	    this.success = function (data, status, xhr){
		    var xtoken = xhr.getResponseHeader('Authorization');
		    if (xtoken) {
			    $auth.setAuthToken(xtoken);
		    }
		    _deferred.resolve(data);
	    };

        this.finished = function (xhr, status) {
	        $event.emitEvent('loading-finished');
        }

    }

    return {

        get: function (url, params, config) {
            var deferred = $q.defer();

	        var httpConfiguration = new HttpConfiguration(config);
	        var requestInterceptor = new RequestInterceptor(httpConfiguration);
            var responseInterceptor = new ResponseInterceptor(deferred);

            $.ajax({
                url: url,
                type: 'GET',
                data: params,
                crossDomain: true,
                success: responseInterceptor.success,
	            complete: responseInterceptor.finished,
                beforeSend: requestInterceptor.intercept
            }).fail(new Failure(deferred, url).func);

            return deferred.promise;
        },
        post: function (url, data, config) {
            var deferred = $q.defer();

	        var httpConfiguration = new HttpConfiguration(config);
	        var requestInterceptor = new RequestInterceptor(httpConfiguration);
	        var responseInterceptor = new ResponseInterceptor(deferred);

	        $.ajax({
                url: url,
                type: 'POST',
                data: JSON.stringify(data),
                processData: false,
                success: responseInterceptor.success,
	            complete: responseInterceptor.finished,
                beforeSend: requestInterceptor.intercept,
                contentType: httpConfiguration.contentType
            }).fail(new Failure(deferred, url).func);

            return deferred.promise;
        },
        put: function (url, data, config) {
            var deferred = $q.defer();

	        var httpConfiguration = new HttpConfiguration(config);
	        var requestInterceptor = new RequestInterceptor(httpConfiguration);
	        var responseInterceptor = new ResponseInterceptor(deferred);

            $.ajax({
                url: url,
                type: 'PUT',
                data: JSON.stringify(data),
                processData: false,
	            success: responseInterceptor.success,
	            complete: responseInterceptor.finished,
	            beforeSend: requestInterceptor.intercept,
                contentType: httpConfiguration.contentType
            }).fail(new Failure(deferred, url).func);

            return deferred.promise;
        },
        remove: function (url, config) {
            var deferred = $q.defer();

	        var httpConfiguration = new HttpConfiguration(config);
	        var requestInterceptor = new RequestInterceptor(httpConfiguration);
	        var responseInterceptor = new ResponseInterceptor(deferred);

            $.ajax({
                url: url,
                type: 'DELETE',
	            success: responseInterceptor.success,
	            complete: responseInterceptor.finished,
	            beforeSend: requestInterceptor.intercept
            }).fail(new Failure(deferred, url).func);

            return deferred.promise;
        }
    }
});


text:
class AddDefaultValueColumnToEnumerations < ActiveRecord::Migration
  def change
  	add_column :enumerations, :default, :boolean
  end
end