text:
/**
 * @lends Puremvc.demo.controller.DeleteUserCommand.prototype
 */
Ext.namespace("Puremvc.demo.controller");
Ext.define("Puremvc.demo.controller.DeleteUserCommand", {

  extend: "puremvc.SimpleCommand",

  execute: function(notification/*INotification*/) {
    var user/*UserVO*/ = notification.getBody();

    var userProxy/*UserProxy*/ = this.facade.retrieveProxy(Puremvc.demo.model.UserProxy.NAME);
    userProxy.deleteItem(user);

    var roleProxy/*RoleProxy*/ = this.facade.retrieveProxy(Puremvc.demo.model.RoleProxy.NAME);
    roleProxy.deleteItem(user);

    this.sendNotification(Puremvc.demo.ApplicationFacade.USER_DELETED);
  }
});

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: miky
 * Date: 09/08/16
 * Time: 09:40
 */

namespace Miky\Bundle\UserBundle\Form\Type\Frontend;

use Miky\Bundle\LocaleBundle\Manager\LanguageManager;
use Miky\Bundle\LocationBundle\Form\Type\Frontend\LocationType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CustomerProfileType extends AbstractType
{

    private $languageManager;

    /**
     * AdType constructor.
     */
    public function __construct(LanguageManager $languageManager)
    {
        $this->languageManager = $languageManager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname', TextType::class)
            ->add('lastname', TextType::class)
            ->add('email', TextType::class)
            ->add('username', TextType::class)
            ->add('activity', TextType::class)
            ->add('plainPassword', RepeatedType::class, array(
                'type' => PasswordType::class,
                'first_options'  => array('label' => 'Password'),
                'second_options' => array('label' => 'Repeat Password'),
                "required" => false
            ))
            ->add('languagesSpoken', ChoiceType::class, array(
                'choices' => $this->languageManager->getArrayAllIsoByName(),
                'multiple' => true,
                'expanded' => false,

            ))
            ->add('companyName', TextType::class)
            ->add('companyId', TextType::class)
            ->add('companyDescription', TextareaType::class, array('attr' => array('rows' => '15','cols' => '14')) )
            ->add('mobile', TextType::class)
            ->add('website', TextType::class)
            ->add('location', LocationType::class)
            ->add('phone', TextType::class)
            ->add('facebook', TextType::class)
            ->add('twitter', TextType::class)
            ->add('linkedin', TextType::class)
            ->add('profileImage', 'miky_media_type', array(
                'provider' => 'miky.media.provider.image',
                'context'  => 'customer'
            ))
        ;

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Miky\Bundle\UserBundle\Entity\Customer'
        ));
    }

    public function getName()
    {
        return 'miky_customer_profile_front';
    }
}


text: python3 gen_table_data.py


text:
RSpec.describe Magick::ImageType, '.values' do
  it 'does not cause an infinite loop' do
    info = Magick::Image::Info.new
    described_class.values do |value|
      info.image_type = value
      expect(info.image_type).to eq(value)
    end
  end
end


text:
(function () {

    'use strict';

    angular
        .module('app')
        .controller('EstimateController', EstimateController);

    EstimateController.$inject = [];

    function EstimateController() {

    }
})();


text:
ANSIBLE_METADATA = {'status': ['stableinterface'],
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = '''
---
module: cs_volume
short_description: Manages volumes on Apache CloudStack based clouds.
description:
    - Create, destroy, attach, detach volumes.
version_added: "2.1"
author:
    - "Jefferson Girão (@jeffersongirao)"
    - "René Moser (@resmo)"
options:
  name:
    description:
      - Name of the volume.
      - C(name) can only contain ASCII letters.
    required: true
  account:
    description:
      - Account the volume is related to.
    required: false
    default: null
  custom_id:
    description:
      - Custom id to the resource.
      - Allowed to Root Admins only.
    required: false
    default: null
  disk_offering:
    description:
      - Name of the disk offering to be used.
      - Required one of C(disk_offering), C(snapshot) if volume is not already C(state=present).
    required: false
    default: null
  display_volume:
    description:
      - Whether to display the volume to the end user or not.
      - Allowed to Root Admins only.
    required: false
    default: true
  domain:
    description:
      - Name of the domain the volume to be deployed in.
    required: false
    default: null
  max_iops:
    description:
      - Max iops
    required: false
    default: null
  min_iops:
    description:
      - Min iops
    required: false
    default: null
  project:
    description:
      - Name of the project the volume to be deployed in.
    required: false
    default: null
  size:
    description:
      - Size of disk in GB
    required: false
    default: null
  snapshot:
    description:
      - The snapshot name for the disk volume.
      - Required one of C(disk_offering), C(snapshot) if volume is not already C(state=present).
    required: false
    default: null
  force:
    description:
      - Force removal of volume even it is attached to a VM.
      - Considered on C(state=absnet) only.
    required: false
    default: false
  shrink_ok:
    description:
      - Whether to allow to shrink the volume.
    required: false
    default: false
  vm:
    description:
      - Name of the virtual machine to attach the volume to.
    required: false
    default: null
  zone:
    description:
      - Name of the zone in which the volume should be deployed.
      - If not set, default zone is used.
    required: false
    default: null
  state:
    description:
      - State of the volume.
    required: false
    default: 'present'
    choices: [ 'present', 'absent', 'attached', 'detached' ]
  poll_async:
    description:
      - Poll async jobs until job has finished.
    required: false
    default: true
extends_documentation_fragment: cloudstack
'''

EXAMPLES = '''
# Create volume within project, zone with specified storage options
- local_action:
    module: cs_volume
    name: web-vm-1-volume
    project: Integration
    zone: ch-zrh-ix-01
    disk_offering: PerfPlus Storage
    size: 20

# Create/attach volume to instance
- local_action:
    module: cs_volume
    name: web-vm-1-volume
    disk_offering: PerfPlus Storage
    size: 20
    vm: web-vm-1
    state: attached

# Detach volume
- local_action:
    module: cs_volume
    name: web-vm-1-volume
    state: detached

# Remove volume
- local_action:
    module: cs_volume
    name: web-vm-1-volume
    state: absent
'''

RETURN = '''
id:
  description: ID of the volume.
  returned: success
  type: string
  sample:
name:
  description: Name of the volume.
  returned: success
  type: string
  sample: web-volume-01
display_name:
  description: Display name of the volume.
  returned: success
  type: string
  sample: web-volume-01
group:
  description: Group the volume belongs to
  returned: success
  type: string
  sample: web
domain:
  description: Domain the volume belongs to
  returned: success
  type: string
  sample: example domain
project:
  description: Project the volume belongs to
  returned: success
  type: string
  sample: Production
zone:
  description: Name of zone the volume is in.
  returned: success
  type: string
  sample: ch-gva-2
created:
  description: Date of the volume was created.
  returned: success
  type: string
  sample: 2014-12-01T14:57:57+0100
attached:
  description: Date of the volume was attached.
  returned: success
  type: string
  sample: 2014-12-01T14:57:57+0100
type:
  description: Disk volume type.
  returned: success
  type: string
  sample: DATADISK
size:
  description: Size of disk volume.
  returned: success
  type: string
  sample: 20
vm:
  description: Name of the vm the volume is attached to (not returned when detached)
  returned: success
  type: string
  sample: web-01
state:
  description: State of the volume
  returned: success
  type: string
  sample: Attached
device_id:
  description: Id of the device on user vm the volume is attached to (not returned when detached)
  returned: success
  type: string
  sample: 1
'''

# import cloudstack common
from ansible.module_utils.cloudstack import *

class AnsibleCloudStackVolume(AnsibleCloudStack):

    def __init__(self, module):
        super(AnsibleCloudStackVolume, self).__init__(module)
        self.returns = {
            'group':            'group',
            'attached':         'attached',
            'vmname':           'vm',
            'deviceid':         'device_id',
            'type':             'type',
            'size':             'size',
        }
        self.volume = None

    #TODO implement in cloudstack utils
    def get_disk_offering(self, key=None):
        disk_offering = self.module.params.get('disk_offering')
        if not disk_offering:
            return None

        # Do not add domain filter for disk offering listing.
        disk_offerings = self.cs.listDiskOfferings()
        if disk_offerings:
            for d in disk_offerings['diskoffering']:
                if disk_offering in [d['displaytext'], d['name'], d['id']]:
                    return self._get_by_key(key, d)
        self.module.fail_json(msg="Disk offering '%s' not found" % disk_offering)

    def get_volume(self):
        if not self.volume:
            args = {}
            args['account'] = self.get_account(key='name')
            args['domainid'] = self.get_domain(key='id')
            args['projectid'] = self.get_project(key='id')
            args['zoneid'] = self.get_zone(key='id')
            args['displayvolume'] = self.module.params.get('display_volume')
            args['type'] = 'DATADISK'

            volumes = self.cs.listVolumes(**args)
            if volumes:
                volume_name = self.module.params.get('name')
                for v in volumes['volume']:
                    if volume_name.lower() == v['name'].lower():
                        self.volume = v
                        break
        return self.volume

    def get_snapshot(self, key=None):
        snapshot = self.module.params.get('snapshot')
        if not snapshot:
            return None

        args = {}
        args['name'] = snapshot
        args['account'] = self.get_account('name')
        args['domainid'] = self.get_domain('id')
        args['projectid'] = self.get_project('id')

        snapshots = self.cs.listSnapshots(**args)
        if snapshots:
            return self._get_by_key(key, snapshots['snapshot'][0])
        self.module.fail_json(msg="Snapshot with name %s not found" % snapshot)

    def present_volume(self):
        volume = self.get_volume()
        if volume:
            volume = self.update_volume(volume)
        else:
            disk_offering_id = self.get_disk_offering(key='id')
            snapshot_id = self.get_snapshot(key='id')

            if not disk_offering_id and not snapshot_id:
                self.module.fail_json(msg="Required one of: disk_offering,snapshot")

            self.result['changed'] = True

            args = {}
            args['name'] = self.module.params.get('name')
            args['account'] = self.get_account(key='name')
            args['domainid'] = self.get_domain(key='id')
            args['diskofferingid'] = disk_offering_id
            args['displayvolume'] = self.module.params.get('display_volume')
            args['maxiops'] = self.module.params.get('max_iops')
            args['miniops'] = self.module.params.get('min_iops')
            args['projectid'] = self.get_project(key='id')
            args['size'] = self.module.params.get('size')
            args['snapshotid'] = snapshot_id
            args['zoneid'] = self.get_zone(key='id')

            if not self.module.check_mode:
                res = self.cs.createVolume(**args)
                if 'errortext' in res:
                    self.module.fail_json(msg="Failed: '%s'" % res['errortext'])
                poll_async = self.module.params.get('poll_async')
                if poll_async:
                    volume = self.poll_job(res, 'volume')
        return volume

    def attached_volume(self):
        volume = self.present_volume()

        if volume:
            if volume.get('virtualmachineid') != self.get_vm(key='id'):
                self.result['changed'] = True

                if not self.module.check_mode:
                    volume = self.detached_volume()

            if 'attached' not in volume:
                self.result['changed'] = True

                args = {}
                args['id'] = volume['id']
                args['virtualmachineid'] = self.get_vm(key='id')
                args['deviceid'] = self.module.params.get('device_id')

                if not self.module.check_mode:
                    res = self.cs.attachVolume(**args)
                    if 'errortext' in res:
                        self.module.fail_json(msg="Failed: '%s'" % res['errortext'])
                    poll_async = self.module.params.get('poll_async')
                    if poll_async:
                        volume = self.poll_job(res, 'volume')
        return volume

    def detached_volume(self):
        volume = self.present_volume()

        if volume:
            if 'attached' not in volume:
                return volume

            self.result['changed'] = True

            if not self.module.check_mode:
                res = self.cs.detachVolume(id=volume['id'])
                if 'errortext' in volume:
                    self.module.fail_json(msg="Failed: '%s'" % res['errortext'])
                poll_async = self.module.params.get('poll_async')
                if poll_async:
                    volume = self.poll_job(res, 'volume')
        return volume

    def absent_volume(self):
        volume = self.get_volume()

        if volume:
            if 'attached' in volume and not self.module.params.get('force'):
                self.module.fail_json(msg="Volume '%s' is attached, use force=true for detaching and removing the volume." % volume.get('name'))

            self.result['changed'] = True
            if not self.module.check_mode:
                volume = self.detached_volume()

                res = self.cs.deleteVolume(id=volume['id'])
                if 'errortext' in res:
                    self.module.fail_json(msg="Failed: '%s'" % res['errortext'])
                poll_async = self.module.params.get('poll_async')
                if poll_async:
                    res = self.poll_job(res, 'volume')

        return volume

    def update_volume(self, volume):
        args_resize = {}
        args_resize['id'] = volume['id']
        args_resize['diskofferingid'] = self.get_disk_offering(key='id')
        args_resize['maxiops'] = self.module.params.get('max_iops')
        args_resize['miniops'] = self.module.params.get('min_iops')
        args_resize['size'] = self.module.params.get('size')

        # change unit from bytes to giga bytes to compare with args
        volume_copy = volume.copy()
        volume_copy['size'] = volume_copy['size'] / (2**30)

        if self.has_changed(args_resize, volume_copy):

            self.result['changed'] = True
            if not self.module.check_mode:
                args_resize['shrinkok'] = self.module.params.get('shrink_ok')
                res = self.cs.resizeVolume(**args_resize)
                if 'errortext' in res:
                    self.module.fail_json(msg="Failed: '%s'" % res['errortext'])
                poll_async = self.module.params.get('poll_async')
                if poll_async:
                    volume = self.poll_job(res, 'volume')
                self.volume = volume

        return volume

def main():
    argument_spec = cs_argument_spec()
    argument_spec.update(dict(
        name = dict(required=True),
        disk_offering = dict(default=None),
        display_volume = dict(type='bool', default=None),
        max_iops = dict(type='int', default=None),
        min_iops = dict(type='int', default=None),
        size = dict(type='int', default=None),
        snapshot = dict(default=None),
        vm = dict(default=None),
        device_id = dict(type='int', default=None),
        custom_id = dict(default=None),
        force = dict(type='bool', default=False),
        shrink_ok = dict(type='bool', default=False),
        state = dict(choices=['present', 'absent', 'attached', 'detached'], default='present'),
        zone = dict(default=None),
        domain = dict(default=None),
        account = dict(default=None),
        project = dict(default=None),
        poll_async = dict(type='bool', default=True),
    ))

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_together=cs_required_together(),
        mutually_exclusive = (
            ['snapshot', 'disk_offering'],
        ),
        supports_check_mode=True
    )

    try:
        acs_vol = AnsibleCloudStackVolume(module)

        state = module.params.get('state')

        if state in ['absent']:
            volume = acs_vol.absent_volume()
        elif state in ['attached']:
            volume = acs_vol.attached_volume()
        elif state in ['detached']:
            volume = acs_vol.detached_volume()
        else:
            volume = acs_vol.present_volume()

        result = acs_vol.get_result(volume)

    except CloudStackException as e:
        module.fail_json(msg='CloudStackException: %s' % str(e))

    module.exit_json(**result)

# import module snippets
from ansible.module_utils.basic import *

if __name__ == '__main__':
    main()


text:
package com.ev34j.core.sensor;

public enum SensorSetting {

  // Touch
  NXT_TOUCH(DriverType.NXT_ANALOG, ModuleType.NXT_TOUCH),
  EV3_TOUCH(DriverType.EV3_ANALOG, ModuleType.EV3_TOUCH),

  // Sound
  NXT_SOUND(DriverType.NXT_ANALOG, ModuleType.NXT_SOUND),

  // Pixy
  PIXY_SENSOR(DriverType.PIXY, ModuleType.NXT_I2C_SENSOR),

  // Ultrasonic
  NXT_US(DriverType.NXT_IC2, ModuleType.NXT_US),
  EV3_US(DriverType.EV3_UART, ModuleType.EV3_US),

  // Color
  NXT1_COLOR(DriverType.NXT_IC2, ModuleType.NXT1_COLOR),
  NXT2_COLOR(DriverType.NXT_IC2, ModuleType.NXT2_COLOR),
  EV3_COLOR(DriverType.EV3_UART, ModuleType.EV3_COLOR),

  // Gyro
  NXT_GYRO(DriverType.NXT_ANALOG, ModuleType.NXT_GYRO),
  EV3_GYRO(DriverType.EV3_UART, ModuleType.EV3_GYRO);

  private final DriverType driverType;
  private final ModuleType moduleType;

  SensorSetting(final DriverType driverType, final ModuleType moduleType) {
    this.driverType = driverType;
    this.moduleType = moduleType;
  }

  public DriverType getDriverType() { return this.driverType; }

  public ModuleType getModuleType() { return this.moduleType; }
}


text:
package org.benchmarkdp.toolevaluator.matcher;

import static org.junit.Assert.assertTrue;

import org.benchmarkdp.toolevaluator.elements.DocumentElements;
import org.benchmarkdp.toolevaluator.elements.GroundTruthElement;
import org.benchmarkdp.toolevaluator.elements.IElement;
import org.benchmarkdp.toolevaluator.elements.Text;
import org.junit.Test;

public class TextMatcherLinearTest {

	@Test
	public void Test1() {
		DocumentElements gt = new DocumentElements();
		Text t = new Text();
		t.setText("this is the first paragraph");
		IElement egt1 = new GroundTruthElement(t);
		gt.addElement(egt1);

		t = new Text();
		t.setText("And now comes the second paragraph in the text");
		IElement egt2 = new GroundTruthElement(t);
		gt.addElement(egt2);

		t = new Text();
		t.setText("And now comes the second paragraph in the text");
		IElement egt3 = new GroundTruthElement(t);
		gt.addElement(egt3);

		DocumentElements tol = new DocumentElements();
		String[] allText = { "this", "is", "the", "first", "paragraph", "And", "now", "comes", "the", "second",
				"paragraph", "hyperlink", "in", "the", "text" };
		tol.setAllText(allText);
		Integer[] wordPositions = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3 };
		tol.setWordPositions(wordPositions);

		IMatcher m = new TextMatcherLinear();
		m.match(gt, tol);

		assertTrue(egt1.isMatched());
		assertTrue(egt1.getStartLinePosition() == 1);
		assertTrue(egt2.isMatched());
		assertTrue(egt2.getStartLinePosition() == 1);
		assertTrue(egt2.getEndLinePosition() == 3);
		assertTrue(egt2.getStartWordPosition() == 5);
		assertTrue(egt2.getEndWordPosition() == 14);
		assertTrue(!egt3.isMatched());
	}

	@Test
	public void Test2() {
		DocumentElements gt = new DocumentElements();
		Text t = new Text();
		t.setText("this is the first paragraph");
		IElement egt1 = new GroundTruthElement(t);
		gt.addElement(egt1);

		t = new Text();
		t.setText("And now comes the second paragraph in the text");
		IElement egt2 = new GroundTruthElement(t);
		gt.addElement(egt2);

		t = new Text();
		t.setText("And now comes the second paragraph in the text");
		IElement egt3 = new GroundTruthElement(t);
		gt.addElement(egt3);

		DocumentElements tol = new DocumentElements();
		String[] allText = { "And", "now", "comes", "the", "second", "paragraph", "in", "the", "text", "test", "test",
				"this", "is", "the", "first", "paragraph", "And", "now", "comes", "the", "second", "paragraph",
				"hyperlink", "in", "the", "text" };
		tol.setAllText(allText);
		Integer[] wordPositions = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4 };
		tol.setWordPositions(wordPositions);

		IMatcher m = new TextMatcherLinear();
		m.match(gt, tol);

		assertTrue(egt1.isMatched());
		assertTrue(egt1.getStartLinePosition() == 2);
		assertTrue(egt2.isMatched());
		assertTrue(egt2.getStartLinePosition() == 1);
		assertTrue(egt2.getEndLinePosition() == 1);
		assertTrue(egt2.getStartWordPosition() == 0);
		assertTrue(egt2.getEndWordPosition() == 8);
		assertTrue(egt3.isMatched());
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <link rel="stylesheet" type="text/css" href="//at.alicdn.com/t/font_404043_qp3zkvxj7wmkuik9.css">
    <title>vue-demo</title>


text:
package org.esupportail.pstage.web.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.esupportail.pstage.utils.Utils;

/**
 * @author Danielle Martineau : danielle.martineau@univ-rennes1.fr
 */
public class MtGratificationValidator implements Validator {

	/**
	 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	public void validate(FacesContext fc, UIComponent uic, Object o)
	throws ValidatorException {
		String value = (String) o;
		value=value.trim();

		if (!Utils.validateMtGratification(value)) {
			throw new ValidatorException(new FacesMessage());
		}

	}

}


text:
<?php

namespace esperanto\CalendarBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class esperantoCalendarBundle extends Bundle
{
}


text:
require 'spec_helper'
require "selenium-webdriver"

RSpec.shared_examples "Capybara::Session" do |session, mode|
  let(:session) {session}

  context 'with selenium driver' do
    before do
      @session = session
    end

    describe '#driver' do
      it "should be a selenium driver" do
        expect(@session.driver).to be_an_instance_of(Capybara::Selenium::Driver)
      end
    end

    describe '#mode' do
      it "should remember the mode" do
        expect(@session.mode).to eq(mode)
      end
    end

    describe "#reset!" do
      it "freshly reset session should not be touched" do
        @session.instance_variable_set(:@touched, true)
        @session.reset!
        expect(@session.instance_variable_get(:@touched)).to eq false
      end
    end

    describe "exit codes" do
      before do
        @current_dir = Dir.getwd
        Dir.chdir(File.join(File.dirname(__FILE__), '..'))
        @env = { 'SELENIUM_BROWSER' => @session.driver.options[:browser].to_s }
        @env['LEGACY_FIREFOX'] = 'TRUE' if mode == :selenium_firefox
      end

      after do
        Dir.chdir(@current_dir)
      end

      it "should have return code 1 when running selenium_driver_rspec_failure.rb" do
        skip if ENV['HEADLESS']
        system(@env, 'rspec spec/fixtures/selenium_driver_rspec_failure.rb', out: File::NULL, err: File::NULL)
        expect($?.exitstatus).to eq(1)
      end

      it "should have return code 0 when running selenium_driver_rspec_success.rb" do
        skip if ENV['HEADLESS']
        system(@env, 'rspec spec/fixtures/selenium_driver_rspec_success.rb', out: File::NULL, err: File::NULL)
        expect($?.exitstatus).to eq(0)
      end
    end

    describe "#accept_alert" do
      it "supports a blockless mode" do
        @session.visit('/with_js')
        @session.click_link('Open alert')
        @session.accept_alert
        expect{@session.driver.browser.switch_to.alert}.to raise_error(@session.driver.send(:modal_error))
      end

      it "can be called before visiting" do
        @session.accept_alert "Initial alert" do
          @session.visit('/initial_alert')
        end
        expect(@session).to have_text('Initial alert page')
      end
    end

    context '#fill_in_with empty string and no options' do
      it 'should trigger change when clearing a field' do
        @session.visit('/with_js')
        @session.fill_in('with_change_event', with: '')
        # click outside the field to trigger the change event
        @session.find(:css, 'body').click
        expect(@session).to have_selector(:css, '.change_event_triggered', match: :one)
      end
    end

    context "#fill_in with { :clear => :backspace } fill_option", requires: [:js] do
      it 'should fill in a field, replacing an existing value' do
        @session.visit('/form')
        @session.fill_in('form_first_name', with: 'Harry',
                          fill_options: { clear: :backspace} )
        expect(@session.find(:fillable_field, 'form_first_name').value).to eq('Harry')
      end

      it 'should only trigger onchange once' do
        @session.visit('/with_js')
        @session.fill_in('with_change_event', with: 'some value',
                         fill_options: { :clear => :backspace })
        # click outside the field to trigger the change event
        @session.find(:css, 'body').click
        expect(@session.find(:css, '.change_event_triggered', match: :one)).to have_text 'some value'
      end

      it 'should trigger change when clearing field' do
        @session.visit('/with_js')
        @session.fill_in('with_change_event', with: '',
                         fill_options: { :clear => :backspace })
        # click outside the field to trigger the change event
        @session.find(:css, 'body').click
        expect(@session).to have_selector(:css, '.change_event_triggered', match: :one)
      end

      it 'should trigger input event field_value.length times' do
        @session.visit('/with_js')
        @session.fill_in('with_change_event', with: '',
                         fill_options: { :clear => :backspace })
        # click outside the field to trigger the change event
        @session.find(:css, 'body').click
        expect(@session).to have_xpath('//p[@class="input_event_triggered"]', count: 13)
      end
    end

    context "#fill_in with { clear: :none } fill_options" do
      it 'should append to content in a field' do
        @session.visit('/form')
        @session.fill_in('form_first_name', with: 'Harry',
                          fill_options: { clear: :none} )
        expect(@session.find(:fillable_field, 'form_first_name').value).to eq('JohnHarry')
      end
    end

    context "#fill_in with { clear: Array } fill_options" do
      it 'should pass the array through to the element' do
        pending "selenium-webdriver/geckodriver doesn't support complex sets of characters" if marionette?(@session)
        #this is mainly for use with [[:control, 'a'], :backspace] - however since that is platform dependant I'm testing with something less useful
        @session.visit('/form')
        @session.fill_in('form_first_name', with: 'Harry',
                          fill_options: { clear: [[:shift, 'abc'], :backspace] } )
        expect(@session.find(:fillable_field, 'form_first_name').value).to eq('JohnABHarry')
      end
    end

    describe "#path" do
      it "returns xpath" do
        # this is here because it is testing for an XPath that is specific to the algorithm used in the selenium driver
        @session.visit('/path')
        element = @session.find(:link, 'Second Link')
        expect(element.path).to eq('/html/body/div[2]/a[1]')
      end
    end

    describe "all with disappearing elements" do
      it "ignores stale elements in results" do
        @session.visit('/path')
        elements = @session.all(:link) { |node| raise Selenium::WebDriver::Error::StaleElementReferenceError }
        expect(elements.size).to eq 0
      end
    end

    describe "#evaluate_script" do
      it "can return an element" do
        @session.visit('/form')
        element = @session.evaluate_script("document.getElementById('form_title')")
        expect(element).to eq @session.find(:id, 'form_title')
      end

      it "can return arrays of nested elements" do
        @session.visit('/form')
        elements = @session.evaluate_script('document.querySelectorAll("#form_city option")')
        elements.each do |el|
          expect(el).to be_instance_of Capybara::Node::Element
        end
        expect(elements).to eq @session.find(:css, '#form_city').all(:css, 'option').to_a
      end

      it "can return hashes with elements" do
        @session.visit('/form')
        result = @session.evaluate_script("{ a: document.getElementById('form_title'), b: {c: document.querySelectorAll('#form_city option')}}")
        expect(result).to eq({
          'a' => @session.find(:id, 'form_title'),
          'b' => {
            'c' => @session.find(:css, '#form_city').all(:css, 'option').to_a
          }
        })
      end

      describe "#evaluate_async_script" do
        it "will timeout if the script takes too long" do
          @session.visit('/with_js')
          expect do
            @session.using_wait_time(1) do
              @session.evaluate_async_script("var cb = arguments[0]; setTimeout(function(){ cb(null) }, 3000)")
            end
          end.to raise_error Selenium::WebDriver::Error::ScriptTimeoutError
        end
      end
    end

    describe "Element#inspect" do
      it "outputs obsolete elements" do
        @session.visit('/form')
        el = @session.find(:button, 'Click me!').click
        expect(@session).to have_no_button('Click me!')
        expect(el).not_to receive(:synchronize)
        expect(el.inspect).to eq "Obsolete #<Capybara::Node::Element>"
      end
    end

    describe "Element#click" do
      it "should handle fixed headers/footers" do
        @session.visit('/with_fixed_header_footer')
        # @session.click_link('Go to root')
        @session.find(:link, 'Go to root').click
        expect(@session).to have_current_path('/')
      end
    end
  end
end


text:
/**
 * @file xmss.h
 * Includes headers required for Extended Hash-Based Signatures (XMSS)
 * as described in [1]. @see Botan::XMSS_PublicKey and @see
 * Botan::XMSS_PrivateKey for further
 * details.
 *
 * <pre>
 * [1] XMSS: Extended Hash-Based Signatures,
 *     Request for Comments: 8391
 *     Release: May 2018.
 *     https://datatracker.ietf.org/doc/rfc8391/
 * </pre>
 *
 * (C) 2016,2017,2018 Matthias Gierlings
 *
 * Botan is released under the Simplified BSD License (see license.txt)
 **/

#ifndef BOTAN_XMSS_H_
#define BOTAN_XMSS_H_

#include <botan/xmss_publickey.h>
#include <botan/xmss_privatekey.h>

#endif


text:
package org.apache.sshd.common.channel;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channel;

/**
 * TODO Add javadoc
 *
 * @author Apache MINA SSHD Project
 */
public class ChannelPipedOutputStream extends OutputStream implements Channel {

    private final ChannelPipedSink sink;
    private final byte[] b = new byte[1];
    private boolean closed;

    public ChannelPipedOutputStream(ChannelPipedSink sink) {
        this.sink = sink;
    }

    @Override
    public void write(int i) throws IOException {
        synchronized (b) {
            b[0] = (byte) i;
            write(b, 0, 1);
        }
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (!isOpen()) {
            throw new IOException("write(len=" + len + ") Stream has been closed");
        }
        sink.receive(b, off, len);
    }

    @Override
    public boolean isOpen() {
        return !closed;
    }

    @Override
    public void flush() throws IOException {
        if (!isOpen()) {
            throw new IOException("flush() Stream has been closed");
        }
    }

    @Override
    public void close() throws IOException {
        if (isOpen()) {
            try {
                sink.eof();
            } finally {
                closed = true;
            }
        }
    }
}


text:
require "testing/nonstandard_lro_grpc/nonstandard_lro_grpc_pb"
require "google/cloud/location"

module Testing
  module NonstandardLroGrpc
    module AnotherLroProvider
      ##
      # Client for the AnotherLroProvider service.
      #
      class Client
        # @private
        attr_reader :another_lro_provider_stub

        ##
        # Configure the AnotherLroProvider Client class.
        #
        # See {::Testing::NonstandardLroGrpc::AnotherLroProvider::Client::Configuration}
        # for a description of the configuration fields.
        #
        # @example
        #
        #   # Modify the configuration for all AnotherLroProvider clients
        #   ::Testing::NonstandardLroGrpc::AnotherLroProvider::Client.configure do |config|
        #     config.timeout = 10.0
        #   end
        #
        # @yield [config] Configure the Client client.
        # @yieldparam config [Client::Configuration]
        #
        # @return [Client::Configuration]
        #
        def self.configure
          @configure ||= begin
            default_config = Client::Configuration.new

            default_config
          end
          yield @configure if block_given?
          @configure
        end

        ##
        # Configure the AnotherLroProvider Client instance.
        #
        # The configuration is set to the derived mode, meaning that values can be changed,
        # but structural changes (adding new fields, etc.) are not allowed. Structural changes
        # should be made on {Client.configure}.
        #
        # See {::Testing::NonstandardLroGrpc::AnotherLroProvider::Client::Configuration}
        # for a description of the configuration fields.
        #
        # @yield [config] Configure the Client client.
        # @yieldparam config [Client::Configuration]
        #
        # @return [Client::Configuration]
        #
        def configure
          yield @config if block_given?
          @config
        end

        ##
        # Create a new AnotherLroProvider client object.
        #
        # @example
        #
        #   # Create a client using the default configuration
        #   client = ::Testing::NonstandardLroGrpc::AnotherLroProvider::Client.new
        #
        #   # Create a client using a custom configuration
        #   client = ::Testing::NonstandardLroGrpc::AnotherLroProvider::Client.new do |config|
        #     config.timeout = 10.0
        #   end
        #
        # @yield [config] Configure the AnotherLroProvider client.
        # @yieldparam config [Client::Configuration]
        #
        def initialize
          # These require statements are intentionally placed here to initialize
          # the gRPC module only when it's required.
          # See https://github.com/googleapis/toolkit/issues/446
          require "gapic/grpc"
          require "testing/nonstandard_lro_grpc/nonstandard_lro_grpc_services_pb"

          # Create the configuration object
          @config = Configuration.new Client.configure

          # Yield the configuration if needed
          yield @config if block_given?

          # Create credentials
          credentials = @config.credentials
          # Use self-signed JWT if the endpoint is unchanged from default,
          # but only if the default endpoint does not have a region prefix.
          enable_self_signed_jwt = @config.endpoint == Client.configure.endpoint &&
                                   !@config.endpoint.split(".").first.include?("-")
          credentials ||= Credentials.default scope: @config.scope,
                                              enable_self_signed_jwt: enable_self_signed_jwt
          if credentials.is_a?(::String) || credentials.is_a?(::Hash)
            credentials = Credentials.new credentials, scope: @config.scope
          end
          @quota_project_id = @config.quota_project
          @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id

          @location_client = Google::Cloud::Location::Locations::Client.new do |config|
            config.credentials = credentials
            config.quota_project = @quota_project_id
            config.endpoint = @config.endpoint
          end

          @another_lro_provider_stub = ::Gapic::ServiceStub.new(
            ::Testing::NonstandardLroGrpc::AnotherLroProvider::Stub,
            credentials:  credentials,
            endpoint:     @config.endpoint,
            channel_args: @config.channel_args,
            interceptors: @config.interceptors
          )
        end

        ##
        # Get the associated client for mix-in of the Locations.
        #
        # @return [Google::Cloud::Location::Locations::Client]
        #
        attr_reader :location_client

        # Service calls

        ##
        # @overload get_another(request, options = nil)
        #   Pass arguments to `get_another` via a request object, either of type
        #   {::Testing::NonstandardLroGrpc::LroAnotherGetRequest} or an equivalent Hash.
        #
        #   @param request [::Testing::NonstandardLroGrpc::LroAnotherGetRequest, ::Hash]
        #     A request object representing the call parameters. Required. To specify no
        #     parameters, or to keep all the default parameter values, pass an empty Hash.
        #   @param options [::Gapic::CallOptions, ::Hash]
        #     Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
        #
        # @overload get_another(another_request_id: nil, another_lro_name: nil)
        #   Pass arguments to `get_another` via keyword arguments. Note that at
        #   least one keyword argument is required. To specify no parameters, or to keep all
        #   the default parameter values, pass an empty Hash as a request object (see above).
        #
        #   @param another_request_id [::String]
        #   @param another_lro_name [::String]
        #
        # @yield [response, operation] Access the result along with the RPC operation
        # @yieldparam response [::Testing::NonstandardLroGrpc::NonstandardOperation]
        # @yieldparam operation [::GRPC::ActiveCall::Operation]
        #
        # @return [::Testing::NonstandardLroGrpc::NonstandardOperation]
        #
        # @raise [::GRPC::BadStatus] if the RPC is aborted.
        #
        # @example Basic example
        #   require "testing/nonstandard_lro_grpc"
        #
        #   # Create a client object. The client can be reused for multiple calls.
        #   client = Testing::NonstandardLroGrpc::AnotherLroProvider::Client.new
        #
        #   # Create a request. To set request fields, pass in keyword arguments.
        #   request = Testing::NonstandardLroGrpc::LroAnotherGetRequest.new
        #
        #   # Call the get_another method.
        #   result = client.get_another request
        #
        #   # The returned object is of type Testing::NonstandardLroGrpc::NonstandardOperation.
        #   p result
        #
        def get_another request, options = nil
          raise ::ArgumentError, "request must be provided" if request.nil?

          request = ::Gapic::Protobuf.coerce request, to: ::Testing::NonstandardLroGrpc::LroAnotherGetRequest

          # Converts hash and nil to an options object
          options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h

          # Customize the options with defaults
          metadata = @config.rpcs.get_another.metadata.to_h

          # Set x-goog-api-client and x-goog-user-project headers
          metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
            lib_name: @config.lib_name, lib_version: @config.lib_version,
            gapic_version: ::Testing::VERSION
          metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id

          options.apply_defaults timeout:      @config.rpcs.get_another.timeout,
                                 metadata:     metadata,
                                 retry_policy: @config.rpcs.get_another.retry_policy

          options.apply_defaults timeout:      @config.timeout,
                                 metadata:     @config.metadata,
                                 retry_policy: @config.retry_policy

          @another_lro_provider_stub.call_rpc :get_another, request, options: options do |response, operation|
            yield response, operation if block_given?
            return response
          end
        end

        ##
        # Configuration class for the AnotherLroProvider API.
        #
        # This class represents the configuration for AnotherLroProvider,
        # providing control over timeouts, retry behavior, logging, transport
        # parameters, and other low-level controls. Certain parameters can also be
        # applied individually to specific RPCs. See
        # {::Testing::NonstandardLroGrpc::AnotherLroProvider::Client::Configuration::Rpcs}
        # for a list of RPCs that can be configured independently.
        #
        # Configuration can be applied globally to all clients, or to a single client
        # on construction.
        #
        # @example
        #
        #   # Modify the global config, setting the timeout for
        #   # get_another to 20 seconds,
        #   # and all remaining timeouts to 10 seconds.
        #   ::Testing::NonstandardLroGrpc::AnotherLroProvider::Client.configure do |config|
        #     config.timeout = 10.0
        #     config.rpcs.get_another.timeout = 20.0
        #   end
        #
        #   # Apply the above configuration only to a new client.
        #   client = ::Testing::NonstandardLroGrpc::AnotherLroProvider::Client.new do |config|
        #     config.timeout = 10.0
        #     config.rpcs.get_another.timeout = 20.0
        #   end
        #
        # @!attribute [rw] endpoint
        #   The hostname or hostname:port of the service endpoint.
        #   Defaults to `"nonstandardlro.example.com"`.
        #   @return [::String]
        # @!attribute [rw] credentials
        #   Credentials to send with calls. You may provide any of the following types:
        #    *  (`String`) The path to a service account key file in JSON format
        #    *  (`Hash`) A service account key as a Hash
        #    *  (`Google::Auth::Credentials`) A googleauth credentials object
        #       (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
        #    *  (`Signet::OAuth2::Client`) A signet oauth2 client object
        #       (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
        #    *  (`GRPC::Core::Channel`) a gRPC channel with included credentials
        #    *  (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
        #    *  (`nil`) indicating no credentials
        #   @return [::Object]
        # @!attribute [rw] scope
        #   The OAuth scopes
        #   @return [::Array<::String>]
        # @!attribute [rw] lib_name
        #   The library name as recorded in instrumentation and logging
        #   @return [::String]
        # @!attribute [rw] lib_version
        #   The library version as recorded in instrumentation and logging
        #   @return [::String]
        # @!attribute [rw] channel_args
        #   Extra parameters passed to the gRPC channel. Note: this is ignored if a
        #   `GRPC::Core::Channel` object is provided as the credential.
        #   @return [::Hash]
        # @!attribute [rw] interceptors
        #   An array of interceptors that are run before calls are executed.
        #   @return [::Array<::GRPC::ClientInterceptor>]
        # @!attribute [rw] timeout
        #   The call timeout in seconds.
        #   @return [::Numeric]
        # @!attribute [rw] metadata
        #   Additional gRPC headers to be sent with the call.
        #   @return [::Hash{::Symbol=>::String}]
        # @!attribute [rw] retry_policy
        #   The retry policy. The value is a hash with the following keys:
        #    *  `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
        #    *  `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
        #    *  `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
        #    *  `:retry_codes` (*type:* `Array<String>`) - The error codes that should
        #       trigger a retry.
        #   @return [::Hash]
        # @!attribute [rw] quota_project
        #   A separate project against which to charge quota.
        #   @return [::String]
        #
        class Configuration
          extend ::Gapic::Config

          config_attr :endpoint,      "nonstandardlro.example.com", ::String
          config_attr :credentials,   nil do |value|
            allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
            allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
            allowed.any? { |klass| klass === value }
          end
          config_attr :scope,         nil, ::String, ::Array, nil
          config_attr :lib_name,      nil, ::String, nil
          config_attr :lib_version,   nil, ::String, nil
          config_attr(:channel_args,  { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil)
          config_attr :interceptors,  nil, ::Array, nil
          config_attr :timeout,       nil, ::Numeric, nil
          config_attr :metadata,      nil, ::Hash, nil
          config_attr :retry_policy,  nil, ::Hash, ::Proc, nil
          config_attr :quota_project, nil, ::String, nil

          # @private
          def initialize parent_config = nil
            @parent_config = parent_config unless parent_config.nil?

            yield self if block_given?
          end

          ##
          # Configurations for individual RPCs
          # @return [Rpcs]
          #
          def rpcs
            @rpcs ||= begin
              parent_rpcs = nil
              parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs)
              Rpcs.new parent_rpcs
            end
          end

          ##
          # Configuration RPC class for the AnotherLroProvider API.
          #
          # Includes fields providing the configuration for each RPC in this service.
          # Each configuration object is of type `Gapic::Config::Method` and includes
          # the following configuration fields:
          #
          #  *  `timeout` (*type:* `Numeric`) - The call timeout in seconds
          #  *  `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
          #  *  `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
          #     include the following keys:
          #      *  `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
          #      *  `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
          #      *  `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
          #      *  `:retry_codes` (*type:* `Array<String>`) - The error codes that should
          #         trigger a retry.
          #
          class Rpcs
            ##
            # RPC-specific configuration for `get_another`
            # @return [::Gapic::Config::Method]
            #
            attr_reader :get_another

            # @private
            def initialize parent_rpcs = nil
              get_another_config = parent_rpcs.get_another if parent_rpcs.respond_to? :get_another
              @get_another = ::Gapic::Config::Method.new get_another_config

              yield self if block_given?
            end
          end
        end
      end
    end
  end
end


text: Repository for our work done for the web ranger competition


text:
package BrickWall_554;

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

/**
 * There is a brick wall in front of you. The wall is rectangular and has several rows of bricks.
 * The bricks have the same height but different width. You want to draw a vertical line
 * from the top to the bottom and cross the least bricks.
 *
 * The brick wall is represented by a list of rows.
 * Each row is a list of integers representing the width of each brick in this row from left to right.
 *
 * If your line go through the edge of a brick, then the brick is not considered as crossed.
 * You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.
 *
 * You cannot draw a line just along one of the two vertical edges of the wall,
 * in which case the line will obviously cross no bricks.
 *
 * Example:
 * Input:
 * [[1,2,2,1],
 * [3,1,2],
 * [1,3,2],
 * [2,4],
 * [3,1,2],
 * [1,3,1,1]]
 * Output: 2
 *
 * Note:
 * The width sum of bricks in different rows are the same and won't exceed INT_MAX.
 * The number of bricks in each row is in range [1,10,000].
 * The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.
 */
public class Solution {
    // intuitive thought:
    // the line must lies on the "gaps" between bricks
    // if not the line must crossed the number of rows.
    // there are at most n-1 gaps in one row(n is the width of the row)
    // imagine 1,1,1,1,1 (four gaps)
    // memory limit exceeded..
    public int leastBricks2(List<List<Integer>> wall) {
        if(wall.size()==0) return 0;
        int width = 0;
        for(int i:wall.get(0)) width += i;
        // so there are gaps 1, 2, ..., width - 1
        // now we calculate the bricks across the gap, then return the gap with
        // least crossing brick
        // map it using array.
        int[] map = new int[width];
        for(List<Integer> l:wall){
            int tm = 0;
            for(Integer b:l){
                for(int p=tm+1;p<tm+b;p++){
                    map[p]++;
                }
                tm+=b;
            }
        }
        int rs = Integer.MAX_VALUE;
        for(int i=1;i<width;i++)
            if(map[i]<rs)
                rs = map[i];
        return rs;
    }

    // the opposite way:
    // record down how many times every gap been reached.
    // the most "reached" gap is the answer. And the answer is
    // rows - most reached times
    public int leastBricks(List<List<Integer>> wall){
        if(wall.size()==0) return 0;
        int width = 0, maxTouch = 0;
        for(int i:wall.get(0)) width += i;
        Map<Integer, Integer> map = new HashMap<>();
        for(List<Integer> l:wall){
            int p = 0;
            for(int i:l){
                if((p+=i) != width){
                    Integer gap = map.get(p);
                    if(gap==null) gap = 0;
                    map.put(p, ++gap);
                    maxTouch = Math.max(maxTouch, gap);
                }
            }
        }
        return wall.size() - maxTouch;
    }
}


text:
using SharpDX;
using SharpDX.Toolkit;

namespace DXFramework.Tweening
{
	public class Tweener
	{
		private IEaseFunction easeFunction;
		private Vector2 from;
		private Vector2 to;
		private Vector2 distance;
		private float duration;
		private float invDuration;
		private float elapsed;

		public Tweener( Vector2 from, Vector2 to, float duration, IEaseFunction easeFunction )
		{
			this.from = from;
			this.to = to;
			this.duration = duration;
			this.easeFunction = easeFunction;

			invDuration = 1f / duration;
			distance = to - from;
			Restart();
		}

		public TweenState State { get; private set; }

		public Vector2 Value { get; private set; }

		public bool Done
		{
			get { return State == TweenState.Stopped; }
		}

		public void Restart()
		{
			State = TweenState.Running;
			Value = from;
			elapsed = 0;
		}

		public void Pause()
		{
			if( State == TweenState.Running )
			{
				State = TweenState.Paused;
			}
		}

		public void Resume()
		{
			switch( State )
			{
				case TweenState.Paused:
					State = TweenState.Running;
					break;

				case TweenState.Stopped:
					Restart();
					break;
			}
		}

		public void Stop()
		{
			Value = to;
			State = TweenState.Stopped;
		}

		public void Revert()
		{
			to = from;
			from = Value;
			distance = to - from;
			State = TweenState.Running;
			elapsed = 0;
		}

		public void Update( GameTime gameTime )
		{
			if( State != TweenState.Running )
			{
				return;
			}

			elapsed += (float)gameTime.ElapsedGameTime.TotalSeconds;

			if( elapsed >= duration )
			{
				Stop();
				return;
			}

			Value = from + distance * easeFunction.Update( elapsed * invDuration );
		}

		public enum TweenState
		{
			Running,
			Paused,
			Stopped,
		}
	}
}


text:
(function (global) {
    var app = global.app = global.app || {};

    document.addEventListener("deviceready", function () {
        app.application = new kendo.mobile.Application(document.body, { layout: "tabstrip-layout" });
    }, false);

})(window);


text:
require 'rails_helper'

RSpec.describe RdMailer, type: :mailer do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
using System;
using System.IO;

namespace Wire.ValueSerializers
{
    public class ObjectReferenceSerializer : ValueSerializer
    {
        public static readonly ObjectReferenceSerializer Instance = new ObjectReferenceSerializer();

        public override void WriteManifest(Stream stream, Type type, SerializerSession session)
        {
            stream.WriteByte(253);
        }

        public override void WriteValue(Stream stream, object value, SerializerSession session)
        {
            stream.WriteInt32((int) value);
        }

        public override object ReadValue(Stream stream, SerializerSession session)
        {
            var id = stream.ReadInt32(session);
            var obj = session.ObjectById[id];
            return obj;
        }

        public override Type GetElementType()
        {
            throw new NotImplementedException();
        }
    }
}


text:
 - Instalar _juju_.

 - Utilizando _juju_, instalar _MySQL_ en un táper.

###Pasos realizados para la resolución del ejercicio:

1. Para instalar _juju_ (y sus dependencias correspondientes), se utiliza el comando

 `apt-get install juju`

2. Inicializar y definir la configuración inicial de los entornos con los que puede trabajar _juju_

 `juju init`

3. Editar el archivo `~/.juju/environments.yaml`, sustituyendo la línea `default: amazon` por `default: local`

4. De ser necesario, instalar _MongoDB_, con el comando

 `apt-get install mongodb-server`

5. Instalar el componente para el manejo local de contenedores locales de _juju_

 `apt-get install juju-local`

6. Inicializar ambiente de virtualización local con _juju_, utilizando la configuración definida por defecto

 `juju bootstrap`

7. Añadir el servicio _MySQL_ (utilizando _charms_ o _encantos_) a un nuevo _táper_

 `juju deploy mysql`

8. Para validar que se ha instalado y desplegado _MySQL_ en el _táper_ correspondiente, se puede utilizar el comando

 `juju status`


text:
use warnings;
use strict;

# convert a game type string to the internal tenhou game type id
#
# this function is *tremendously* important: it should work fine unless things
# change on tenhou, in which case behaviour is UNDEFINED. for this reason,
# gtypestr_sc MUST be called to ensure a safe conversion
sub str2gtype($) {
    my $str = shift;
    my $gtype = 0 | 0x0001; # multiplayer
    $gtype |= 0x0002 unless($str =~ /赤/); # no red 5s
    $gtype |= 0x0004 unless($str =~ /喰/); # no open tanyao
    $gtype |= 0x0008 if($str =~ /南/); # south
    $gtype |= 0x0010 if($str =~ /三/); # 3man
    $gtype |= 0x0020 if($str =~ /(?:特|琥)/); # upperdan
    $gtype |= 0x0040 if($str =~ /速/); # fast
    $gtype |= 0x0080 if($str =~ /(?:上|銀)/); # dan
    $gtype |= 0x20 | 0x80 if($str =~ /(?:鳳|孔)/); # houou
    $gtype |= 0x0100 if($str =~ /暗/); # tsumokiri (discontinued)
    if($str =~ /祝/) { # shuugi/jansou/whatever modes
        if($str =~ /祝5/) { $gtype |= 0x200 | 0x400; } # chip and jansou mode
        elsif($str =~ /祝2/) { $gtype |= 0x200; } # just chip mode
        elsif($str =~ /祝0/) { $gtype |= 0x400; } # just jansou mode
        else { $gtype |= 0x400; } # this corresponds to 祝0 (I think)
    }
    $gtype |= 0x800 if($str =~ /技/); # tech mode

    return $gtype;

# last reviewed: Mon 03 Jun 2013 02:14:45 AM UTC
# last reviewed: TIMESTAM P
}

# cf. http://tenhou.net/1/script/tenhou.js
sub gt_ISJANS($)   { my $x = shift; return ($x & (0x200|0x400)) != 0; }
sub gt_ISTECH($)   { my $x = shift; return ($x & 0x800) != 0; }
sub gt_ISDAN($)    { my $x = shift; return ($x & (0x200|0x400|0x800)) == 0; }
sub gt_GETTAKU($)  { my $x = shift; return (($x&0x20)>>4) | (($x&0x80)>>7); }
sub gt_GETTAKU2($) {
    my $x = shift;
    return gt_GETTAKU($x)+(gt_ISJANS($x)?4:0)+(gt_ISTECH($x)?8:0);
}

sub gtype2str($) {
    my $gtype = shift;
    my @a = ("般","上","特","鳳","若","銀","琥","孔","技","-","-","-");
    my $str = (($gtype&0x0010) ? "三" : "四").
              $a[gt_GETTAKU2($gtype)].
              (gt_ISTECH($gtype) ? "" : $gtype & 0x8 ? "南" : "東").
              (gt_ISJANS($gtype) ?
                  #"喰赤".
                  ($gtype & 0x4   ? "" : "喰"). # tenhou.js adds these
                  ($gtype & 0x2   ? "" : "赤"). #  indiscriminately...
                  #(($gtype&0x8) ? "" : "速").
                  ($gtype & 0x40  ? "速" : "").
                  (((~$gtype)&0x200) ? "祝0" :($gtype&0x400)? "祝5" : "祝2")
              :
                  ($gtype & 0x4   ? "" : "喰").
                  ($gtype & 0x2   ? "" : "赤").
                  ($gtype & 0x40  ? "速" : "").
                  ($gtype & 0x100 ? "暗" : "").
                  ($gtype & 0x200 ? "祝" : ""));
    return $str;

# last reviewed: Mon 03 Jun 2013 02:25:53 AM UTC
}

# v Mon 03 Jun 2013 02:25:53 AM UTC
# remark: there does seem to be some possible loss of information here. because
# tsuno wants to stop these gametype strings from getting stupidly long, his
# version of gtype2str will assume that, for example, any ISJANS game will be
# with red fives. this isn't actually always the case as far as I can tell,
# e.g.: 四般南喰-祝 vs 四般南喰赤祝 (both of these have occurred). I have
# taken the decision to take each string at face value and assume nothing in
# the reverse direction when computing str2gtype, and then gtype2str should be
# an inverse function of str2gtype up to instances of "-" (which are scattered
# pretty randomly and are not worth(/even possible to be) keeping track of).
# the consequence of this is that maybe some games were played that were e.g.
# red fives, but turn up in the database as not red fives. the rationale behind
# this being OK is simply that tenhou publishes it in the same way. at the end
# of the day the difference between red5/fast/nashi is fairly trivial and my
# database should still concur with the strings that are published (again, up
# to instances of "-").

# another annoying thing is that by this truncation that tenhou does, we never
# know if a game played in a championship lobby that is ISJANS is 祝5 or 祝2
# or (the seemingly never-occurring) 祝0. thus we assume that it is only CHIP
# and not JANS, thereby making it come up as 祝0 always. this can either be
# explained on ranking.pl or another possible workaround is to just filter it
# out post-extraction-from-database. I see no good reason to play with this on
# a gtype level, since there is no way of knowing and this is a justifiably
# neutral way to store it.
# ^ Mon 03 Jun 2013 02:25:53 AM UTC

# game type string sanity check
#
# this function is just as important as str2gtype (if not more important) - it
# will check for a revised game type string format, returning 1 if everything
# is fine, 0 if something is wrong. I don't really have an intelligent way of
# detailing what is wrong with the return value, and the means for checking if
# something is wrong are quite primitive anyway so this function is not
# foolproof. still, we do our best to ensure data integrity
sub gtypestr_sc($) {
    my $str = shift;
    return 0 if($str =~ /[^般上特鳳若銀琥孔技-四三東南赤喰速暗025]/);
    return 1;

    # told you it was primitive...

# last reviewed: Mon 03 Jun 2013 02:14:45 AM UTC
# last reviewed: TIMESTAM P
}


text:
package com.github.ruediste.rise.core.security.web.rememberMe;

import com.github.ruediste.rise.core.security.authentication.core.AuthenticationSuccess;

/**
 * Interface for {@link AuthenticationSuccess}es which are aware of the concept
 * of a "rememeber-me" functionality.
 */
public interface RememberMeAwareAuthenticationSuccess extends AuthenticationSuccess {

    /**
     * return true if this authentication success succeeded using some
     * remeber-me technique.
     */
    boolean isSucceededThroughRememberMe();
}


text:
package org.jboss.resteasy.test.finegrain.resource;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.test.EmbeddedContainer;
import org.jboss.resteasy.util.HttpResponseCodes;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import static org.jboss.resteasy.test.TestPortProvider.generateURL;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class ComplexPathParamTest
{
   private static Dispatcher dispatcher;

   @Path("/")
   public static class ExtensionResource
   {
      @GET
      @Path("/{1},{2}/{3}/blah{4}-{5}ttt")
      public String get(@PathParam("1") int one, @PathParam("2") int two, @PathParam("3") int three,
                        @PathParam("4") int four, @PathParam("5") int five)
      {
         Assert.assertEquals(one, 1);
         Assert.assertEquals(two, 2);
         Assert.assertEquals(three, 3);
         Assert.assertEquals(four, 4);
         Assert.assertEquals(five, 5);
         return "hello";
      }

   }

   @Path("/tricky")
   public static class TrickyResource
   {
      @GET
      @Path("{hello}")
      public String getHello(@PathParam("hello") int one)
      {
         Assert.assertEquals(one, 1);
         return "hello";
      }

      @GET
      @Path("{1},{2}")
      public String get2Groups(@PathParam("1") int one, @PathParam("2") int two)
      {
         Assert.assertEquals(1, one);
         Assert.assertEquals(2, two);
         return "2Groups";
      }

      @GET
      @Path("h{1}")
      public String getPrefixed(@PathParam("1") int one)
      {
         Assert.assertEquals(1, one);
         return "prefixed";
      }
   }

   @Path("/unlimited")
   public static class UnlimitedResource
   {
      @Path("{1}-{rest:.*}")
      @GET
      public String get(@PathParam("1") int one, @PathParam("rest") String rest)
      {
         Assert.assertEquals(1, one);
         Assert.assertEquals("on/and/on", rest);
         return "ok";
      }
   }

   public static class Sub1
   {
      @GET
      public String get()
      {
         return "sub1";
      }
   }

   public static class Sub2
   {
      @GET
      public String get()
      {
         return "sub2";
      }
   }

   @Path("/repository/workspaces")
   public static class Resteasy145
   {
      @Path("{service: x.*}")
      public Sub1 getService(@PathParam("service") String serviceName)
      {
         return new Sub1();
      }

      @Path("{path:.*}")
      public Sub2 getChild(@PathParam("path") String path)
      {
         return new Sub2();
      }

   }

   @BeforeClass
   public static void before() throws Exception
   {
   }

   @AfterClass
   public static void after() throws Exception
   {
   }

   private void _test(String path, String body)
   {
      ClientRequest request = new ClientRequest(generateURL(path));
      try
      {
         ClientResponse<String> response = request.get(String.class);
         Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
         Assert.assertEquals(body, response.getEntity());
      } catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

   @Test
   public void testIt() throws Exception
   {
      dispatcher = EmbeddedContainer.start().getDispatcher();
      try
      {
         dispatcher.getRegistry().addPerRequestResource(ExtensionResource.class);
         dispatcher.getRegistry().addPerRequestResource(TrickyResource.class);
         dispatcher.getRegistry().addPerRequestResource(UnlimitedResource.class);
         dispatcher.getRegistry().addPerRequestResource(Resteasy145.class);
         _test("/1,2/3/blah4-5ttt", "hello");
         _test("/tricky/1,2", "2Groups");
         _test("/tricky/h1", "prefixed");
         _test("/tricky/1", "hello");
         _test("/unlimited/1-on/and/on", "ok");
         _test("/repository/workspaces/aaaaaaxvi/wdddd", "sub2");
      }
      finally
      {
         EmbeddedContainer.stop();
      }

   }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hoang.fu;

/**
 *
 * @author hoangpt
 */
public class Administrative extends Employee {

  @Override //annotation
  float calculateSalary(){
    return 1000f;
  }

}


text:
import {
	Agent as HttpAgent,
	request as httpRequest,
	type IncomingMessage,
	type RequestOptions,
} from 'http';
import {URL} from 'url';
import test from 'ava';
import is from '@sindresorhus/is';
import type {Handler} from 'express';
import delay from 'delay';
import got, {
	Options,
	type BeforeRequestHook,
	type Headers,
	type Hooks,
	type OptionsInit,
	type RequestFunction,
} from '../source/index.js';
import withServer from './helpers/with-server.js';

const echoHeaders: Handler = (request, response) => {
	request.resume();
	response.end(JSON.stringify(request.headers));
};

test('preserves global defaults', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const globalHeaders = await got('').json();
	const instanceHeaders = await got.extend()('').json();
	t.deepEqual(instanceHeaders, globalHeaders);
});

test('supports instance defaults', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instance = got.extend({
		headers: {
			'user-agent': 'custom-ua-string',
		},
	});
	const headers = await instance('').json<Headers>();
	t.is(headers['user-agent'], 'custom-ua-string');
});

test('supports invocation overrides', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instance = got.extend({
		headers: {
			'user-agent': 'custom-ua-string',
		},
	});
	const headers = await instance({
		headers: {
			'user-agent': 'different-ua-string',
		},
	}).json<Headers>();
	t.is(headers['user-agent'], 'different-ua-string');
});

test('carries previous instance defaults', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instanceA = got.extend({
		headers: {
			'x-foo': 'foo',
		},
	});
	const instanceB = instanceA.extend({
		headers: {
			'x-bar': 'bar',
		},
	});
	const headers = await instanceB('').json<Headers>();
	t.is(headers['x-foo'], 'foo');
	t.is(headers['x-bar'], 'bar');
});

test('custom headers (extend)', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const options = {headers: {unicorn: 'rainbow'}};

	const instance = got.extend(options);
	const headers = await instance('').json<Headers>();
	t.is(headers.unicorn, 'rainbow');
});

test('extend overwrites arrays with a deep clone', t => {
	const x = () => {};
	const y = () => {};

	const beforeRequest = [x];
	const a = got.extend({hooks: {beforeRequest} as unknown as Hooks});
	beforeRequest[0] = y;
	t.deepEqual(a.defaults.options.hooks.beforeRequest, [x] as unknown as BeforeRequestHook[]);
	t.not(a.defaults.options.hooks.beforeRequest, beforeRequest as unknown as BeforeRequestHook[]);
});

test('hooks are merged on got.extend()', t => {
	const hooksA = [() => {}];
	const hooksB = [() => {}];

	const instanceA = got.extend({hooks: {beforeRequest: hooksA}});

	const extended = instanceA.extend({hooks: {beforeRequest: hooksB}});
	t.deepEqual(extended.defaults.options.hooks.beforeRequest, [...hooksA, ...hooksB]);
});

test('custom endpoint with custom headers (extend)', withServer, async (t, server) => {
	server.all('/', echoHeaders);

	const instance = got.extend({headers: {unicorn: 'rainbow'}, prefixUrl: server.url});
	const headers = await instance('').json<Headers>();
	t.is(headers.unicorn, 'rainbow');
	t.not(headers['user-agent'], undefined);
});

test('no tampering with defaults', t => {
	t.throws(() => {
		got.defaults.options.prefixUrl = 'http://google.com';
	});

	t.is(got.defaults.options.prefixUrl, '');
});

test('can set defaults to `new Options(...)`', t => {
	const instance = got.extend({
		mutableDefaults: true,
		followRedirect: false,
	});

	t.notThrows(() => {
		instance.defaults.options = new Options({
			followRedirect: false,
		}, undefined, instance.defaults.options);
	});

	t.false(instance.defaults.options.followRedirect);

	t.notThrows(() => {
		instance.defaults.options = new Options({});
	});

	t.true(instance.defaults.options.followRedirect);
});

test('can set mutable defaults using got.extend', t => {
	const instance = got.extend({
		mutableDefaults: true,
		followRedirect: false,
	});

	t.notThrows(() => {
		instance.defaults.options.followRedirect = true;
	});

	t.true(instance.defaults.options.followRedirect);
});

test('only plain objects are freezed', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instance = got.extend({
		agent: {
			http: new HttpAgent({keepAlive: true}),
		},
		mutableDefaults: true,
	});

	t.notThrows(() => {
		(instance.defaults.options.agent as any).http.keepAlive = true;
	});
});

// eslint-disable-next-line ava/no-skip-test
test.skip('defaults are cloned on instance creation', t => {
	const options: OptionsInit = {hooks: {beforeRequest: [() => {}]}};
	const instance = got.extend(options);
	const context = {
		foo: {},
	};

	t.notThrows(() => {
		options.context = context;
		delete options.hooks!.beforeRequest![0];
	});

	t.not(options.context!.foo, instance.defaults.options.context.foo);
	t.not(options.hooks!.beforeRequest, instance.defaults.options.hooks.beforeRequest);
});

test('ability to pass a custom request method', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	let isCalled = false;

	const request: RequestFunction = (...args: [
		string | URL | RequestOptions,
		(RequestOptions | ((response: IncomingMessage) => void))?,
		((response: IncomingMessage) => void)?,
	]) => {
		isCalled = true;
		// @ts-expect-error Overload error
		return httpRequest(...args);
	};

	const instance = got.extend({request});
	await instance('');

	t.true(isCalled);
});

test('does not include the `request` option in normalized `http` options', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	let isCalled = false;

	const request: RequestFunction = (...args: [
		string | URL | RequestOptions,
		(RequestOptions | ((response: IncomingMessage) => void))?,
		((response: IncomingMessage) => void)?,
	]) => {
		isCalled = true;

		t.false(Reflect.has(args[0] as RequestOptions, 'request'));

		// @ts-expect-error Overload error
		return httpRequest(...args);
	};

	const instance = got.extend({request});
	await instance('');

	t.true(isCalled);
});

test('should pass an options object into an initialization hook after .extend', withServer, async (t, server, got) => {
	t.plan(1);

	server.get('/', echoHeaders);

	let first = true;

	const instance = got.extend({
		hooks: {
			init: [
				options => {
					if (!first) {
						t.deepEqual(options, {});
					}

					first = false;
				},
			],
		},
	});

	await instance('', {});
});

test('hooks aren\'t overriden when merging options', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	let isCalled = false;
	const instance = got.extend({
		hooks: {
			beforeRequest: [
				() => {
					isCalled = true;
				},
			],
		},
	});

	await instance({});

	t.true(isCalled);
});

test('extend with custom handlers', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instance = got.extend({
		handlers: [
			(options, next) => {
				options.headers.unicorn = 'rainbow';
				return next(options);
			},
		],
	});
	const headers = await instance('').json<Headers>();
	t.is(headers.unicorn, 'rainbow');
});

test('extend with instances', t => {
	const a = got.extend({prefixUrl: new URL('https://example.com/')});
	const b = got.extend(a);
	t.is(b.defaults.options.prefixUrl.toString(), 'https://example.com/');
});

test('extend with a chain', t => {
	const a = got.extend({prefixUrl: 'https://example.com/'});
	const b = got.extend(a, {headers: {foo: 'bar'}});
	t.is(b.defaults.options.prefixUrl.toString(), 'https://example.com/');
	t.is(b.defaults.options.headers.foo, 'bar');
});

test('async handlers', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instance = got.extend({
		handlers: [
			(options, next) => {
				if (options.isStream) {
					return next(options);
				}

				return (async () => {
					const result = await next(options);
					// @ts-expect-error Manual tests
					result.modified = true;

					return result;
				})();
			},
		],
	});

	const promise = instance('');
	t.true(is.function_(promise.cancel));
	// @ts-expect-error Manual tests
	t.true((await promise).modified);
});

test('async handlers can throw', async t => {
	const message = 'meh';

	const instance = got.extend({
		handlers: [
			async () => {
				throw new Error(message);
			},
		],
	});

	await t.throwsAsync(instance('https://example.com'), {
		instanceOf: Error,
		message,
	});
});

test('setting dnsCache to true points to global cache', t => {
	const a = got.extend({
		dnsCache: true,
	});

	const b = got.extend({
		dnsCache: true,
	});

	t.is(a.defaults.options.dnsCache, b.defaults.options.dnsCache);
});

test('waits for handlers to finish', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instance = got.extend({
		handlers: [
			async (options, next) => {
				await delay(1000);
				return next(options);
			},
			async (options, next) => {
				options.headers.foo = 'bar';
				return next(options);
			},
		],
	});

	const {foo} = await instance('').json<{foo: 'bar'}>();
	t.is(foo, 'bar');
});

test('does not append to internal _init on new requests', withServer, async (t, server, got) => {
	server.get('/', echoHeaders);

	const instance = got.extend({
		mutableDefaults: true,
	});

	const {length} = (instance.defaults.options as any)._init;

	await got('', {
		context: {},
	});

	t.is((instance.defaults.options as any)._init.length, length);
});


text:
/**
 *
 */
package org.jbehave.core.steps.weld;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Singleton;

import org.jbehave.core.annotations.weld.WeldConfiguration;
import org.jbehave.core.annotations.weld.WeldStep;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.steps.AbstractStepsFactory;
import org.jbehave.core.steps.InjectableStepsFactory;

/**
 * An {@link InjectableStepsFactory} that uses a Weld {@link Inject} for the
 * composition and instantiation of all components that contain JBehave
 * annotated methods.
 *
 * @author Aaron Walker
 */
@Singleton
public class WeldStepsFactory extends AbstractStepsFactory {

    @Inject
    @Any
    @WeldStep
    private Instance<Object> instances;

    @Inject
    public WeldStepsFactory(@WeldConfiguration Configuration configuration) {
        super(configuration);
    }

    @Override
    protected List<Class<?>> stepsTypes() {
        List<Class<?>> types = new ArrayList<Class<?>>();
        for (Object o : instances) {
            types.add(o.getClass());
        }
        return types;
    }

    public Object createInstanceOfType(Class<?> type) {
        for (Object o : instances) {
            if ( type.equals(o.getClass())){
                return o;
            }
        }
        throw new StepsInstanceNotFound(type, this);
    }

}


text:
require 'spec_helper'

describe FayeRails::Controller::Channel do

  let(:channel) { double(:channel) }
  let(:endpoint) { double(:endpoint) }
  let(:client) { double(:client) }
  subject { FayeRails::Controller::Channel.new(channel, endpoint) }

  describe '#client' do
    example do
      FayeRails.should_receive(:client).with(endpoint)
      subject.client
    end
  end

  describe '#publish' do
    example do
      subject.should_receive(:client).and_return(client)
      client.should_receive(:publish).with(channel, "Hello bob")
      subject.publish("Hello bob")
    end
  end

  describe "#monitor" do
    it "raises ArgumentError for unknown event" do
      expect { subject.monitor(:blarg) }.to raise_error(ArgumentError, /^Unknown event/)
    end

    example do
    end
  end

end


text:
package org.assertj.core.util;

import static org.assertj.core.util.Lists.newArrayList;
import static org.assertj.core.api.Assertions.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.junit.Test;

/**
 * Tests for <code>{@link IterableUtil#isNullOrEmpty(Iterable)}</code>.
 *
 * @author Alex Ruiz
 */
public class IterableUtil_isNullOrEmpty_Test {
  @Test
  public void should_return_true_if_Collection_is_empty() {
    Iterable<String> c = new ArrayList<>();
    assertThat(IterableUtil.isNullOrEmpty(c)).isTrue();
  }

  @Test
  public void should_return_false_if_Collection_has_elements() {
    Iterable<String> c = newArrayList("Frodo");
    assertThat(IterableUtil.isNullOrEmpty(c)).isFalse();
  }

  @Test
  public void should_return_true_if_Iterable_is_empty() {
    Iterable<String> i = new StringIterable();
    assertThat(IterableUtil.isNullOrEmpty(i)).isTrue();
  }

  @Test
  public void should_return_true_if_Iterable_is_null() {
    assertThat(IterableUtil.isNullOrEmpty(null)).isTrue();
  }

  @Test
  public void should_return_false_if_Iterable_has_elements() {
    Iterable<String> i = new StringIterable("Frodo");
    assertThat(IterableUtil.isNullOrEmpty(i)).isFalse();
  }

  private static class StringIterable implements Iterable<String> {
    private final List<String> elements;

    StringIterable(String...elements) {
      this.elements = Lists.newArrayList(elements);
    }

    @Override
    public Iterator<String> iterator() {
      return elements.iterator();
    }
  }
}


text:
/**
***		Opcodes, Opcode Types, and Opcode Flags
***		---------------------------------------
***
*** Description:
***
***	This interface describes all the opcode names, operators,
***	types associated with opcodes, and properties associated with opcodes.
***	The files opcode_gen_core.h and opcode_gen_core.c are generated by
***	running './opcodegen', which uses perl prodecure calls to encode
***	all legal opcodes and types in a tabular form.
***
***	This code require absolutely no #includes to use, and is thus useful
***	for programs other than the compiler proper.
***
*** Reserved Prefixes:
***
***	OPC		for OPCODE members only.
***	OPR		for OPERATOR members only.
***	OPCODE		for other opcode information, e.g. external
***			function names.
***	OPERATOR	for the operator, i.e. untyped operation
***
*** Exported types:
***
***	OPCODE
***
***	    An enumerated type.  The members are generated automatically.
***	    All OPCODEs are prefixed with OPC.
***
***	    OPCODE has the following fields:
***
***	    const OPERATOR operator
***
***		The operator for this opcode.
***		E.g. OPCODE_operator(OPC_F8ADD) is OPR_ADD.
***
***	    const TYPE_ID rtype
***
***		The 'return type' of this opcode.
***		E.g. OPCODE_rtype(OPC_F8ADD) is MTYPE_F8.
***
***	    const TYPE_ID desc
***
***		The 'descriptor type' of this opcode.
***		E.g. OPCODE_desc(OPC_F8ADD) is MTYPE_V.
***
***	    An opcode is fully and uniquely defined by these three components.
***
***	OPERATOR
***
***	    An enumerated type representing the operator.
***	    These are all prefixed with OPR.
***
***	OPCODE_MAPCAT
***
***	    The annotation category for opcodes, one of
***
***		  OPCODE_MAPCAT_HDR
***		  OPCODE_MAPCAT_SCF
***		  OPCODE_MAPCAT_LDST
***		  OPCODE_MAPCAT_PRAGMA
***		  OPCODE_MAPCAT_OSTMT
***		  OPCODE_MAPCAT_OEXP
***		  OPCODE_MAPCAT_ARRAY
***		  OPCODE_MAPCAT_CALL
***
***	    These are an enumerated type, the first value of which is 0.
***	    There are WN_MAP_CATEGORIES values, 0 through WN_MAP_CATEGORIES-1.
***
***
*** Exported data:
***
***	Commonly, these data structures would be used by opcode.h and opcode.c
***	to look up interesting information.  However, they are provided
***	separately because there is demand for them.
***
***	struct OPCODE_gop_info_struct {
***	  char name[16];
***	  OPCODE first;
***	  OPCODE last;
***	} OPCODE_gop_info[];
***
***	    Used to look up information about a OPERATOR: what the first
***	    opcode and last opcode are for that operator, and the ascii
***	    representation of the operator.
***
***	extern struct OPCODE_info_struct {
***	  char          _name[20];
***	  mUINT16       _operator;
***	  mUINT8        _rtype;
***	  mUINT8        _desc;
***	  mINT8         nkids;
***	  mUINT16	wnfields;
***	  mUINT16       _flags;
***	} OPCODE_info[];
***
***	    Used to look up information about an OPCODE: the ascii name,
***	    the "operator", the "return type" and "descriptor type" of
***	    the opcode, the number of kids (-1 if unknown) and the flags
***	    that define the boolean properties, currently
***
***	    OPCODE_PROPERTY_scf			structured control flow
***	    OPCODE_PROPERTY_stmt		statement
***	    OPCODE_PROPERTY_expression		expression
***	    OPCODE_PROPERTY_leaf		nkids is zero
***	    OPCODE_PROPERTY_store		is a store
***	    OPCODE_PROPERTY_load		is a load
***	    OPCODE_PROPERTY_call		is a call
***	    OPCODE_PROPERTY_compare		is a comparison
***	    OPCODE_PROPERTY_non_scf		control flow, but not scf
***	    OPCODE_PROPERTY_boolean		boolean returns, e.g. GE
**/

/** $Revision: 1.1 $
*** $Date: 2001/10/30 16:59:45 $
*** $Author: ciancu $
*** $Source: bitbucket.org:berkeleylab/upc-translator.git/open64/osprey1.0/common/com/opcode_core.h $
**/

#ifndef opcode_core_INCLUDED
#define opcode_core_INCLUDED "opcode_core.h"

#ifdef _KEEP_RCS_ID
static char *opcode_core_rcs_id = opcode_core_INCLUDED "$Revision: 1.1 $";
#endif /* _KEEP_RCS_ID */

#include "opcode_gen_core.h"

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/water-rivers-lakes#snake-river-769404" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">snake-river-769404</uri-title>
      <source>snake-river-769404</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>Idaho</subject>
          <subject>snake river</subject>
          <subject>water</subject>
          <subject>reflections</subject>
          <subject>sky</subject>
          <subject>nature</subject>
          <subject>outdoors</subject>
          <subject>trees</subject>
          <subject>cliffs</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/water-rivers-lakes/snake-river-769404-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/water-rivers-lakes/snake-river-769404-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>84 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/water-rivers-lakes/snake-river-769404-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>115 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/water-rivers-lakes/snake-river-769404-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>253 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/water-rivers-lakes/snake-river-769404-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>424 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/water-rivers-lakes/snake-river-769404-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="snake-river-769404" locale="eng" uri="/media-library/images/water-rivers-lakes#snake-river-769404" status="publish" site="ldsorg" source="chq" words="129" tgp="0.451"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:23.573084-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
"""

0.0.004_regions

Revision ID: 462a91ed51ac
Revises: 26644fc2924e
Create Date: 2013-12-17 13:16:46.415506

Регионы

"""

# revision identifiers, used by Alembic.
revision = '462a91ed51ac'
down_revision = '26644fc2924e'

from alembic import op

from sqlalchemy import (
  Column,
  Integer,
  String,
  ForeignKey,
  Boolean,
)

def upgrade():
    op.create_table(
    'CL_Region',
    Column('id',Integer, primary_key=True, autoincrement=False),
    Column('name',String(length=300), nullable=False, index=True),
    Column('pid',Integer, ForeignKey('CL_Region.id'), nullable=True, index=True),
    Column('level',Integer, nullable=False),
    Column('active',Boolean, nullable=False)
  )

def downgrade():
    op.drop_table('CL_Region')