text:
<?xml version="1.0" encoding="utf-8"?>
<!--197 Real Estate Title Evidence-->
<TransactionSpecification TransactionSetIdentifierCode="197" xmlns="http://tempuri.org/X12ParserSpecification.xsd">
  <Segment SegmentId="BGN" />
  <Loop LoopId="N1">
    <Name>Name</Name>
    <StartingSegment SegmentId="N1" />
    <Segment SegmentId="N2" />
    <Segment SegmentId="N3" />
    <Segment SegmentId="N4" />
    <Segment SegmentId="REF" />
    <Segment SegmentId="PER" />
  </Loop>
  <Loop LoopId="PID">
    <Name>Product/Item Description</Name>
    <StartingSegment SegmentId="PID" />
    <Segment SegmentId="REF" />
    <Segment SegmentId="DTP" />
    <Segment SegmentId="MSG" />
    <Loop LoopId="NM1">
      <Name>Individual or Organizational Name</Name>
      <StartingSegment SegmentId="NM1" />
      <Segment SegmentId="N2" />
      <Segment SegmentId="N3" />
      <Segment SegmentId="N4" />
      <Loop LoopId="EFI">
        <Name>Electronic Format Identification</Name>
        <StartingSegment SegmentId="EFI" />
        <Segment SegmentId="BIN" />
      </Loop>
    </Loop>
    <Loop LoopId="NX1">
      <Name>Property or Entity Identification</Name>
      <StartingSegment SegmentId="NX1" />
      <Segment SegmentId="NX2" />
      <Segment SegmentId="PDS" />
      <Segment SegmentId="PDE" />
    </Loop>
    <Loop LoopId="FGS">
      <Name>Form Group</Name>
      <StartingSegment SegmentId="FGS" />
      <Segment SegmentId="DTP" />
      <Segment SegmentId="FPT" />
      <Segment SegmentId="MSG" />
      <Segment SegmentId="N9" />
      <Loop LoopId="IN1">
        <Name>Individual Identification</Name>
        <StartingSegment SegmentId="IN1" />
        <Segment SegmentId="IN2" />
        <Segment SegmentId="AMT" />
        <Segment SegmentId="M1" />
        <Segment SegmentId="MSG" />
      </Loop>
      <Loop LoopId="LQ">
        <Name>Industry Code</Name>
        <StartingSegment SegmentId="LQ" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="REF" />
        <Segment SegmentId="MSG" />
        <Loop LoopId="IN1">
          <Name>Individual Identification</Name>
          <StartingSegment SegmentId="IN1" />
          <Segment SegmentId="IN2" />
          <Segment SegmentId="M1" />
          <Segment SegmentId="MSG" />
        </Loop>
      </Loop>
    </Loop>
    <Loop LoopId="LX">
      <Name>Assigned Number</Name>
      <StartingSegment SegmentId="LX" />
      <Segment SegmentId="G86" />
    </Loop>
  </Loop>
</TransactionSpecification>


text:
class AddIndexToUsers < ActiveRecord::Migration
  def change
    change_table :users do |t|
      t.index :twitter_id, unique: true
      t.index :screen_name, unique: true
      t.string :send_key
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
require 'puppet/network/http/api'

module Puppet::Network::HTTP::API::V1
  # How we map http methods and the indirection name in the URI
  # to an indirection method.
  METHOD_MAP = {
    "GET" => {
      :plural => :search,
      :singular => :find
    },
    "POST" => {
      :singular => :find,
    },
    "PUT" => {
      :singular => :save
    },
    "DELETE" => {
      :singular => :destroy
    },
    "HEAD" => {
      :singular => :head
    }
  }

  def uri2indirection(http_method, uri, params)
    environment, indirection, key = uri.split("/", 4)[1..-1] # the first field is always nil because of the leading slash

    raise ArgumentError, "The environment must be purely alphanumeric, not '#{environment}'" unless environment =~ /^\w+$/
    raise ArgumentError, "The indirection name must be purely alphanumeric, not '#{indirection}'" unless indirection =~ /^\w+$/

    method = indirection_method(http_method, indirection)

    params[:environment] = Puppet::Node::Environment.new(environment)
    params.delete(:bucket_path)

    raise ArgumentError, "No request key specified in #{uri}" if key == "" or key.nil?

    key = URI.unescape(key)

    [indirection, method, key, params]
  end

  def indirection2uri(request)
    indirection = request.method == :search ? pluralize(request.indirection_name.to_s) : request.indirection_name.to_s
    "/#{request.environment.to_s}/#{indirection}/#{request.escaped_key}#{request.query_string}"
  end

  def request_to_uri_and_body(request)
    indirection = request.method == :search ? pluralize(request.indirection_name.to_s) : request.indirection_name.to_s
    ["/#{request.environment.to_s}/#{indirection}/#{request.escaped_key}", request.query_string.sub(/^\?/,'')]
  end

  def indirection_method(http_method, indirection)
    raise ArgumentError, "No support for http method #{http_method}" unless METHOD_MAP[http_method]

    unless method = METHOD_MAP[http_method][plurality(indirection)]
      raise ArgumentError, "No support for plural #{http_method} operations"
    end

    method
  end

  def pluralize(indirection)
    return(indirection == "status" ? "statuses" : indirection + "s")
  end

  def plurality(indirection)
    # NOTE This specific hook for facts is ridiculous, but it's a *many*-line
    # fix to not need this, and our goal is to move away from the complication
    # that leads to the fix being too long.
    return :singular if indirection == "facts"
    return :singular if indirection == "status"
    return :singular if indirection == "certificate_status"
    return :plural if indirection == "inventory"

    result = (indirection =~ /s$|_search$/) ? :plural : :singular

    indirection.sub!(/s$|_search$/, '')
    indirection.sub!(/statuse$/, 'status')

    result
  end
end


text:
use key::parse::parse;
use key::MultiKey;
use mode_map::ModeMap;
use op::{HasOperator, HasMotion, HasObject, PendingOp, ObjectOp, MotionOp, InsertOp, NormalOp,
         OperatorOp};
use ordered_vec_map::InsertionResult;

impl HasOperator<MultiKey> for ModeMap<MultiKey, NormalOp> {
    fn insert_operator(&mut self, key: Vec<MultiKey>, op: OperatorOp) -> InsertionResult {
        self.insert_op(key, NormalOp::Operator(op))
    }
}

impl HasMotion<MultiKey> for ModeMap<MultiKey, NormalOp> {
    fn insert_motion(&mut self, key: Vec<MultiKey>, op: MotionOp) -> InsertionResult {
        self.insert_op(key, NormalOp::Motion(op))
    }
}

impl HasOperator<MultiKey> for ModeMap<MultiKey, PendingOp> {
    fn insert_operator(&mut self, key: Vec<MultiKey>, op: OperatorOp) -> InsertionResult {
        self.insert_op(key, PendingOp::Operator(op))
    }
}

impl HasMotion<MultiKey> for ModeMap<MultiKey, PendingOp> {
    fn insert_motion(&mut self, key: Vec<MultiKey>, op: MotionOp) -> InsertionResult {
        self.insert_op(key, PendingOp::Motion(op))
    }
}

impl HasObject<MultiKey> for ModeMap<MultiKey, PendingOp> {
    fn insert_object(&mut self, key: Vec<MultiKey>, op: ObjectOp) -> InsertionResult {
        self.insert_op(key, PendingOp::Object(op))
    }
}

fn add_operators<Op>(map: &mut ModeMap<MultiKey, Op>)
where
    Op: Copy,
    ModeMap<MultiKey, Op>: HasOperator<MultiKey>,
{
    use op::OperatorOp::*;
    map.insert_operator(parse("c"), Change);
    map.insert_operator(parse("d"), Delete);
    map.insert_operator(parse("y"), Yank);
    map.insert_operator(parse("g~"), SwapCase);
    map.insert_operator(parse("gu"), ToLower);
    map.insert_operator(parse("gU"), ToUpper);
    map.insert_operator(parse("!"), ExternalPrg);
    map.insert_operator(parse("="), EqualPrg);
    map.insert_operator(parse("gq"), TextFormat);
    map.insert_operator(parse("g?"), Rot13);
    map.insert_operator(parse(">"), ShiftRight);
    map.insert_operator(parse("<"), ShiftLeft);
    map.insert_operator(parse("<lt>"), ShiftLeft);
    map.insert_operator(parse("zf"), DefineFold);
    map.insert_operator(parse("g@"), OperatorFunc);
}

fn add_motions<Op>(map: &mut ModeMap<MultiKey, Op>)
where
    Op: Copy,
    ModeMap<MultiKey, Op>: HasMotion<MultiKey>,
{
    use op::MotionOp::*;
    map.insert_motion(parse("<left>"), Left);
    map.insert_motion(parse("<right>"), Right);
    map.insert_motion(parse("<up>"), Up);
    map.insert_motion(parse("<down>"), Down);
    map.insert_motion(parse("h"), Left);
    map.insert_motion(parse("l"), Right);
    map.insert_motion(parse("k"), Up);
    map.insert_motion(parse("j"), Down);
    map.insert_motion(parse("gg"), Top);
    map.insert_motion(parse("G"), Bottom);
    map.insert_motion(parse("w"), Word);
    map.insert_motion(parse("<bs>"), Backspace);
    map.insert_motion(parse("<home>"), Home);
    map.insert_motion(parse("<end>"), End);
    map.insert_motion(parse("<khome>"), Home);
    map.insert_motion(parse("<kend>"), End);
    map.insert_motion(parse("<pageup>"), PageUp);
    map.insert_motion(parse("<pagedown>"), PageDown);
    map.insert_motion(parse("<kpageUp>"), PageUp);
    map.insert_motion(parse("<kpageDown>"), PageDown);
}

fn add_objects<Op>(map: &mut ModeMap<MultiKey, Op>)
where
    Op: Copy,
    ModeMap<MultiKey, Op>: HasObject<MultiKey>,
{
    use op::ObjectOp::*;
    map.insert_object(parse("aw"), AWord);
    map.insert_object(parse("iw"), InnerWord);
    map.insert_object(parse("aW"), AWORD);
    map.insert_object(parse("iW"), InnerWORD);
    map.insert_object(parse("as"), ASentence);
    map.insert_object(parse("is"), InnerSentence);
    map.insert_object(parse("ap"), AParagraph);
    map.insert_object(parse("ip"), InnerParagraph);
    map.insert_object(parse("a["), ASquareBlock);
    map.insert_object(parse("a]"), ASquareBlock);
    map.insert_object(parse("i["), InnerSquareBlock);
    map.insert_object(parse("i]"), InnerSquareBlock);
    map.insert_object(parse("a("), AParen);
    map.insert_object(parse("a)"), AParen);
    map.insert_object(parse("i("), InnerParen);
    map.insert_object(parse("i)"), InnerParen);
    map.insert_object(parse("a<"), AAngle);
    map.insert_object(parse("a>"), AAngle);
    map.insert_object(parse("i<"), InnerAngle);
    map.insert_object(parse("i>"), InnerAngle);
    map.insert_object(parse("at"), ATag);
    map.insert_object(parse("it"), InnerTag);
    map.insert_object(parse("a{"), ABrace);
    map.insert_object(parse("a}"), ABrace);
    map.insert_object(parse("i{"), InnerBrace);
    map.insert_object(parse("i}"), InnerBrace);
    map.insert_object(parse("a'"), ASingleQuote);
    map.insert_object(parse("i'"), InnerSingleQuote);
    map.insert_object(parse("a\""), ADoubleQuote);
    map.insert_object(parse("i\""), InnerDoubleQuote);
    map.insert_object(parse("a`"), ABackTick);
    map.insert_object(parse("i`"), InnerBackTick);
}

pub fn normal_mode_map() -> ModeMap<MultiKey, NormalOp> {
    use op::NormalOp::*;
    let mut map = ModeMap::new();
    map.insert_op(parse("<Esc>"), Cancel);
    map.insert_op(parse("i"), Insert);
    map.insert_op(parse("r"), ReplaceChar);
    map.insert_op(parse("R"), ReplaceMode);
    map.insert_op(parse("."), Repeat);
    add_operators(&mut map);
    add_motions(&mut map);
    return map;
}

pub fn pending_mode_map() -> ModeMap<MultiKey, PendingOp> {
    use op::PendingOp::*;
    let mut map = ModeMap::new();
    map.insert_op(parse("<Esc>"), Cancel);
    add_operators(&mut map);
    add_objects(&mut map);
    add_motions(&mut map);
    return map;
}

pub fn insert_mode_map() -> ModeMap<MultiKey, InsertOp> {
    use op::InsertOp::*;
    let mut map = ModeMap::new();
    map.insert_op(parse("<Esc>"), Cancel);
    map.insert_op(parse("<Up>"), Up);
    map.insert_op(parse("<Down>"), Down);
    map.insert_op(parse("<Left>"), Left);
    map.insert_op(parse("<Right>"), Right);
    map.insert_op(parse("<Backspace>"), Backspace);
    map.insert_op(parse("<Delete>"), Delete);
    map.insert_op(parse("<PageUp>"), PageUp);
    map.insert_op(parse("<PageDown>"), PageDown);
    map.insert_op(parse("<kpageUp>"), PageUp);
    map.insert_op(parse("<kpageDown>"), PageDown);
    map.insert_op(parse("<home>"), Home);
    map.insert_op(parse("<end>"), End);
    map.insert_op(parse("<khome>"), Home);
    map.insert_op(parse("<kend>"), End);
    map.insert_op(parse("<C-w>"), DeleteWord); // (Ctrl-W));
    map.insert_op(parse("<C-u>"), DeleteLine); // (Ctrl-U));
    map.insert_op(parse("<Tab>"), Tab);
    map.insert_op(parse("<C-k>"), Digraph); // (Ctrl-K));
    map.insert_op(parse("<C-r>"), InsertRegister); // (Ctrl-R));
    map.insert_op(parse("<C-r><C-r>"), InsertRegisterContents); // (Ctrl-R Ctrl-R));
    return map;
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn decimal_full_match() {
        let mut typeahead = Typeahead::new();
        typeahead.put_front(&parse("12345g"), RemapType::Remap);
        let result = typeahead.parse_decimal();
        assert_eq!(Match::FullMatch(12345), result);
        assert_eq!(1, typeahead.len());
    }

    #[test]
    fn decimal_full_match_two() {
        let mut typeahead = Typeahead::new();
        typeahead.put_front(&parse("12345gg1"), RemapType::Remap);
        let result = typeahead.parse_decimal();
        assert_eq!(Match::FullMatch(12345), result);
        assert_eq!(3, typeahead.len());
    }

    #[test]
    fn decimal_partial_match() {
        let mut typeahead = Typeahead::new();
        typeahead.put_front(&parse("12345"), RemapType::Remap);
        let result = typeahead.parse_decimal();
        assert_eq!(Match::PartialMatch, result);
        assert_eq!(5, typeahead.len());
    }

    #[test]
    fn decimal_no_match() {
        let mut typeahead = Typeahead::new();
        typeahead.put_front(&parse("g12345"), RemapType::Remap);
        let result = typeahead.parse_decimal();
        assert_eq!(Match::NoMatch, result);
        assert_eq!(6, typeahead.len());
    }
}


text:
import pytest

# TODO: check redirect url

@pytest.mark.parametrize(
    'route', [
        '/admin',
        '/admin/account/regular',
        '/admin/repository/regular/repo1',
        '/admin/role/admin'
    ]
)
def test_unauthorized_get(filled_db_session, app_client, route):
    assert app_client.get(route).status == '404 NOT FOUND'

@pytest.mark.parametrize(
    'route', [
        '/admin/account/regular/ban',
        '/admin/account/regular/delete',
        '/admin/repository/regular/repo1/visibility',
        '/admin/repository/regular/repo1/delete',
        '/admin/role/admin/edit',
        '/admin/role/admin/delete',
        '/admin/roles/create',
        '/admin/role/admin/add',
        '/admin/role/admin/remove'
    ]
)
def test_unauthorized_post(filled_db_session, app_client, route):
    assert app_client.post(route).status == '404 NOT FOUND'

@pytest.mark.parametrize(
    'route', [
        '/admin',
        '/admin/account/regular',
        '/admin/repository/regular/repo1',
        '/admin/role/admin'
    ]
)
def test_authorized_get(filled_db_session, app_client, route):
    app_client.get('/test/login/admin')
    assert app_client.get(route).status == '200 OK'
    app_client.get('/test/logout')

@pytest.mark.parametrize(
    'route', [
        '/admin/account/mrNotFound',
        '/admin/repository/mrNotFound/repo1',
        '/admin/repository/regular/repoNotFound',
        '/admin/role/notFound'
    ]
)
def test_authorized_get_unexisting(filled_db_session, app_client, route):
    app_client.get('/test/login/admin')
    assert app_client.get(route).status == '404 NOT FOUND'
    app_client.get('/test/logout')

@pytest.mark.parametrize(
    'route', [
        '/admin/account/mrNotFound/ban',
        '/admin/account/mrNotFound/delete',
        '/admin/repository/mrNotFound/repo1/visibility',
        '/admin/repository/mrNotFound/repo1/delete',
        '/admin/repository/regular/repoNotFound/visibility',
        '/admin/repository/regular/repoNotFound/delete',
        '/admin/role/notFound/edit',
        '/admin/role/notFound/delete',
        '/admin/role/notFound/add',
        '/admin/role/notFound/remove'
    ]
)
def test_authorized_post_unexisting(filled_db_session, app_client, route):
    app_client.get('/test/login/admin')
    assert app_client.post(route).status == '404 NOT FOUND'
    app_client.get('/test/logout')

def test_account_ban_unban(filled_db_session, app_client):
    from repocribro.models import User
    app_client.get('/test/login/admin')
    user = filled_db_session.query(User).filter_by(login='regular').first()
    assert user.user_account.is_active
    ret = app_client.post('/admin/account/regular/ban', data={'active': '0'})
    assert ret.status == '302 FOUND'
    assert not user.user_account.is_active
    ret = app_client.post('/admin/account/regular/ban', data={'active': '0'})
    assert ret.status == '302 FOUND'
    assert not user.user_account.is_active
    ret = app_client.post('/admin/account/regular/ban', data={'active': '1'})
    assert ret.status == '302 FOUND'
    assert user.user_account.is_active
    ret = app_client.post('/admin/account/regular/ban', data={'active': '1'})
    assert ret.status == '302 FOUND'
    assert user.user_account.is_active
    app_client.get('/test/logout')

def test_account_delete(filled_db_session, app_client):
    from repocribro.models import User
    app_client.get('/test/login/admin')
    user = filled_db_session.query(User).filter_by(login='regular').first()
    assert user is not None

    ret = app_client.post('/admin/account/regular/delete')
    assert ret.status == '302 FOUND'

    user = filled_db_session.query(User).filter_by(login='regular').first()
    assert user is None

    app_client.get('/test/logout')

def test_role_create_edit_delete(filled_db_session, app_client):
    from repocribro.models import Role
    app_client.get('/test/login/admin')
    existing_role = {'name': 'admin', 'privileges': '*', 'description': ''}
    ret = app_client.post('/admin/roles/create', data=existing_role)
    assert ret.status == '302 FOUND'

    bad_role = {'name': '', 'privileges': '', 'description': ''}
    ret = app_client.post('/admin/roles/create', data=bad_role)
    assert ret.status == '302 FOUND'

    role = filled_db_session.query(Role).filter_by(name='testadmin').first()
    assert role is None
    new_role = {'name': 'testadmin', 'privileges': 'login:s*',
                'description': ''}
    ret = app_client.post('/admin/roles/create', data=new_role)
    assert ret.status == '302 FOUND'
    role = filled_db_session.query(Role).filter_by(name='testadmin').first()
    assert role is not None
    assert role.name == 'testadmin'

    ret = app_client.post('/admin/role/testadmin/edit', data=existing_role)
    assert ret.status == '302 FOUND'
    role = filled_db_session.query(Role).filter_by(name='testadmin').first()
    assert role.name == 'testadmin'

    ret = app_client.post('/admin/role/testadmin/edit', data=bad_role)
    assert ret.status == '302 FOUND'
    role = filled_db_session.query(Role).filter_by(name='testadmin').first()
    assert role.name == 'testadmin'

    role = filled_db_session.query(Role).filter_by(name='test_admin').first()
    assert role is None
    edit_role = {'name': 'test_admin', 'privileges': '*', 'description': ''}
    ret = app_client.post('/admin/role/testadmin/edit', data=edit_role)
    assert ret.status == '302 FOUND'
    role = filled_db_session.query(Role).filter_by(name='test_admin').first()
    assert role.name == 'test_admin'

    ret = app_client.post('/admin/role/test_admin/delete')
    assert ret.status == '302 FOUND'
    role = filled_db_session.query(Role).filter_by(name='test_admin').first()
    assert role is None

    app_client.get('/test/logout')

def test_role_add_remove(filled_db_session, app_client):
    from repocribro.models import Role, User
    app_client.get('/test/login/admin')
    role = filled_db_session.query(Role).filter_by(name='admin').first()
    user = filled_db_session.query(User).filter_by(login='regular').first()
    account = user.user_account
    assert role not in account.roles
    assert not account.has_role('admin')

    data = {'login': 'regular'}
    ret = app_client.post('/admin/role/admin/add', data=data)
    assert ret.status == '302 FOUND'
    assert role in account.roles
    assert account.has_role('admin')

    ret = app_client.post('/admin/role/admin/add', data=data)
    assert ret.status == '302 FOUND'
    assert role in account.roles
    assert account.has_role('admin')

    ret = app_client.post('/admin/role/admin/remove', data=data)
    assert ret.status == '302 FOUND'
    assert role not in account.roles
    assert not account.has_role('admin')

    ret = app_client.post('/admin/role/admin/remove', data=data)
    assert ret.status == '302 FOUND'
    assert role not in account.roles
    assert not account.has_role('admin')

    app_client.get('/test/logout')

def test_repo_visibility(filled_db_session, app_client):
    from repocribro.models import Repository
    app_client.get('/test/login/admin')
    repo = filled_db_session.query(Repository).filter_by(
        full_name='regular/repo1'
    ).first()
    assert repo.is_public

    ret = app_client.post('/admin/repository/regular/repo1/visibility',
                          data={'enable': Repository.VISIBILITY_HIDDEN})
    assert ret.status == '302 FOUND'
    assert repo.is_hidden
    assert repo.secret is not None
    old_secret = repo.secret

    ret = app_client.post('/admin/repository/regular/repo1/visibility',
                          data={'enable': '666 YOLO'})
    assert ret.status == '302 FOUND'
    assert repo.is_hidden
    assert repo.secret == old_secret

    ret = app_client.post('/admin/repository/regular/repo1/visibility',
                          data={'enable': Repository.VISIBILITY_HIDDEN})
    assert ret.status == '302 FOUND'
    assert repo.is_hidden
    assert repo.secret is not None
    assert repo.secret != old_secret

    ret = app_client.post('/admin/repository/regular/repo1/visibility',
                          data={'enable': Repository.VISIBILITY_PRIVATE})
    assert ret.status == '302 FOUND'
    assert repo.is_private

    ret = app_client.post('/admin/repository/regular/repo1/visibility',
                          data={'enable': Repository.VISIBILITY_PRIVATE})
    assert ret.status == '302 FOUND'
    assert repo.is_private

    ret = app_client.post('/admin/repository/regular/repo1/visibility',
                          data={'enable': Repository.VISIBILITY_PUBLIC})
    assert ret.status == '302 FOUND'
    assert repo.is_public

    ret = app_client.post('/admin/repository/regular/repo1/visibility',
                          data={'enable': '666 YOLO'})
    assert ret.status == '302 FOUND'
    assert repo.is_public

    app_client.get('/test/logout')

def test_repo_delete(filled_db_session, app_client):
    from repocribro.models import Repository
    app_client.get('/test/login/admin')
    repo = filled_db_session.query(Repository).filter_by(
        full_name='regular/repo1'
    ).first()
    assert repo is not None

    ret = app_client.post('/admin/repository/regular/repo1/delete')
    assert ret.status == '302 FOUND'
    repo = filled_db_session.query(Repository).filter_by(
        full_name='regular/repo1'
    ).first()
    assert repo is None

    app_client.get('/test/logout')

# TODO: learn how to teardown (its weird)
def test_dummy_last(empty_db_session, app_client):
    app_client.get('/test/logout')


text:
var express = require('express'),
    app = express();

var port = 8000;

app.use(express.static(__dirname + '/dist'));

console.log('listening on port: ' + port);
app.listen(port)


text:
import {StripTagsPipe} from '../../src/string/strip-tags.pipe';

describe('EndsWithPipe', () => {
  let pipe: StripTagsPipe;

  beforeEach(() => {
    pipe = new StripTagsPipe();
  });

  it('should get a string with tags and splash it', () => {
    expect(pipe.transform('
lorem ipsum
')).toEqual('lorem ipsum');
    expect(pipe.transform('
foo bar
')).toEqual('foo bar');
    expect(pipe.transform('<title>awesome title</title>')).toEqual('awesome title');
  });
});


text:
#ifdef __FFMPEG
#include "TheoraAudioInterface.h"
#include "TheoraDataSource.h"
#include "TheoraException.h"
#include "TheoraTimer.h"
#include "TheoraUtil.h"
#include "TheoraFrameQueue.h"
#include "TheoraVideoFrame.h"
#include "TheoraVideoManager.h"
#include "TheoraVideoClip_FFmpeg.h"
#include "TheoraPixelTransform.h"

#define READ_BUFFER_SIZE 4096

#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS
#ifdef _STDINT_H
#undef _STDINT_H
#endif
# include <stdint.h>
#endif

#define _FFMPEG_DEBUG

extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include "libavutil/avassert.h"
}

static bool ffmpegInitialised = 0;

static int readFunction(void* data, uint8_t* buf, int buf_size)
{
#ifdef _FFMPEG_DEBUG
	th_writelog("reading " + str(buf_size) + " bytes");
#endif

	TheoraDataSource* src = (TheoraDataSource*) data;
	return src->read(buf, buf_size);
}

static int64_t seekFunction(void* data, int64_t offset, int whence)
{
#ifdef _FFMPEG_DEBUG
	th_writelog("seeking: offset = " + str((long) offset) + ", whence = " + str(whence));
#endif

	TheoraDataSource* src = (TheoraDataSource*) data;
    if (whence == AVSEEK_SIZE)
		return src->size();
	else if (whence == SEEK_SET)
		src->seek((long) offset);
	else if (whence == SEEK_END)
		src->seek(src->size() - (long) offset);
    return src->tell();
}

static void avlog_theoraplayer(void* p, int level, const char* fmt, va_list vargs)
{
	th_writelog(fmt);
	static char logstr[2048];
	vsprintf(logstr, fmt, vargs);
	th_writelog("ffmpeg: " + std::string(logstr));
}

std::string text;

static void _log(const char* s)
{
	text += s;
//	th_writelog(text);
//	text = "";
}

static void _log(const char c)
{
	char s[2] = {c, 0};
	_log(s);
}

static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
                                        int encoder)
{
    while ((prev = av_codec_next(prev))) {
        if (prev->id == id &&
            (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
            return prev;
    }
    return NULL;
}

static int compare_codec_desc(const void *a, const void *b)
{
    const AVCodecDescriptor **da = (const AVCodecDescriptor **) a;
    const AVCodecDescriptor **db = (const AVCodecDescriptor **) b;

    return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
	strcmp((*da)->name, (*db)->name);
}

static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
{
    const AVCodecDescriptor *desc = NULL;
    const AVCodecDescriptor **codecs;
    unsigned nb_codecs = 0, i = 0;

    while ((desc = avcodec_descriptor_next(desc)))
        ++nb_codecs;
    if (!(codecs = (const AVCodecDescriptor**) av_calloc(nb_codecs, sizeof(*codecs)))) {
        av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
        exit(1);
    }
    desc = NULL;
    while ((desc = avcodec_descriptor_next(desc)))
        codecs[i++] = desc;
    av_assert0(i == nb_codecs);
    qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
    *rcodecs = codecs;
    return nb_codecs;
}

static char get_media_type_char(enum AVMediaType type)
{
    switch (type) {
        case AVMEDIA_TYPE_VIDEO:    return 'V';
        case AVMEDIA_TYPE_AUDIO:    return 'A';
        case AVMEDIA_TYPE_DATA:     return 'D';
        case AVMEDIA_TYPE_SUBTITLE: return 'S';
        case AVMEDIA_TYPE_ATTACHMENT:return 'T';
        default:                    return '?';
    }
}

static void print_codecs_for_id(enum AVCodecID id, int encoder)
{
    const AVCodec *codec = NULL;

    _log(encoder ? "encoders" : "decoders");

    while ((codec = next_codec_for_id(id, codec, encoder)))
        _log(codec->name);

    _log(")");
}

int show_codecs(void *optctx, const char *opt, const char *arg)
{
    const AVCodecDescriptor **codecs;
    unsigned i, nb_codecs = get_codecs_sorted(&codecs);

	char tmp[1024];
    th_writelog("Codecs:\n"
           " D..... = Decoding supported\n"
           " .E.... = Encoding supported\n"
           " ..V... = Video codec\n"
           " ..A... = Audio codec\n"
           " ..S... = Subtitle codec\n"
           " ...I.. = Intra frame-only codec\n"
           " ....L. = Lossy compression\n"
           " .....S = Lossless compression\n"
           " -------\n");
    for (i = 0; i < nb_codecs; ++i) {
        const AVCodecDescriptor *desc = codecs[i];
        const AVCodec *codec = NULL;

        _log(" ");
        _log(avcodec_find_decoder(desc->id) ? "D" : ".");
        _log(avcodec_find_encoder(desc->id) ? "E" : ".");

        _log(get_media_type_char(desc->type));
        _log((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
        _log((desc->props & AV_CODEC_PROP_LOSSY)      ? "L" : ".");
        _log((desc->props & AV_CODEC_PROP_LOSSLESS)   ? "S" : ".");

        sprintf(tmp, " %-20s %s", desc->name, desc->long_name ? desc->long_name : "");

		_log(tmp);
        /* print decoders/encoders when there's more than one or their
         * names are different from codec name */
        while ((codec = next_codec_for_id(desc->id, codec, 0))) {
            if (strcmp(codec->name, desc->name)) {
                print_codecs_for_id(desc->id, 0);
                break;
            }
        }
        codec = NULL;
        while ((codec = next_codec_for_id(desc->id, codec, 1))) {
            if (strcmp(codec->name, desc->name)) {
                print_codecs_for_id(desc->id, 1);
                break;
            }
        }
		_log("\n");
    }
    av_free(codecs);

	av_log(0, 0, "%s", text.c_str());
    return 0;
}

TheoraVideoClip_FFmpeg::TheoraVideoClip_FFmpeg(TheoraDataSource* data_source,
														 TheoraOutputMode output_mode,
														 int nPrecachedFrames,
														 bool usePower2Stride):
								 						 TheoraVideoClip(data_source, output_mode, nPrecachedFrames, usePower2Stride),
														 TheoraAudioPacketQueue()
{
	mFormatContext = NULL;
	mCodecContext = NULL;
	mCodec = NULL;
	mFrame = NULL;
	mVideoStreamIndex = -1;
}

TheoraVideoClip_FFmpeg::~TheoraVideoClip_FFmpeg()
{
	unload();
}

void TheoraVideoClip_FFmpeg::load(TheoraDataSource* source)
{
	mVideoStreamIndex = -1;
	mFrameNumber = 0;
	AVDictionary* optionsDict = NULL;

	if (!ffmpegInitialised)
	{
#ifdef _FFMPEG_DEBUG
		th_writelog("Initializing ffmpeg");
#endif
		th_writelog("avcodec version: " + str(avcodec_version()));
		av_register_all();
		av_log_set_level(AV_LOG_DEBUG);
		av_log_set_callback(avlog_theoraplayer);
		ffmpegInitialised = 1;
		//show_codecs(0, 0, 0);
	}

	mInputBuffer = (unsigned char*) av_malloc(READ_BUFFER_SIZE);
	mAvioContext = avio_alloc_context(mInputBuffer, READ_BUFFER_SIZE, 0, source, &readFunction, NULL, &seekFunction);

#ifdef _FFMPEG_DEBUG
	th_writelog(mName + ": avio context created");
#endif

	mFormatContext = avformat_alloc_context();
#ifdef _FFMPEG_DEBUG
	th_writelog(mName + ": avformat context created");
#endif
	mFormatContext->pb = mAvioContext;

	int err;
	if ((err = avformat_open_input(&mFormatContext, "", NULL, NULL)) != 0)
	{
		th_writelog(mName + ": avformat input opening failed!");
		th_writelog(mName + ": error_code: " + str(err));
		return;
	}

#ifdef _FFMPEG_DEBUG
	th_writelog(mName + ": avformat input opened");
#endif

	// Retrieve stream information
	if (avformat_find_stream_info(mFormatContext, NULL) < 0)
		return; // Couldn't find stream information

#ifdef _FFMPEG_DEBUG
	th_writelog(mName + ": got stream info");
#endif

	// Dump information about file onto standard error
	//	av_dump_format(mFormatContext, 0, "", 0);

	// Find the first video stream
	for (int i = 0; i < mFormatContext->nb_streams; ++i)
	{
		if(mFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			mVideoStreamIndex = i;
			break;
		}
	}
	if (mVideoStreamIndex == -1)
		return; // Didn't find a video stream

#ifdef _FFMPEG_DEBUG
	th_writelog(mName + ": Found video stream at index " + str(mVideoStreamIndex));
#endif

	// Get a pointer to the codec context for the video stream
	mCodecContext = mFormatContext->streams[mVideoStreamIndex]->codec;

	// Find the decoder for the video stream
	mCodec = avcodec_find_decoder(mCodecContext->codec_id);
	if (mCodec == NULL)
	{
		th_writelog("Unsupported codec!");
		return; // Codec not found
	}
	// Open codec
	if(avcodec_open2(mCodecContext, mCodec, &optionsDict) < 0)
		return; // Could not open codec

#ifdef _FFMPEG_DEBUG
	th_writelog(mName + ": Codec opened");
#endif

	mFrame = avcodec_alloc_frame();

#ifdef _FFMPEG_DEBUG
	th_writelog(mName + ": Frame allocated");
#endif

	//AVRational rational = mCodecContext->time_base;

	mFPS = 25; //TODOOOOOO!!!

	mWidth = mStride = mCodecContext->width;
	mHeight = mCodecContext->height;
	mFrameDuration = 1.0f / mFPS;
	mDuration = mFormatContext->duration / AV_TIME_BASE;

	if (mFrameQueue == NULL) // todo - why is this set in the backend class? it should be set in the base class, check other backends as well
	{
		mFrameQueue = new TheoraFrameQueue(this);
		mFrameQueue->setSize(mNumPrecachedFrames);
	}
}

void TheoraVideoClip_FFmpeg::unload()
{
	if (mInputBuffer)
	{
//		av_free(mInputBuffer);
		mInputBuffer = NULL;
	}
	if (mAvioContext)
	{
		av_free(mAvioContext);
		mAvioContext = NULL;
	}
	if (mFrame)
	{
		av_free(mFrame);
		mFrame = NULL;
	}
	if (mCodecContext)
	{
		avcodec_close(mCodecContext);
		mCodecContext = NULL;
	}
	if (mFormatContext)
	{
		avformat_close_input(&mFormatContext);
		mFormatContext = NULL;
	}
}

bool TheoraVideoClip_FFmpeg::_readData()
{
	return 1;
}

bool TheoraVideoClip_FFmpeg::decodeNextFrame()
{
	TheoraVideoFrame* frame = mFrameQueue->requestEmptyFrame();
	if (!frame) return 0;

	AVPacket packet;
	int frameFinished;

	while (av_read_frame(mFormatContext, &packet) >= 0)
	{
		if (packet.stream_index == mVideoStreamIndex)
		{
			avcodec_decode_video2(mCodecContext, mFrame, &frameFinished, &packet);

			if (frameFinished)
			{
				TheoraPixelTransform t;
				memset(&t, 0, sizeof(TheoraPixelTransform));

				t.y = mFrame->data[0]; t.yStride = mFrame->linesize[0];
				t.u = mFrame->data[1]; t.uStride = mFrame->linesize[1];
				t.v = mFrame->data[2]; t.vStride = mFrame->linesize[2];

				frame->decode(&t);
				frame->mTimeToDisplay = mFrameNumber / mFPS;
				frame->mIteration = mIteration;
				frame->_setFrameNumber(mFrameNumber++);

				av_free_packet(&packet);
				break;
			}
		}
		av_free_packet(&packet);
	}
	return 1;
}

void TheoraVideoClip_FFmpeg::decodedAudioCheck()
{
	if (!mAudioInterface || mTimer->isPaused()) return;

	mAudioMutex->lock();
	flushAudioPackets(mAudioInterface);
	mAudioMutex->unlock();
}

float TheoraVideoClip_FFmpeg::decodeAudio()
{
	return -1;
}

void TheoraVideoClip_FFmpeg::doSeek()
{

}

void TheoraVideoClip_FFmpeg::_restart()
{

}

#endif


text:
var request = require("superagent")
  , page = require("page")
  , loading = require("loading-lock")
  , dom = require("dom")
  , json = require("json")
  , each = require("each")
  , locker = loading(dom("#actual_results").els[0], {size: 80})
  , advlocker = loading(dom("#advancedOptions").els[0], {size: 60})
  , notify = require("notification")
  , isArray = require("isArray")
  ;

function isIntNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n) && n % 1 === 0;
}

function formatIntNumber(n) {
  return Math.floor(parseFloat(n));
}

function clearPage(){
  dom("#main, #about").each(function (item){
    item.els[0].style.display = 'none';
  });
}

function showIndex(){
  clearPage();
  dom("#main").els[0].style.display = '';
}

function showAssumptions(){
  clearPage();
  dom("#about").els[0].style.display = '';
}

module.exports = function run(){
  page("", showIndex);
  page("/", showIndex);
  page("/about", showAssumptions);
  page();

  var numberFields = [
    "#defRating"
  , "#shieldRating"
  , "#absorbRating"
  , "#armorRating"
  ];

  each(numberFields, function (field){
    dom(field).on('keyup', validateNumber);
    dom(field).on('change', validateNumber);
    dom(field).on('blur', validateNumber);
  });

  dom("#process").on('click', function (e){
    e.preventDefault();

    locker.lock();

    var klass = dom("#class").els[0];
    var stim = dom("#stim").els[0];
    var relic1 = dom("#relic1").els[0];
    var relic2 = dom("#relic2").els[0];

    var data = {
      'class': klass.options[klass.selectedIndex].value
    , 'stim': stim.options[stim.selectedIndex].value
    , 'defRating': formatIntNumber(dom("#defRating").els[0].value)
    , 'shieldRating': formatIntNumber(dom("#shieldRating").els[0].value)
    , 'absorbRating': formatIntNumber(dom("#absorbRating").els[0].value)
    , 'armorRating': formatIntNumber(dom("#armorRating").els[0].value)
    , 'relic1': relic1.options[relic1.selectedIndex].value
    , 'relic2': relic2.options[relic2.selectedIndex].value
    , 'advanced': false
    };

    if (dom("#useAdvanced").els[0].checked){
      data.advanced = {
        dmgMRKE: parseFloat(dom("#dmgMRKE").els[0].value)
      , dmgFTKE: parseFloat(dom("#dmgFTKE").els[0].value)
      , dmgFTIE: parseFloat(dom("#dmgFTIE").els[0].value)
      , timePerSwing: parseFloat(dom("#swingTime").els[0].value)
      , shieldLow: parseFloat(dom("#shieldLow").els[0].value)
      , shieldHigh: parseFloat(dom("#shieldHigh").els[0].value)
      };
    }

    request.post("/api/optimize")
           .send(data)
           .set('Accept', 'application/json')
           .end(function (err, res){
              if (err || (res.status != 200 && res.status != 304)){
                notify.error(err);
              }
              else {
                var resp = json.parse(res.text);
                if (resp.error){
                  if (isArray(resp.error)){
                    each(resp.error, function (err){
                      notify.error(err);
                    });
                  }
                  else {
                    notify.error(resp.error);
                  }
                }
                else {
                  var all_data = resp.result;
                  var results = all_data.after;
                  var prior = all_data.before;

                  var ddiff = results.defRating - prior.defRating;
                  var dclass = ddiff >= 0 ? 'add' : 'sub';
                  ddiff = "" + (ddiff >= 0 ? "+" : "") + ddiff;

                  var sdiff = results.shieldRating - prior.shieldRating;
                  var sclass = sdiff >= 0 ? 'add' : 'sub';
                  sdiff = "" + (sdiff >= 0 ? "+" : "") + sdiff;

                  var adiff = results.absorbRating - prior.absorbRating;
                  var aclass = adiff >= 0 ? 'add' : 'sub';
                  adiff = "" + (adiff >= 0 ? "+" : "") + adiff;

                  var defdiff1 = results.defPctNBNS - prior.defPctNBNS;
                  var defclass1 = defdiff1 >= 0 ? 'add' : 'sub';
                  defdiff1 = "" + (defdiff1 >= 0 ? "+" : "") + Math.floor(defdiff1 * 10000) / 100 + "%";

                  var defdiff2 = results.defPctNB - prior.defPctNB;
                  var defclass2 = defdiff2 >= 0 ? 'add' : 'sub';
                  defdiff2 = "" + (defdiff2 >= 0 ? "+" : "") + Math.floor(defdiff2 * 10000) / 100 + "%";

                  var spdiff = results.shieldPctNB - prior.shieldPctNB;
                  var spclass = spdiff >= 0 ? 'add' : 'sub';
                  spdiff = "" + (spdiff >= 0 ? "+" : "") + Math.floor(spdiff * 10000) / 100 + "%";

                  var apdiff = results.absorbPctNB - prior.absorbPctNB;
                  var apclass = apdiff >= 0 ? 'add' : 'sub';
                  apdiff = "" + (apdiff >= 0 ? "+" : "") + Math.floor(apdiff * 10000) / 100 + "%";

                  var mdiff = results.mitigation - prior.mitigation;
                  var mclass = mdiff >= 0 ? 'add' : 'sub';
                  mdiff = "" + (mdiff >= 0 ? "+" : "") + Math.floor(mdiff * 10000) / 100 + "%";

                  dom("#actual_results #defRatingValue").els[0].innerHTML = results.defRating;
                  dom("#actual_results #defRatingDiff").els[0].innerHTML = "" + ddiff + "";
                  dom("#actual_results #shieldRatingValue").els[0].innerHTML = results.shieldRating;
                  dom("#actual_results #shieldRatingDiff").els[0].innerHTML = "" + sdiff + "";
                  dom("#actual_results #absorbRatingValue").els[0].innerHTML = results.absorbRating;
                  dom("#actual_results #absorbRatingDiff").els[0].innerHTML = "" + adiff + "";

                  dom("#actual_results #defPctNS").els[0].innerHTML = Math.floor(results.defPctNBNS * 10000) / 100 + "%";
                  dom("#actual_results #defPctNSDiff").els[0].innerHTML = "" + defdiff1 + "";
                  dom("#actual_results #defPctS").els[0].innerHTML = Math.floor(results.defPctNB * 10000) / 100 + "%";
                  dom("#actual_results #defPctSDiff").els[0].innerHTML = "" + defdiff2 + "";
                  dom("#actual_results #shieldPct").els[0].innerHTML = Math.floor(results.shieldPctNB * 10000) / 100 + "%";
                  dom("#actual_results #shieldPctDiff").els[0].innerHTML = "" + spdiff + "";
                  dom("#actual_results #absorbPct").els[0].innerHTML = Math.floor(results.absorbPctNB * 10000) / 100 + "%";
                  dom("#actual_results #absorbPctDiff").els[0].innerHTML = "" + apdiff + "";
                  dom("#actual_results #mitigationPct").els[0].innerHTML = Math.floor(results.mitigation * 10000) / 100 + "%";
                  dom("#actual_results #mitigationPctDiff").els[0].innerHTML = "" + mdiff + "";
                }
              }
              locker.unlock();
           });
  });

  dom("#clear").on('click', function (e){
    e.preventDefault();
    each(numberFields, function (field){
      dom(field).els[0].value = 0;
    });

    dom("#class").els[0].selectedIndex = 0;
    dom("#stim").els[0].selectedIndex = 0;
  });

  dom("a#extraParams").on('click', function (e){
    e.preventDefault();

    var left_to_do = 2;

    function finallie(){
      if (left_to_do <= 0){
        advlocker.unlock();
        dom("#advancedOptions>fieldset").els[0].style.display = '';
      }
    }

    advlocker.lock();
    request.get("/api/combat-data").end(function (err, res){
      if (err){
        notify.error(err);
      }
      else {
        var resp = json.parse(res.text);

        if (resp.error){
          if (isArray(resp.error)){
            each(resp.error, function (err){
              notify.error(err);
            });
          }
          else {
            notify.error(resp.error);
          }
        }
        else {
          dom("#dmgMRKE").els[0].value = parseFloat(resp.dmgMRKE || 0);
          dom("#dmgFTKE").els[0].value = parseFloat(resp.dmgFTKE || 0);
          dom("#dmgFTIE").els[0].value = parseFloat(resp.dmgFTIE || 0);
          dom("#swingTime").els[0].value = parseFloat(resp.timePerSwing || 0);
        }
      }

      left_to_do -= 1;
      finallie();
    });

    request.get("/api/shield-data").end(function (err, res){
      if (err){
        notify.error(err);
      }
      else {
        var resp = json.parse(res.text);
        if (resp.error){
          if (isArray(resp.error)){
            each(resp.error, function (err){
              notify.error(err);
            });
          }
          else {
            notify.error(resp.error);
          }
        }
        else {
          dom("#shieldLow").els[0].value = parseFloat(resp.low);
          dom("#shieldHigh").els[0].value = parseFloat(resp.high);
        }
      }

      left_to_do -= 1;
      finallie();
    });
  });
}

function validateNumber(e){
  if (!isIntNumber(e.target.value) && e.target.value !== ''){
    e.target.value = formatIntNumber(e.target.value);
  }
}


text:
id: 5900f4de1000cf542c50fff0
challengeType: 5
title: 'Problem 369: Badugi'
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions
undefined

## Tests

```yml
tests:
  - text: ''
    testString: 'assert.strictEqual(euler369(), 862400558448, "<code>euler369()</code> should return 862400558448.");'

```

## Challenge Seed

```js
function euler369() {
  // Good luck!
  return true;
}

euler369();

```

## Solution

```js
// solution required
```


text:
import random
from collections import deque
from .actions import JoinAction
from .actions import VoteAction
from .phases import Signup
from .roles import Townie
from .roles import Cop
from .roles import Mafioso

next_phase = {'signup': 'day',
              'day': 'night',
              'night': 'day'}

legal_roles = {'t': Townie,
               'm': Mafioso,
               'c': Cop}

class Player(object):
    _role = None
    _status = None

    @property
    def role(self):
        return self._role

    def __init__(self, contact, nickname):
        self.contact = contact
        self.nickname = nickname
        self._status = 'alive'
        self.night_message = None

    def is_dead(self):
        return self._status == 'dead'

    def is_alive(self):
        return self._status == 'alive'

    def lynch(self):
        self._status = 'dead'

    def kill(self):
        self._status = 'dead'

    def set_role(self, role):
        self._role = role

    def get_role(self):
        return self._role

    def __eq__(self, other):
        return isinstance(other, Player) and other.contact == self.contact

    def __ne__(self, other):
        return not self.__eq__(other)

    def resolve_action(self, target):
        self.role.resolve_action(self, target)

    def append_to_night_message(self, message: str):
        if self.night_message:
            self.night_message = self.night_message + ' ' + message
        else:
            self.night_message = message

    def get_night_message(self):
        return self.night_message

    def clear_night_message(self):
        self.night_message = None

class Game:
    phase = 'signup'
    day_number = 0
    players = []
    roles = []
    randomized_roles = []
    votes = {}
    actions = {}
    public_message = None

    def __init__(self, game_setup: str, messenger):
        assert Game.is_valid_setup(game_setup), (
            'Please validate the setup before creating a game.')
        self.roles = Game.parse_roles(game_setup)
        self.randomized_roles = random.sample(self.roles, len(self.roles))
        self.phases = [Signup()]
        self.day_number = 0
        self.players = []
        self.messenger = messenger
        self.messenger.message_all_players(
            'A new game has started, join with "!join"')

    def join(self, player):
        """Returns True if the player was able to join the game."""
        self.add_action(JoinAction(self, player))

    def old_join(self, player):
        #TODO delete me
        if self.phase != "signup":
            return False
        if player not in self.players:
            self.players.append(player)
            self.messenger.message_all_players(
                '{name} has joined the fray!'.format(name=player.nickname))
        if len(self.players) == len(self.roles):
            self.assign_roles()
            self.advance_phase()
        return True

    def vote(self, player_name: str, target_name: str):
        player = self.get_player(player_name)
        target = self.get_player(target_name)
        assert player, "Player {name} isn't playing.".format(name=player_name)
        assert target, "Target {name} isn't playing.".format(name=player_name)
        self.add_action(VoteAction(self, player, target))

    def old_vote(self, player_name: str, target_name: str) -> bool:
        """Returns True if the vote was cast."""
        player = self.get_player(player_name)
        target = self.get_player(target_name)
        if self.phase != 'day':
            return False
        if player in self.players and target in self.players:
            self.votes[player.nickname] = target
            vote_count = 0
            for vote_target in self.votes.values():
                if target == vote_target:
                    vote_count += 1
            self.messenger.message_all_players(
                '{name} has voted for {target}, '
                'bringing the total to {count}'
                .format(name=player.nickname,
                        target=target.nickname,
                        count=vote_count))
            if vote_count > len(self.players)/2:
                target.kill()
                self.messenger.message_all_players(
                    'The crowd has spoken and {name} has been lynched! '
                    'They were a {role}.'.format(name=target.nickname,
                                                 role=target.role.name()))
                self.advance_phase()
            return True
        return False

    def action(self, player_name: str, *args):
        player = self.get_player(player_name)
        action = player.get_role().get_action()
        self.add_action(action(self, player, *args))

    def target(self, player_name: str, target_name: str) -> bool:
        '''Returns True if the action was accepted.'''
        player = self.get_player(player_name)
        target = self.get_player(target_name)
        if (self.phase != 'night'
            or player.is_dead()
            or not player.role.has_night_action()):
            return False
        if player in self.players and target in self.players:
            self.actions[player.nickname] = target
            if self.all_actions_submitted():
                self.resolve_actions()
                self.send_night_messages()
                self.advance_phase()
            return True
        return False

    def check_phase_end():
        if self.get_current_phase().is_over():
            self.phase.append(self.get_current_phase().advance_phase())

    def is_valid_setup(game_setup: str) -> bool:
        roles =  game_setup.split(',')
        for role in roles:
            if role not in legal_roles:
                return False
        return True

    def parse_roles(game_setup: str):
        roles = []
        for role in game_setup.split(','):
            roles.append(legal_roles[role])
        return roles

    def get_next_role(self):
        return self.randomized_roles.pop()

    def assign_roles(self):
        assert len(self.roles) == len(self.players), (
            'Cannot assign roles if unequal to number of players')
        randomized_roles = random.sample(self.roles, len(self.players))
        for player in self.players:
            player.set_role(randomized_roles.pop())
        for player in self.players:
            self.messenger.message_player(player,
                                          player.role.get_role_message(self))

    def _assign_players_for_testing(self, *players):
        '''Add players to the game and assign roles deterministically.'''
        assert not self.players, 'Use this function instead of "join".'
        assert len(self.roles) == len(players), (
            '{role_count} roles, but {player_count} players'
            .format(role_count=len(self.roles), player_count=len(players)))
        players = deque(players)
        for role in self.roles:
            player = players.popleft()
            player.set_role(role)
            self.players.append(player)
            self.messenger.message_player(player,
                                          player.role.get_role_message(self))

    def unrecognized_roles(roles: str) -> list:
        roles = roles.split(',')
        unrecognized_roles = []
        for role in roles:
            if role not in legal_roles:
                unrecognized_roles.append(role)
        return unrecognized_roles

    def advance_phase(self):
        self.votes = {}
        self.actions = {}
        self.phase = next_phase[self.phase]
        if self.public_message:
            self.messenger.message_all_players(self.public_message)
            self.public_message = None
        if self.phase == 'day':
            self.day_number += 1
        if self.is_game_end():
            self.phase = None
        else:
            self.messenger.message_all_players(
                'It is now {phase} {number}'.format(
                    phase=self.phase, number=self.day_number))

    def is_game_end(self):
        for player in self.players:
            game_end_message = player.role.game_ending_message(self)
            if game_end_message:
                self.messenger.message_all_players(game_end_message)
                return True
        return False

    def get_current_phase(self):
        return self.phases[-1]

    def player_count(self):
        return len(self.players)

    def add_player(self, player):
        self.players.append(player)

    def role_count(self):
        return len(self.roles)

    def vote_count(self, player):
        votes = self.get_current_phase().compile_votes()
        if player.nickname not in votes:
            return 0
        return votes[player.nickname]

    def add_action(self, action):
        phase = self.get_current_phase()
        phase.add_action(action)
        if (not phase.is_checking()
            and not phase.is_ended()
            and phase.is_phase_end(self)):
            next_phase = phase.advance_phase()
            self.phases.append(next_phase)

    def get_player(self, name: str):
        for player in self.players:
            if player.nickname.lower() == name.lower():
                return player
            if player.contact == name:
                return player

    def count_faction(self, faction: str):
        count = 0
        for player in self.players:
            if player.role.get_faction() == faction:
                count += 1
        return count

    def count_living(self):
        count = 0
        for player in self.players:
            if player.is_alive():
                count += 1
        return count

    def get_team(self, faction: str):
        team = []
        for player in self.players:
            if player.role.get_faction() == faction:
                team.append(player.nickname)
        return team

    def all_actions_submitted(self):
        for player in self.players:
            if (player.is_alive()
                and player.role.has_night_action()
                and player.nickname not in self.actions):
                return False
        return True

    def resolve_actions(self):
        mafia_votes = {}
        mafia_target = None
        mafia_count = 0
        for player in self.players:
            if player.nickname in self.actions and player.role == Mafioso:
                target = self.actions[player.nickname]
                if target.nickname in mafia_votes:
                    mafia_votes[target.nickname] += 1
                else:
                    mafia_votes[target.nickname] = 1
                if mafia_votes[target.nickname] > mafia_count:
                    mafia_target = target
                    mafia_count += 1
        if mafia_target:
            mafia_target.kill()
            self.public_message = ('You all awake, but there is someone missing... '
                                   'looks like {name} has been killed during '
                                   'the night!'
                                   .format(name=mafia_target.nickname))
            mafia_target.append_to_night_message('You have been killed! =(')
        for player in self.players:
            if player.role.get_faction() == 'Mafia':
                player.append_to_night_message(
                    'You recieve word that {target} has been dispatched.'
                    .format(target=mafia_target.nickname))
        for player in self.players:
            if (player.is_alive()
                and player.role.has_night_action()
                and player.role != Mafioso):
                player.resolve_action(self.actions[player.nickname])

    def send_night_messages(self):
        for player in self.players:
            night_message = player.get_night_message()
            if night_message:
                self.messenger.message_player(player, night_message)
                player.clear_night_message()
            elif player.is_alive():
                self.messenger.message_player(player,
                                              'You have an uneventful night.')

    def message_player(self, player, message):
        self.messenger.message_player(player, message)

    def message_all_players(self, message):
        self.messenger.message_all_players(message)


text:
Ext.define('Ext.rtl.form.field.FileButton', {
    override: 'Ext.form.field.FileButton',

    createFileInput : function(isTemporary) {
        var me = this;
        me.fileInputEl = me.el.createChild({
            name: me.inputName,
            id: !isTemporary ? me.id + '-fileInputEl' : undefined,
            cls: me.inputCls + ' ' + (me.getInherited().rtl ? Ext.baseCSSPrefix + 'rtl' : ''),
            tag: 'input',
            type: 'file',
            size: 1,
            role: 'button'
        });

        // We place focus and blur listeners on fileInputEl to activate Button's
        // focus and blur style treatment
        me.fileInputEl.on({
            scope: me,
            change: me.fireChange,
            focus: me.onFocus,
            blur: me.onBlur
        });
    }
});


text:
namespace google {
namespace cloud {
namespace run_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

class RevisionsStub {
 public:
  virtual ~RevisionsStub() = 0;

  virtual StatusOr<google::cloud::run::v2::Revision> GetRevision(
      grpc::ClientContext& context,
      google::cloud::run::v2::GetRevisionRequest const& request) = 0;

  virtual StatusOr<google::cloud::run::v2::ListRevisionsResponse> ListRevisions(
      grpc::ClientContext& context,
      google::cloud::run::v2::ListRevisionsRequest const& request) = 0;

  virtual future<StatusOr<google::longrunning::Operation>> AsyncDeleteRevision(
      google::cloud::CompletionQueue& cq,
      std::unique_ptr<grpc::ClientContext> context,
      google::cloud::run::v2::DeleteRevisionRequest const& request) = 0;

  virtual future<StatusOr<google::longrunning::Operation>> AsyncGetOperation(
      google::cloud::CompletionQueue& cq,
      std::unique_ptr<grpc::ClientContext> context,
      google::longrunning::GetOperationRequest const& request) = 0;

  virtual future<Status> AsyncCancelOperation(
      google::cloud::CompletionQueue& cq,
      std::unique_ptr<grpc::ClientContext> context,
      google::longrunning::CancelOperationRequest const& request) = 0;
};

class DefaultRevisionsStub : public RevisionsStub {
 public:
  DefaultRevisionsStub(
      std::unique_ptr<google::cloud::run::v2::Revisions::StubInterface>
          grpc_stub,
      std::unique_ptr<google::longrunning::Operations::StubInterface>
          operations)
      : grpc_stub_(std::move(grpc_stub)), operations_(std::move(operations)) {}

  StatusOr<google::cloud::run::v2::Revision> GetRevision(
      grpc::ClientContext& client_context,
      google::cloud::run::v2::GetRevisionRequest const& request) override;

  StatusOr<google::cloud::run::v2::ListRevisionsResponse> ListRevisions(
      grpc::ClientContext& client_context,
      google::cloud::run::v2::ListRevisionsRequest const& request) override;

  future<StatusOr<google::longrunning::Operation>> AsyncDeleteRevision(
      google::cloud::CompletionQueue& cq,
      std::unique_ptr<grpc::ClientContext> context,
      google::cloud::run::v2::DeleteRevisionRequest const& request) override;

  future<StatusOr<google::longrunning::Operation>> AsyncGetOperation(
      google::cloud::CompletionQueue& cq,
      std::unique_ptr<grpc::ClientContext> context,
      google::longrunning::GetOperationRequest const& request) override;

  future<Status> AsyncCancelOperation(
      google::cloud::CompletionQueue& cq,
      std::unique_ptr<grpc::ClientContext> context,
      google::longrunning::CancelOperationRequest const& request) override;

 private:
  std::unique_ptr<google::cloud::run::v2::Revisions::StubInterface> grpc_stub_;
  std::unique_ptr<google::longrunning::Operations::StubInterface> operations_;
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace run_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_RUN_INTERNAL_REVISIONS_STUB_H


text:
package edu.uah.rsesc.aadlsimulator.agree.ui.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import edu.uah.rsesc.aadlsimulator.agree.engine.AGREESimulationEngine;
import edu.uah.rsesc.aadlsimulator.ui.SimulatorHandlerHelper;

public class SimulateSingleLayerHandler extends AbstractHandler {
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		return SimulatorHandlerHelper.startSimulator(event, AGREESimulationEngine.ENGINE_TYPE_ID_SINGLE_LAYER);
	}
}


text:
#pragma once

#define lGetMemoryUsage_symbol          "_ZN8Database9Scripting3Lua15lGetMemoryUsageEP9lua_State"
#define lGetMemoryUsage_hook_length     7

#define SetActiveDLCAndMods_symbol      "_ZN25CvModdingFrameworkAppSide19SetActiveDLCandModsERK22cvContentPackageIDListRKNSt3__14listIN15ModAssociations7ModInfoENS3_9allocatorIS6_EEEEbb"
#define SetActiveDLCAndMods_hook_length 10


text:
namespace GeekLearning.Templating
{
    using Storage;

    public interface ITemplateLoaderFactory
    {
        ITemplateLoader Create(IStore store);

        ITemplateLoader Create(IStore store, string scope);
    }
}


text:
module Yt
  module Associations
    # @private
    # Associations are a set of macro-like class methods to express
    # relationship between YouTube resources like "Channel has many Videos" or
    # "Account has one Id". They are inspired by ActiveRecord::Associations.
    module HasOne
      # @example Adds the +status+ method to the Video resource.
      #   class Video < Resource
      #     has_one :status
      #   end
      def has_one(attribute)
        require 'yt/associations/has_many'
        extend Associations::HasMany

        attributes = attribute.to_s.pluralize
        has_many attributes
        define_memoized_method(attribute) { send(attributes).first! }
      end
    end
  end
end


text:
@interface RHMKPolygonFactory : NSObject

@end


text:
var fs = require('fs')
process.on('message', function(message) {
  if(message == 'shutdown') {
    fs.writeFileSync('tmp', 'shutdown')
    process.send('offline')
  }
})
process.send('online')


text:
(function (angular) {
  "use strict";

  angular.module('commune.host.room', ['ngRoute', 'ngSocket'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/host/:room', {
        templateUrl: 'modules/hostRoom/room.tpl.html',
        controller: 'hostRoomCtrl'
      });
  })
  .controller('hostRoomCtrl', ['$scope', '$socket', 'stream',
    function ($scope, $socket, stream) {
    // Initialize queue size
    $scope.queue = 0;

    // Request new question
    $scope.play = function () {
      $socket.emit('play');
      $scope.playing = true;
    };
    // Listen for (no more) questions
    $socket.on('play', function (data) {
      $scope.playing = data;
    });
    // Listen for audio
    $socket.on('audio', function (packet) {
      $scope.packet = packet;
    });
    // Listen for queue size
    $socket.on('queue', function (data) {
      $scope.queue = data;
    });
  }]);
}(angular));


text:
The `/camli/<blobref>` endpoint returns a blob the server knows about.

A request with the GET verb will return 200 and the blob contents if
present, 404 if not. A request with the HEAD verb will return 200 and
the blob meta data (i.e., content-length), or 404 if the blob is not
present.

The response must include an explicit Content-Length, even with HTTP/1.1.
(The one piece of metadata a blobserver keeps on a blob is its length,
 which is used in both enumerate-blobs bodies and responses to blob GETs.)

## Get a blob

Reqeust:

    GET /camli/sha1-126249fd8c18cbb5312a5705746a2af87fba9538 HTTP/1.1
    Host: example.com

Response:

    HTTP/1.1 200 OK
    Content-Type: application/octet-stream
    Content-Length: <the blob length in bytes>

    <the blob contents>

## Existence check

Request:

    HEAD /camli/sha1-126249fd8c18cbb5312a5705746a2af87fba9538 HTTP/1.1
    Host: example.com

Response:

    HTTP/1.1 200 OK
    Content-Type: application/octet-stream
    Content-Length: <the blob length in bytes>

## Does not exist

Request:

    GET /camli/sha1-126249fd8c18cbb5312a5705746a2af87fba9538 HTTP/1.1
    Host: example.com

Response:

    HTTP/1.1 404 Not Found


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

/*
 * Functions that need to be different for different versions of BSD
 * kernel should be kept here, along with any global storage specific
 * to this BSD variant.
 */
#include <fs/nfs/nfsport.h>
#include <sys/sysctl.h>
#include <vm/vm.h>
#include <vm/vm_object.h>
#include <vm/vm_page.h>
#include <vm/vm_param.h>
#include <vm/vm_map.h>
#include <vm/vm_kern.h>
#include <vm/vm_extern.h>
#include <vm/uma.h>

extern int nfscl_ticks;
extern int nfsrv_nfsuserd;
extern struct nfssockreq nfsrv_nfsuserdsock;
extern void (*nfsd_call_recall)(struct vnode *, int, struct ucred *,
    struct thread *);
extern int nfsrv_useacl;
struct mount nfsv4root_mnt;
int newnfs_numnfsd = 0;
struct nfsstats newnfsstats;
int nfs_numnfscbd = 0;
int nfscl_debuglevel = 0;
char nfsv4_callbackaddr[INET6_ADDRSTRLEN];
struct callout newnfsd_callout;
void (*nfsd_call_servertimer)(void) = NULL;
void (*ncl_call_invalcaches)(struct vnode *) = NULL;

static int nfs_realign_test;
static int nfs_realign_count;

SYSCTL_NODE(_vfs, OID_AUTO, nfs, CTLFLAG_RW, 0, "New NFS filesystem");
SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_test, CTLFLAG_RW, &nfs_realign_test,
    0, "Number of realign tests done");
SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_count, CTLFLAG_RW, &nfs_realign_count,
    0, "Number of mbuf realignments done");
SYSCTL_STRING(_vfs_nfs, OID_AUTO, callback_addr, CTLFLAG_RW,
    nfsv4_callbackaddr, sizeof(nfsv4_callbackaddr),
    "NFSv4 callback addr for server to use");
SYSCTL_INT(_vfs_nfs, OID_AUTO, debuglevel, CTLFLAG_RW, &nfscl_debuglevel,
    0, "Debug level for new nfs client");

/*
 * Defines for malloc
 * (Here for FreeBSD, since they allocate storage.)
 */
MALLOC_DEFINE(M_NEWNFSRVCACHE, "NFSD srvcache", "NFSD Server Request Cache");
MALLOC_DEFINE(M_NEWNFSDCLIENT, "NFSD V4client", "NFSD V4 Client Id");
MALLOC_DEFINE(M_NEWNFSDSTATE, "NFSD V4state",
    "NFSD V4 State (Openowner, Open, Lockowner, Delegation");
MALLOC_DEFINE(M_NEWNFSDLOCK, "NFSD V4lock", "NFSD V4 byte range lock");
MALLOC_DEFINE(M_NEWNFSDLOCKFILE, "NFSD lckfile", "NFSD Open/Lock file");
MALLOC_DEFINE(M_NEWNFSSTRING, "NFSD string", "NFSD V4 long string");
MALLOC_DEFINE(M_NEWNFSUSERGROUP, "NFSD usrgroup", "NFSD V4 User/group map");
MALLOC_DEFINE(M_NEWNFSDREQ, "NFS req", "NFS request header");
MALLOC_DEFINE(M_NEWNFSFH, "NFS fh", "NFS file handle");
MALLOC_DEFINE(M_NEWNFSCLOWNER, "NFSCL owner", "NFSCL Open Owner");
MALLOC_DEFINE(M_NEWNFSCLOPEN, "NFSCL open", "NFSCL Open");
MALLOC_DEFINE(M_NEWNFSCLDELEG, "NFSCL deleg", "NFSCL Delegation");
MALLOC_DEFINE(M_NEWNFSCLCLIENT, "NFSCL client", "NFSCL Client");
MALLOC_DEFINE(M_NEWNFSCLLOCKOWNER, "NFSCL lckown", "NFSCL Lock Owner");
MALLOC_DEFINE(M_NEWNFSCLLOCK, "NFSCL lck", "NFSCL Lock");
MALLOC_DEFINE(M_NEWNFSV4NODE, "NEWNFSnode", "New nfs vnode");
MALLOC_DEFINE(M_NEWNFSDIRECTIO, "NEWdirectio", "New nfs Direct IO buffer");
MALLOC_DEFINE(M_NEWNFSDIROFF, "NFSCL diroffdiroff",
    "New NFS directory offset data");
MALLOC_DEFINE(M_NEWNFSDROLLBACK, "NFSD rollback",
    "New NFS local lock rollback");
MALLOC_DEFINE(M_NEWNFSLAYOUT, "NFSCL layout", "NFSv4.1 Layout");
MALLOC_DEFINE(M_NEWNFSFLAYOUT, "NFSCL flayout", "NFSv4.1 File Layout");
MALLOC_DEFINE(M_NEWNFSDEVINFO, "NFSCL devinfo", "NFSv4.1 Device Info");
MALLOC_DEFINE(M_NEWNFSSOCKREQ, "NFSCL sockreq", "NFS Sock Req");
MALLOC_DEFINE(M_NEWNFSCLDS, "NFSCL session", "NFSv4.1 Session");
MALLOC_DEFINE(M_NEWNFSLAYRECALL, "NFSCL layrecall", "NFSv4.1 Layout Recall");

/*
 * Definition of mutex locks.
 * newnfsd_mtx is used in nfsrvd_nfsd() to protect the nfs socket list
 * and assorted other nfsd structures.
 */
struct mtx newnfsd_mtx;
struct mtx nfs_sockl_mutex;
struct mtx nfs_state_mutex;
struct mtx nfs_nameid_mutex;
struct mtx nfs_req_mutex;
struct mtx nfs_slock_mutex;

/* local functions */
static int nfssvc_call(struct thread *, struct nfssvc_args *, struct ucred *);

#ifdef __NO_STRICT_ALIGNMENT
/*
 * These architectures don't need re-alignment, so just return.
 */
int
newnfs_realign(struct mbuf **pm, int how)
{

	return (0);
}
#else	/* !__NO_STRICT_ALIGNMENT */
/*
 *	newnfs_realign:
 *
 *	Check for badly aligned mbuf data and realign by copying the unaligned
 *	portion of the data into a new mbuf chain and freeing the portions
 *	of the old chain that were replaced.
 *
 *	We cannot simply realign the data within the existing mbuf chain
 *	because the underlying buffers may contain other rpc commands and
 *	we cannot afford to overwrite them.
 *
 *	We would prefer to avoid this situation entirely.  The situation does
 *	not occur with NFS/UDP and is supposed to only occassionally occur
 *	with TCP.  Use vfs.nfs.realign_count and realign_test to check this.
 *
 */
int
newnfs_realign(struct mbuf **pm, int how)
{
	struct mbuf *m, *n;
	int off, space;

	++nfs_realign_test;
	while ((m = *pm) != NULL) {
		if ((m->m_len & 0x3) || (mtod(m, intptr_t) & 0x3)) {
			/*
			 * NB: we can't depend on m_pkthdr.len to help us
			 * decide what to do here.  May not be worth doing
			 * the m_length calculation as m_copyback will
			 * expand the mbuf chain below as needed.
			 */
			space = m_length(m, NULL);
			if (space >= MINCLSIZE) {
				/* NB: m_copyback handles space > MCLBYTES */
				n = m_getcl(how, MT_DATA, 0);
			} else
				n = m_get(how, MT_DATA);
			if (n == NULL)
				return (ENOMEM);
			/*
			 * Align the remainder of the mbuf chain.
			 */
			n->m_len = 0;
			off = 0;
			while (m != NULL) {
				m_copyback(n, off, m->m_len, mtod(m, caddr_t));
				off += m->m_len;
				m = m->m_next;
			}
			m_freem(*pm);
			*pm = n;
			++nfs_realign_count;
			break;
		}
		pm = &m->m_next;
	}

	return (0);
}
#endif	/* __NO_STRICT_ALIGNMENT */

#ifdef notdef
static void
nfsrv_object_create(struct vnode *vp, struct thread *td)
{

	if (vp == NULL || vp->v_type != VREG)
		return;
	(void) vfs_object_create(vp, td, td->td_ucred);
}
#endif

/*
 * Look up a file name. Basically just initialize stuff and call namei().
 */
int
nfsrv_lookupfilename(struct nameidata *ndp, char *fname, NFSPROC_T *p)
{
	int error;

	NDINIT(ndp, LOOKUP, FOLLOW | LOCKLEAF, UIO_USERSPACE, fname,
	    p);
	error = namei(ndp);
	if (!error) {
		NDFREE(ndp, NDF_ONLY_PNBUF);
	}
	return (error);
}

/*
 * Copy NFS uid, gids to the cred structure.
 */
void
newnfs_copycred(struct nfscred *nfscr, struct ucred *cr)
{

	KASSERT(nfscr->nfsc_ngroups >= 0,
	    ("newnfs_copycred: negative nfsc_ngroups"));
	cr->cr_uid = nfscr->nfsc_uid;
	crsetgroups(cr, nfscr->nfsc_ngroups, nfscr->nfsc_groups);
}

/*
 * Map args from nfsmsleep() to msleep().
 */
int
nfsmsleep(void *chan, void *mutex, int prio, const char *wmesg,
    struct timespec *ts)
{
	u_int64_t nsecval;
	int error, timeo;

	if (ts) {
		timeo = hz * ts->tv_sec;
		nsecval = (u_int64_t)ts->tv_nsec;
		nsecval = ((nsecval * ((u_int64_t)hz)) + 500000000) /
		    1000000000;
		timeo += (int)nsecval;
	} else {
		timeo = 0;
	}
	error = msleep(chan, (struct mtx *)mutex, prio, wmesg, timeo);
	return (error);
}

/*
 * Get the file system info for the server. For now, just assume FFS.
 */
void
nfsvno_getfs(struct nfsfsinfo *sip, int isdgram)
{
	int pref;

	/*
	 * XXX
	 * There should be file system VFS OP(s) to get this information.
	 * For now, assume ufs.
	 */
	if (isdgram)
		pref = NFS_MAXDGRAMDATA;
	else
		pref = NFS_MAXDATA;
	sip->fs_rtmax = NFS_MAXDATA;
	sip->fs_rtpref = pref;
	sip->fs_rtmult = NFS_FABLKSIZE;
	sip->fs_wtmax = NFS_MAXDATA;
	sip->fs_wtpref = pref;
	sip->fs_wtmult = NFS_FABLKSIZE;
	sip->fs_dtpref = pref;
	sip->fs_maxfilesize = 0xffffffffffffffffull;
	sip->fs_timedelta.tv_sec = 0;
	sip->fs_timedelta.tv_nsec = 1;
	sip->fs_properties = (NFSV3FSINFO_LINK |
	    NFSV3FSINFO_SYMLINK | NFSV3FSINFO_HOMOGENEOUS |
	    NFSV3FSINFO_CANSETTIME);
}

/*
 * Do the pathconf vnode op.
 */
int
nfsvno_pathconf(struct vnode *vp, int flag, register_t *retf,
    struct ucred *cred, struct thread *p)
{
	int error;

	error = VOP_PATHCONF(vp, flag, retf);
	if (error == EOPNOTSUPP || error == EINVAL) {
		/*
		 * Some file systems return EINVAL for name arguments not
		 * supported and some return EOPNOTSUPP for this case.
		 * So the NFSv3 Pathconf RPC doesn't fail for these cases,
		 * just fake them.
		 */
		switch (flag) {
		case _PC_LINK_MAX:
			*retf = LINK_MAX;
			break;
		case _PC_NAME_MAX:
			*retf = NAME_MAX;
			break;
		case _PC_CHOWN_RESTRICTED:
			*retf = 1;
			break;
		case _PC_NO_TRUNC:
			*retf = 1;
			break;
		default:
			/*
			 * Only happens if a _PC_xxx is added to the server,
			 * but this isn't updated.
			 */
			*retf = 0;
			printf("nfsrvd pathconf flag=%d not supp\n", flag);
		};
		error = 0;
	}
	NFSEXITCODE(error);
	return (error);
}

/* Fake nfsrv_atroot. Just return 0 */
int
nfsrv_atroot(struct vnode *vp, long *retp)
{

	return (0);
}

/*
 * Set the credentials to refer to root.
 * If only the various BSDen could agree on whether cr_gid is a separate
 * field or cr_groups[0]...
 */
void
newnfs_setroot(struct ucred *cred)
{

	cred->cr_uid = 0;
	cred->cr_groups[0] = 0;
	cred->cr_ngroups = 1;
}

/*
 * Get the client credential. Used for Renew and recovery.
 */
struct ucred *
newnfs_getcred(void)
{
	struct ucred *cred;
	struct thread *td = curthread;

	cred = crdup(td->td_ucred);
	newnfs_setroot(cred);
	return (cred);
}

/*
 * Nfs timer routine
 * Call the nfsd's timer function once/sec.
 */
void
newnfs_timer(void *arg)
{
	static time_t lasttime = 0;
	/*
	 * Call the server timer, if set up.
	 * The argument indicates if it is the next second and therefore
	 * leases should be checked.
	 */
	if (lasttime != NFSD_MONOSEC) {
		lasttime = NFSD_MONOSEC;
		if (nfsd_call_servertimer != NULL)
			(*nfsd_call_servertimer)();
	}
	callout_reset(&newnfsd_callout, nfscl_ticks, newnfs_timer, NULL);
}

/*
 * Sleep for a short period of time unless errval == NFSERR_GRACE, where
 * the sleep should be for 5 seconds.
 * Since lbolt doesn't exist in FreeBSD-CURRENT, just use a timeout on
 * an event that never gets a wakeup. Only return EINTR or 0.
 */
int
nfs_catnap(int prio, int errval, const char *wmesg)
{
	static int non_event;
	int ret;

	if (errval == NFSERR_GRACE)
		ret = tsleep(&non_event, prio, wmesg, 5 * hz);
	else
		ret = tsleep(&non_event, prio, wmesg, 1);
	if (ret != EINTR)
		ret = 0;
	return (ret);
}

/*
 * Get referral. For now, just fail.
 */
struct nfsreferral *
nfsv4root_getreferral(struct vnode *vp, struct vnode *dvp, u_int32_t fileno)
{

	return (NULL);
}

static int
nfssvc_nfscommon(struct thread *td, struct nfssvc_args *uap)
{
	int error;

	error = nfssvc_call(td, uap, td->td_ucred);
	NFSEXITCODE(error);
	return (error);
}

static int
nfssvc_call(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
{
	int error = EINVAL;
	struct nfsd_idargs nid;

	if (uap->flag & NFSSVC_IDNAME) {
		error = copyin(uap->argp, (caddr_t)&nid, sizeof (nid));
		if (error)
			goto out;
		error = nfssvc_idname(&nid);
		goto out;
	} else if (uap->flag & NFSSVC_GETSTATS) {
		error = copyout(&newnfsstats,
		    CAST_USER_ADDR_T(uap->argp), sizeof (newnfsstats));
		if (error == 0) {
			if ((uap->flag & NFSSVC_ZEROCLTSTATS) != 0) {
				newnfsstats.attrcache_hits = 0;
				newnfsstats.attrcache_misses = 0;
				newnfsstats.lookupcache_hits = 0;
				newnfsstats.lookupcache_misses = 0;
				newnfsstats.direofcache_hits = 0;
				newnfsstats.direofcache_misses = 0;
				newnfsstats.accesscache_hits = 0;
				newnfsstats.accesscache_misses = 0;
				newnfsstats.biocache_reads = 0;
				newnfsstats.read_bios = 0;
				newnfsstats.read_physios = 0;
				newnfsstats.biocache_writes = 0;
				newnfsstats.write_bios = 0;
				newnfsstats.write_physios = 0;
				newnfsstats.biocache_readlinks = 0;
				newnfsstats.readlink_bios = 0;
				newnfsstats.biocache_readdirs = 0;
				newnfsstats.readdir_bios = 0;
				newnfsstats.rpcretries = 0;
				newnfsstats.rpcrequests = 0;
				newnfsstats.rpctimeouts = 0;
				newnfsstats.rpcunexpected = 0;
				newnfsstats.rpcinvalid = 0;
				bzero(newnfsstats.rpccnt,
				    sizeof(newnfsstats.rpccnt));
			}
			if ((uap->flag & NFSSVC_ZEROSRVSTATS) != 0) {
				newnfsstats.srvrpc_errs = 0;
				newnfsstats.srv_errs = 0;
				newnfsstats.srvcache_inproghits = 0;
				newnfsstats.srvcache_idemdonehits = 0;
				newnfsstats.srvcache_nonidemdonehits = 0;
				newnfsstats.srvcache_misses = 0;
				newnfsstats.srvcache_tcppeak = 0;
				newnfsstats.srvclients = 0;
				newnfsstats.srvopenowners = 0;
				newnfsstats.srvopens = 0;
				newnfsstats.srvlockowners = 0;
				newnfsstats.srvlocks = 0;
				newnfsstats.srvdelegates = 0;
				newnfsstats.clopenowners = 0;
				newnfsstats.clopens = 0;
				newnfsstats.cllockowners = 0;
				newnfsstats.cllocks = 0;
				newnfsstats.cldelegates = 0;
				newnfsstats.cllocalopenowners = 0;
				newnfsstats.cllocalopens = 0;
				newnfsstats.cllocallockowners = 0;
				newnfsstats.cllocallocks = 0;
				bzero(newnfsstats.srvrpccnt,
				    sizeof(newnfsstats.srvrpccnt));
				bzero(newnfsstats.cbrpccnt,
				    sizeof(newnfsstats.cbrpccnt));
			}
		}
		goto out;
	} else if (uap->flag & NFSSVC_NFSUSERDPORT) {
		u_short sockport;

		error = copyin(uap->argp, (caddr_t)&sockport,
		    sizeof (u_short));
		if (!error)
			error = nfsrv_nfsuserdport(sockport, p);
	} else if (uap->flag & NFSSVC_NFSUSERDDELPORT) {
		nfsrv_nfsuserddelport();
		error = 0;
	}

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * called by all three modevent routines, so that it gets things
 * initialized soon enough.
 */
void
newnfs_portinit(void)
{
	static int inited = 0;

	if (inited)
		return;
	inited = 1;
	/* Initialize SMP locks used by both client and server. */
	mtx_init(&newnfsd_mtx, "newnfsd_mtx", NULL, MTX_DEF);
	mtx_init(&nfs_state_mutex, "nfs_state_mutex", NULL, MTX_DEF);
}

/*
 * Determine if the file system supports NFSv4 ACLs.
 * Return 1 if it does, 0 otherwise.
 */
int
nfs_supportsnfsv4acls(struct vnode *vp)
{
	int error;
	register_t retval;

	ASSERT_VOP_LOCKED(vp, "nfs supports nfsv4acls");

	if (nfsrv_useacl == 0)
		return (0);
	error = VOP_PATHCONF(vp, _PC_ACL_NFS4, &retval);
	if (error == 0 && retval != 0)
		return (1);
	return (0);
}

extern int (*nfsd_call_nfscommon)(struct thread *, struct nfssvc_args *);

/*
 * Called once to initialize data structures...
 */
static int
nfscommon_modevent(module_t mod, int type, void *data)
{
	int error = 0;
	static int loaded = 0;

	switch (type) {
	case MOD_LOAD:
		if (loaded)
			goto out;
		newnfs_portinit();
		mtx_init(&nfs_nameid_mutex, "nfs_nameid_mutex", NULL, MTX_DEF);
		mtx_init(&nfs_sockl_mutex, "nfs_sockl_mutex", NULL, MTX_DEF);
		mtx_init(&nfs_slock_mutex, "nfs_slock_mutex", NULL, MTX_DEF);
		mtx_init(&nfs_req_mutex, "nfs_req_mutex", NULL, MTX_DEF);
		mtx_init(&nfsrv_nfsuserdsock.nr_mtx, "nfsuserd", NULL,
		    MTX_DEF);
		callout_init(&newnfsd_callout, CALLOUT_MPSAFE);
		newnfs_init();
		nfsd_call_nfscommon = nfssvc_nfscommon;
		loaded = 1;
		break;

	case MOD_UNLOAD:
		if (newnfs_numnfsd != 0 || nfsrv_nfsuserd != 0 ||
		    nfs_numnfscbd != 0) {
			error = EBUSY;
			break;
		}

		nfsd_call_nfscommon = NULL;
		callout_drain(&newnfsd_callout);
		/* and get rid of the mutexes */
		mtx_destroy(&nfs_nameid_mutex);
		mtx_destroy(&newnfsd_mtx);
		mtx_destroy(&nfs_state_mutex);
		mtx_destroy(&nfs_sockl_mutex);
		mtx_destroy(&nfs_slock_mutex);
		mtx_destroy(&nfs_req_mutex);
		mtx_destroy(&nfsrv_nfsuserdsock.nr_mtx);
		loaded = 0;
		break;
	default:
		error = EOPNOTSUPP;
		break;
	}

out:
	NFSEXITCODE(error);
	return error;
}
static moduledata_t nfscommon_mod = {
	"nfscommon",
	nfscommon_modevent,
	NULL,
};
DECLARE_MODULE(nfscommon, nfscommon_mod, SI_SUB_VFS, SI_ORDER_ANY);

/* So that loader and kldload(2) can find us, wherever we are.. */
MODULE_VERSION(nfscommon, 1);
MODULE_DEPEND(nfscommon, nfssvc, 1, 1, 1);
MODULE_DEPEND(nfscommon, krpc, 1, 1, 1);


text:
typedef void (^SuccessBlock) (id response);
typedef void (^FailureBlock) (NSError *error);

@interface ZRRequestManager : NSObject

DEFINE_SINGLETON_FOR_HEADER(RequestManager);

- (void) getRequestWithURL:(NSString *)urlString
                    params:(NSDictionary *)params
              successBlock:(SuccessBlock) successBlock
              failureBlock:(FailureBlock) failureBlock;

- (void) postRequestWithURL:(NSString *)urlString
                     params:(NSDictionary *)params
               successBlock:(SuccessBlock) successBlock
               failureBlock:(FailureBlock) failureBlock;
@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RimWorld;
using Verse;
using RimTrans.Framework.HarmonyPatches;
using RimTrans.Framework.Utility;

namespace RimTrans.Framework {
    [StaticConstructorOnStartup]
    public class RimTransFrameworkController {
        static RimTransFrameworkController() {
            LongEventHandler.ExecuteWhenFinished(CallAll);
        }

        public static void CallAll() {
            PawnBioAndBacktoryUtility.TranslateVanilla();
            PawnBioAndBacktoryUtility.AddAllCustom();
            ShuffledNameUtility.TranslateVanilla();
            ShuffledNameUtility.AddAllCustom();
            CombineNameUtility.CombineAndAddToDatabase();

#if DEBUG
            // DEBUG
            Debug();
#endif
        }

        public static void Debug() {
            NameBank nameBank = PawnNameDatabaseShuffled.BankOf(PawnNameCategory.HumanStandard);
            Log.Message($"PawnNameDatabaseShuffled {PawnNameSlot.First} {Gender.Male} {nameBank.NamesFor(PawnNameSlot.First, Gender.Male).Count}");
            Log.Message($"PawnNameDatabaseShuffled {PawnNameSlot.First} {Gender.Female} {nameBank.NamesFor(PawnNameSlot.First, Gender.Female).Count}");
            Log.Message($"PawnNameDatabaseShuffled {PawnNameSlot.Nick} {Gender.Male} {nameBank.NamesFor(PawnNameSlot.Nick, Gender.Male).Count}");
            Log.Message($"PawnNameDatabaseShuffled {PawnNameSlot.Nick} {Gender.Female} {nameBank.NamesFor(PawnNameSlot.Nick, Gender.Female).Count}");
            Log.Message($"PawnNameDatabaseShuffled {PawnNameSlot.Nick} {Gender.None} {nameBank.NamesFor(PawnNameSlot.Nick, Gender.None).Count}");
            Log.Message($"PawnNameDatabaseShuffled {PawnNameSlot.Last} {Gender.None} {nameBank.NamesFor(PawnNameSlot.Last, Gender.None).Count}");
            Log.Message($"PawnNameDatabaseSolid {PawnNameDatabaseSolid.AllNames().Count()}");
        }
    }
}


text:
package convert

import (
	"testing"

	swarmtypes "github.com/docker/docker/api/types/swarm"
	swarmapi "github.com/docker/swarmkit/api"
	google_protobuf3 "github.com/gogo/protobuf/types"
)

func TestServiceConvertFromGRPCRuntimeContainer(t *testing.T) {
	gs := swarmapi.Service{
		Meta: swarmapi.Meta{
			Version: swarmapi.Version{
				Index: 1,
			},
			CreatedAt: nil,
			UpdatedAt: nil,
		},
		SpecVersion: &swarmapi.Version{
			Index: 1,
		},
		Spec: swarmapi.ServiceSpec{
			Task: swarmapi.TaskSpec{
				Runtime: &swarmapi.TaskSpec_Container{
					Container: &swarmapi.ContainerSpec{
						Image: "alpine:latest",
					},
				},
			},
		},
	}

	svc, err := ServiceFromGRPC(gs)
	if err != nil {
		t.Fatal(err)
	}

	if svc.Spec.TaskTemplate.Runtime != swarmtypes.RuntimeContainer {
		t.Fatalf("expected type %s; received %T", swarmtypes.RuntimeContainer, svc.Spec.TaskTemplate.Runtime)
	}
}

func TestServiceConvertFromGRPCGenericRuntimePlugin(t *testing.T) {
	kind := string(swarmtypes.RuntimePlugin)
	url := swarmtypes.RuntimeURLPlugin
	gs := swarmapi.Service{
		Meta: swarmapi.Meta{
			Version: swarmapi.Version{
				Index: 1,
			},
			CreatedAt: nil,
			UpdatedAt: nil,
		},
		SpecVersion: &swarmapi.Version{
			Index: 1,
		},
		Spec: swarmapi.ServiceSpec{
			Task: swarmapi.TaskSpec{
				Runtime: &swarmapi.TaskSpec_Generic{
					Generic: &swarmapi.GenericRuntimeSpec{
						Kind: kind,
						Payload: &google_protobuf3.Any{
							TypeUrl: string(url),
						},
					},
				},
			},
		},
	}

	svc, err := ServiceFromGRPC(gs)
	if err != nil {
		t.Fatal(err)
	}

	if svc.Spec.TaskTemplate.Runtime != swarmtypes.RuntimePlugin {
		t.Fatalf("expected type %s; received %T", swarmtypes.RuntimePlugin, svc.Spec.TaskTemplate.Runtime)
	}
}

func TestServiceConvertToGRPCGenericRuntimePlugin(t *testing.T) {
	s := swarmtypes.ServiceSpec{
		TaskTemplate: swarmtypes.TaskSpec{
			Runtime: swarmtypes.RuntimePlugin,
		},
		Mode: swarmtypes.ServiceMode{
			Global: &swarmtypes.GlobalService{},
		},
	}

	svc, err := ServiceSpecToGRPC(s)
	if err != nil {
		t.Fatal(err)
	}

	v, ok := svc.Task.Runtime.(*swarmapi.TaskSpec_Generic)
	if !ok {
		t.Fatal("expected type swarmapi.TaskSpec_Generic")
	}

	if v.Generic.Payload.TypeUrl != string(swarmtypes.RuntimeURLPlugin) {
		t.Fatalf("expected url %s; received %s", swarmtypes.RuntimeURLPlugin, v.Generic.Payload.TypeUrl)
	}
}

func TestServiceConvertToGRPCContainerRuntime(t *testing.T) {
	image := "alpine:latest"
	s := swarmtypes.ServiceSpec{
		TaskTemplate: swarmtypes.TaskSpec{
			ContainerSpec: swarmtypes.ContainerSpec{
				Image: image,
			},
		},
		Mode: swarmtypes.ServiceMode{
			Global: &swarmtypes.GlobalService{},
		},
	}

	svc, err := ServiceSpecToGRPC(s)
	if err != nil {
		t.Fatal(err)
	}

	v, ok := svc.Task.Runtime.(*swarmapi.TaskSpec_Container)
	if !ok {
		t.Fatal("expected type swarmapi.TaskSpec_Container")
	}

	if v.Container.Image != image {
		t.Fatalf("expected image %s; received %s", image, v.Container.Image)
	}
}

func TestServiceConvertToGRPCGenericRuntimeCustom(t *testing.T) {
	s := swarmtypes.ServiceSpec{
		TaskTemplate: swarmtypes.TaskSpec{
			Runtime: "customruntime",
		},
		Mode: swarmtypes.ServiceMode{
			Global: &swarmtypes.GlobalService{},
		},
	}

	if _, err := ServiceSpecToGRPC(s); err != ErrUnsupportedRuntime {
		t.Fatal(err)
	}
}


text:
package psidev.psi.mi.jami.xml.io.writer.elements.impl;

import psidev.psi.mi.jami.model.Annotation;
import psidev.psi.mi.jami.model.CvTerm;
import psidev.psi.mi.jami.xml.io.writer.elements.PsiXmlElementWriter;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

/**
 * Xml writer for open cv terms
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
12/11/13

 */
public class XmlOpenCvTermWriter extends XmlCvTermWriter {
    private PsiXmlElementWriter<Annotation> attributeWriter;

    /**
     *
Constructor for XmlOpenCvTermWriter.

     *
     * @param writer a {@link javax.xml.stream.XMLStreamWriter} object.
     */
    public XmlOpenCvTermWriter(XMLStreamWriter writer) {
        super(writer);
    }

    /**
     *
Getter for the field attributeWriter.

     *
     * @return a {@link psidev.psi.mi.jami.xml.io.writer.elements.PsiXmlElementWriter} object.
     */
    public PsiXmlElementWriter<Annotation> getAttributeWriter() {
        if (this.attributeWriter == null){
            this.attributeWriter = new XmlAnnotationWriter(getStreamWriter());
        }
        return attributeWriter;
    }

    /**
     *
Setter for the field attributeWriter.

     *
     * @param attributeWriter a {@link psidev.psi.mi.jami.xml.io.writer.elements.PsiXmlElementWriter} object.
     */
    public void setAttributeWriter(PsiXmlElementWriter<Annotation> attributeWriter) {
        this.attributeWriter = attributeWriter;
    }

    /** {@inheritDoc} */
    @Override
    protected void writeOtherProperties(CvTerm object) throws XMLStreamException {
        // write attributes
        if (!object.getAnnotations().isEmpty()){
            // write start attribute list
            getStreamWriter().writeStartElement("attributeList");
            for (Annotation ann : object.getAnnotations()){
                getAttributeWriter().write(ann);
            }
            // write end attributeList
            getStreamWriter().writeEndElement();
        }
    }
}


text:
/**
 * @file
 * This test burns some CPU cycles in user space and kernel space in order to
 * get some non-zero values returned by times(2).
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <sched.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

#include <sys/syscall.h>
#include <sys/times.h>
#include <sys/wait.h>

enum {
	NUM_USER_ITERS = 1000000,
	PARENT_CPUTIME_LIMIT_NSEC = 200000000,
	CHILD_CPUTIME_LIMIT_NSEC = 300000000
};

int
main (void)
{
	struct timespec ts;
	volatile int dummy;
	int i;

	pid_t pid = fork();

	if (pid < 0)
		return 77;

	const long cputime_limit =
		pid ? PARENT_CPUTIME_LIMIT_NSEC : CHILD_CPUTIME_LIMIT_NSEC;

	/* Enjoying my user time */
	while (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == 0) {
		if (ts.tv_sec || ts.tv_nsec >= cputime_limit)
			break;

		for (i = 0; i < NUM_USER_ITERS; ++i)
			++dummy;
	}

	/* Enjoying my system time */
	while (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == 0) {
		if (ts.tv_sec || ts.tv_nsec >= cputime_limit * 2)
			break;

		sched_yield();
	}

	if (pid == 0) {
		return 0;
	} else {
		wait(NULL);
	}

	struct tms tbuf;
	unsigned long long llres;

	/*
	 * On systems where user's and kernel's long types are the same,
	 * prefer direct times syscall over libc's times function because
	 * the latter is more prone to return value truncation.
	 */
#if !defined __NR_times \
 || defined LINUX_MIPSN32 \
 || defined __x86_64__ && defined __ILP32__
	clock_t res = times(&tbuf);

	if ((clock_t) -1 == res)
		return 77;
	if (sizeof(res) < sizeof(unsigned long long))
		llres = (unsigned long) res;
	else
		llres = res;
#else
	long res = syscall(__NR_times, &tbuf);

	if (-1L == res)
		return 77;
	else
		llres = (unsigned long) res;
#endif

	printf("times({tms_utime=%llu, tms_stime=%llu, ",
		(unsigned long long) tbuf.tms_utime,
		(unsigned long long) tbuf.tms_stime);
	printf("tms_cutime=%llu, tms_cstime=%llu}) = %llu\n",
		(unsigned long long) tbuf.tms_cutime,
		(unsigned long long) tbuf.tms_cstime,
		llres);
	puts("+++ exited with 0 +++");

	return 0;
}


text:
class BidPolicy < ApplicationPolicy

 def index?
    @current_user.permission('Bid', :guest)
 end

 # GET /bids/1
 # GET /bids/1.json
 def show?
    @current_user.permission('Bid', :guest)
 end

 # GET /bids/new
 def new?
    @current_user.permission('Bid', :clerk)
 end

 # GET /bids/1/edit
 def edit?
    @current_user.permission('Bid', :clerk)
 end

 # POST /bids
 # POST /bids.json
 def create?
    @current_user.permission('Bid', :clerk)
 end

 # PATCH/PUT /bids/1
 # PATCH/PUT /bids/1.json
 def update?
    @current_user.permission('Bid', :clerk)
 end

 # DELETE /bids/1
 # DELETE /bids/1.json
 def destroy?
    @current_user.permission('Bid', :clerk)
 end

 def update_status?
    @current_user.permission('Bid', :clerk)
 end

 def request_for_quotations?
    @current_user.permission('Bid', :clerk)
 end

def download_rfq?
    @current_user.permission('Bid', :clerk)
end

 def upload_rfq?
    @current_user.permission('Bid', :clerk)
 end

 def generate_winners?
    @current_user.permission('Bid', :clerk)
 end

 def regenerate_bid?
    @current_user.permission('Bid', :clerk)
 end

 def transporter_quotes?
    @current_user.permission('Bid', :clerk)
 end

 def remove_bid_quotation?
    @current_user.permission('Bid', :clerk)
 end

 def view_bid_winners?
    @current_user.permission('Bid', :clerk)
 end

 def contracts?
    @current_user.permission('Bid', :clerk)
 end

 def download_contract?
    @current_user.permission('Bid', :clerk)
 end

 def sign_contract?
    @current_user.permission('Bid', :clerk)
 end

end