text:
import math
import random
import functools
from collections import Counter
import logging
from datetime import datetime, date, timedelta as td
import csv
import io

class Rota:
    _days = [1,2,3,4,5]
    _start = 0
    _end = 0
    _bank_holidays = [datetime.strptime("2016/12/26","%Y/%m/%d"),
                        datetime.strptime("2016/12/27","%Y/%m/%d"),
                        datetime.strptime("2017/01/02","%Y/%m/%d"),
                        datetime.strptime("2017/01/03","%Y/%m/%d"),
                        datetime.strptime("2017/04/14","%Y/%m/%d"),
                        datetime.strptime("2017/04/17","%Y/%m/%d"),
                        datetime.strptime("2017/05/01","%Y/%m/%d"),
                        datetime.strptime("2017/05/29","%Y/%m/%d"),
                        datetime.strptime("2017/07/17","%Y/%m/%d"),
                        datetime.strptime("2017/09/25","%Y/%m/%d"),
                        datetime.strptime("2017/12/25","%Y/%m/%d"),
                        datetime.strptime("2017/12/26","%Y/%m/%d"),
                        datetime.strptime("2018/01/01","%Y/%m/%d"),
                        datetime.strptime("2017/01/02","%Y/%m/%d")]
    _persons = []
    _haystack = []
    _rota = []
    _min_days = 3
    _type = "ooh"

    _attempts = 1000

    def __init__(self, start_date, end_date, persons, type="ooh"):
        self._start = start_date
        self._end = end_date
        self._persons = persons
        if type == "gentrim" or type == "general trim" :
            self._days = [1,2,4,5]
            self._type = "gentrim"
            self._min_days = 14
        logging.debug("Rota for %d days." % self._get_days())

    def _get_workdays(self):
        workdays = 0
        for person in self._persons:
            workdays += len(person._days_worked)
        return workdays

    def _get_days(self):
        days = self._end - self._start
        number_days = 0
        for i in range(days.days + 1):
            d = self._start + td(days=i)
            if d.isoweekday() in self._days:
                number_days += 1
        return number_days

    def _ooh_coefficient(self):
        total_days = self._get_days()
        days = total_days
        workdays = self._get_workdays()
        logging.debug("Days: %d; Workdays: %d; Persons: %d" % (days, workdays, len(self._persons)))
        ooh_coefficient = ((days / len(self._persons))) / ((workdays / len(self._persons)) /5)
        return ooh_coefficient

    def _build_haystack(self):
        total_days = self._get_days()
        days = total_days
        k = self._ooh_coefficient()
        haystack = []
        for person in self._persons:
            num = int(round(len(person._days_worked)/5 * k))
            for i in range(0,num):
                haystack.append(person._name)

        while len(haystack) > days:
            haystack.pop(random.randint(0,len(haystack)-1))

        while len(haystack) < days:
            person = self._persons[random.randint(0,len(self._persons)-1)]
            haystack.append(person._name)

        logging.debug(haystack)
        logging.debug(len(haystack))

        return haystack

    def _do_rota(self, haystack):
        rota = []
        total_days = self._get_days()
        days = self._end - self._start
        for i in range(0, days.days+1):
            day = self._start + td(days=i)
            if day not in self._bank_holidays and day.isoweekday() in self._days :
                logging.debug ("Doing day %d of %d..." % (i, days.days))
                selected = False
                attempt = 0
                while not selected and attempt < (len(haystack) * 3):
                    choice = random.randint(0,len(haystack)-1)
                    logging.debug("Trying number %d of %d" % (choice, len(haystack)))
                    for person in self._persons:
                        if selected == False:
                            if person._name == haystack[choice]:
                                logging.debug("Found %s." % (haystack[choice]))
                                if person.can_work(day) and person._name not in rota[-self._min_days:]:
                                    logging.debug("%s is a HIT." % (haystack[choice]))
                                    selected = True
                                    rota.append(haystack.pop(choice))
                                else:
                                    logging.debug("%s is a miss." % (haystack[choice]))

                    attempt += 1
                if not selected:
                    return None
            elif day.isoweekday() not in self._days:
                rota.append("---------")
            else:
                rota.append("BANK HOLIDAY")
        return rota

    def go(self):
        haystack = self._build_haystack()
        success = False
        attempt = 0
        while not success and attempt <= self._attempts:
            logging.debug("ATTEMPT %s" % attempt)
            copy_haystack = [h for h in haystack]

            rota = self._do_rota(copy_haystack)

            if self._type != "ooh":
                success = True
            else:
                if rota is not None:
                    days = self._end - self._start
                    fridays =  []
                    j = 0
                    for i in range(0, days.days + 1):
                        day = self._start + td(days=i)
                        if day.isoweekday() == 5:
                            fridays.append(rota[i])

                    work_fridays = []
                    for person in self._persons:
                        if 5 in person._days_worked:
                            work_fridays.append(person._name)

                    fridays_people = {}
                    for person in fridays:
                        if person not in fridays_people and person != "BANK HOLIDAY" and person != "---------":
                            fridays_people[person] =  fridays.count(person)

                    max_fridays = 0
                    logging.debug("Fridays:")
                    logging.debug(fridays)
                    for person,worked in fridays_people.items():
                        max_fridays = worked if worked > max_fridays else max_fridays

                    logging.debug("The most Fridays worked is %d." % max_fridays)

                    min_fridays = 1000
                    for person in self._persons:
                        if 5 in person._days_worked:
                            min_fridays = fridays.count(person._name) if fridays.count(person._name) < min_fridays else min_fridays
                    logging.debug("The least Fridays worked is %d." % min_fridays)

                    if max_fridays <= min_fridays + 1:
                        success = True
                attempt += 1
            logging.debug(rota)
        if success:
            self._rota = rota
            logging.info("SUCCEEDED ON ATTEMPT: %d" % attempt)
        else:
            logging.critical("FAILED TO CREATE ROTA.")
        return success

    def print_rota(self):
        total_days = self._get_days()
        days = self._end - self._start
        fridays = []
        print ("|    Day   | %s | %s |" % ("Weekday".ljust(9), "Name".ljust(13)))
        print ("|:--------:|:----------|:--------------|")
        for i in range(0, days.days + 1):
            day = self._start + td(days=i)
            print("| %s | %s | %s |" % (day.strftime("%d/%m/%y"), day.strftime("%A").ljust(9), self._rota[i].ljust(13)))
            if day.isoweekday() == 5:
                fridays.append(self._rota[i])
        print()
        print()

    def md_rota(self, show_fridays=False):
        total_days = self._get_days()
        days = self._end - self._start
        fridays = []
        md = "|    Day   | %s | %s |\n" % ("Weekday".ljust(9), "Name".ljust(13))
        md += "|:--------:|:----------|:--------------|\n"
        for i in range(0, days.days + 1):
            day = self._start + td(days=i)
            md += "| %s | %s | %s |\n" % (day.strftime("%d/%m/%y"), day.strftime("%A").ljust(9), self._rota[i].ljust(13))
            if day.isoweekday() == 5:
                fridays.append(self._rota[i])

        if show_fridays:
            md += "\n| Name          | Fridays |\n"
            md +=   "|:--------------|:--------|\n"

            for p in self._persons:
                md += "| %s | %s |\n" %(p._name.ljust(13), str(fridays.count(p._name)).ljust(7))
        return md

    def rota_csv(self):
        total_days = self._get_days()
        days = self._end - self._start
        csv_output  = io.StringIO()
        fieldnames=['Subject','Start Date','All Day Event']
        if self._type == "gentrim":
            fieldnames = ['Subject','Start Date','Start Time', 'End Time']
        writer = csv.DictWriter(csv_output, fieldnames=fieldnames)
        writer.writeheader()

        for i in range(0, days.days + 1):
            day = self._start + td(days=i)
            if self._rota[i] != "---------" and self._rota[i] != "BANK HOLIDAY":
                if self._type == "gentrim":
                    writer.writerow({'Subject':self._rota[i], 'Start Date':day.strftime("%Y/%m/%d"),'Start Time':'1:00 PM','End Time':'2:00 PM'})
                else:
                    writer.writerow({'Subject':self._rota[i], 'Start Date':day.strftime("%Y/%m/%d"),'All Day Event':'True'})

        return csv_output.getvalue()

class Person:
    _name = ""
    _days_worked = []
    _days_off = []

    def __init__(self, name, days_worked, days_off):
        self._name = name
        self._days_worked = days_worked
        self._days_off = days_off

    def can_work(self, day):
        if day not in self._days_off and day.isoweekday() in self._days_worked:
            return True
        return False


text:
<?php

/**
 * CodeMommy WebPHP
 * @author Candison November <www.kandisheng.com>
 */

namespace CodeMommy\Script;

use CodeMommy\TaskPHP\Console;
use CodeMommy\TaskPHP\PHP;
use CodeMommy\DevelopPHP\Clean;

/**
 * Class Run
 * @package CodeMommy\Script
 */
class Run
{
    /**
     * Run constructor.
     */
    public function __construct()
    {
    }

    /**
     * Start
     */
    public static function start()
    {
        Clean::workbench();
        Console::printLine('Visit http://localhost', 'information');
        PHP::run('public');
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import * as typemoq from 'typemoq';
import { LaunchBrowserCommand } from '../../../../client/application/diagnostics/commands/launchBrowser';
import { IDiagnostic, IDiagnosticCommand } from '../../../../client/application/diagnostics/types';
import { IBrowserService } from '../../../../client/common/types';
import { IServiceContainer } from '../../../../client/ioc/types';

suite('Application Diagnostics - Commands Launch Browser', () => {
    let cmd: IDiagnosticCommand;
    let serviceContainer: typemoq.IMock<IServiceContainer>;
    let diagnostic: typemoq.IMock<IDiagnostic>;
    const url = 'xyz://abc';
    setup(() => {
        serviceContainer = typemoq.Mock.ofType<IServiceContainer>();
        diagnostic = typemoq.Mock.ofType<IDiagnostic>();
        cmd = new LaunchBrowserCommand(diagnostic.object, serviceContainer.object, url);
    });

    test('Invoking Command should launch the browser', async () => {
        const browser = typemoq.Mock.ofType<IBrowserService>();
        serviceContainer
            .setup((s) => s.get(typemoq.It.isValue(IBrowserService)))
            .returns(() => browser.object)
            .verifiable(typemoq.Times.once());
        browser.setup((s) => s.launch(typemoq.It.isValue(url))).verifiable(typemoq.Times.once());

        await cmd.invoke();
        serviceContainer.verifyAll();
    });
});


text:
import { existsAsync, mkdirAsync } from 'fs-extra-promise';
import { join } from 'path';
import {
  mainAnswers,
  bundlesDir,
} from '../utils';

const questions = [
  {
    type: 'input',
    name: 'bundleName',
    message: 'Bundle name',
    async validate(name) {
      if (await existsAsync(join(bundlesDir, name))) {
        return `Bundle "${name}" already exists`;
      }

      return true;
    },
  },
];

mainAnswers(questions, async (context) => {
  const directory = join(bundlesDir, context.bundleName);

  await mkdirAsync(directory);
  await mkdirAsync(join(directory, 'components'));
});


text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: NCA.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="NCA" comment="To specify the action that is to be taken in response to a nonconformance condition">
  <Field name="AssignedIdentification" required="y" min="1" max="20" comment="Alphanumeric characters assigned for differentiation within a transaction set"/>
  <Field name="NonconformanceResultantResponseCode" required="y" min="1" max="2" validation="T887" comment="Code identifying a response that is the result of a nonconformance situation"/>
  <Field name="Description" required="y" min="1" max="80" comment="A free-form description to clarify the related data elements and their content"/>
  <Field name="Quantity" type="double" required="y" min="1" max="15" comment="Numeric value of quantity"/>
  <Field name="CompositeUnitOfMeasure" type="C001" required="y" min="0" max="inf" comment="To identify a composite unit of measure (See Figures Appendix for examples of use)"/>
</Segment>


text:
exports.View =
{
    title: "{{{name}}}",
    elements:
    [
        { control: "text", value: "{{{description}}}", fontsize: 12 },

        { control: "stackpanel", orientation: "Horizontal", contents: [
            { control: "text", value: "Name:", fontsize: 12, width: 200, textAlignment: "Right", margin: { top: 10, right: 10 } },
            { control: "edit", fontsize: 12, width: 200, binding: "name" },
        ] },

        { control: "text", value: "Welcome to Synchro {name}", fontsize: 12 },
    ]
}

exports.InitializeViewModel = function(context, session)
{
    var viewModel =
    {
        name: ""
    }
    return viewModel;
}


text:
/*	$OpenBSD: strlcat.c,v 1.18 2016/10/16 17:37:39 dtucker Exp $	*/

/*
 * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdc.h>

/*
 * Appends src to string dst of size dsize (unlike strncat, dsize is the
 * full size of dst, not space left).  At most dsize-1 characters
 * will be copied.  Always NUL terminates (unless dsize <= strlen(dst)).
 * Returns strlen(src) + MIN(dsize, strlen(initial dst)).
 * If retval >= dsize, truncation occurred.
 */
size_t
strlcat(char *dst, const char *src, size_t dsize)
{
	const char *odst = dst;
	const char *osrc = src;
	size_t n = dsize;
	size_t dlen;

	/* Find the end of dst and adjust bytes left but don't go past end. */
	while (n-- != 0 && *dst != '\0')
		dst++;
	dlen = dst - odst;
	n = dsize - dlen;

	if (n-- == 0)
		return(dlen + strlen(src));
	while (*src != '\0') {
		if (n != 0) {
			*dst++ = *src;
			n--;
		}
		src++;
	}
	*dst = '\0';

	return(dlen + (src - osrc));	/* count does not include NUL */
}


text:
package com.fpt.mic.micweb.model.dto.form;

import com.fpt.mic.micweb.model.dao.CustomerDao;
import com.fpt.mic.micweb.utils.ConfigUtils;
import com.fpt.mic.micweb.utils.DateUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.*;
import javax.validation.constraints.Pattern;
import java.sql.Timestamp;
import java.util.Date;

/**
 * Created by TriPQM on 06/23/2015.
 */
public class PublicHomeFormDto {
    @NotEmpty(message = "Họ tên không được để trống")
    @Pattern(regexp = "\\S[^0-9!@#$%^&*()+=~`]+", message = "Họ tên không hợp lệ")
    @Size(min = 3, max = 80, message = "Họ tên phải từ {min} đến {max} ký tự")
    private String name;
    @NotEmpty(message = "Email không được để trống")
    @Pattern(regexp = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,3}$", message = "Email không hợp lệ")
    private String email;
    @NotEmpty(message = "Số điện thoại không được để trống")
    @Pattern(regexp = "[0-9]+", message = "Số điện thoại không hợp lệ")
    @Size(min = 8, max = 15, message = "Số điện thoại phải từ {min} đến {max} ký tự")
    private String phone;
    //    @Pattern(regexp = "[0-9]+",message = "Số CMND/Hộ chiếu không hợp lệ")
//    @Size(min = 8, max = 15, message = "Số CMND/Hộ chiếu phải từ {min} đến {max} ký tự")
    private String personalId;
    @NotEmpty(message = "Địa chỉ không được để trống")
    @Size(min = 3, max = 250, message = "Địa chỉ phải từ {min} đến {max} ký tự")
    private String address;
    @NotNull(message = "Ngày bắt đầu không được để trống")
    private Timestamp startDate;
    @NotNull(message = "Quyền lợi bảo hiểm không được để trống")
    private Integer contractType;
    @NotNull(message = "Phí bảo hiểm không được để trống")
    @Range(min = 0, message = "Phí bảo hiểm phải lớn hơn {min}")
    private Float contractFee;

    private Integer captchaFirstNumber;
    private Integer captchaSecondNumber;
    private Integer captchaTotalNumber;

    @AssertTrue(message = "Ngày bắt đầu phải kể từ ngày hôm nay trở đi")
    private boolean isValidStartDate() {
        if (startDate != null) {
            Timestamp currentDate = DateUtils.currentDateWithoutTime();
            return !startDate.before(currentDate);
        }
        return false;
    }

    @AssertTrue(message = "Ngày bắt đầu không được sau thời gian quy định")
    private boolean isValidStartDateMax() {
        if (startDate != null) {
            ConfigUtils configUtils = new ConfigUtils();
            Timestamp startDateMax = new Timestamp(configUtils.getStartDateMax().toDateTimeAtStartOfDay().getMillis());
            return !startDate.after(startDateMax);
        }
        return false;
    }

    @AssertTrue(message = "Số CMND/Hộ chiếu không hợp lệ")
    public boolean isValidPersonalId() {
        if (personalId == null || personalId.isEmpty()) {
            return true;
        } else {
            if (personalId.length() > 7 && personalId.length() < 16) {
                java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[0-9]+");
                return pattern.matcher(personalId).matches();
            }
            return false;
        }
    }

    @AssertTrue(message = "Email đã được đăng ký bởi người dùng khác")
    public boolean isValidEmail() {
        CustomerDao customerDao = new CustomerDao();
        return !customerDao.isExistByEmail(email);
    }

    @AssertTrue(message = "Trả lời câu hỏi bảo mật không chính xác")
    public boolean isCaptchaValid() {
        return captchaFirstNumber != null
                && captchaSecondNumber != null
                && captchaTotalNumber != null
                && captchaFirstNumber + captchaSecondNumber == captchaTotalNumber;
    }

    private String plate;
    private String brand;
    private String chassis;
    private String engine;
    private String capacity;
    private String type;
    private String model;
    private String color;
    private Integer yearOfMan;
    private Integer weight;
    private Integer seatCapacity;

    public String getPlate() {
        return plate;
    }

    public void setPlate(String plate) {
        this.plate = plate;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getChassis() {
        return chassis;
    }

    public void setChassis(String chassis) {
        this.chassis = chassis;
    }

    public String getEngine() {
        return engine;
    }

    public void setEngine(String engine) {
        this.engine = engine;
    }

    public String getCapacity() {
        return capacity;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Integer getYearOfMan() {
        return yearOfMan;
    }

    public void setYearOfMan(Integer yearOfMan) {
        this.yearOfMan = yearOfMan;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    public Integer getSeatCapacity() {
        return seatCapacity;
    }

    public void setSeatCapacity(Integer seatCapacity) {
        this.seatCapacity = seatCapacity;
    }

    public Integer getCaptchaFirstNumber() {
        return captchaFirstNumber;
    }

    public void setCaptchaFirstNumber(Integer captchaFirstNumber) {
        this.captchaFirstNumber = captchaFirstNumber;
    }

    public Integer getCaptchaSecondNumber() {
        return captchaSecondNumber;
    }

    public void setCaptchaSecondNumber(Integer captchaSecondNumber) {
        this.captchaSecondNumber = captchaSecondNumber;
    }

    public Integer getCaptchaTotalNumber() {
        return captchaTotalNumber;
    }

    public void setCaptchaTotalNumber(Integer captchaTotalNumber) {
        this.captchaTotalNumber = captchaTotalNumber;
    }

    public PublicHomeFormDto() {
    }

    public PublicHomeFormDto(String name, String email, String phone, String personalId, String address,
                             Timestamp startDate, Integer contractType, Float contractFee) {
        this.name = name;
        this.email = email;
        this.phone = phone;
        this.personalId = personalId;
        this.address = address;
        this.startDate = startDate;
        this.contractType = contractType;
        this.contractFee = contractFee;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPersonalId() {
        return personalId;
    }

    public void setPersonalId(String personalId) {
        this.personalId = personalId;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Timestamp getStartDate() {
        return startDate;
    }

    public void setStartDate(Timestamp startDate) {
        this.startDate = startDate;
    }

    public Integer getContractType() {
        return contractType;
    }

    public void setContractType(Integer contractType) {
        this.contractType = contractType;
    }

    public Float getContractFee() {
        return contractFee;
    }

    public void setContractFee(Float contractFee) {
        this.contractFee = contractFee;
    }
}


text:
package ru.job4j.chess;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Проверка.
 *
 * @author imoskovtsev
 */
public class ChessboardTest extends TestBase {
    /**
     * Правило для проверки исключений.
     */
    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    /**
     * Конструктор.
     *
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     */
    public ChessboardTest() throws ImpossibleMoveException {
    }

    /**
     * Слон C1->D2.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveBishopC1toD2() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Bishop(c1);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(c1, d2);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterD));
        assertThat(resultNumber, is(number2));
    }

    /**
     * Слон C1->E3.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveBishopC1toE3() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Bishop(c1);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(c1, e3);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterE));
        assertThat(resultNumber, is(number3));
    }

    /**
     * Слон C8->B7.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveBishopC8toB7() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Bishop(c8);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(c8, b7);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterB));
        assertThat(resultNumber, is(number7));
    }

    /**
     * Слон C8->B7.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveBishopC8toD7() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Bishop(c8);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(c8, d7);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterD));
        assertThat(resultNumber, is(number7));
    }

    /**
     * Слон. В начальной ячейке нет фигуры.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveBishopFigureNotFound() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Bishop(c1);
        chessboard = new Chessboard(chessPieces);

        thrown.expect(FigureNotFoundException.class);
        thrown.expectMessage("В начальной ячейке нет фигуры.");
        chessboard.move(c8, d2);
    }

    /**
     * Слон. Фигура не может туда пойти.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveBishopImpossibleMoveException() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Bishop(c1);
        chessboard = new Chessboard(chessPieces);

        thrown.expect(ImpossibleMoveException.class);
        thrown.expectMessage(IMPOSSIBLE_MOVE);
        chessboard.move(c1, c2);
    }

    /**
     * Слон. Путь занят фигурами.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveBishopOccupiedWayException() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        ChessPiece[] chessPieces = new ChessPiece[2];
        chessPieces[0] = new Bishop(c1);
        chessPieces[1] = new Bishop(d2);
        chessboard = new Chessboard(chessPieces);

        thrown.expect(OccupiedWayException.class);
        thrown.expectMessage("Путь занят фигурами.");
        chessboard.move(c1, d2);
    }

    /**
     * Пешка А2->А3.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMovePawnA2toA3() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Pawn(a2);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(a2, a3);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterA));
        assertThat(resultNumber, is(number3));
    }

    /**
     * Пешка B2->B4.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMovePawnB2toB4() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Pawn(b2);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(b2, b4);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterB));
        assertThat(resultNumber, is(number4));
    }

    /**
     * Пешка C2->C5. Фигура не может туда пойти.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMovePawnImpossibleMoveException() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Pawn(c2);
        chessboard = new Chessboard(chessPieces);

        thrown.expect(ImpossibleMoveException.class);
        thrown.expectMessage(IMPOSSIBLE_MOVE);
        chessboard.move(c2, c5);
    }

    /**
     * Ладья А1->А8.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveCastleA1toA8() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Castle(a1);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(a1, a8);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterA));
        assertThat(resultNumber, is(number8));
    }

    /**
     * Ладья А1->H1.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveCastleA1toH1() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Castle(a1);
        chessboard = new Chessboard(chessPieces);

        chessboard.move(a1, h1);
        int resultLetter = chessboard.getChessPieces()[0].getCurrentPosition().getLetter();
        int resultNumber = chessboard.getChessPieces()[0].getCurrentPosition().getNumber();

        assertThat(resultLetter, is(letterH));
        assertThat(resultNumber, is(number1));
    }

    /**
     * Ладья A1->B2. Фигура не может туда пойти.
     *
     * @throws FigureNotFoundException В начальной ячейке нет фигуры.
     * @throws ImpossibleMoveException Координата за пределами шахматной доски. Фигура не может туда пойти.
     * @throws OccupiedWayException    Путь занят фигурами.
     */
    @Test
    public void shouldMoveCastleImpossibleMoveException() throws FigureNotFoundException, ImpossibleMoveException, OccupiedWayException {
        chessPieces[0] = new Castle(a1);
        chessboard = new Chessboard(chessPieces);

        thrown.expect(ImpossibleMoveException.class);
        thrown.expectMessage(IMPOSSIBLE_MOVE);
        chessboard.move(a1, b2);
    }
}


text:
{% if site.fb-share %}

{% endif %}


text:
package com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Cache;

import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCachedExpressionTree;
import com.google.security.zynamics.zylib.general.ListenerProvider;
import com.google.security.zynamics.zylib.types.lists.FilledList;
import com.google.security.zynamics.zylib.types.lists.IFilledList;

/**
 * Keeps track of previously executed Select by Criteria trees and stores them for later reuse.
 */
public final class CCriteriumCache {
  /**
   * Maximum number of items in the cache.
   */
  private static final int MAXIMUM_CACHE_SIZE = 10;

  /**
   * Cached trees for later reuse.
   */
  private final IFilledList<CCachedExpressionTree> m_trees =
      new FilledList<>();

  /**
   * Listeners that are notified about changed in the criterium cache.
   */
  private final ListenerProvider<ICriteriumCacheListener> m_listeners =
      new ListenerProvider<>();

  /**
   * Adds a new expression tree to the cache.
   *
   * @param tree The tree to cache.
   */
  public void add(final CCachedExpressionTree tree) {
    for (final CCachedExpressionTree cachedTree : m_trees) {
      // Don't store duplicate formulas

      if (cachedTree.getFormulaString().equals(tree.getFormulaString())) {
        return;
      }
    }

    m_trees.add(tree);

    while (m_trees.size() > MAXIMUM_CACHE_SIZE) {
      m_trees.remove(0);
    }

    for (final ICriteriumCacheListener listener : m_listeners) {
      try {
        listener.changedCriteria(this);
      } catch (final Exception exception) {
        CUtilityFunctions.logException(exception);
      }
    }
  }

  /**
   * Adds a listener object that is notified about changes in the criterium cache.
   *
   * @param listener The listener object to add.
   */
  public void addListener(final ICriteriumCacheListener listener) {
    m_listeners.addListener(listener);
  }

  /**
   * Returns the cached expression trees.
   *
   * @return The cached expression trees.
   */
  public IFilledList<CCachedExpressionTree> getTrees() {
    return new FilledList<CCachedExpressionTree>(m_trees);
  }

  /**
   * Removes a listener object that was previously added to the criterium cache.
   *
   * @param listener The listener object to remove.
   */
  public void removeListener(final ICriteriumCacheListener listener) {
    m_listeners.removeListener(listener);
  }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.11.22 at 01:45:09 PM EST
//

package uk.org.siri.siri_2;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Type for Service Heartbeat Notification.
 *
 *
Java class for HeartbeatNotificationStructure complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="HeartbeatNotificationStructure">
 *   <complexContent>
 *     <extension base="{http://www.siri.org.uk/siri}ProducerRequestEndpointStructure">
 *       <sequence>
 *         <group ref="{http://www.siri.org.uk/siri}CheckStatusPayloadGroup"/>
 *         <element ref="{http://www.siri.org.uk/siri}Extensions" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HeartbeatNotificationStructure", propOrder = {
    "status",
    "dataReady",
    "errorCondition",
    "validUntil",
    "shortestPossibleCycle",
    "serviceStartedTime",
    "extensions"
})
public class HeartbeatNotificationStructure
    extends ProducerRequestEndpointStructure
{

    @XmlElement(name = "Status", defaultValue = "true")
    protected Boolean status;
    @XmlElement(name = "DataReady")
    protected Boolean dataReady;
    @XmlElement(name = "ErrorCondition")
    protected uk.org.siri.siri_2.CheckStatusResponseBodyStructure.ErrorCondition errorCondition;
    @XmlElement(name = "ValidUntil")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar validUntil;
    @XmlElement(name = "ShortestPossibleCycle")
    protected Duration shortestPossibleCycle;
    @XmlElement(name = "ServiceStartedTime")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar serviceStartedTime;
    @XmlElement(name = "Extensions")
    protected ExtensionsStructure extensions;

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setStatus(Boolean value) {
        this.status = value;
    }

    /**
     * Gets the value of the dataReady property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isDataReady() {
        return dataReady;
    }

    /**
     * Sets the value of the dataReady property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setDataReady(Boolean value) {
        this.dataReady = value;
    }

    /**
     * Gets the value of the errorCondition property.
     *
     * @return
     *     possible object is
     *     {@link uk.org.siri.siri_2.CheckStatusResponseBodyStructure.ErrorCondition }
     *
     */
    public uk.org.siri.siri_2.CheckStatusResponseBodyStructure.ErrorCondition getErrorCondition() {
        return errorCondition;
    }

    /**
     * Sets the value of the errorCondition property.
     *
     * @param value
     *     allowed object is
     *     {@link uk.org.siri.siri_2.CheckStatusResponseBodyStructure.ErrorCondition }
     *
     */
    public void setErrorCondition(uk.org.siri.siri_2.CheckStatusResponseBodyStructure.ErrorCondition value) {
        this.errorCondition = value;
    }

    /**
     * Gets the value of the validUntil property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getValidUntil() {
        return validUntil;
    }

    /**
     * Sets the value of the validUntil property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setValidUntil(XMLGregorianCalendar value) {
        this.validUntil = value;
    }

    /**
     * Gets the value of the shortestPossibleCycle property.
     *
     * @return
     *     possible object is
     *     {@link Duration }
     *
     */
    public Duration getShortestPossibleCycle() {
        return shortestPossibleCycle;
    }

    /**
     * Sets the value of the shortestPossibleCycle property.
     *
     * @param value
     *     allowed object is
     *     {@link Duration }
     *
     */
    public void setShortestPossibleCycle(Duration value) {
        this.shortestPossibleCycle = value;
    }

    /**
     * Gets the value of the serviceStartedTime property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getServiceStartedTime() {
        return serviceStartedTime;
    }

    /**
     * Sets the value of the serviceStartedTime property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setServiceStartedTime(XMLGregorianCalendar value) {
        this.serviceStartedTime = value;
    }

    /**
     * Gets the value of the extensions property.
     *
     * @return
     *     possible object is
     *     {@link ExtensionsStructure }
     *
     */
    public ExtensionsStructure getExtensions() {
        return extensions;
    }

    /**
     * Sets the value of the extensions property.
     *
     * @param value
     *     allowed object is
     *     {@link ExtensionsStructure }
     *
     */
    public void setExtensions(ExtensionsStructure value) {
        this.extensions = value;
    }

}


text:
require 'open-uri'
require 'nokogiri'
require 'yaml'

module Movies
  module Utils
    class ImdbParser
      attr_reader :budgets

      def initialize
        @budgets = {}
      end

      def run(collection)
        bar = ProgressBar.new(collection.size, :bar, :counter, :eta)
        collection.each do |movie|
          url = "http://www.imdb.com/title/#{movie.imdb_id}"

          doc = Nokogiri::HTML(open(url))
          budget = find_text(doc, 'Budget:')

          @budgets[movie.imdb_id] = budget unless budget.nil?
          bar.increment!
        end
      end

      def save
        File.write(Movies::MovieCollection::BUDGETS_FILE, @budgets.to_yaml)
      end

      private

      def find_text(doc, str)
        node = doc.at_xpath("//h4[contains(text(), '#{str}')]")
        return if node.nil?

        node
          .parent
          .children
          .select { |child| child.is_a?(Nokogiri::XML::Text) }
          .map(&:text)
          .join('')
          .strip
      end
    end
  end
end


text:
class Camera
{
public:
	static Camera* GetInstance();
	static void	   Release();
	void Init(AglVector3 Position, AglVector3 Target, AglVector3 WorldUpVector, int Width, int Height);
	AglMatrix GetCameraMatrix();
	AglMatrix GetProjectionMatrix();
	AglMatrix GetViewMatrix();

	//Returns the local axises of the camera.
	AglVector3 LocalXAxis();
	AglVector3 LocalYAxis();
	AglVector3 LocalZAxis();

	//Move Function relative to world space
	void Move(AglVector3 Distance);

	//Move Functions relative to camera space
	void MoveLeft(float Distance);
	void MoveRight(float Distance);
	void MoveForwards(float Distance);
	void MoveForwardsMaintainTarget(float Distance);
	void MoveBackwards(float Distance);
	void MoveUp(float Distance);
	void MoveDown(float Distance);

	//Rotating functions
	void Panorate(float Angle);
	void Tilt(float Angle);
	void Roll(float Angle);
	void ArbitraryRotatation(float Angle, AglVector3 Axis);

	AglVector3 Position() const{ return mPosition; }
	void	MoveTo(AglVector3 pos);
	void SetY(float y);
	void SetLens(float Angle, int Width, int Height, int n, int f);
	float GetViewAngle();
	AglVector3 GetPosition(){ return mPosition; }
	AglVector3 GetTarget(){ return mTarget;}

	void MoveToPreserveTarget(AglVector3 pPosition);

private:
	Camera();
private:
	AglVector3 mPosition;
	AglVector3 mTarget;
	AglVector3 mUpDirection;
	AglMatrix mView;
	AglMatrix mProj;
	double mViewAngle;
	static Camera* mInstance;

	bool mViewNeedsUpdate;

};

#endif


text:
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <cstdint>
#include <utility>
#include <vector>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END

using pomdog::detail::BinaryReader;
using pomdog::detail::MakeFourCC;

namespace pomdog::WAV {
namespace {

#if defined(POMDOG_INTERNAL_PACKED)
#error "'POMDOG_INTERNAL_PACKED' already defined."
#elif defined(_MSC_VER)
#define POMDOG_INTERNAL_PACKED(type) __pragma(pack(push, 1)) type __pragma(pack(pop))
#elif defined(__clang__) || defined(__GNUC__)
#define POMDOG_INTERNAL_PACKED(type) type __attribute__((packed))
#else
#error "'POMDOG_INTERNAL_PACKED' is not supported in this compiler."
#endif

POMDOG_INTERNAL_PACKED(struct RIFFChunk final {
    std::uint32_t ChunkID;
    std::uint32_t ChunkSize;
    std::uint32_t FourCCType;
});

POMDOG_INTERNAL_PACKED(struct SubChunkHeader final {
    std::uint32_t ChunkID;
    std::uint32_t ChunkSize;
});

POMDOG_INTERNAL_PACKED(struct PCMWaveFormat final {
    std::uint16_t FormatTag;
    std::uint16_t Channels;
    std::uint32_t SamplesPerSec;
    std::uint32_t AvgBytesPerSec;
    std::uint16_t BlockAlign;
    std::uint16_t BitsPerSample;
});

struct WaveFormat final {
    PCMWaveFormat PCMFormat;
    std::uint16_t ExtraBytes = 0;
    std::vector<std::uint8_t> ExtraData;
};

[[nodiscard]] std::unique_ptr<Error>
ReadRIFFChunk(std::ifstream& stream)
{
    const auto riffChunk = BinaryReader::Read<RIFFChunk>(stream);

    if (stream.fail()) {
        return errors::New("failed to read read RiffChunk");
    }

    if (riffChunk.ChunkID != MakeFourCC('R', 'I', 'F', 'F')) {
        return errors::New("missing RIFF chunk");
    }
    if (riffChunk.FourCCType != MakeFourCC('W', 'A', 'V', 'E')) {
        return errors::New("FourCCType is not 'WAVE'");
    }

    return nullptr;
}

[[nodiscard]] std::tuple<WaveFormat, std::unique_ptr<Error>>
ReadWaveFormat(std::ifstream& stream)
{
    const auto fmtChunkHeader = BinaryReader::Read<SubChunkHeader>(stream);

    if (stream.fail()) {
        auto err = errors::New("failed to read SubChunkHeader");
        return std::make_tuple(WaveFormat{}, std::move(err));
    }

    if (fmtChunkHeader.ChunkID != MakeFourCC('f', 'm', 't', ' ')) {
        auto err = errors::New("cannot find the 'fmt ' chunk");
        return std::make_tuple(WaveFormat{}, std::move(err));
    }
    if (fmtChunkHeader.ChunkSize < sizeof(PCMWaveFormat)) {
        auto err = errors::New("The 'fmt ' chunk size is too small: " + std::to_string(fmtChunkHeader.ChunkSize));
        return std::make_tuple(WaveFormat{}, std::move(err));
    }

    WaveFormat waveFormat;
    waveFormat.PCMFormat = BinaryReader::Read<PCMWaveFormat>(stream);
    waveFormat.ExtraBytes = 0;

    if (stream.fail()) {
        auto err = errors::New("failed to read the 'fmt ' chunk into PCMWaveFormat");
        return std::make_tuple(std::move(waveFormat), std::move(err));
    }

    // NOTE: WAVE_FORMAT_PCM
    constexpr std::uint16_t WaveFormatTagPCM = 0x0001;

    if (waveFormat.PCMFormat.FormatTag == WaveFormatTagPCM) {
        waveFormat.ExtraBytes = 0;
        waveFormat.ExtraData.clear();
    }
    else {
        waveFormat.ExtraBytes = BinaryReader::Read<std::uint16_t>(stream);
        if (stream.fail()) {
            auto err = errors::New("failed to read read the extra bytes");
            return std::make_tuple(std::move(waveFormat), std::move(err));
        }

        waveFormat.ExtraData.resize(waveFormat.ExtraBytes);
        stream.read(reinterpret_cast<char*>(waveFormat.ExtraData.data()), waveFormat.ExtraBytes);

        if (stream.fail()) {
            auto err = errors::New("failed to read read the extra data");
            return std::make_tuple(std::move(waveFormat), std::move(err));
        }
    }

    return std::make_tuple(std::move(waveFormat), nullptr);
}

[[nodiscard]] std::tuple<std::vector<std::uint8_t>, std::unique_ptr<Error>>
ReadWaveAudioData(std::ifstream& stream)
{
    POMDOG_ASSERT(stream);

    const auto chunkHeader = BinaryReader::Read<SubChunkHeader>(stream);

    if (stream.fail()) {
        auto err = errors::New("failed to read 'data' chunk header");
        return std::make_tuple(std::vector<std::uint8_t>{}, std::move(err));
    }
    if (chunkHeader.ChunkID != MakeFourCC('d', 'a', 't', 'a')) {
        auto err = errors::New("cannot find the 'data' chunk");
        return std::make_tuple(std::vector<std::uint8_t>{}, std::move(err));
    }
    if (chunkHeader.ChunkSize <= 0) {
        auto err = errors::New("data chunk is empty");
        return std::make_tuple(std::vector<std::uint8_t>{}, std::move(err));
    }

    std::vector<std::uint8_t> audioData;
    audioData.resize(chunkHeader.ChunkSize);

    for (auto& dest : audioData) {
        dest = BinaryReader::Read<std::uint8_t>(stream);
        if (stream.fail()) {
            auto err = errors::New("failed to read wave data");
            return std::make_tuple(std::move(audioData), std::move(err));
        }
    }

    return std::make_tuple(std::move(audioData), nullptr);
}

[[nodiscard]] AudioChannels ToAudioChannels(std::uint32_t channels) noexcept
{
    POMDOG_ASSERT(channels > 0);
    POMDOG_ASSERT(channels <= 2);

    switch (channels) {
    case 1:
        return AudioChannels::Mono;
    case 2:
        return AudioChannels::Stereo;
    default:
        break;
    }
    return AudioChannels::Mono;
}

} // namespace

[[nodiscard]] std::tuple<std::shared_ptr<AudioClip>, std::unique_ptr<Error>>
Load(const std::shared_ptr<AudioEngine>& audioEngine, std::ifstream&& stream, std::size_t byteLength) noexcept
{
    constexpr auto MinimumWaveFormatSizeInBytes = 4 * 11;
    if (byteLength < MinimumWaveFormatSizeInBytes) {
        return std::make_tuple(nullptr, errors::New("the wave file is too small"));
    }

    if (!stream) {
        return std::make_tuple(nullptr, errors::New("invalid file stream"));
    }

    if (auto readErr = ReadRIFFChunk(stream); readErr != nullptr) {
        auto err = errors::Wrap(std::move(readErr), "cannot read the wave file");
        return std::make_tuple(nullptr, std::move(err));
    }

    auto [waveFormat, waveFormatErr] = ReadWaveFormat(stream);
    if (waveFormatErr != nullptr) {
        auto err = errors::Wrap(std::move(waveFormatErr), "cannot read the wave format");
        return std::make_tuple(nullptr, std::move(err));
    }

    auto [audioData, audioDataErr] = ReadWaveAudioData(stream);
    if (audioDataErr != nullptr) {
        auto err = errors::Wrap(std::move(audioDataErr), "cannot read the wave audio data");
        return std::make_tuple(nullptr, std::move(err));
    }

    auto channels = ToAudioChannels(waveFormat.PCMFormat.Channels);

    if (audioEngine == nullptr) {
        auto err = errors::New("audioEngine is null.");
        return std::make_tuple(nullptr, std::move(err));
    }
    POMDOG_ASSERT(audioEngine != nullptr);

    // NOTE: Create audio clip.
    auto [audioClip, audioClipErr] = audioEngine->CreateAudioClip(
        audioData.data(),
        audioData.size(),
        static_cast<int>(waveFormat.PCMFormat.SamplesPerSec),
        static_cast<int>(waveFormat.PCMFormat.BitsPerSample),
        channels);

    if (audioClipErr != nullptr) {
        auto err = errors::Wrap(std::move(audioClipErr), "CreateAudioClip() failed.");
        return std::make_tuple(nullptr, std::move(err));
    }

    return std::make_tuple(std::move(audioClip), nullptr);
}

} // namespace pomdog::WAV


text:
module RailsWorkflow
  class ProcessTemplateDecorator < Decorator
    delegate_all

    def form
      'form'
    end

    def default_class
      RailsWorkflow.config.process_class
    end

    def default_manager
      RailsWorkflow.config.manager_class
    end

    def default_type
      RailsWorkflow.config.process_template_type
    end
  end
end


text:
<template name="todolist_item_details">

			Text:

{{long_text}}

			Short text:
			{{short_text}}

			Priority:
			{{priority}}

			Status:
			{{status}}

			Category:
			{{category}}

			Created on:
			{{created_on}}

			Due date:
			{{due_date}}

			Created by:
			{{get_username_for_id created_by}}

			Background color:

	view all items
</template>


text:
using System;

public class Tests {

	public delegate bool FilterStackFrame(object o);

	public static void DumpException(FilterStackFrame fsf) {
	}

	public static void foo (out bool continueInteraction) {
		continueInteraction = false;

		try {
		}
		catch (Exception ex) {
			DumpException(delegate(object o) {
				return true;
			});
		}
	}

	public static void Main (String[] args) {
		bool b;

		foo (out b);
	}
}


text:
import _normalizeOptions from "../lib/normalize-options.js";
const normalizeOptions = _normalizeOptions.default;

describe("normalize options", () => {
  (process.env.BABEL_8_BREAKING ? describe : describe.skip)("Babel 8", () => {
    it("should throw on unknown options", () => {
      expect(() => normalizeOptions({ throwIfNamespaces: true })).toThrowError(
        "@babel/preset-react: 'throwIfNamespaces' is not a valid top-level option.\n- Did you mean 'throwIfNamespace'?",
      );
    });
    it.each(["development", "pure", "throwIfNamespace"])(
      "should throw when `%p` is not a boolean",
      optionName => {
        expect(() => normalizeOptions({ [optionName]: 0 })).toThrow(
          `@babel/preset-react: '${optionName}' option must be a boolean.`,
        );
      },
    );
    it.each(["importSource", "pragma", "pragmaFrag", "runtime"])(
      "should throw when `%p` is not a string",
      optionName => {
        expect(() => normalizeOptions({ [optionName]: 0 })).toThrow(
          `@babel/preset-react: '${optionName}' option must be a string.`,
        );
      },
    );
    it("should throw on Babel 7 'useBuiltIns' option", () => {
      expect(() => normalizeOptions({ useBuiltIns: true }))
        .toThrowErrorMatchingInlineSnapshot(`
        "@babel/preset-react: Since \\"useBuiltIns\\" is removed in Babel 8, you can remove it from the config.
        - Babel 8 now transforms JSX spread to object spread. If you need to transpile object spread with
        \`useBuiltIns: true\`, you can use the following config
        {
          \\"plugins\\": [
            [\\"@babel/plugin-proposal-object-rest-spread\\", { \\"loose\\": true, \\"useBuiltIns\\": true }]
          ],
          \\"presets\\": [\\"@babel/preset-react\\"]
        }"
      `);
    });
    it("should throw on Babel 7 'useSpread' option", () => {
      expect(() =>
        normalizeOptions({ useSpread: true }),
      ).toThrowErrorMatchingInlineSnapshot(
        `"@babel/preset-react: Since Babel 8, an inline object with spread elements is always used, and the \\"useSpread\\" option is no longer available. Please remove it from your config."`,
      );
    });
    it("should throw on unknown 'runtime' option", () => {
      expect(() => normalizeOptions({ runtime: "classical" }))
        .toThrowErrorMatchingInlineSnapshot(`
        "@babel/preset-react: 'runtime' must be one of ['automatic', 'classic'] but we have 'classical'
        - Did you mean 'classic'?"
      `);
    });
    it("should not throw when options are not defined", () => {
      expect(() => normalizeOptions()).not.toThrowError();
    });
    it("default values", () => {
      expect(normalizeOptions({})).toMatchInlineSnapshot(`
        Object {
          "development": false,
          "importSource": "react",
          "pragma": undefined,
          "pragmaFrag": undefined,
          "pure": undefined,
          "runtime": "automatic",
          "throwIfNamespace": true,
        }
      `);
      expect(normalizeOptions({ runtime: "classic" })).toMatchInlineSnapshot(`
        Object {
          "development": false,
          "importSource": undefined,
          "pragma": "React.createElement",
          "pragmaFrag": "React.Fragment",
          "pure": undefined,
          "runtime": "classic",
          "throwIfNamespace": true,
        }
      `);
    });
  });
  (process.env.BABEL_8_BREAKING ? describe.skip : describe)("Babel 7", () => {
    it("should not throw on unknown options", () => {
      expect(() =>
        normalizeOptions({ throwIfNamespaces: true }),
      ).not.toThrowError();
    });
    it.each(["development", "pure", "throwIfNamespace"])(
      "should not throw when `%p` is not a boolean",
      optionName => {
        expect(() => normalizeOptions({ [optionName]: 0 })).not.toThrowError();
      },
    );
    it.each(["importSource", "pragma", "pragmaFrag", "runtime"])(
      "should throw when `%p` is not a string",
      optionName => {
        expect(() => normalizeOptions({ [optionName]: 0 })).not.toThrowError();
      },
    );
    it("default values", () => {
      expect(normalizeOptions({})).toMatchInlineSnapshot(`
        Object {
          "development": false,
          "importSource": undefined,
          "pragma": "React.createElement",
          "pragmaFrag": "React.Fragment",
          "pure": undefined,
          "runtime": "classic",
          "throwIfNamespace": true,
          "useBuiltIns": undefined,
          "useSpread": undefined,
        }
      `);
      expect(normalizeOptions({ runtime: "automatic" })).toMatchInlineSnapshot(`
        Object {
          "development": false,
          "importSource": undefined,
          "pragma": undefined,
          "pragmaFrag": undefined,
          "pure": undefined,
          "runtime": "automatic",
          "throwIfNamespace": true,
          "useBuiltIns": undefined,
          "useSpread": undefined,
        }
      `);
    });
  });
});


text:
from io import StringIO
from antlr4.tree.Tree import RuleNode, INVALID_INTERVAL, ParseTreeVisitor
from antlr4.tree.Trees import Trees

# need forward declarations
RuleContext = None
Parser = None

class RuleContext(RuleNode):

    EMPTY = None

    def __init__(self, parent:RuleContext=None, invokingState:int=-1):
        super().__init__()
        # What context invoked this rule?
        self.parentCtx = parent
        # What state invoked the rule associated with this context?
        #  The "return address" is the followState of invokingState
        #  If parent is null, this should be -1.
        self.invokingState = invokingState

    def depth(self):
        n = 0
        p = self
        while p is not None:
            p = p.parentCtx
            n += 1
        return n

    # A context is empty if there is no invoking state; meaning nobody call
    #  current context.
    def isEmpty(self):
        return self.invokingState == -1

    # satisfy the ParseTree / SyntaxTree interface

    def getSourceInterval(self):
        return INVALID_INTERVAL

    def getRuleContext(self):
        return self

    def getPayload(self):
        return self

   # Return the combined text of all child nodes. This method only considers
    #  tokens which have been added to the parse tree.
    #  <p>
    #  Since tokens on hidden channels (e.g. whitespace or comments) are not
    #  added to the parse trees, they will not appear in the output of this
    #  method.
    #/
    def getText(self):
        if self.getChildCount() == 0:
            return ""
        with StringIO() as builder:
            for child in self.getChildren():
                builder.write(child.getText())
            return builder.getvalue()

    def getRuleIndex(self):
        return -1

    def getChild(self, i:int):
        return None

    def getChildCount(self):
        return 0

    def getChildren(self):
        for c in []:
            yield c

    def accept(self, visitor:ParseTreeVisitor):
        return visitor.visitChildren(self)

   # # Call this method to view a parse tree in a dialog box visually.#/
   #  public Future<JDialog> inspect(@Nullable Parser parser) {
   #      List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;
   #      return inspect(ruleNames);
   #  }
   #
   #  public Future<JDialog> inspect(@Nullable List<String> ruleNames) {
   #      TreeViewer viewer = new TreeViewer(ruleNames, this);
   #      return viewer.open();
   #  }
   #
   # # Save this tree in a postscript file#/
   #  public void save(@Nullable Parser parser, String fileName)
   #      throws IOException, PrintException
   #  {
   #      List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;
   #      save(ruleNames, fileName);
   #  }
   #
   # # Save this tree in a postscript file using a particular font name and size#/
   #  public void save(@Nullable Parser parser, String fileName,
   #                   String fontName, int fontSize)
   #      throws IOException
   #  {
   #      List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;
   #      save(ruleNames, fileName, fontName, fontSize);
   #  }
   #
   # # Save this tree in a postscript file#/
   #  public void save(@Nullable List<String> ruleNames, String fileName)
   #      throws IOException, PrintException
   #  {
   #      Trees.writePS(this, ruleNames, fileName);
   #  }
   #
   # # Save this tree in a postscript file using a particular font name and size#/
   #  public void save(@Nullable List<String> ruleNames, String fileName,
   #                   String fontName, int fontSize)
   #      throws IOException
   #  {
   #      Trees.writePS(this, ruleNames, fileName, fontName, fontSize);
   #  }
   #
   # # Print out a whole tree, not just a node, in LISP format
   #  #  (root child1 .. childN). Print just a node if this is a leaf.
   #  #  We have to know the recognizer so we can get rule names.
   #  #/
   #  @Override
   #  public String toStringTree(@Nullable Parser recog) {
   #      return Trees.toStringTree(this, recog);
   #  }
   #
   # Print out a whole tree, not just a node, in LISP format
   #  (root child1 .. childN). Print just a node if this is a leaf.
   #
    def toStringTree(self, ruleNames:list=None, recog:Parser=None):
        return Trees.toStringTree(self, ruleNames=ruleNames, recog=recog)
   #  }
   #
   #  @Override
   #  public String toStringTree() {
   #      return toStringTree((List<String>)null);
   #  }
   #
    def __str__(self):
        return self.toString(None, None)

   #  @Override
   #  public String toString() {
   #      return toString((List<String>)null, (RuleContext)null);
   #  }
   #
   #  public final String toString(@Nullable Recognizer<?,?> recog) {
   #      return toString(recog, ParserRuleContext.EMPTY);
   #  }
   #
   #  public final String toString(@Nullable List<String> ruleNames) {
   #      return toString(ruleNames, null);
   #  }
   #
   #  // recog null unless ParserRuleContext, in which case we use subclass toString(...)
   #  public String toString(@Nullable Recognizer<?,?> recog, @Nullable RuleContext stop) {
   #      String[] ruleNames = recog != null ? recog.getRuleNames() : null;
   #      List<String> ruleNamesList = ruleNames != null ? Arrays.asList(ruleNames) : null;
   #      return toString(ruleNamesList, stop);
   #  }

    def toString(self, ruleNames:list, stop:RuleContext)->str:
        with StringIO() as buf:
            p = self
            buf.write("[")
            while p is not None and p is not stop:
                if ruleNames is None:
                    if not p.isEmpty():
                        buf.write(str(p.invokingState))
                else:
                    ri = p.getRuleIndex()
                    ruleName = ruleNames[ri] if ri >= 0 and ri < len(ruleNames) else str(ri)
                    buf.write(ruleName)

                if p.parentCtx is not None and (ruleNames is not None or not p.parentCtx.isEmpty()):
                    buf.write(" ")

                p = p.parentCtx

            buf.write("]")
            return buf.getvalue()


text:
RC TEST_RM_13b(const string &tableName)
{
    // Functions Tested:
    // 1. Conditional scan - including NULL values
    cout << endl << "***** In RM Test Case 13B *****" << endl;

    RID rid;
    int tupleSize = 0;
    int numTuples = 500;
    void *tuple;
    void *returnedData = malloc(200);
    int ageVal = 25;
    int age = 0;

    RID rids[numTuples];
    vector<char *> tuples;
	string tupleName;
	char *suffix = (char *)malloc(10);

    bool nullBit = false;

    // GetAttributes
    vector<Attribute> attrs;
    RC rc = rm->getAttributes(tableName, attrs);
    assert(rc == success && "RelationManager::getAttributes() should not fail.");

    int nullAttributesIndicatorActualSize = getActualByteForNullsIndicator(attrs.size());
    unsigned char *nullsIndicator = (unsigned char *) malloc(nullAttributesIndicatorActualSize);
	memset(nullsIndicator, 0, nullAttributesIndicatorActualSize);

    unsigned char *nullsIndicatorWithNull = (unsigned char *) malloc(nullAttributesIndicatorActualSize);
	memset(nullsIndicatorWithNull, 0, nullAttributesIndicatorActualSize);

	// age field : NULL
	nullsIndicatorWithNull[0] = 64; // 01000000

    for(int i = 0; i < numTuples; i++)
    {
        tuple = malloc(100);

        // Insert Tuple
        float height = (float)i;

        age = (rand()%20) + 15;

        sprintf(suffix, "%d", i);

		if (i % 10 == 0) {
			tupleName = "TesterNull";
			tupleName += suffix;
	        prepareTuple(attrs.size(), nullsIndicatorWithNull, tupleName.length(), tupleName, 0, height, 456, tuple, &tupleSize);
		} else {
			tupleName = "Tester";
			tupleName += suffix;
	        prepareTuple(attrs.size(), nullsIndicator, tupleName.length(), tupleName, age, height, 123, tuple, &tupleSize);
		}
        rc = rm->insertTuple(tableName, tuple, rid);
        assert(rc == success && "RelationManager::insertTuple() should not fail.");

        rids[i] = rid;
    }

    // Set up the iterator
    RM_ScanIterator rmsi;
    string attr = "Age";
    vector<string> attributes;
    attributes.push_back(attr);
    rc = rm->scan(tableName, attr, GT_OP, &ageVal, attributes, rmsi);
    assert(rc == success && "RelationManager::scan() should not fail.");

    while(rmsi.getNextTuple(rid, returnedData) != RM_EOF)
    {
    	// Check the first bit of the returned data since we only returns one attribute in this test case
    	// However, the age with NULL should not be returned since the condition NULL > 25 can't hold.
    	// All comparison operations with NULL should return FALSE
    	// (e.g., NULL > 25, NULL >= 25, NULL <= 25, NULL < 25, NULL == 25, NULL != 25: ALL FALSE)
		nullBit = *(unsigned char *)((char *)returnedData) & (1 << 7);
		if (!nullBit) {
			age = *(int *)((char *)returnedData+1);
			if (age <= ageVal) {
				// Comparison didn't work in this case
				cout << "Returned value from a scan is not correct: returned Age <= 25." << endl;
				cout << "***** [FAIL] Test Case 13B Failed *****" << endl << endl;
				rmsi.close();
				free(returnedData);
				return -1;
			}
		} else {
			// Age with NULL value should not be returned.
			cout << "Returned value from a scan is not correct. NULL returned." << endl;
			cout << "***** [FAIL] Test Case 13B Failed *****" << endl << endl;
			rmsi.close();
			free(returnedData);
			return -1;
		}
    }
    rmsi.close();
    free(returnedData);

	rc = rm->deleteTable("tbl_b_employee5");

    cout << "***** [PASS] Test Case 13B Passed *****" << endl << endl;

    return success;
}

int main()
{
	// Scan with conditions
    RC rcmain = createTable("tbl_b_employee5");
    rcmain = TEST_RM_13b("tbl_b_employee5");

    return rcmain;
}