text:
namespace scm {
namespace gl {

// blend_state ////////////////////////////////////////////////////////////////////////////////////
blend_ops::blend_ops(bool            in_enabled,
                     blend_func      in_src_rgb_func,
                     blend_func      in_dst_rgb_func,
                     blend_func      in_src_alpha_func,
                     blend_func      in_dst_alpha_func,
                     blend_equation  in_rgb_equation,
                     blend_equation  in_alpha_equation,
                     unsigned        in_write_mask)
  : _enabled(in_enabled)
  , _src_rgb_func(in_src_rgb_func)
  , _dst_rgb_func(in_dst_rgb_func)
  , _src_alpha_func(in_src_alpha_func)
  , _dst_alpha_func(in_dst_alpha_func)
  , _rgb_equation(in_rgb_equation)
  , _alpha_equation(in_alpha_equation)
  , _write_mask(in_write_mask)
{
}

blend_ops_array
blend_ops::operator()(bool            in_enabled,
                      blend_func      in_src_rgb_func,
                      blend_func      in_dst_rgb_func,
                      blend_func      in_src_alpha_func,
                      blend_func      in_dst_alpha_func,
                      blend_equation  in_rgb_equation,
                      blend_equation  in_alpha_equation,
                      unsigned        in_write_mask)
{
    blend_ops_array ret(*this);

    return (ret(in_enabled,
                in_src_rgb_func,   in_dst_rgb_func,
                in_src_alpha_func, in_dst_alpha_func,
                in_rgb_equation,   in_alpha_equation,
                in_write_mask));
}

bool
blend_ops::operator==(const blend_ops& rhs) const
{
    return (   (_enabled == rhs._enabled)
            && (_src_rgb_func == rhs._src_rgb_func)
            && (_dst_rgb_func == rhs._dst_rgb_func)
            && (_rgb_equation == rhs._rgb_equation)
            && (_src_alpha_func == rhs._src_alpha_func)
            && (_dst_alpha_func == rhs._dst_alpha_func)
            && (_alpha_equation == rhs._alpha_equation)
            && (_write_mask == rhs._write_mask));
}

bool
blend_ops::operator!=(const blend_ops& rhs) const
{
    return (   (_enabled != rhs._enabled)
            || (_src_rgb_func != rhs._src_rgb_func)
            || (_dst_rgb_func != rhs._dst_rgb_func)
            || (_rgb_equation != rhs._rgb_equation)
            || (_src_alpha_func != rhs._src_alpha_func)
            || (_dst_alpha_func != rhs._dst_alpha_func)
            || (_alpha_equation != rhs._alpha_equation)
            || (_write_mask != rhs._write_mask));
}

blend_ops_array::blend_ops_array(const blend_ops_array& in_blend_op_array)
  : _array(in_blend_op_array._array)
{
}

blend_ops_array::blend_ops_array(const blend_ops& in_blend_ops)
  : _array(1, in_blend_ops)
{
}

blend_ops_array::blend_ops_array(bool            in_enabled,
                                 blend_func      in_src_rgb_func,
                                 blend_func      in_dst_rgb_func,
                                 blend_func      in_src_alpha_func,
                                 blend_func      in_dst_alpha_func,
                                 blend_equation  in_rgb_equation,
                                 blend_equation  in_alpha_equation,
                                 unsigned        in_write_mask)
  : _array(1, blend_ops(in_enabled,
                        in_src_rgb_func,   in_dst_rgb_func,
                        in_src_alpha_func, in_dst_alpha_func,
                        in_rgb_equation,   in_alpha_equation,
                        in_write_mask))
{
}

blend_ops_array&
blend_ops_array::operator()(const blend_ops& in_blend_ops)
{
    _array.push_back(in_blend_ops);
    return (*this);
}

blend_ops_array&
blend_ops_array::operator()(bool            in_enabled,
                            blend_func      in_src_rgb_func,
                            blend_func      in_dst_rgb_func,
                            blend_func      in_src_alpha_func,
                            blend_func      in_dst_alpha_func,
                            blend_equation  in_rgb_equation,
                            blend_equation  in_alpha_equation,
                            unsigned        in_write_mask)
{
    _array.push_back(blend_ops(in_enabled,
                               in_src_rgb_func,   in_dst_rgb_func,
                               in_src_alpha_func, in_dst_alpha_func,
                               in_rgb_equation,   in_alpha_equation,
                               in_write_mask));
    return (*this);
}

const blend_ops&
blend_ops_array::operator[](int in_index) const
{
    assert(in_index < _array.size());
    return (_array[in_index]);
}

size_t
blend_ops_array::size() const
{
    return (_array.size());
}

const blend_ops_array::blend_ops_vector&
blend_ops_array::blend_operations() const
{
    return (_array);
}

bool
blend_ops_array::operator==(const blend_ops_array& rhs) const
{
    return (_array == rhs._array);
}

bool
blend_ops_array::operator!=(const blend_ops_array& rhs) const
{
    return (_array != rhs._array);
}

blend_state_desc::blend_state_desc(const blend_ops& in_blend_ops,
                                   bool in_alpha_to_coverage)
  : _alpha_to_coverage(in_alpha_to_coverage)
  , _blend_ops(in_blend_ops)
{
    assert(1 == _blend_ops.size());
}

blend_state_desc::blend_state_desc(const blend_ops_array& in_blend_ops,
                                   bool in_alpha_to_coverage)
  : _blend_ops(in_blend_ops),
    _alpha_to_coverage(in_alpha_to_coverage)
{
    assert(in_blend_ops.size() == _blend_ops.size());
    assert(0 < _blend_ops.size());
}

blend_state::blend_state(      render_device&    in_device,
                         const blend_state_desc& in_desc)
  : render_device_child(in_device),
    _descriptor(in_desc)
{
    if (_descriptor._blend_ops.size() > in_device.capabilities()._max_draw_buffers) {
        state().set(object_state::OS_ERROR_INVALID_VALUE);
    }
}

blend_state::~blend_state()
{
}

const blend_state_desc&
blend_state::descriptor() const
{
    return (_descriptor);
}

void
blend_state::apply(const render_context& in_context, const math::vec4f& in_blend_color,
                   const blend_state&    in_applied_state, const math::vec4f& in_applied_blend_color) const
{
    const opengl::gl_core& glapi = in_context.opengl_api();

    if (_descriptor._alpha_to_coverage != in_applied_state._descriptor._alpha_to_coverage) {
        if (_descriptor._alpha_to_coverage) {
            glapi.glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
        }
        else {
            glapi.glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
        }
    }

    if (in_blend_color != in_applied_blend_color) {
        glapi.glBlendColor(in_blend_color.r,
                           in_blend_color.g,
                           in_blend_color.b,
                           in_blend_color.a);
    }

    if (_descriptor._blend_ops.size() == 1) {
        if (in_applied_state._descriptor._blend_ops.size() == 1) {
            checked_apply(in_context, _descriptor._blend_ops[0], in_applied_state._descriptor._blend_ops[0]);
        }
        else {
            for (unsigned i = 0; i < in_applied_state._descriptor._blend_ops.size(); ++i) {
                force_disable_i(in_context, i);
            }
            force_apply(in_context, _descriptor._blend_ops[0]);
        }
    }
    else {
        if (SCM_GL_CORE_OPENGL_CORE_VERSION < SCM_GL_CORE_OPENGL_CORE_VERSION_400) {
            glapi.glBlendEquationSeparate(util::gl_blend_equation(_descriptor._blend_ops[0]._rgb_equation),
                                          util::gl_blend_equation(_descriptor._blend_ops[0]._alpha_equation));
            glapi.glBlendFuncSeparate(util::gl_blend_func(_descriptor._blend_ops[0]._src_rgb_func),
                                      util::gl_blend_func(_descriptor._blend_ops[0]._dst_rgb_func),
                                      util::gl_blend_func(_descriptor._blend_ops[0]._src_alpha_func),
                                      util::gl_blend_func(_descriptor._blend_ops[0]._dst_alpha_func));
        }

        unsigned op_size = static_cast<unsigned>(_descriptor._blend_ops.size());
        unsigned ap_size = static_cast<unsigned>(in_applied_state._descriptor._blend_ops.size());
        unsigned max_size = math::max(op_size, ap_size);
        for (unsigned i = 0; i < max_size; ++i) {
            if ((i < op_size) && (i < ap_size)) {
                checked_apply_i(in_context, i, _descriptor._blend_ops[i], in_applied_state._descriptor._blend_ops[i]);
            }
            else if ((i < op_size) && !(i < ap_size)) {
                force_apply_i(in_context, i, _descriptor._blend_ops[i]);
            }
            else if (!(i < op_size) && (i < ap_size)) {
                force_disable_i(in_context, i);
            }
        }
    }

    gl_assert(glapi, leaving blend_state::apply());
}

void
blend_state::force_apply(const render_context& in_context, const math::vec4f& in_blend_color) const
{
    const opengl::gl_core& glapi = in_context.opengl_api();

    if (_descriptor._alpha_to_coverage) {
        glapi.glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
    }
    else {
        glapi.glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
    }

    glapi.glBlendColor(in_blend_color.r,
                       in_blend_color.g,
                       in_blend_color.b,
                       in_blend_color.a);

    if (_descriptor._blend_ops.size() == 1) {
        force_apply(in_context, _descriptor._blend_ops[0]);
    }
    else {
        if (SCM_GL_CORE_OPENGL_CORE_VERSION < SCM_GL_CORE_OPENGL_CORE_VERSION_400) {
            glapi.glBlendEquationSeparate(util::gl_blend_equation(_descriptor._blend_ops[0]._rgb_equation),
                                          util::gl_blend_equation(_descriptor._blend_ops[0]._alpha_equation));
            glapi.glBlendFuncSeparate(util::gl_blend_func(_descriptor._blend_ops[0]._src_rgb_func),
                                      util::gl_blend_func(_descriptor._blend_ops[0]._dst_rgb_func),
                                      util::gl_blend_func(_descriptor._blend_ops[0]._src_alpha_func),
                                      util::gl_blend_func(_descriptor._blend_ops[0]._dst_alpha_func));
        }

        for (int i = 0; i < _descriptor._blend_ops.size(); ++i) {
            force_apply_i(in_context, i, _descriptor._blend_ops[i]);
        }
    }

    gl_assert(glapi, leaving blend_state::force_apply());
}

void
blend_state::force_apply(const render_context& in_context,
                         const blend_ops&      in_blend_ops) const
{
    const opengl::gl_core& glapi = in_context.opengl_api();

    if (in_blend_ops._enabled) {
        glapi.glEnable(GL_BLEND);
    }
    else {
        glapi.glDisable(GL_BLEND);
    }

    glapi.glColorMask(util::masked(in_blend_ops._write_mask, COLOR_RED),  util::masked(in_blend_ops._write_mask, COLOR_GREEN),
                      util::masked(in_blend_ops._write_mask, COLOR_BLUE), util::masked(in_blend_ops._write_mask, COLOR_ALPHA));

    glapi.glBlendEquationSeparate(util::gl_blend_equation(in_blend_ops._rgb_equation),
                                  util::gl_blend_equation(in_blend_ops._alpha_equation));
    glapi.glBlendFuncSeparate(util::gl_blend_func(in_blend_ops._src_rgb_func),   util::gl_blend_func(in_blend_ops._dst_rgb_func),
                              util::gl_blend_func(in_blend_ops._src_alpha_func), util::gl_blend_func(in_blend_ops._dst_alpha_func));

    gl_assert(glapi, leaving blend_state::force_apply());
}

void
blend_state::force_apply_i(const render_context& in_context,
                           unsigned              in_index,
                           const blend_ops&      in_blend_ops) const
{
    const opengl::gl_core& glapi = in_context.opengl_api();

    if (in_blend_ops._enabled) {
        glapi.glEnablei(GL_BLEND, in_index);
    }
    else {
        glapi.glDisablei(GL_BLEND, in_index);
    }
    // color mask per render target
    glapi.glColorMaski(in_index, util::masked(in_blend_ops._write_mask, COLOR_RED),  util::masked(in_blend_ops._write_mask, COLOR_GREEN),
                                 util::masked(in_blend_ops._write_mask, COLOR_BLUE), util::masked(in_blend_ops._write_mask, COLOR_ALPHA));

    if (SCM_GL_CORE_OPENGL_CORE_VERSION >= SCM_GL_CORE_OPENGL_CORE_VERSION_400) {
        glapi.glBlendEquationSeparatei(in_index, util::gl_blend_equation(in_blend_ops._rgb_equation),
                                                 util::gl_blend_equation(in_blend_ops._alpha_equation));
        glapi.glBlendFuncSeparatei(in_index, util::gl_blend_func(in_blend_ops._src_rgb_func),   util::gl_blend_func(in_blend_ops._dst_rgb_func),
                                             util::gl_blend_func(in_blend_ops._src_alpha_func), util::gl_blend_func(in_blend_ops._dst_alpha_func));
    }

    gl_assert(glapi, leaving blend_state::force_apply_i());
}

void
blend_state::checked_apply(const render_context& in_context,
                           const blend_ops&      in_blend_ops,
                           const blend_ops&      in_applied_blend_ops) const
{
    const opengl::gl_core& glapi = in_context.opengl_api();

    if (in_blend_ops._enabled != in_applied_blend_ops._enabled) {
        if (in_blend_ops._enabled) {
            glapi.glEnable(GL_BLEND);
        }
        else {
            glapi.glDisable(GL_BLEND);
        }
    }
    if (in_blend_ops._write_mask != in_applied_blend_ops._write_mask) {
        glapi.glColorMask(util::masked(in_blend_ops._write_mask, COLOR_RED),  util::masked(in_blend_ops._write_mask, COLOR_GREEN),
                          util::masked(in_blend_ops._write_mask, COLOR_BLUE), util::masked(in_blend_ops._write_mask, COLOR_ALPHA));
    }
    glapi.glBlendEquationSeparate(util::gl_blend_equation(in_blend_ops._rgb_equation),
                                  util::gl_blend_equation(in_blend_ops._alpha_equation));
    glapi.glBlendFuncSeparate(util::gl_blend_func(in_blend_ops._src_rgb_func),   util::gl_blend_func(in_blend_ops._dst_rgb_func),
                              util::gl_blend_func(in_blend_ops._src_alpha_func), util::gl_blend_func(in_blend_ops._dst_alpha_func));

    gl_assert(glapi, leaving blend_state::checked_apply());
}

void
blend_state::checked_apply_i(const render_context& in_context,
                             unsigned              in_index,
                             const blend_ops&      in_blend_ops,
                             const blend_ops&      in_applied_blend_ops) const
{
    const opengl::gl_core& glapi = in_context.opengl_api();

    if (in_blend_ops._enabled != in_applied_blend_ops._enabled) {
        if (in_blend_ops._enabled) {
            glapi.glEnablei(GL_BLEND, in_index);
        }
        else {
            glapi.glDisablei(GL_BLEND, in_index);
        }
    }
    if (in_blend_ops._write_mask != in_applied_blend_ops._write_mask) {
        glapi.glColorMaski(in_index, util::masked(in_blend_ops._write_mask, COLOR_RED),  util::masked(in_blend_ops._write_mask, COLOR_GREEN),
                                     util::masked(in_blend_ops._write_mask, COLOR_BLUE), util::masked(in_blend_ops._write_mask, COLOR_ALPHA));
    }
    if (SCM_GL_CORE_OPENGL_CORE_VERSION >= SCM_GL_CORE_OPENGL_CORE_VERSION_400) {
        glapi.glBlendEquationSeparatei(in_index, util::gl_blend_equation(in_blend_ops._rgb_equation),
                                                 util::gl_blend_equation(in_blend_ops._alpha_equation));
        glapi.glBlendFuncSeparatei(in_index, util::gl_blend_func(in_blend_ops._src_rgb_func),   util::gl_blend_func(in_blend_ops._dst_rgb_func),
                                             util::gl_blend_func(in_blend_ops._src_alpha_func), util::gl_blend_func(in_blend_ops._dst_alpha_func));
    }
    gl_assert(glapi, leaving blend_state::checked_apply_i());
}

void
blend_state::force_disable_i(const render_context& in_context,
                             unsigned              in_index) const
{
    // apply default blend_ops to buffer index
    force_apply_i(in_context, in_index, blend_ops(false));
}

} // namespace gl
} // namespace scm


text:
import * as utils from './utils'

type TestContext = {
  app: any
}

describe('Shell', function () {
  beforeEach(async function (this: TestContext): Promise<void> {
    this.app = utils.createApplication()
    await utils.startApplication(this.app)
    await this.app.client.waitUntilWindowLoaded()
  }, utils.LONG_TIMEOUT)

  afterEach(async function (this: TestContext): Promise<void> {
    await utils.stopApplication(this.app)
  })

  it('is not visible', async function (this: TestContext): Promise<void> {
    const isVisible = await this.app.browserWindow.isVisible()
    expect(isVisible).toBe(false)
  })

  it('is not full screen', async function (this: TestContext): Promise<void> {
    const isFullScreen = await this.app.browserWindow.isFullScreen()
    expect(isFullScreen).toBe(false)
  })

  it('is not showing dev tools', async function (this: TestContext): Promise<void> {
    const isDevToolsOpened = await this.app.browserWindow.isDevToolsOpened()
    expect(isDevToolsOpened).toBe(false)
  })
})

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Sonata\PageBundle\Tests\Site;

use Sonata\PageBundle\CmsManager\DecoratorStrategy;
use Sonata\PageBundle\Model\SiteManagerInterface;
use Sonata\PageBundle\Request\SiteRequest;
use Sonata\PageBundle\Site\HostPathByLocaleSiteSelector;
use Sonata\SeoBundle\Seo\SeoPageInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * @author BadPixxel <eshop.bpaquier@gmail.com>
 */
final class SubRequestsSiteSelectorTest extends BaseLocaleSiteSelectorTest
{
    protected function setUp(): void
    {
        $siteManager = $this->createMock(SiteManagerInterface::class);
        $decoratorStrategy = new DecoratorStrategy([], [], []);
        $seoPage = $this->createMock(SeoPageInterface::class);

        $this->siteSelector = $this->getMockBuilder(HostPathByLocaleSiteSelector::class)
            ->setConstructorArgs([$siteManager, $decoratorStrategy, $seoPage])
            ->setMethods(['getSites'])
            ->getMock();
    }

    /**
     * Tests onKernelRequest method with Master request detect default site.
     */
    public function testOnKernelRequestWithMasterDetectEn(): void
    {
        $kernel = $this->createMock(HttpKernelInterface::class);
        $request = SiteRequest::create('http://www.example.com');

        // Ensure request locale is null
        static::assertNull($request->attributes->get('_locale'));

        $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);

        $this->siteSelector
            ->expects(static::once())
            ->method('getSites')
            ->with($request)
            ->willReturn($this->getSites());

        $this->siteSelector->onKernelRequest($event);

        // Ensure request locale is still null
        static::assertNull($request->attributes->get('_locale'));

        $site = $this->getSite();

        // Ensure no site was retrieved
        static::assertNull($site);
    }

    /**
     * Tests onKernelRequest method with Master request detect /fr site.
     */
    public function testOnKernelRequestWithMasterDetectFr(): void
    {
        $kernel = $this->createMock(HttpKernelInterface::class);
        $request = SiteRequest::create('http://www.example.com/fr');

        // Ensure request locale is null
        static::assertNull($request->attributes->get('_locale'));

        $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);

        $this->siteSelector
            ->expects(static::once())
            ->method('getSites')
            ->with($request)
            ->willReturn($this->getSites());

        $this->siteSelector->onKernelRequest($event);

        // Ensure request locale is now fr
        static::assertSame('fr', $request->attributes->get('_locale'));

        $site = $this->getSite();

        // Ensure /fr site was retrieved
        static::assertNotEmpty($site);
        static::assertSame('/fr', $site->getRelativePath());
    }

    /**
     * Tests onKernelRequest method with Sub request detect default site.
     */
    public function testOnKernelRequestWithSubDetectEn(): void
    {
        $kernel = $this->createMock(HttpKernelInterface::class);
        $request = SiteRequest::create('http://www.example.com');

        // Ensure request locale is null
        static::assertNull($request->attributes->get('_locale'));

        $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST);

        $this->siteSelector
            ->expects(static::once())
            ->method('getSites')
            ->with($request)
            ->willReturn($this->getSites());

        $this->siteSelector->onKernelRequest($event);

        // Ensure request locale is still null
        static::assertNull($request->attributes->get('_locale'));

        $site = $this->getSite();

        // Ensure no site was retrieved
        static::assertNull($site);
    }

    /**
     * Tests onKernelRequest method with Sub request detect /fr site.
     */
    public function testOnKernelRequestWithSubDetectFr(): void
    {
        $kernel = $this->createMock(HttpKernelInterface::class);
        $request = SiteRequest::create('http://www.example.com/fr');

        // Ensure request locale is null
        static::assertNull($request->attributes->get('_locale'));

        $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST);

        $this->siteSelector
            ->expects(static::once())
            ->method('getSites')
            ->with($request)
            ->willReturn($this->getSites());

        $this->siteSelector->onKernelRequest($event);

        // Ensure request locale is now fr
        static::assertSame('fr', $request->attributes->get('_locale'));

        $site = $this->getSite();

        // Ensure /fr site was retrieved
        static::assertNotEmpty($site);
        static::assertSame('/fr', $site->getRelativePath());
    }
}


text:
require File.dirname(__FILE__) + '/../test_helper'

class UnlessTest < Test::Unit::TestCase
  include TestHelper

  define_method :'test unless block, semicolon separated' do
    src = "unless true; false end"
    assert_build(src) do |node|
      assert_equal Ruby::Unless, node.first.class
    end
  end

  define_method :'test unless block, newline separated' do
    src = "unless true\n false end"
    assert_build(src)
  end

  define_method :'test unless block w/ then, not separated' do
    src = "unless true then false end"
    assert_build(src)
  end

  define_method :'test unless block w/ else block, semicolon separated' do
    src = "unless true; false; else; true end"
    assert_build(src)
  end

  define_method :'test unless block w/ else block, newline separated' do
    src = "unless true\n false\n else\n true end"
    assert_build(src)
  end

  define_method :'test unless modifier' do
    src = "foo unless true"
    assert_build(src)
  end

  define_method :'test chained unless and if modifiers' do
    src = "1 unless false if true"
    assert_build(src)
  end
end


text:
"""Proof of concept alarm handler."""

import logging
import time
import json
from flask import request
from flask_api import FlaskAPI
from kafka import KafkaProducer

APP = FlaskAPI(__name__)

logging.basicConfig(level=logging.INFO)

# This sleep is needed to give kafka time to start up.
time.sleep(2)
producer = KafkaProducer(bootstrap_servers='platform_kafka:9092')

@APP.route('/')
def root():
    """."""
    return {
        "message": "The demo alarm handler says hi",
        "_links": {
            "items": [
                {"href": "{}".format(request.url)}
            ]
        }
    }

@APP.route('/', methods=['POST'])
def alarm():
    """."""
    if request.method == 'POST':
        response = {'message': 'POST Accepted'}
        logging.info('alarm POSTED!')
        data = request.data
        logging.info(data)
        string = json.dumps(data)
        producer.send('SIP-alarms', string.encode())
        return response
    return ""


text:
@c:\pscp Output\mutefm_setup_0_9_15.exe jaredsohn_mutetunes@ssh.phx.nearlyfreespeech.net:

REM @c:\pscp Output\patcher\*.* jaredsohn_mutetunes@ssh.phx.nearlyfreespeech.net:patcher


text:
require 'guard/compat/test/helper'
require 'guard/jekyll_plus'

RSpec.describe Guard::JekyllPlus do
  let(:server) { instance_double(Guard::JekyllPlus::Server) }
  let(:config) { instance_double(Guard::JekyllPlus::Config) }
  let(:builder) { instance_double(Guard::JekyllPlus::Builder) }

  before do
    allow(Guard::Compat::UI).to receive(:info)

    allow(Guard::JekyllPlus::Config).to receive(:new).and_return(config)
    allow(Guard::JekyllPlus::Server).to receive(:new).and_return(server)
    allow(Guard::JekyllPlus::Builder).to receive(:new).and_return(builder)

    allow(config).to receive(:info)
    allow(config).to receive(:source)
    allow(config).to receive(:destination)
  end

  describe '#initialize' do
    it 'sets up the configuration' do
      options = double('options')
      expect(Guard::JekyllPlus::Config).to receive(:new).with(options)
      described_class.new(options)
    end
  end

  describe '#start' do
    before do
      allow(config).to receive(:serve?)
      allow(builder).to receive(:build)
    end

    it 'processes the site' do
      expect(builder).to receive(:build)
      subject.start
    end

    context 'when not serving' do
      before do
        allow(config).to receive(:serve?).and_return(false)
      end

      it 'does not start the server' do
        expect(server).to_not receive(:start)
        subject.start
      end
    end

    context 'when serving' do
      before do
        allow(config).to receive(:serve?).and_return(true)
      end

      it 'starts the server' do
        expect(server).to receive(:start)
        subject.start
      end
    end
  end

  describe '#run_on_modifications' do
    before do
      allow(builder).to receive(:modified)
    end

    context 'with normal modifications' do
      before do
        allow(config).to receive(:config_file?).and_return(false)
      end

      it 'updates based on given paths' do
        paths = [double('paths')]
        expect(builder).to receive(:modified).with(paths)
        subject.run_on_modifications(paths)
      end
    end

    context 'with changed config' do
      before do
        allow(config).to receive(:config_file?).and_return(true)

        # after config changes
        allow(builder).to receive(:build)
        allow(server).to receive(:stop)
        allow(config).to receive(:reload)
        allow(config).to receive(:serve?).and_return(false)
      end

      it 'reloads config' do
        paths = [double('paths')]
        expect(builder).to receive(:reload)
        subject.run_on_modifications(paths)
      end
    end
  end

  describe '#run_on_additions' do
    it 'updates based on given paths' do
      paths = [double('paths')]
      expect(builder).to receive(:added).with(paths)
      subject.run_on_additions(paths)
    end
  end

  describe '#run_on_removals' do
    it 'updates based on given paths' do
      paths = [double('paths')]
      expect(builder).to receive(:removed).with(paths)
      subject.run_on_removals(paths)
    end
  end
end


text:
using System;
using System.Diagnostics;
using System.Xml;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.IO;
using System.Collections;
namespace Netron.Lithium
{
	/// <summary>
	/// Simple proxy class for the control to display only specific properties.
	/// Not as sophisticated as the property-bag of the full Netron-control
	/// but does the job in this simple context.
	/// </summary>
	public class Proxy
	{
		#region Fields
		private LithiumControl site;
		#endregion

		#region Constructor
		/// <summary>
		/// Default ctor
		/// </summary>
		/// <param name="site"></param>
		public Proxy(LithiumControl site)
		{this.site = site;}
		#endregion

		#region Methods
		/// <summary>
		/// Gets or sets the reference to the control instance
		/// </summary>
		[Browsable(false)]
		public LithiumControl Site
		{
			get{return site;}
			set{site = value;}
		}
		/// <summary>
		/// Gets or sets the backcolor
		/// </summary>
		[Browsable(true), Description("The backcolor of the canvas"), Category("Layout")]
		public Color BackColor
		{
			get{return this.site.BackColor;}
			set{this.site.BackColor = value;}
		}

		/// <summary>
		/// Gets or set the branch height
		/// </summary>
		[Browsable(true), Description("The height between the tree branches")]
		public int BranchHeight
		{
			get{return site.BranchHeight;}
			set{site.BranchHeight = value;}
		}
		/// <summary>
		/// Gets or sets the spacing between the nodes
		/// </summary>
		[Browsable(true)]
		public int WordSpacing
		{
			get{return site.WordSpacing;}
			set
			{
				site.WordSpacing = value;
			}
		}

		/// <summary>
		/// Gets or sets the description of the diagram
		/// </summary>
		[Browsable(true), Description("The description of the diagram."), Category("Diagram")]
		public string Description
		{
			get{return this.site.graphAbstract.Description;}
			set{this.site.graphAbstract.Description = value;}
		}

		/// <summary>
		/// Gets or sets the global connection type
		/// </summary>
		[Browsable(true), Description("The type of connection."), Category("Diagram")]
		public ConnectionType ConnectionType
		{
			get{return site.ConnectionType;}
			set
			{
				site.ConnectionType = value;
			}
		}
		#endregion
	}
}


text:
#ifndef __al_included_allegro5_aintern_gp2xwiz_h
#define __al_included_allegro5_aintern_gp2xwiz_h

#include "allegro5/allegro.h"
#include "allegro5/allegro_opengl.h"
#include "allegro5/internal/aintern.h"
#include "allegro5/internal/aintern_system.h"
#include "allegro5/internal/aintern_bitmap.h"
#include "allegro5/platform/aintwiz.h"
#include "allegro5/internal/aintern_opengl.h"

#include <wiz/castor.h>

typedef struct ALLEGRO_SYSTEM_GP2XWIZ ALLEGRO_SYSTEM_GP2XWIZ;
typedef struct ALLEGRO_DISPLAY_GP2XWIZ_OGL ALLEGRO_DISPLAY_GP2XWIZ_OGL;
typedef struct ALLEGRO_DISPLAY_GP2XWIZ_FB ALLEGRO_DISPLAY_GP2XWIZ_FB;

struct ALLEGRO_SYSTEM_GP2XWIZ
{
   ALLEGRO_SYSTEM system; /* This must be the first member, we "derive" from it. */

   ALLEGRO_EXTRA_DISPLAY_SETTINGS extras;
};

/* This is our version of ALLEGRO_DISPLAY with driver specific extra data. */
struct ALLEGRO_DISPLAY_GP2XWIZ_OGL
{
   ALLEGRO_DISPLAY display; /* This must be the first member. */

   EGLDisplay egl_display;
   EGLConfig egl_config;
   EGLContext egl_context;
   EGLSurface egl_surface;
   NativeWindowType hNativeWnd;
};

/* This is our version of ALLEGRO_DISPLAY with driver specific extra data. */
struct ALLEGRO_DISPLAY_GP2XWIZ_FB
{
   ALLEGRO_DISPLAY display; /* This must be the first member. */

   ALLEGRO_BITMAP *backbuffer;
   /*
    * We create the backbuffer bitmap then points it's ->memory at
    * lc_fb1 (initialized with libcastor. This is a backup of the
    * ->memory as created by al_create_bitmap.
    */
   unsigned char *screen_mem;
};

#endif


text:
package com.tickaroo.tikxml.annotation;

import com.tickaroo.tikxml.TypeConverter;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This annotation is used to map xml element attributes to java fields. {@code <book id="123" /> }
 * maps to {@code
 *
 * @author Hannes Dorfmann
 * @Xml class Book {
 * @Attribute int id; } }
 * @since 1.0
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface Attribute {

  /**
   * Specify the name of the attribute
   *
   * @return The specified name. Default value is the name of the annotated java class field.
   */
  String name() default "";

  /**
   * Specify which {@link TypeConverter} you want to use to serialize / deserialize the given xml
   * attribute.
   *
   * @return The TypeConverter class to use
   */
  Class<? extends TypeConverter> converter() default TypeConverter.NoneTypeConverter.class;
}


text:
<?php namespace Modules\Core\Providers;

use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Modules\Core\Console\InstallCommand;
use Modules\Core\Console\PublishModuleAssetsCommand;
use Modules\Core\Console\PublishThemeAssetsCommand;
use Modules\Core\Foundation\Theme\ThemeManager;
use Pingpong\Modules\Module;

class CoreServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * @var string
     */
    protected $prefix = 'asgard';

    /**
     * The filters base class name.
     *
     * @var array
     */
    protected $middleware = [
        'Core' => [
            'permissions'           => 'PermissionMiddleware',
            'auth.admin'            => 'AdminMiddleware',
            'public.checkLocale'    => 'PublicMiddleware',
            'localizationRedirect'  => 'LocalizationMiddleware',
            'can' => 'Authorization',
        ],
    ];

    public function boot(Dispatcher $dispatcher)
    {
        $dispatcher->mapUsing(function ($command) {
            $command = str_replace('Commands\\', 'Commands\\Handlers\\', get_class($command));

            return trim($command, '\\') . 'Handler@handle';
        });

        $this->registerMiddleware($this->app['router']);
        $this->registerModuleResourceNamespaces();
        $this->setLocalesConfigurations();
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('asgard.isInstalled', function ($app) {
            $envFileLocation = "{$app->environmentPath()}/{$app->environmentFile()}";

            try {
                $hasTable = Schema::hasTable('setting__settings');
            } catch (\Exception $e) {
                $hasTable = false;
            }

            return $app['files']->isFile($envFileLocation) && $hasTable;
        });

        $this->registerCommands();
        $this->registerServices();
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array();
    }

    /**
     * Register the filters.
     *
     * @param  Router $router
     * @return void
     */
    public function registerMiddleware(Router $router)
    {
        foreach ($this->middleware as $module => $middlewares) {
            foreach ($middlewares as $name => $middleware) {
                $class = "Modules\\{$module}\\Http\\Middleware\\{$middleware}";

                $router->middleware($name, $class);
            }
        }
    }

    /**
     * Register the console commands
     */
    private function registerCommands()
    {
        $this->commands([
            InstallCommand::class,
            PublishThemeAssetsCommand::class,
            PublishModuleAssetsCommand::class,
        ]);
    }

    private function registerServices()
    {
        $this->app->bindShared(ThemeManager::class, function ($app) {
            $path = $app['config']->get('asgard.core.core.themes_path');

            return new ThemeManager($app, $path);
        });
    }

    /**
     * Register the modules aliases
     */
    private function registerModuleResourceNamespaces()
    {
        foreach ($this->app['modules']->getOrdered() as $module) {
            $this->registerViewNamespace($module);
            $this->registerLanguageNamespace($module);
            $this->registerConfigNamespace($module);
        }
    }

    /**
     * Register the view namespaces for the modules
     * @param Module $module
     */
    protected function registerViewNamespace(Module $module)
    {
        if ($module->getName() == 'user') {
            return;
        }
        $this->app['view']->addNamespace(
            $module->getName(),
            $module->getPath() . '/Resources/views'
        );
    }

    /**
     * Register the language namespaces for the modules
     * @param Module $module
     */
    protected function registerLanguageNamespace(Module $module)
    {
        $moduleName = $module->getName();

        $langPath = base_path("resources/lang/$moduleName");
        $secondPath = base_path("resources/lang/translation/$moduleName");

        if ($moduleName !== 'translation' && $this->hasPublishedTranslations($langPath)) {
            return $this->loadTranslationsFrom($langPath, $moduleName);
        }
        if ($this->hasPublishedTranslations($secondPath)) {
            if ($moduleName === 'translation') {
                return $this->loadTranslationsFrom($secondPath, $moduleName);
            }

            return $this->loadTranslationsFrom($secondPath, $moduleName);
        }
        if ($this->moduleHasCentralisedTranslations($module)) {
            return $this->loadTranslationsFrom($this->getCentralisedTranslationPath($module), $moduleName);
        }

        return $this->loadTranslationsFrom($module->getPath() . '/Resources/lang', $moduleName);
    }

    /**
     * Register the config namespace
     * @param Module $module
     */
    private function registerConfigNamespace(Module $module)
    {
        $files = $this->app['files']->files($module->getPath() . '/Config');

        $package = $module->getName();

        foreach ($files as $file) {
            $filename = $this->getConfigFilename($file, $package);

            $this->mergeConfigFrom($file, $filename);

            $this->publishes([$file => config_path($filename . '.php'), ], 'config');
        }
    }

    /**
     * @param $file
     * @param $package
     * @return string
     */
    private function getConfigFilename($file, $package)
    {
        $name = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($file));

        $filename = $this->prefix . '.' . $package . '.' . $name;

        return $filename;
    }

    /**
     * Set the locale configuration for
     * - laravel localization
     * - laravel translatable
     */
    private function setLocalesConfigurations()
    {
        if (! $this->app['asgard.isInstalled']) {
            return;
        }

        $localeConfig = $this->app['cache']
            ->tags('setting.settings', 'global')
            ->remember("asgard.locales", 120,
                function () {
                    return DB::table('setting__settings')->whereName('core::locales')->first();
                }
            );

        if ($localeConfig) {
            $locales = json_decode($localeConfig->plainValue);
            $availableLocales = [];
            foreach ($locales as $locale) {
                $availableLocales = array_merge($availableLocales, [$locale => config("asgard.core.available-locales.$locale")]);
            }

            $laravelDefaultLocale = $this->app->config->get('app.locale');
            if (! in_array($laravelDefaultLocale, array_keys($availableLocales))) {
                $this->app->config->set('app.locale', array_keys($availableLocales)[0]);
            }
            $this->app->config->set('laravellocalization.supportedLocales', $availableLocales);
            $this->app->config->set('translatable.locales', $locales);
        }
    }

    /**
     * @param string $path
     * @return bool
     */
    private function hasPublishedTranslations($path)
    {
        return is_dir($path);
    }

    /**
     * Does a Module have it's Translations centralised in the Translation module?
     * @param Module $module
     * @return bool
     */
    private function moduleHasCentralisedTranslations(Module $module)
    {
        if (! array_has($this->app['modules']->enabled(), 'Translation')) {
            return false;
        }

        return is_dir($this->getCentralisedTranslationPath($module));
    }

    /**
     * Get the absolute path to the Centralised Translations for a Module (via the Translations module)
     * @param Module $module
     * @return string
     */
    private function getCentralisedTranslationPath(Module $module)
    {
        return $this->app['modules']->find('Translation')->getPath() . "/Resources/lang/{$module->getName()}";
    }
}


text:
package org.elasticsearch.index.snapshots;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.index.shard.IndexShardException;
import org.elasticsearch.index.shard.ShardId;

import java.io.IOException;

/**
 * Generic shard restore exception
 */
public class IndexShardRestoreException extends IndexShardException {
    public IndexShardRestoreException(ShardId shardId, String msg) {
        super(shardId, msg);
    }

    public IndexShardRestoreException(ShardId shardId, String msg, Throwable cause) {
        super(shardId, msg, cause);
    }

    public IndexShardRestoreException(StreamInput in) throws IOException{
        super(in);
    }
}


text:
package org.jetbrains.plugins.scala.codeInspection.scalastyle

import com.intellij.codeInspection._
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.{PsiDocumentManager, PsiElement, PsiFile}
import org.jetbrains.plugins.scala.extensions.PsiElementExt
import org.jetbrains.plugins.scala.lang.psi.api.ScalaFile
import org.scalastyle._

import scala.collection.mutable

object ScalastyleCodeInspection {
  private type TimestampedScalastyleConfiguration = (Long, ScalastyleConfiguration)
  private val cache = new mutable.HashMap[VirtualFile, TimestampedScalastyleConfiguration]()

  private object locations {
    val possibleConfigFileNames = Seq("scalastyle_config.xml", "scalastyle-config.xml")
    val possibleLocations = Seq(".idea", "project")

    def findConfigFile(dir: VirtualFile): Option[VirtualFile] = possibleConfigFileNames.flatMap(name => Option(dir.findChild(name))).headOption

    def findIn(project: Project): Option[VirtualFile] = {
      val root = project.getBaseDir
      if (root == null) return None

      val dirs = possibleLocations.flatMap(name => Option(root.findChild(name))) :+ root
      dirs.flatMap(findConfigFile).headOption
    }
  }

  def configuration(project: Project): Option[ScalastyleConfiguration] = {

    def latest(scalastyleXml: VirtualFile): Option[ScalastyleConfiguration] = {
      def read(): TimestampedScalastyleConfiguration = {
        val configuration = ScalastyleConfiguration.readFromString(new String(scalastyleXml.contentsToByteArray()))
        (scalastyleXml.getModificationStamp, configuration)
      }

      val currentStamp = scalastyleXml.getModificationStamp
      cache.get(scalastyleXml) match {
        case Some((`currentStamp`, config)) => Option(config)
        case _ =>
          val fromFile = cache.put(scalastyleXml, read())
          fromFile.map(_._2)
      }
    }

    locations.findIn(project).flatMap(latest)
  }

}

class ScalastyleCodeInspection extends LocalInspectionTool {

  override def checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array[ProblemDescriptor] = {
    def withConfiguration(f: ScalastyleConfiguration => Iterable[ProblemDescriptor]): Array[ProblemDescriptor] = {
      ScalastyleCodeInspection.configuration(file.getProject).map(c => f(c).toArray).getOrElse(Array.empty)
    }

    if (!file.isInstanceOf[ScalaFile]) Array.empty
    else withConfiguration { configuration =>
      val scalaFile = file.asInstanceOf[ScalaFile]
      val result = new ScalastyleChecker(None).checkFiles(configuration, Seq(new SourceSpec(file.getName, file.getText)))
      val document = PsiDocumentManager.getInstance(file.getProject).getDocument(file)

      def atPosition(e: PsiElement, line: Int, column: Option[Int]): Boolean = {
        val correctLine = if (line > 0) line - 1 else 0
        val sameLine = correctLine == document.getLineNumber(e.getTextOffset)
        column match {
          case Some(col) =>
            val offset = document.getLineStartOffset(correctLine) + col
            sameLine && e.getTextRange.contains(offset)
          case None => sameLine
        }
      }

      def findPsiElement(line: Int, column: Option[Int]): Option[PsiElement] = {
        (for {
          element <- scalaFile.depthFirst()
          if element != scalaFile && atPosition(element, line, column)
        } yield element).toList.headOption
      }

      def levelToProblemType(level: Level): ProblemHighlightType = level.name match {
        case Level.Info => ProblemHighlightType.INFORMATION
        case Level.Error => ProblemHighlightType.GENERIC_ERROR
        case Level.Warning => ProblemHighlightType.WEAK_WARNING
        case _ => ProblemHighlightType.GENERIC_ERROR
      }

      result.flatMap {
        case StyleError(_, _, key, level, args, Some(line), column, customMessage) =>
          findPsiElement(line, column).filter(e => e.isPhysical && !e.getTextRange.isEmpty).map { e =>
            val message = Messages.format(key, args, customMessage)
            manager.createProblemDescriptor(e, message, Array.empty[LocalQuickFix], levelToProblemType(level), true, false)
          }

        case _ => None
      }

    }

  }
}


text:
package com.sap.mlt.xliff12.impl.rfc4646.enums;

import java.util.Locale;

import com.sap.mlt.xliff12.impl.rfc4646.Subtag;

/**
 * Enum constants used to validate language tags
 */
public enum Variant {

  _1606NICT(null,null,"frm","Late Middle French (to 1606)"),
  _1694ACAD(null,null,"fr","Early Modern French"),
  _1901(null,null,"de","Traditional German orthography"),
  _1994(null,null,new String[] {"sl-rozaj","sl-rozaj-biske","sl-rozaj-njiva","sl-rozaj-osojs","sl-rozaj-solba"},"Standardized Resian orthography"),
  _1996(null,null,"de","German orthography of 1996"),
  AREVELA(null,null,"hy","Eastern Armenian"),
  AREVMDA(null,null,"hy","Western Armenian"),
  BAKU1926(null,null,new String[] {"az","ba","crh","kk","krc","ky","sah","tk","tt","uz"},"Unified Turkic Latin Alphabet (Historical)"),
  BISKE(null,null,"sl-rozaj","The San Giorgio dialect of Resian","The Bila dialect of Resian"),
  BOONT(null,null,"en","Boontling"),
  FONIPA(null,null,(String)null,"International Phonetic Alphabet"),
  FONUPA(null,null,(String)null,"Uralic Phonetic Alphabet"),
  LIPAW(null,null,"sl-rozaj","The Lipovaz dialect of Resian","The Lipovec dialect of Resian"),
  MONOTON(null,null,"el","Monotonic Greek"),
  NEDIS(null,null,"sl","Natisone dialect","Nadiza dialect"),
  NJIVA(null,null,"sl-rozaj","The Gniva dialect of Resian","The Njiva dialect of Resian"),
  OSOJS(null,null,"sl-rozaj","The Oseacco dialect of Resian","The Osojane dialect of Resian"),
  POLYTON(null,null,"el","Polytonic Greek"),
  ROZAJ(null,null,"sl","Resian","Resianic","Rezijan"),
  SCOTLAND(null,null,"en","Scottish Standard English"),
  SCOUSE(null,null,"en","Scouse"),
  SOLBA(null,null,"sl-rozaj","The Stolvizza dialect of Resian","The Solbica dialect of Resian"),
  TARASK(null,null,"be","Belarusian in Taraskievica orthography"),
  VALENCIA(null,null,"ca","Valencian")
;

  private final String deprecated;
  private final String preferred;
  private final String[] prefixes;
  private final String[] descriptions;

  private Variant(
    String dep,
    String pref,
    String prefix,
    String... desc) {
      this(dep,pref,new String[] {prefix},desc);
    }

  private Variant(
    String dep,
    String pref,
    String[] prefixes,
    String... desc) {
      this.deprecated = dep;
      this.preferred = pref;
      this.prefixes = prefixes;
      this.descriptions = desc;
  }

  public boolean isDeprecated() {
    return deprecated != null;
  }

  public String getDeprecated() {
    return deprecated;
  }

  public String getPreferredValue() {
    return preferred;
  }

  public Variant getPreferred() {
    return preferred != null ?
      valueOf(preferred.toUpperCase(Locale.ENGLISH)) : this;
  }

  public String getPrefix() {
    return prefixes != null && prefixes.length > 0 ? prefixes[0] : null;
  }

  public String[] getPrefixes() {
    return prefixes.clone();
  }

  public String getDescription() {
    return descriptions.length > 0 ? descriptions[0] : null;
  }

  public String[] getDescriptions() {
    return descriptions.clone();
  }

  public Subtag newSubtag() {
    return new Subtag(this);
  }

  public static Variant valueOf(Subtag subtag) {
    if (subtag == null) return null;
    if (subtag.getType() == Subtag.Type.VARIANT) {
      String name = subtag.getName();
      if (name.startsWith("1")) name = "_" + name;
      return valueOf(name.toUpperCase(Locale.ENGLISH));
    } else throw new IllegalArgumentException("Wrong subtag type");
  }

}


text:
buster.testCase('View#module()', {
  setUp: function() {
    var layout = new Layout({});
    var apple = new Apple({ slot: 1 });
    var orange = new Orange({ slot: 2 });
    var pear = new Pear({ slot: 3 });

    layout
      .add(apple)
      .add(orange)
      .add(pear);

    this.view = layout;
  },

  "Should return module type if no arguments given": function() {
    assert.equals(this.view.module(), 'layout');
  },

  "Should return the first child module with the specified type.": function() {
    var child = this.view.module('pear');

    assert.equals(child, this.view.children[2]);
  },

  "If there is more than one child of this module type, only the first is returned.": function() {
    this.view
      .add({ module: 'apple' });

    var child = this.view.module('apple');
    var firstChild = this.view.children[0];
    var lastChild = this.view.children[this.view.children.length-1];

    assert.equals(child, firstChild);
    refute.equals(child, lastChild);
  },

  "Should return the module name if defined with the name key": function() {
    var Henry = fruitmachine.define({ name: 'henry' });
    var henry = new Henry();

    assert.equals(henry.module(), 'henry');
    assert.equals(henry.name, 'henry');
  },

  "Should walk down the fruitmachine tree, recursively": function() {
    var Elizabeth = fruitmachine.define({ name: 'elizabeth' });
    var elizabeth = new Elizabeth();
    this.view.module('apple').add(elizabeth);

    var elizabethInstance = this.view.module('elizabeth');
    assert.equals(elizabethInstance.module(), 'elizabeth');
    assert.equals(elizabethInstance.name, 'elizabeth');
  },

  "Regression Test: Should still recurse even if the root view used to have a module of the same type": function() {
    var pear = this.view.module('pear').remove();
    this.view.module('apple').add(pear);

    var pearInstance = this.view.module('pear');
    assert.equals(pearInstance.module(), 'pear');
    assert.equals(pearInstance.name, 'pear');
  }
});


text:
NAME

speaker-test - command-line speaker test tone generator for ALSA
SYNOPSIS

speaker-test [-options]

DESCRIPTION

speaker-test generates a tone that can be used to test the speakers of a computer.

speaker-test by default will test the default device. If you want to test another sound device you will have first to get a list of all of the sound cards in your system and the devices associated with those cards. Notice that there might be for example, one device for analog sound, one for digital sound and one for HDMI sound. To get the list of available cards and devices you can run aplay -L.

$ aplay -L
null
    Discard all samples (playback) or generate zero samples (capture)
default:CARD=ICH5
    Intel ICH5, Intel ICH5
    Default Audio Device
front:CARD=ICH5,DEV=0
    Intel ICH5, Intel ICH5
    Front speakers
surround40:CARD=ICH5,DEV=0
    Intel ICH5, Intel ICH5
    4.0 Surround output to Front and Rear speakers
(...)

in the above example, there are four devices listed: null, default, front and surround40. So, if you want to test the last device you can run speaker-test -Dsurround40:ICH5 -c 6. The -c option will indicate that the six audio channels in the device have to be tested.

OPTIONS

-c | --channels NUM NUM channels in stream

-D | --device NAME PCM device name NAME

-f | --frequency FREQ sine wave of FREQ Hz

--help Print usage help

-b | --buffer TIME Use buffer size of TIME microseconds. When 0 is given, use the maximal buffer size. The default value is 0.

-p | --period TIME Use period size of TIME microseconds. When 0 is given, the periods given by -P option is used. The default value is 0.

-P | --nperiods PERIODS Use number of periods.  The default value is 4.

-r | --rate RATE stream of RATE Hz

-t | --test pink|sine|wav -t pink means use pink noise (default).

Pink noise is perceptually uniform noise -- that is, it sounds like every frequency at once.  If you can hear any tone it may indicate resonances in your speaker system or room.

-t sine means to use sine wave.

-t wav means to play WAV files, either pre-defined files or given via -w option.

You can pass the number from 1 to 3 as a backward compatibility.

-l | --nloops COUNT

Specifies the number of loops.  Zero means to run infinitely.

When -s option below with a valid channel is given, speaker-test will perform always a single-shot without looping.

-s | --speaker CHANNEL Do a single-shot speaker test for the given channel.  The channel number starts from 1. The channel number corresponds to left, right, rear-left, rear-right, center, LFE, side-left, side-right, and so on.

For example, when 1 is passed, it tests the left channel only once rather than both channels with looping.

-w | --wavfile FILE Use the given WAV file for the playback instead of pre-defined WAV files.

-W | --wavdir DIRECTORY Specify the directory containing WAV files for playback. The default path is /usr/share/sounds/alsa.

-m | --chmap MAP Pass the channel map to override. If the playback in a specific channel order or channel positions is required, pass the channel position strings to this option.

-X | --force-frequency Allow supplied FREQ to be outside the default range of 30-8000Hz. A minimum of 1Hz is still enforced.

USAGE EXAMPLES

Produce stereo sound from one stereo jack:

  speaker-test -Dplug:front -c2

Produce 4 speaker sound from two stereo jacks:

  speaker-test -Dplug:surround40 -c4

Produce 5.1 speaker sound from three stereo jacks:

  speaker-test -Dplug:surround51 -c6

To send a nice low 75Hz tone to the Woofer and then exit without touching any other speakers:

  speaker-test -Dplug:surround51 -c6 -s1 -f75

To do a 2-speaker test using the spdif (coax or optical) output:

  speaker-test -Dplug:spdif -c2

Play in the order of front-right and front-left from the front PCM

  speaker-test -Dplug:front -c2 -mFR,FL

SEE ALSO

aplay(1)

AUTHOR

The speaker-test program was written by James Courtier-Dutton. Pink noise support was added by Nathan Hurst. Further extensions by Takashi Iwai.


text:
'use strict';

angular.module('mean.projekat').config(['$stateProvider',
  function($stateProvider) {
    $stateProvider
    .state('lista projekata', {
      url: '/projekat/lista',
      templateUrl: 'projekat/views/lista.html'
    })
    .state('dodaj projekat', {
      url: '/projekat/dodaj',
      templateUrl: 'projekat/views/dodaj.html'
    })
    .state('izmeni projekat', {
      url: '/projekat/izmeni/:projekatId',
      templateUrl: 'projekat/views/izmeni.html'
    })
    .state('dodaj mentore ili ucesnike', {
      url: '/projekat/dodajMentoreIliUcesnike',
      templateUrl: 'projekat/views/dodajMenUce.html'
    });
  }
]);


text:
import * as React from "react";

import type { Nullable } from "core/types";
import type { IExplorerExtensibilityGroup } from "core/Debug/debugLayer";

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBan } from "@fortawesome/free-solid-svg-icons";
import { TreeItemSelectableComponent } from "./treeItemSelectableComponent";
import { Tools } from "../../tools";
import { ContextMenu, MenuItem, ContextMenuTrigger } from "react-contextmenu";
import type { GlobalState } from "../../globalState";

import expandedIcon from "../../imgs/expandedIcon.svg";
import collapsedIcon from "../../imgs/collapsedIcon.svg";

interface ITreeItemExpandableHeaderComponentProps {
    isExpanded: boolean;
    label: string;
    onClick: () => void;
    onExpandAll: (expand: boolean) => void;
}

class TreeItemExpandableHeaderComponent extends React.Component<ITreeItemExpandableHeaderComponentProps> {
    constructor(props: ITreeItemExpandableHeaderComponentProps) {
        super(props);
    }

    expandAll() {
        this.props.onExpandAll(!this.props.isExpanded);
    }

    render() {
        const chevron = this.props.isExpanded ?  : ;

        return (

 this.props.onClick()}>
                        {chevron}

{this.props.label}

 this.expandAll()} title={this.props.isExpanded ? "Collapse all" : "Expand all"}>
                    {chevron}

        );
    }
}

interface ITreeItemRootHeaderComponentProps {
    label: string;
}

class TreeItemRootHeaderComponent extends React.Component<ITreeItemRootHeaderComponentProps> {
    constructor(props: ITreeItemRootHeaderComponentProps) {
        super(props);
    }

    render() {
        return (

                        <FontAwesomeIcon icon={faBan} />

{this.props.label}

        );
    }
}

export interface ITreeItemComponentProps {
    items?: Nullable<any[]>;
    label: string;
    offset: number;
    filter: Nullable<string>;
    forceSubitems?: boolean;
    globalState: GlobalState;
    entity?: any;
    selectedEntities: any[];
    extensibilityGroups?: IExplorerExtensibilityGroup[];
    contextMenuItems?: { label: string; action: () => void }[];
}

export class TreeItemComponent extends React.Component<ITreeItemComponentProps, { isExpanded: boolean; mustExpand: boolean }> {
    static _ContextMenuUniqueIdGenerator = 0;

    constructor(props: ITreeItemComponentProps) {
        super(props);

        this.state = { isExpanded: true, mustExpand: true };
    }

    switchExpandedState(): void {
        this.setState({ isExpanded: !this.state.isExpanded, mustExpand: false });
    }

    shouldComponentUpdate(nextProps: ITreeItemComponentProps, nextState: { isExpanded: boolean }) {
        if (!nextState.isExpanded && this.state.isExpanded) {
            return true;
        }

        const items = nextProps.items;

        if (items && items.length) {
            for (const item of items) {
                if (Tools.LookForItems(item, nextProps.selectedEntities)) {
                    nextState.isExpanded = true;
                    return true;
                }
            }
        }

        return true;
    }

    expandAll(expand: boolean) {
        this.setState({ isExpanded: expand, mustExpand: expand });
    }

    renderContextMenu() {
        if (!this.props.contextMenuItems) {
            TreeItemComponent._ContextMenuUniqueIdGenerator++;
            return null;
        }

        return (
            <ContextMenu id={"contextmenu#" + TreeItemComponent._ContextMenuUniqueIdGenerator++} className="context-menu">
                {this.props.contextMenuItems.map((c) => {
                    return (
                        <MenuItem onClick={() => c.action()} key={c.label}>
                            {c.label}
                        </MenuItem>
                    );
                })}
            </ContextMenu>
        );
    }

    render() {
        let items = this.props.items;

        const marginStyle = {
            paddingLeft: 10 * (this.props.offset + 0.5) + "px",
        };

        if (!items) {
            if (this.props.forceSubitems) {
                items = [];
            } else {
                return (

{this.props.label}

                );
            }
        }

        if (!items.length) {
            return (

                    <ContextMenuTrigger id={"contextmenu#" + TreeItemComponent._ContextMenuUniqueIdGenerator}>
                        {this.renderContextMenu()}
                        <TreeItemRootHeaderComponent label={this.props.label} />
                    </ContextMenuTrigger>

            );
        }

        if (!this.state.isExpanded) {
            return (

                    <ContextMenuTrigger id={"contextmenu#" + TreeItemComponent._ContextMenuUniqueIdGenerator}>
                        {this.renderContextMenu()}
                        <TreeItemExpandableHeaderComponent
                            isExpanded={false}
                            label={this.props.label}
                            onClick={() => this.switchExpandedState()}
                            onExpandAll={(expand) => this.expandAll(expand)}
                        />
                    </ContextMenuTrigger>

            );
        }

        const sortedItems = Tools.SortAndFilter(null, items)[0].getChildren();
        return (

                {sortedItems.map((item: { uniqueId: React.Key | null | undefined; name: React.Key | null | undefined }) => {
                    return (
                        <TreeItemSelectableComponent
                            extensibilityGroups={this.props.extensibilityGroups}
                            key={item.uniqueId !== undefined && item.uniqueId !== null ? item.uniqueId : item.name}
                            offset={this.props.offset + 1}
                            selectedEntities={this.props.selectedEntities}
                            entity={item}
                            globalState={this.props.globalState}
                            filter={this.props.filter}
                        />
                    );
                })}

        );
    }
}


text:
  <button class="btn btn-success pull-right" ng-click="addDataQuery(panel.target)">Add query</button>

    <button class="btn btn-info dropdown-toggle" data-toggle="dropdown" bs-tooltip="'Datasource'">{{datasource.name}} </button>

        {{datasource.name}}


text:
// @flow

import _ from 'lodash';

export class ModulesSearchIndex {

  tokenToUidToDocumentMap: Object;

  constructor() {
    this.tokenToUidToDocumentMap = {};
  }

  indexDocument(token: string, uid: string, document: Object): void {
    if (!this.tokenToUidToDocumentMap[token]) {
      this.tokenToUidToDocumentMap[token] = {};
    }

    this.tokenToUidToDocumentMap[token][uid] = document;
  }

  search(tokens: Array<string>): Array<Object> {
    const query: string = tokens[0];
    let uidToDocumentMap: Object = this.tokenToUidToDocumentMap[query] || {};

    for (let i = 1, numTokens = tokens.length; i < numTokens; i += 1) {
      const token: string = tokens[i];
      const currentUidToDocumentMap: Object = this.tokenToUidToDocumentMap[token] || {};

      uidToDocumentMap = _.pickBy(uidToDocumentMap, (value: Object, key: string) => {
        return currentUidToDocumentMap[key];
      });
    }

    const lowerCaseQuery: string = query.toLowerCase();
    /*
    First sort based on a case insensitive index of how early
    the query appears.
    If they are the same, sort based on the module code.
    */
    const documents: Array<Object> = _.values(uidToDocumentMap);
    documents.sort((a: Object, b: Object) => {
      const indexOfA: number = a.label.toLowerCase().indexOf(lowerCaseQuery);
      const indexOfB: number = b.label.toLowerCase().indexOf(lowerCaseQuery);
      const difference: number = indexOfA - indexOfB;
      if (difference === 0) {
        return a.value.localeCompare(b.value);
      }
      return difference;
    });
    return documents;
  }
}

export class ModulesTokenizer {
  tokenize(text: string): Array<string> { // eslint-disable-line class-methods-use-this
    const arrayOfTokens: Array<string> = text
      .split(/[^a-zA-Z0-9\-']+/)
      .filter(str => !!str); // Filter empty tokens
    const codeWithoutPrefix: string = arrayOfTokens[0].replace(/\D+/, '');
    if (codeWithoutPrefix) {
      arrayOfTokens.unshift(codeWithoutPrefix); // Prepend
    }
    return arrayOfTokens;
  }
}


text:
/**
 * @file 	MyDijkstra.cpp
 * @author 	Fabian Wegscheider
 * @date 	Jul 10, 2017
 */

#include <boost/heap/fibonacci_heap.hpp>
#include "MyDijkstra.h"

using std::pair;

using Pair = pair<int, double>;
typedef graph_traits<Graph>::vertex_descriptor Vertex;

typename graph_traits<Graph>::out_edge_iterator out_i, out_end;

/**
 * Data that is stored in one node of a heap. Contains an integer and a double.
 * Comparisons are made by the double, smaller has higher priority
 */
struct heap_data
{
    heap::fibonacci_heap<heap_data>::handle_type handle;
    Pair pair;

    heap_data(Pair p):
        pair(p)
    {}

    bool operator<(heap_data const & rhs) const {
        return pair.second > rhs.pair.second;
    }
};

using Heap = heap::fibonacci_heap<heap_data>;

void MyDijkstra::computeShortestPaths(Graph& g, int numVertices, int source,
		double distances[], int predecessors[]) {

	predecessors[source] = source;

	Heap heap;

	Heap::handle_type *handles = new Heap::handle_type[numVertices];

	//initialization of the heap
	for (int i = 0; i < numVertices; ++i) {
		if (i == source) {
			handles[i] = heap.push(std::make_pair(i,0.));
			distances[i] = 0.;
		} else {
			handles[i] = heap.push(std::make_pair(i, std::numeric_limits<double>::infinity()));
			distances[i] = std::numeric_limits<double>::infinity();
		}
	}

	property_map<Graph, edge_weight_t>::type weights = get(edge_weight, g);
	property_map<Graph, vertex_index_t>::type index = get(vertex_index, g);

	//the actual algorithm
	while (!heap.empty()) {
		Pair min = heap.top().pair;
		heap.pop();
		for (tie(out_i, out_end) = out_edges(*(vertices(g).first+min.first), g);
				out_i != out_end; ++out_i) {
			double tmp = min.second + weights[*out_i];
			int targetIndex = index[target(*out_i, g)];
			if (tmp < distances[targetIndex]) {
				distances[targetIndex] = tmp;
				predecessors[targetIndex] = min.first;
				(*handles[targetIndex]).pair.second = tmp;
				heap.increase(handles[targetIndex]);
			}
		}
	}

	delete[] handles;
}


text:
import * as React from 'react';
import { connect } from 'react-redux';

import { increment, decrement } from '../actions/counter';
import Counter from '../components/counter';

import {IAppState} from '../reducers';

import {Container, Row, Column} from '../components/layout';

interface ICounterPageProps extends React.Props<any> {
  counter: number;
  increaseCounter: () => void;
  decreaseCounter: () => void;
};

function mapStateToProps(state: IAppState) {
  return {
    counter: state.counter.count,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    increaseCounter: (): void => dispatch(increment()),
    decreaseCounter: (): void => dispatch(decrement()),
  };
}

class CounterPage extends React.Component<ICounterPageProps, void> {
  render() {
    const { counter, increaseCounter, decreaseCounter } = this.props;

    return (
      <Container testid="counter">
        <Row>
          <Column size={12}>
            <h2
              data-testid="counter-heading"
              className="center caps"
              id="qa-counter-heading">
              Counter
            </h2>

            <Counter
              counter={ counter }
              increment={ increaseCounter }
              decrement={ decreaseCounter } />
          </Column>
        </Row>
    </Container>
    );
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CounterPage);


text: Simple real estate calculator app


text:
import train as train
import time, random
import scipy.sparse
import pycrfsuite as crf
import helper
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.tag import pos_tag
import random
import text2num as t2n

def trainModel(holdback=-1):
    ## extract features
    trainer = crf.Trainer(verbose=True)

    for xseq, yseq in zip(trainX, trainY):
        trainer.append(xseq, yseq, group = 0)

    for xseq, yseq in zip(testX, testY):
        trainer.append(xseq, yseq, group = 1)

    trainer.set_params({
        'c1': 2.0,   # coefficient for L1 penalty
        'c2': 1e-3,  # coefficient for L2 penalty
        # include transitions that are possible, but not observed
        'max_iterations': 250,  # stop earlier
        'feature.possible_transitions': True,
        'feature.possible_states': True,
    })
    trainer.train(trained_model, holdback)
    return trainer

def predict():
    tagger = crf.Tagger()
    tagger.open(trained_model)

    predictedY  =  []
    confidences =  []
    confidences_beam = []

    for xseq in testX:
        yseq = tagger.tag(xseq)
        predictedY.append(yseq)
        confidences.append([tagger.marginal(yseq[i],i) for i in range(len(yseq))])
        confidences_beam.append([ [tagger.marginal(tag, i)  for tag in train.int2tags]   for i in range(len(yseq))])
    return predictedY, testY, confidences, confidences_beam, tagger.info()

def predict(article, trained_model):
    tagger = crf.Tagger()
    tagger.open(trained_model)

    xseq = articleFeatureExtract(article)
    yseq  =  tagger.tag(xseq)

    confidences =  [tagger.marginal(yseq[i],i) for i in range(len(yseq))]
    confidences_beam = [ [tagger.marginal(tag, i)  for tag in train.int2tags]   for i in range(len(yseq))]

    return yseq, confidences

def featureExtract(data, identifier,  prev_n = 4, next_n = 4):
    features = []
    labels   = []
    int2tags = ["TAG"] + train.int2tags
    for index in range(len(data)):
        article = data[index][0]
        article_labels = [int2tags[t] for t in data[index][1]]
        article_features = articleFeatureExtract(article, prev_n, next_n)
        features.append(article_features)
        labels.append(article_labels)
    return features, labels

def articleFeatureExtract(article, prev_n = 4, next_n = 4):
    article_features = []
    title_features = {}
    labels = []
    # if '.' in article:
        # title = article[:article.index('.')]
        # for i in range(len(title)):
        #     t = title[i]
        #     tf = {}
        #     tf[t] = 1
        #     title_features[t] = 1
    for token_ind in range(len(article)):
        token = article[token_ind]
        context = {}
        for i in range(max(0, token_ind - prev_n), min(token_ind + next_n, len(article))):
            context_token = article[i]
            context[context_token] =1
        token_features = {}
        token_features["context"] = context
        # token_features["title"] = title_features
        token_features["token"] = token
        token_features[token]   = 1
        token_features["other"] = helper.getOtherFeatures(token)
        article_features.append(token_features)

    return article_features

if __name__ == '__main__':
    ##SCRIPT
    print "reload helper"
    reload(helper)
    helper.load_constants()
    print "end load helper"

    retrain =  True
    if retrain:
        num_blocks = 1
        ## num_blocks = 5
        training_file = "../data/tagged_data/EMA/train.tag"
        dev_file      = "../data/tagged_data/EMA/dev.tag"
        test_file      = "../data/tagged_data/EMA/test.tag"

        trained_model = "trained_model_crf.EMA.p"
        print "load files"
        train_data, train_identifier = train.load_data(training_file)
        test_data, test_identifier = train.load_data(dev_file)
        print "End load files"
        prev_n = 2
        next_n = 2
        print "Start Feature extract on train set"
        trainX, trainY = featureExtract(train_data,train_identifier, prev_n, next_n )
        print "Done Feature extract on train set"
        #trainX, trainY = featureExtract(dev_data, prev_n, next_n)
        print "Start Feature extract on test set"
        testX, testY = featureExtract(test_data, test_identifier, prev_n, next_n)
        print "Done Feature extract on test set"
        #testX, testY = featureExtract(train_data[split_index:], prev_n, next_n)
        trainer = trainModel(1)


text:
package net.bis5.mattermost.model;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.bis5.mattermost.model.AutocompleteArg.AutocompleteArgType.AutocompleteArgTypeDeserializer;
import net.bis5.mattermost.model.serialize.HasCodeSerializer;

/**
 * Slash Command Autocomplete Argument
 *
 * @since Mattermost Server 5.24.0
 */
@Data
public class AutocompleteArg {

  private String name;
  @JsonProperty("HelpText")
  private String helpText;
  private AutocompleteArgType type;
  private boolean required;
  private AutocompleteArgData data;

  @JsonSerialize(using = HasCodeSerializer.class)
  @JsonDeserialize(using = AutocompleteArgTypeDeserializer.class)
  @Getter
  @RequiredArgsConstructor
  public enum AutocompleteArgType implements HasCode<AutocompleteArgType> {
    TEXT_INPUT("TextInput"), STATIC_LIST("StaticList"), DYNAMIC_LIST("DynamicList");
    private final String code;

    static AutocompleteArgType of(String code) {
      return Arrays.stream(values()).filter(e -> e.getCode().equals(code)).findFirst().orElse(null);
    }
    public static class AutocompleteArgTypeDeserializer extends JsonDeserializer<AutocompleteArgType> {

      @Override
      public AutocompleteArgType deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
        String jsonValue = p.getText();
        return of(jsonValue);
      }
    }
  }

  @Data
  public static class AutocompleteArgData implements AutocompleteTextArg, AutocompleteStaticListArg, AutocompleteDynamicListArg {
    private String hint;
    private String pattern;
    @JsonProperty("PossibleArguments")
    private List<AutocompleteListItem> possibleArguments;
    @JsonProperty("FetchURL")
    private String fetchUrl;
  }

  public static interface AutocompleteTextArg {
    String getHint();
    void setHint(String hint);
    String getPattern();
    void setPattern(String pattern);
  }

  public static interface AutocompleteStaticListArg {
    List<AutocompleteListItem> getPossibleArguments();
    void setPossibleArguments(List<AutocompleteListItem> arguments);
  }

  @Data
  public static class AutocompleteListItem {
    private String item;
    private String hint;
    @JsonProperty("HelpText")
    private String helpText;
  }

  public static interface AutocompleteDynamicListArg {
    String getFetchUrl();
    void setFetchUrl(String fetchUrl);
  }

  public AutocompleteTextArg getTextArgumentData() {
    return getData();
  }

  public AutocompleteStaticListArg getStaticListArgumentData() {
    return getData();
  }

  public AutocompleteDynamicListArg getDynamicListArgumentData() {
    return getData();
  }

}


text:
QuickSpecBegin(SDLEndAudioPassThruResponseSpec)

QuickSpecEnd


text:
struct marl_fiber_context {
  // parameter registers (First two)
  uintptr_t a0;
  uintptr_t a1;

  // callee-saved registers
  uintptr_t s0;
  uintptr_t s1;
  uintptr_t s2;
  uintptr_t s3;
  uintptr_t s4;
  uintptr_t s5;
  uintptr_t s6;
  uintptr_t s7;
  uintptr_t s8;

  uintptr_t fs0;
  uintptr_t fs1;
  uintptr_t fs2;
  uintptr_t fs3;
  uintptr_t fs4;
  uintptr_t fs5;
  uintptr_t fs6;
  uintptr_t fs7;

  uintptr_t ra;
  uintptr_t sp;
  uintptr_t fp;
};

#ifdef __cplusplus
#include <cstddef>
static_assert(offsetof(marl_fiber_context, a0) == MARL_REG_a0,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, a1) == MARL_REG_a1,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s0) == MARL_REG_s0,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s1) == MARL_REG_s1,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s2) == MARL_REG_s2,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s3) == MARL_REG_s3,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s4) == MARL_REG_s4,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s5) == MARL_REG_s5,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s6) == MARL_REG_s6,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s7) == MARL_REG_s7,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, s8) == MARL_REG_s8,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs0) == MARL_REG_fs0,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs1) == MARL_REG_fs1,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs2) == MARL_REG_fs2,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs3) == MARL_REG_fs3,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs4) == MARL_REG_fs4,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs5) == MARL_REG_fs5,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs6) == MARL_REG_fs6,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fs7) == MARL_REG_fs7,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, ra) == MARL_REG_ra,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, sp) == MARL_REG_sp,
              "Bad register offset");
static_assert(offsetof(marl_fiber_context, fp) == MARL_REG_fp,
              "Bad register offset");
#endif // __cplusplus

#endif // MARL_BUILD_ASM


text:
title: Типы данных (классы со стереотипом type) и их свойства
sidebar: flexberry-designer_sidebar
keywords: Flexberry Designer, Flexberry ORM, типы данных, type, стереотип, дополнительные свойства, редактирование свойств, пример
summary: Особенности генерации типов данных, свойства типов данных и их редактирование, пример сгенерированного кода
toc: true
permalink: ru/fd_data-types-properties.html
lang: ru
---

`Type`, [стереотип](fd_key-concepts.html), вводящий новый тип. При генерации кода на целевом языке объявляется этот тип. Типы не могут связываться никакими ассоциациями, но могут наследоваться.

Пример:

![](/images/pages/products/flexberry-designer/class-diagram/type.jpg)

{% include note.html content="Если классы находятся в разных пакетах, то будет сгенерировано 2 отдельные сборки, которые будут ссылаться друг на друга. Код успешно сгенерируется, но не будет компилироваться." %}

![](/images/pages/products/flexberry-designer/class-diagram/types.png)

## Описание типа

Что генерируется | Генерация в SQL DDL | Генерация в .Net-язык
:----------------------------|:--------------------------------|:--------------------------------------
| Любая часть любого UML-класса (атрибут, параметр метода и т.д.), объявленная этим типом | Как есть или указывается преобразование в карте типов для генератора | Как есть. Атрибут, параметр метода и т.п. объявляются этим типом
UML-класс | | .Net-класс
Атрибут UML-класса | | Публичное виртуальное свойство с тем же именем и соответствующим модификатором (# - `protected`, + - `public`, - - `private`) и приватный член класса для этого свойства. Тип свойства и приватного члена - тип атрибута.
Метод UML-класса | | Публичный виртуальный метод с соответствующими параметрами. Тело метода пустое со скобкой программиста для внесения кода метода.

### Дополнительно редактируемые свойства и что как генерируется

Окно редактирования свойств типа данных выглядит следующим образом:

1.Закладка редактирования свойств UML-класса:

![](/images/pages/products/flexberry-designer/class-diagram/typepropp1.png)

Свойство | Описание | Генерация в .Net-язык
:------------|:---------------------|:------------------------------------
`Stored` | |
`Name` | Имя UML-класса, оно же имя типа | Имя .Net-класса
`Description` | Рекоторое развёрнутое описание, при необходимости, для пояснительных целей | Как `DocComment` к классу в код на .Net-языке
`PrimaryKeyStorage` | |
`Storage` | |
`AutoAltered` | |
`LoadingOrder` | |
`Trim` | |
`Packet, NamespacePostfix` | Позволяют настроить сборку и пространство имен, в которое должен генерироваться тип | см. [Расположение сборок после генерации кода](fo_location-assembly.html)
`PBCustomAttributes` | | Если галочка указана - генерируется [скобка программиста](fo_programmer-brackets.html) для "ручного" внесения атрибутов перед классом.
`PBMembers` | Позволяет указать, необходима ли [скобка программиста](fo_programmer-brackets.html) внутри класса для "ручного" внесения членов класса | Если галочка указана - генерируется [скобка программиста](fo_programmer-brackets.html) для "ручного" внесения членов класса
`PBClass` | |
`PublishToEBSD` | | Если галочка указана - перед классом генерируется указание атрибута `PublishToEBSDAttribute`, который указывает доступность данного класса для использования в редакторе диаграмм сценариев

2.Закладка редактирования свойств атрибутов UML-класса:

![](/images/pages/products/flexberry-designer/class-diagram/typepropp2.png)

Свойство | Описание | Генерация в .Net-язык
:----------------|:---------------------|:------------------------------------------
`AccessModifier` | модификатор доступа к соответствующему свойству `.Net`-класса | Модификаторы:+ - public - - private # - protected
`Stored` | |
`Name` | то же самое имя атрибута, что на диаграмме | Имя свойства в `.Net`-классе, а также некоторое производное имя приватного члена (в зависимости от формата приватного члена, который указывается в настройках генератора).
`Description`| описание для пояснительных целей | Как `DocComment` к свойству
`Type` | тип данных свойства | Как тип свойства и тип приватного члена
`DefaultValue` | значение по умолчанию | Как инициализатор приватного члена
`NotNull` | |
`DataServiceExpression` | |
`Storage` | |
`Hint` | |
`Order` | |
`PBCustomAttributes` | | Если галочка указана - перед определением свойства генерируется [скобка программиста](fo_programmer-brackets.html) для "ручного" внесения .Net-атрибутов.
`PBGetStart` | | Если галочка указана - генерируется [скобка программиста](fo_programmer-brackets.html) в аксессоре get свойства непосредственно после начала кода аксессора.
`PBGetEnd` | | Если галочка указана - генерируется [скобка программиста](fo_programmer-brackets.html) в аксессоре get свойства непосредственно перед концом кода аксессора.
`PBSetStart` | | Если галочка указана - генерируется [скобка программиста](fo_programmer-brackets.html) в аксессоре set свойства непосредственно после начала кода аксессора.
`PBSetEnd` | | Если галочка указана - генерируется [скобка программиста](fo_programmer-brackets.html) в аксессоре set свойства непосредственно перед концом кода аксессора.
`Autoincrement` | |

3.Закладка редактирования свойств методов UML-класса:

![](/images/pages/products/flexberry-designer/class-diagram/typepropp3.png)

В верхней части - методы, в нижней - параметры выбранного в верхней части метода.

Для методов:

Свойство | Описание | Генерация в .Net-язык
:--------------|:---------------------|:--------------------------
`AccessModifier` | модификатор доступа к соответствующему методу .Net-класса | Модификаторы: + - public - - private # - protected
`Name` | то же самое имя метода, что на диаграмме | Имя метода в `.Net`-классе
`Description` | описание для пояснительных целей | Как `DocComment` к методу. Если `IsEvent` указан, описание генерируется перед событием и перед методом, взводящим событие.
`Type` | тип данных метода | Как тип метода. Если не заполнено - `void`.
`IsEvent`| указывает, что это не метод, а событие | Если IsEvent указан, то метод должен иметь ровно один параметр с типом, объявленным как [UML-класс со стереотипом EventArg](fd_eventarg.html). Рядом с описанием EventArg, - генерируется соответствующий делегат. Внутри класса-типа - событие. Внутри класса-типа - метод, взводящий событие (навроде OnXXXXXXX)
`PBCustomAttributes` | | Если галочка указана - генерируется [скобка программиста](fo_programmer-brackets.html) непосредственно перед методом для "ручного" внесения .Net-атрибутов.] Если `IsEvent` указан, [скобка программиста](fo_programmer-brackets.html) генерируется перед методом взведения события OnXXXXXXX

Для параметров методов:

Свойство  | Описание | Генерация в .Net-язык
:--------------|:----------------------|:---------------------------------------
`Name` | то же самое имя параметра, что на диаграмме | Имя параметра метода в `.Net`-классе
`Description` | описание для пояснительных целей | Как описание параметра в `DocComment` к методу, чей это параметр.
`Type` | тип данных параметра | Тип данных параметра
`Modifier` | | Модификатор передачи параметра: byref - ref; byval - ничего; out - out; in - in.

### Пример сгенерированного кода на C# по примеру

```csharp
 /// <summary>
    /// Представление интервалов времени
    /// </summary>
    // *** Start programmer edit section *** (МинСек CustomAttributes)
    // *** End programmer edit section *** (МинСек CustomAttributes)
    public class МинСек
    {

        private int fМин;

        private int fСек;

        public virtual int Мин
        {
            get
            {
                return this.fМин;
            }
            set
            {
                this.fМин = value;
            }
        }

        public virtual int Сек
        {
            get
            {
                return this.fСек;
            }
            set
            {
                this.fСек = value;
            }
        }
    }
```


text:
package org.cloudfoundry.client.v2.serviceplanvisibilities;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;

/**
 * The response payload for the the Create Service Plan Visibility request.
 */
@JsonDeserialize
@Value.Immutable
abstract class _CreateServicePlanVisibilityResponse extends AbstractServicePlanVisibilityResource {

}


text:
module Coupler
  module Models
    module Jobify
      def self.included(base)
        base.one_to_many :jobs
        base.one_to_many(:running_jobs, {
          :class => "Coupler::Models::Job",
          :conditions => { :status => 'running' }, :read_only => true
        })
        base.one_to_many(:scheduled_jobs, {
          :class => "Coupler::Models::Job",
          :conditions => { :status => 'scheduled' }, :read_only => true
        })
      end
    end
  end
end