text:
.PHONY: install uninstall

TEMPDIR := $(shell mktemp --directory)

install:
	wget --directory-prefix="$(TEMPDIR)" "https://cdn.jsdelivr.net/gh/git/git/contrib/subtree/git-subtree.sh"
	install --mode=755 "$(TEMPDIR)/git-subtree.sh" /usr/local/bin/git-subtree
	rm -rf "$(TEMPDIR)"

uninstall:
	rm --force /usr/local/bin/git-subtree


text:
SpecBegin(ASTGroupBy)

NSArray *array = @[ @"Hello", @"Bonjour", @"Hallo", @"Hej" ];

it(@"should return a dictionary of sets, grouped by the blocks return value", ^{
    NSDictionary *dictionary = ASTGroupBy(array, ^(NSString *string) {
        return @(string.length);
    });

    expect(dictionary).to.haveCountOf(3);

    expect(dictionary[@3]).to.contain(@"Hej");
    expect(dictionary[@5]).to.contain(@"Hello");
    expect(dictionary[@5]).to.contain(@"Hallo");
    expect(dictionary[@7]).to.contain(@"Bonjour");
});

it(@"should remove elements that grouped by `nil`", ^{
    NSDictionary *dictionary = ASTGroupBy(@[ @[ @1 ], @[ @2, @3 ], @[] ], ^(NSArray *array) {
        return array.firstObject;
    });

    expect(dictionary).to.haveCountOf(2);

    expect(dictionary[@1]).to.contain(@[ @1 ]);
    expect(dictionary[@2]).to.contain(( @[ @2, @3 ] ));
});

it(@"should return a dictionary of sets, grouped by their value for a key path", ^{
    NSDictionary *dictionary = ASTGroupBy(array, @"length");

    expect(dictionary).to.haveCountOf(3);

    expect(dictionary[@3]).to.contain(@"Hej");
    expect(dictionary[@5]).to.contain(@"Hello");
    expect(dictionary[@5]).to.contain(@"Hallo");
    expect(dictionary[@7]).to.contain(@"Bonjour");
});

it(@"should use the values of dictionaries", ^{
    NSDictionary *dict = @{ @"foo": @"Hello" };

    NSDictionary *blockResult = ASTGroupBy(dict, ^(NSString *string) {
        return @(string.length);
    });

    expect(blockResult[@5]).to.contain(@"Hello");

    NSDictionary *keyPathResult = ASTGroupBy(dict, @"length");

    expect(keyPathResult[@5]).to.contain(@"Hello");
});

SpecEnd

redpajama_set_name: RedPajamaGithub


text:
          {{ participant.firstName }}{{ $last ? '' : ',' }}

{{ chatObj.chat.messages[chatObj.chat.messages.length-1].datetime | datetime }}


text:
namespace OrchardCore.Deployment.ViewModels
{
    public class ImportJsonViewModel
    {
        public string Json { get; set; }
    }
}


text:
import {
  interactor,
  scoped,
  Interactor,
  collection,
} from '@bigtest/interactor';

import ButtonInteractor from '@folio/stripes-components/lib/Button/tests/interactor'; // eslint-disable-line
import MultiColumnListInteractor from '@folio/stripes-components/lib/MultiColumnList/tests/interactor'; // eslint-disable-line

@interactor class ClosedLoans {
  static defaultScope = '[data-test-closed-loans]';

  anonymizeButton = new ButtonInteractor('#anonymize-all');
  anonymizationFeesFinesErrorModal = new Interactor('#anonymization-fees-fines-modal');
  anonymizationConfirmButton = new ButtonInteractor('#anonymization-fees-fines-modal-footer button');
  list = scoped('#list-loanshistory', MultiColumnListInteractor);
  rowButtons = collection('[data-test-closed-loans] [data-row-inner]', ButtonInteractor);
  callNumbers = collection('[data-test-list-call-numbers]');
  columnHeaders = collection('[role="columnheader"]');

  whenLoaded() {
    return this.when(() => this.list.isVisible);
  }
}

export default new ClosedLoans();


text:
def do_report(data_source):
    # fetch and prepare data
    data = fetch_data(data_source)
    parsed_data = parse_data(data)
    filtered_data = filter_data(parsed_data)
    polished_data = polish_data(filtered_data)

    # run algorithms on data
    final_data = analyse(polished_data)

    # create and return report
    report = Report(final_data)
    return report

if __name__ == "__main__":

    print(
        "Please don't call the `do_report` function. "
        "It's just and example."
    )


text:
package de.fhws.tutorium.ss17.tut3;

import java.io.*;

public class Person {
    protected String vorname, nachname;
    protected int alter;

    public static void main(String[] args) {
        String file = "/tmp/Personen.csv";
        Person[] pers = new Person[6];

        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(file)
                    )
            );

            String line;
            int offset = 0;
            while ((line = br.readLine()) != null)
            {
                String[] data = line.split(";");

                pers[offset++] = new Person(data[0], data[1], Integer.parseInt(data[2]));
            }

            br.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }

        for (Person x:pers ) {
            System.out.println(x.toString());
        }
    }

    @Override
    public String toString() {
        return vorname + " " + nachname + " (" + alter + " Jahre)";
    }

    //
    // getter, setter
    //

    public Person(String vorname, String nachname, int alter) {
        this.vorname = vorname;
        this.nachname = nachname;
        this.alter = alter;
    }

    public String getVorname() {
        return vorname;
    }

    public void setVorname(String vorname) {
        this.vorname = vorname;
    }

    public String getNachname() {
        return nachname;
    }

    public void setNachname(String nachname) {
        this.nachname = nachname;
    }

    public int getAlter() {
        return alter;
    }

    public void setAlter(int alter) {
        this.alter = alter;
    }

}


text:
//-----------------------------------------------------------------------
// <copyright company="Sherlock">
//     Copyright 2013 Sherlock. Licensed under the Apache License, Version 2.0.
// </copyright>
//-----------------------------------------------------------------------

namespace Sherlock.Executor
{
    /// <summary>
    /// Defines the application wide constants.
    /// </summary>
    internal static class Constants
    {
        /// <summary>
        /// The application exit code that indicates that the tests failed.
        /// </summary>
        public const int TestsFailedApplicationExitCode = 2;

        /// <summary>
        /// The application exit code that indicates that the application was terminated.
        /// </summary>
        public const int ApplicationTerminatedExitCode = 3;
    }
}


text:
namespace sepia
{
namespace comm
{

class MessageHandler
{
public:
    MessageHandler( const std::string a_name );
    ~MessageHandler();
    void create();
    void create_or_open();
    void open();
    void close();
    bool getMessage( char* a_buffer, size_t& a_receivedBytes );
    void putMessage( const char* a_buffer, const size_t& a_bytes );
    size_t getMaxSize();

private:
    boost::interprocess::message_queue* m_queue;
    std::string m_name;
    bool m_removeQueueOnClose;
    size_t m_maxMessages;
    size_t m_maxMessageSize;
};

}
}

#endif // SEPIA_COMM_MESSAGEHANDLER_H


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>HCI Lab2 Virtual Keyboard</title>
	<link href="css/jquery-ui.css" rel="stylesheet">

	<link href="css/keyboard.css" rel="stylesheet">

	<link href="demo/demo.css" rel="stylesheet">

HCI Lab - Comparison of Keyboard Layouts

Comparison between QWERTY and DVORAK Keyboard Layouts

QWERTY Text Area

		<textarea class="qwerty"></textarea>

<!-- HTML -->
			<textarea class="qwerty"></textarea>

		// Script
		$('.qwerty:eq(2)')
		 .keyboard({
		  layout   : 'qwerty',
		 })
		 .addTyping();

Dvorak

		<textarea id="dvorak"></textarea>

<!-- HTML -->
		<textarea id="dvorak"></textarea>

		// Script
		$('#dvorak')
		 .keyboard({ layout: 'dvorak' })
		 .addTyping();


text:
package kieker.common.record.database;

import kieker.common.exception.RecordInstantiationException;
import kieker.common.record.factory.IRecordFactory;
import kieker.common.record.io.IValueDeserializer;

/**
 * @author Christian Zirkelbach (czi@informatik.uni-kiel.de)
 *
 * @since 1.14
 */
public final class AfterDatabaseEventFactory implements IRecordFactory<AfterDatabaseEvent> {

	@Override
	public AfterDatabaseEvent create(final IValueDeserializer deserializer) throws RecordInstantiationException {
		return new AfterDatabaseEvent(deserializer);
	}

	@Override
	public String[] getValueNames() {
		return AfterDatabaseEvent.VALUE_NAMES; // NOPMD
	}

	@Override
	public Class<?>[] getValueTypes() {
		return AfterDatabaseEvent.TYPES; // NOPMD
	}

	public int getRecordSizeInBytes() {
		return AfterDatabaseEvent.SIZE;
	}
}


text:
<?php
/**
 * PROJECT git-webhook-phpAutoDeploy
 * FileName ShellCommand.php
 * Author: Yi Wu
 * Email: wushunyi@vip.qq.com
 * Time: 2015/11/19 0:28
 * description:命令行执行
 *
 */
class ShellCommand{
    private $_exec_bin = '';
    private $_safa_bin = array('cd','dir','git');

    public function __construct($commands)
    {

    }

}


text:
Subject: New Private Message has arrived
Charset: UTF-8

Hello {USERNAME},

You have received a new private message to your account on "{SITENAME}" and you have requested that you be notified on this event. You can view your new message by clicking on the following link:

{U_INBOX}

Remember that you can always choose not to be notified of new messages by changing the appropriate setting in your profile.

{EMAIL_SIG}


text:
/**
 * Stores error information; delivered via [NgZone.onError] stream.
 */
export class NgZoneError {
    constructor(error, stackTrace) {
        this.error = error;
        this.stackTrace = stackTrace;
    }
}
export class NgZoneImpl {
    constructor({ trace, onEnter, onLeave, setMicrotask, setMacrotask, onError }) {
        this.onEnter = onEnter;
        this.onLeave = onLeave;
        this.setMicrotask = setMicrotask;
        this.setMacrotask = setMacrotask;
        this.onError = onError;
        if (Zone) {
            this.outer = this.inner = Zone.current;
            if (Zone['wtfZoneSpec']) {
                this.inner = this.inner.fork(Zone['wtfZoneSpec']);
            }
            if (trace && Zone['longStackTraceZoneSpec']) {
                this.inner = this.inner.fork(Zone['longStackTraceZoneSpec']);
            }
            this.inner = this.inner.fork({
                name: 'angular',
                properties: { 'isAngularZone': true },
                onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
                    try {
                        this.onEnter();
                        return delegate.invokeTask(target, task, applyThis, applyArgs);
                    }
                    finally {
                        this.onLeave();
                    }
                },
                onInvoke: (delegate, current, target, callback, applyThis, applyArgs, source) => {
                    try {
                        this.onEnter();
                        return delegate.invoke(target, callback, applyThis, applyArgs, source);
                    }
                    finally {
                        this.onLeave();
                    }
                },
                onHasTask: (delegate, current, target, hasTaskState) => {
                    delegate.hasTask(target, hasTaskState);
                    if (current == target) {
                        // We are only interested in hasTask events which originate from our zone
                        // (A child hasTask event is not interesting to us)
                        if (hasTaskState.change == 'microTask') {
                            this.setMicrotask(hasTaskState.microTask);
                        }
                        else if (hasTaskState.change == 'macroTask') {
                            this.setMacrotask(hasTaskState.macroTask);
                        }
                    }
                },
                onHandleError: (delegate, current, target, error) => {
                    delegate.handleError(target, error);
                    this.onError(new NgZoneError(error, error.stack));
                    return false;
                }
            });
        }
        else {
            throw new Error('Angular2 needs to be run with Zone.js polyfill.');
        }
    }
    static isInAngularZone() { return Zone.current.get('isAngularZone') === true; }
    runInner(fn) { return this.inner.runGuarded(fn); }
    ;
    runOuter(fn) { return this.outer.run(fn); }
    ;
}


text:
package io.jeo.filter.cql;

import io.jeo.filter.FilterBuilder;
import io.jeo.filter.Literal;
import io.jeo.util.Convert;

import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

/**
 * Helper for CQL/ECQL parsing.
 *
 * @author Justin Deoliveira, OpenGeo
 */
class CQLHelper extends FilterBuilder {

    String cql;

    public CQLHelper(String cql) {
        this.cql = cql;
    }

    public void intLiteral(Token token) {
        literal(Integer.parseInt(token.image));
    }

    public void floatLiteral(Token token) {
        literal(Double.parseDouble(token.image));
    }

    public void stringLiteral(Token token) {
        literal(dequote(token.image));
    }

    public void wktLiteral(Token token) throws ParseException {
        literal(new WKTReader().read(scan(token)));
    }

    public void fidLiteral(Token token) {
        literal(dequote(token.image));
    }

    String scan(final Token t) {

        Token end = t;

        while (end.next != null) {
            end = end.next;
        }

        return cql.substring(t.beginColumn -1, end.endColumn);
    }

    String dequote(String str) {
        if (str.startsWith("'") && str.endsWith("'")) {
            str = str.substring(1, str.length()-1);
        }
        return str.replaceAll("''", "'");
    }

    public void idPart(Token token) {
        stack.push(token.image);
    }

    public void property() {
        property((String)stack.pop());
    }

    public CQLHelper bbox() {
        Literal e1 = (Literal) pop();
        Literal e2 = (Literal) pop();
        Literal e3 = (Literal) pop();
        Literal e4 = (Literal) pop();

        double x1 = Convert.toNumber(e4.evaluate(null)).get().doubleValue();
        double y1 = Convert.toNumber(e3.evaluate(null)).get().doubleValue();
        double x2 = Convert.toNumber(e2.evaluate(null)).get().doubleValue();
        double y2 = Convert.toNumber(e1.evaluate(null)).get().doubleValue();

        literal(new Envelope(x1, x2, y1, y2));
        super.bbox();

        return this;
    }

    public void bboxWithSRS() {
        pop();
        bbox();
    }

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var base_1 = require("./base");
var machine_1 = require("./machine");
var image_1 = require("./image");
var container_1 = require("./container");
var volume_1 = require("./volume");
var Cmd = (function () {
    function Cmd(machineName) {
        this.machineName = machineName !== undefined ? machineName : 'default';
        this.container = new container_1.Container(this.machineName);
        this.machine = new machine_1.Machine(this.machineName);
        this.image = new image_1.Image(this.machineName);
        this.volume = new volume_1.Volume(this.machineName);
    }
    Cmd.prototype.debug = function (debugging) {
        this.isDebug = (debugging === undefined || debugging === true) ? true : false;
        this.container.debug(this.isDebug);
        return this;
    };
    Cmd.prototype.run = function (command, noNewLines) {
        return base_1.run(command, this.machineName, this.isDebug, noNewLines);
    };
    Cmd.prototype.runSync = function (command) {
        return base_1.runSync(command, this.machineName, this.isDebug);
    };
    Cmd.prototype.resToJSON = function (s) {
        return base_1.resToJSON(s);
    };
    return Cmd;
}());
exports.Cmd = Cmd;


text:
namespace spvtools {
namespace fuzz {

namespace fuzzerutil {

bool IsFreshId(opt::IRContext* context, uint32_t id) {
  return !context->get_def_use_mgr()->GetDef(id);
}

void UpdateModuleIdBound(opt::IRContext* context, uint32_t id) {
  // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/2541) consider the
  //  case where the maximum id bound is reached.
  context->module()->SetIdBound(
      std::max(context->module()->id_bound(), id + 1));
}

opt::BasicBlock* MaybeFindBlock(opt::IRContext* context,
                                uint32_t maybe_block_id) {
  auto inst = context->get_def_use_mgr()->GetDef(maybe_block_id);
  if (inst == nullptr) {
    // No instruction defining this id was found.
    return nullptr;
  }
  if (inst->opcode() != SpvOpLabel) {
    // The instruction defining the id is not a label, so it cannot be a block
    // id.
    return nullptr;
  }
  return context->cfg()->block(maybe_block_id);
}

bool PhiIdsOkForNewEdge(
    opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
    const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids) {
  if (bb_from->IsSuccessor(bb_to)) {
    // There is already an edge from |from_block| to |to_block|, so there is
    // no need to extend OpPhi instructions.  Do not allow phi ids to be
    // present. This might turn out to be too strict; perhaps it would be OK
    // just to ignore the ids in this case.
    return phi_ids.empty();
  }
  // The edge would add a previously non-existent edge from |from_block| to
  // |to_block|, so we go through the given phi ids and check that they exactly
  // match the OpPhi instructions in |to_block|.
  uint32_t phi_index = 0;
  // An explicit loop, rather than applying a lambda to each OpPhi in |bb_to|,
  // makes sense here because we need to increment |phi_index| for each OpPhi
  // instruction.
  for (auto& inst : *bb_to) {
    if (inst.opcode() != SpvOpPhi) {
      // The OpPhi instructions all occur at the start of the block; if we find
      // a non-OpPhi then we have seen them all.
      break;
    }
    if (phi_index == static_cast<uint32_t>(phi_ids.size())) {
      // Not enough phi ids have been provided to account for the OpPhi
      // instructions.
      return false;
    }
    // Look for an instruction defining the next phi id.
    opt::Instruction* phi_extension =
        context->get_def_use_mgr()->GetDef(phi_ids[phi_index]);
    if (!phi_extension) {
      // The id given to extend this OpPhi does not exist.
      return false;
    }
    if (phi_extension->type_id() != inst.type_id()) {
      // The instruction given to extend this OpPhi either does not have a type
      // or its type does not match that of the OpPhi.
      return false;
    }

    if (context->get_instr_block(phi_extension)) {
      // The instruction defining the phi id has an associated block (i.e., it
      // is not a global value).  Check whether its definition dominates the
      // exit of |from_block|.
      auto dominator_analysis =
          context->GetDominatorAnalysis(bb_from->GetParent());
      if (!dominator_analysis->Dominates(phi_extension,
                                         bb_from->terminator())) {
        // The given id is no good as its definition does not dominate the exit
        // of |from_block|
        return false;
      }
    }
    phi_index++;
  }
  // Return false if not all of the ids for extending OpPhi instructions are
  // needed. This might turn out to be stricter than necessary; perhaps it would
  // be OK just to not use the ids in this case.
  return phi_index == static_cast<uint32_t>(phi_ids.size());
}

void AddUnreachableEdgeAndUpdateOpPhis(
    opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
    bool condition_value,
    const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids) {
  assert(PhiIdsOkForNewEdge(context, bb_from, bb_to, phi_ids) &&
         "Precondition on phi_ids is not satisfied");
  assert(bb_from->terminator()->opcode() == SpvOpBranch &&
         "Precondition on terminator of bb_from is not satisfied");

  // Get the id of the boolean constant to be used as the condition.
  opt::analysis::Bool bool_type;
  opt::analysis::BoolConstant bool_constant(
      context->get_type_mgr()->GetRegisteredType(&bool_type)->AsBool(),
      condition_value);
  uint32_t bool_id = context->get_constant_mgr()->FindDeclaredConstant(
      &bool_constant, context->get_type_mgr()->GetId(&bool_type));

  const bool from_to_edge_already_exists = bb_from->IsSuccessor(bb_to);
  auto successor = bb_from->terminator()->GetSingleWordInOperand(0);

  // Add the dead branch, by turning OpBranch into OpBranchConditional, and
  // ordering the targets depending on whether the given boolean corresponds to
  // true or false.
  bb_from->terminator()->SetOpcode(SpvOpBranchConditional);
  bb_from->terminator()->SetInOperands(
      {{SPV_OPERAND_TYPE_ID, {bool_id}},
       {SPV_OPERAND_TYPE_ID, {condition_value ? successor : bb_to->id()}},
       {SPV_OPERAND_TYPE_ID, {condition_value ? bb_to->id() : successor}}});

  // Update OpPhi instructions in the target block if this branch adds a
  // previously non-existent edge from source to target.
  if (!from_to_edge_already_exists) {
    uint32_t phi_index = 0;
    for (auto& inst : *bb_to) {
      if (inst.opcode() != SpvOpPhi) {
        break;
      }
      assert(phi_index < static_cast<uint32_t>(phi_ids.size()) &&
             "There should be exactly one phi id per OpPhi instruction.");
      inst.AddOperand({SPV_OPERAND_TYPE_ID, {phi_ids[phi_index]}});
      inst.AddOperand({SPV_OPERAND_TYPE_ID, {bb_from->id()}});
      phi_index++;
    }
    assert(phi_index == static_cast<uint32_t>(phi_ids.size()) &&
           "There should be exactly one phi id per OpPhi instruction.");
  }
}

bool BlockIsInLoopContinueConstruct(opt::IRContext* context, uint32_t block_id,
                                    uint32_t maybe_loop_header_id) {
  // We deem a block to be part of a loop's continue construct if the loop's
  // continue target dominates the block.
  auto containing_construct_block = context->cfg()->block(maybe_loop_header_id);
  if (containing_construct_block->IsLoopHeader()) {
    auto continue_target = containing_construct_block->ContinueBlockId();
    if (context->GetDominatorAnalysis(containing_construct_block->GetParent())
            ->Dominates(continue_target, block_id)) {
      return true;
    }
  }
  return false;
}

opt::BasicBlock::iterator GetIteratorForInstruction(
    opt::BasicBlock* block, const opt::Instruction* inst) {
  for (auto inst_it = block->begin(); inst_it != block->end(); ++inst_it) {
    if (inst == &*inst_it) {
      return inst_it;
    }
  }
  return block->end();
}

bool BlockIsReachableInItsFunction(opt::IRContext* context,
                                   opt::BasicBlock* bb) {
  auto enclosing_function = bb->GetParent();
  return context->GetDominatorAnalysis(enclosing_function)
      ->Dominates(enclosing_function->entry().get(), bb);
}

bool CanInsertOpcodeBeforeInstruction(
    SpvOp opcode, const opt::BasicBlock::iterator& instruction_in_block) {
  if (instruction_in_block->PreviousNode() &&
      (instruction_in_block->PreviousNode()->opcode() == SpvOpLoopMerge ||
       instruction_in_block->PreviousNode()->opcode() == SpvOpSelectionMerge)) {
    // We cannot insert directly after a merge instruction.
    return false;
  }
  if (opcode != SpvOpVariable &&
      instruction_in_block->opcode() == SpvOpVariable) {
    // We cannot insert a non-OpVariable instruction directly before a
    // variable; variables in a function must be contiguous in the entry block.
    return false;
  }
  // We cannot insert a non-OpPhi instruction directly before an OpPhi, because
  // OpPhi instructions need to be contiguous at the start of a block.
  return opcode == SpvOpPhi || instruction_in_block->opcode() != SpvOpPhi;
}

bool CanMakeSynonymOf(opt::IRContext* ir_context, opt::Instruction* inst) {
  if (!inst->HasResultId()) {
    // We can only make a synonym of an instruction that generates an id.
    return false;
  }
  if (!inst->type_id()) {
    // We can only make a synonym of an instruction that has a type.
    return false;
  }
  // We do not make synonyms of objects that have decorations: if the synonym is
  // not decorated analogously, using the original object vs. its synonymous
  // form may not be equivalent.
  return ir_context->get_decoration_mgr()
      ->GetDecorationsFor(inst->result_id(), true)
      .empty();
}

bool IsCompositeType(const opt::analysis::Type* type) {
  return type && (type->AsArray() || type->AsMatrix() || type->AsStruct() ||
                  type->AsVector());
}

std::vector<uint32_t> RepeatedFieldToVector(
    const google::protobuf::RepeatedField<uint32_t>& repeated_field) {
  std::vector<uint32_t> result;
  for (auto i : repeated_field) {
    result.push_back(i);
  }
  return result;
}

uint32_t WalkCompositeTypeIndices(
    opt::IRContext* context, uint32_t base_object_type_id,
    const google::protobuf::RepeatedField<google::protobuf::uint32>& indices) {
  uint32_t sub_object_type_id = base_object_type_id;
  for (auto index : indices) {
    auto should_be_composite_type =
        context->get_def_use_mgr()->GetDef(sub_object_type_id);
    assert(should_be_composite_type && "The type should exist.");
    if (SpvOpTypeArray == should_be_composite_type->opcode()) {
      auto array_length = GetArraySize(*should_be_composite_type, context);
      if (array_length == 0 || index >= array_length) {
        return 0;
      }
      sub_object_type_id = should_be_composite_type->GetSingleWordInOperand(0);
    } else if (SpvOpTypeMatrix == should_be_composite_type->opcode()) {
      auto matrix_column_count =
          should_be_composite_type->GetSingleWordInOperand(1);
      if (index >= matrix_column_count) {
        return 0;
      }
      sub_object_type_id = should_be_composite_type->GetSingleWordInOperand(0);
    } else if (SpvOpTypeStruct == should_be_composite_type->opcode()) {
      if (index >= GetNumberOfStructMembers(*should_be_composite_type)) {
        return 0;
      }
      sub_object_type_id =
          should_be_composite_type->GetSingleWordInOperand(index);
    } else if (SpvOpTypeVector == should_be_composite_type->opcode()) {
      auto vector_length = should_be_composite_type->GetSingleWordInOperand(1);
      if (index >= vector_length) {
        return 0;
      }
      sub_object_type_id = should_be_composite_type->GetSingleWordInOperand(0);
    } else {
      return 0;
    }
  }
  return sub_object_type_id;
}

uint32_t GetNumberOfStructMembers(
    const opt::Instruction& struct_type_instruction) {
  assert(struct_type_instruction.opcode() == SpvOpTypeStruct &&
         "An OpTypeStruct instruction is required here.");
  return struct_type_instruction.NumInOperands();
}

uint32_t GetArraySize(const opt::Instruction& array_type_instruction,
                      opt::IRContext* context) {
  auto array_length_constant =
      context->get_constant_mgr()
          ->GetConstantFromInst(context->get_def_use_mgr()->GetDef(
              array_type_instruction.GetSingleWordInOperand(1)))
          ->AsIntConstant();
  if (array_length_constant->words().size() != 1) {
    return 0;
  }
  return array_length_constant->GetU32();
}

bool IsValid(opt::IRContext* context) {
  std::vector<uint32_t> binary;
  context->module()->ToBinary(&binary, false);
  return SpirvTools(context->grammar().target_env()).Validate(binary);
}

std::unique_ptr<opt::IRContext> CloneIRContext(opt::IRContext* context) {
  std::vector<uint32_t> binary;
  context->module()->ToBinary(&binary, false);
  return BuildModule(context->grammar().target_env(), nullptr, binary.data(),
                     binary.size());
}

}  // namespace fuzzerutil

}  // namespace fuzz
}  // namespace spvtools


text:
package smile.validation;

/**
 * Fall-out, false alarm rate, or false positive rate (FPR)
 *

 * FPR = FP / N = FP / (FP + TN)
 *

 * Fall-out is actually Type I error and closely related to specificity
 * (1 - specificity).
 *
 * @author Haifeng Li
 */
public class Fallout implements ClassificationMeasure {

    @Override
    public double measure(int[] truth, int[] prediction) {
        if (truth.length != prediction.length) {
            throw new IllegalArgumentException(String.format("The vector sizes don't match: %d != %d.", truth.length, prediction.length));
        }

        int tn = 0;
        int n = 0;
        for (int i = 0; i < truth.length; i++) {
            if (truth[i] != 1) {
                n++;

                if (prediction[i] == truth[i]) {
                    tn++;
                }
            }
        }

        return 1.0 - (double) tn / n;
    }

    @Override
    public String toString() {
        return "Fall-out";
    }
}


text:
<?php
// Created: 2014
// Modified: 18 jan 2015

class QrController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('deny',  // deny all guest users
				'users'=>array('?'),),
			array(	'allow', // only when $_GET are set
					'actions'=>array('moveUpDown'),
					'expression'=> 'Qr::model()->isActionAllowed(
						Yii::app()->controller->id,
						Yii::app()->controller->action->id,
						$_GET["event_id"],
						$_GET["qr_id"],
						"",
						$_GET["date"],
						$_GET["volgorde"],
						$_GET["up_down"])'),
            array(	'allow', // allow admin user to perform 'viewplayers' actions
                    'actions'=>array('index', 'update', 'delete', 'create', 'report', 'createIntroductie'),
                    'expression'=> 'Qr::model()->isActionAllowed(
                        Yii::app()->controller->id,
                        Yii::app()->controller->action->id,
                        $_GET["event_id"])'),
			array('deny',  // deny all users
				'users'=>array('*'),),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model = new Qr;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Qr']))
		{

			$model->qr_code = Qr::model()->getUniqueQrCode();
			$model->event_ID = $_GET['event_id'];
			$model->route_ID = $_GET['route_id'];
			$model->qr_volgorde = Qr::model()->getNewOrderForQr($_GET['event_id'], $_GET['route_id']);
			$model->attributes=$_POST['Qr'];
			if($model->save())
				$this->redirect(array(
					'/route/view',
					'event_id'=>$model->event_ID,
					'route_id'=>$model->route_ID));
		}
		$this->layout='/layouts/column1';
		$this->render('create',
					  array('model'=>$model,
		));
	}

	public function actioncreateIntroductie()
	{
		$model = new Qr;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_GET['event_id']))
		{
			$model->qr_name = "Introductie";
			$model->qr_code = Qr::model()->getUniqueQrCode();
			$model->event_ID = $_GET['event_id'];
			$model->route_ID = Route::model()-> getIntroductieRouteId($_GET['event_id']);
			$model->qr_volgorde = Qr::model()->getNewOrderForIntroductieQr($_GET['event_id']);
			$model->score = 5;

			if($model->save());
			{
				$this->redirect(array('route/viewIntroductie','event_id'=>$_GET['event_id']));
			}
		}
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		$qr_id = $_GET['qr_id'];
		$model=$this->loadModel($qr_id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Qr']))
		{
			$model->attributes=$_POST['Qr'];
			if($model->save())
				if( Route::model()->routeIdIntroduction($model->route_ID) ){
					$this->redirect(array('/route/viewIntroductie',
							'route_id'=>$model->route_ID,
							'event_id'=>$model->event_ID));
				} else {
					$this->redirect(array('/route/view',
							'route_id'=>$model->route_ID,
							'event_id'=>$model->event_ID));
				}
		}
		$this->layout='/layouts/column1';
		$this->render('update',
					  array('model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		$qr_id = $_GET['qr_id'];
		try
		{
			$this->loadModel($qr_id)->delete();
		}
		catch(CDbException $e)
		{
			throw new CHttpException(400,"Je kan deze stille post niet verwijderen.");
		}

		if (Route::model()->routeIdIntroduction($_GET['route_id'])){
			$this->redirect(isset($_POST['returnUrl']) ?
					$_POST['returnUrl'] : array('/route/viewIntroductie',
									'event_id'=>$_GET['event_id'],
									'route_id'=>$_GET['route_id']));
		} else {
			$this->redirect(isset($_POST['returnUrl']) ?
					$_POST['returnUrl'] : array('/route/view',
									'event_id'=>$_GET['event_id'],
									'route_id'=>$_GET['route_id']));
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$event_id = $_GET['event_id'];
		$where = "event_ID = $event_id";

		$dataProvider=new CActiveDataProvider('Qr',
		    array(
			'criteria'=>array(
			    'condition'=>$where,
			    'order'=>'route_ID ASC, qr_volgorde ASC',
			    ),
			'pagination'=>array(
				'pageSize'=>15,
			),
		));

		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Qr('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Qr']))
			$model->attributes=$_GET['Qr'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	public function actionReport()
	{
		$id = $_GET['id'];
		$model=Qr::model()->findByPk($id);
		if ($model->qr_code == $_GET['qr_code'] and
			$model->event_ID == $_GET['event_id']) {
			$this->renderPartial("reportview", $id);
		}
		throw new CHttpException(404,'Ongeldige QR code, daarom kun je deze QR niet printen.');
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Qr the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Qr::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Qr $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='qr-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionMoveUpDown()
    {
		$event_id = $_GET['event_id'];
		$qr_id = $_GET['qr_id'];
		$qr_volgorde = $_GET['volgorde'];
		$up_down = $_GET['up_down'];
		$route_id = Qr::model()->getQrRouteID($qr_id);

		$currentModel = Qr::model()->findByPk($qr_id);

		$criteria = new CDbCriteria;

		if ($up_down=='up')
		{
			$criteria->condition = 'event_ID =:event_id AND
									qr_ID !=:id AND
									route_ID=:route_id AND
									qr_volgorde <=:order';
			$criteria->params=array(':event_id' => $event_id,
									':id' => $qr_id,
									':route_id' => $route_id ,
									':order' => $qr_volgorde);
			$criteria->order= 'qr_volgorde DESC';
		}
		if ($up_down=='down')
		{
			$criteria->condition = 'event_ID =:event_id AND
									qr_ID !=:id AND
								 	route_ID=:route_id AND
									qr_volgorde >:order';
			$criteria->params=array(':event_id' => $event_id,
									':id' => $qr_id,
									':route_id' => $route_id ,
									':order' => $qr_volgorde);
			$criteria->order= 'qr_volgorde ASC';
		}
			$criteria->limit=1;
		$previousModel = Qr::model()->find($criteria);

		$tempCurrentVolgorde = $currentModel->qr_volgorde;
		$currentModel->qr_volgorde = $previousModel->qr_volgorde;
		$previousModel->qr_volgorde = $tempCurrentVolgorde;

		$currentModel->save();
		$previousModel->save();

		if (Route::model()->routeIdIntroduction($currentModel->route_ID))
		{
			$this->redirect(array('route/viewIntroductie',
				"route_id"=>$currentModel->route_ID,
				"event_id"=>$currentModel->event_ID,));
		}
		else
		{
			$this->redirect(array('route/view',
				"route_id"=>$currentModel->route_ID,
				"event_id"=>$currentModel->event_ID,));
		}
	}
}


text:
#include "compressor.h"
#include "mldb/base/exc_assert.h"
#include <iostream>
#include <mutex>
#include <map>
#include <cstring>
#include "mldb/base/thread_pool.h"

using namespace std;

namespace MLDB {

/*****************************************************************************/
/* COMPRESSOR                                                                */
/*****************************************************************************/

Compressor::
~Compressor()
{
}

void
Compressor::
notifyInputSize(uint64_t inputSize)
{
}

namespace {

std::mutex mutex;
std::map<std::string, std::string> extensions;
std::map<std::string, Compressor::Info> compressors;
std::map<std::string, Decompressor::Info> decompressors;

} // file scope

std::string
Compressor::
filenameToCompression(const std::string & filename)
{
    std::unique_lock<std::mutex> guard(mutex);

    for (string::size_type pos = filename.rfind('.');
         pos != string::npos && pos > 0;
         pos = filename.rfind('.', pos - 1)) {

        std::string extension(filename, pos + 1);

        while (!extension.empty() && extension[extension.size() - 1] == '~') {
            extension = string(extension, 0, extension.size() - 1);
        }

        if (extension.empty())
            return std::string();

        auto it = extensions.find(extension);
        if (it != extensions.end()) {
            return it->second;
        }
    }

    return std::string();
}

Compressor *
Compressor::
create(const std::string & compression,
       int level)
{
    std::unique_lock<std::mutex> guard(mutex);
    auto it = compressors.find(compression);
    if (it == compressors.end()) {
        throw Exception("unknown compression %s:%d", compression.c_str(),
                        level);
    }
    return it->second.create(level);
}

std::shared_ptr<void>
Compressor::
registerCompressor(const std::string & name,
                   const std::vector<std::string> & compressorExtensions,
                   std::function<Compressor * (int level)> create)
{
    Info info{ name, compressorExtensions, std::move(create)};
    std::unique_lock<std::mutex> guard(mutex);
    if (!compressors.emplace(name, info).second) {
        throw Exception("Attempt to double register compressor " + name);
    }

    for (auto & ex: compressorExtensions) {
        extensions.emplace(ex, name);
    }

    return nullptr;
}

const Compressor::Info &
Compressor::
getCompressorInfo(const std::string & compressor)
{
    std::unique_lock<std::mutex> guard(mutex);
    auto it = compressors.find(compressor);
    if (it == compressors.end()) {
        throw Exception("Unknown compressor " + compressor);
    }
    return it->second;
}

/*****************************************************************************/
/* DECOMPRESSOR                                                              */
/*****************************************************************************/

Decompressor::
~Decompressor()
{
}

void
Decompressor::
decompress(std::shared_ptr<const char> data, size_t len,
           const OnSharedData & onSharedData,
           const Allocate & allocate)
{
    auto onData = [&] (const char * p, size_t len)
        {
            auto block = allocate(len);
            std::memcpy(block.get(), p, len);
            onSharedData(std::move(block), len);
            return len;
        };

    decompress(data.get(), len, onData);
}

void
Decompressor::
finish(const OnSharedData & onSharedData,
       const Allocate & allocate)
{
    auto onData = [&] (const char * p, size_t len)
        {
            auto block = allocate(len);
            std::memcpy(block.get(), p, len);
            onSharedData(std::move(block), len);
            return len;
        };

    finish(onData);
}

bool
Decompressor::
forEachBlockParallel(size_t requestedBlockSize,
                     const GetDataFunction & getData,
                     const ForEachBlockFunction & onBlock,
                     const Allocate & allocate,
                     int maxParallelism)
{
    bool finished = false;
    size_t blockNumber = 0;
    size_t currentOffset = 0;
    size_t numChars = 0;
    std::shared_ptr<const char> buf;

    ThreadWorkGroup tp(maxParallelism);

    while (std::get<0>((std::tie(buf, numChars) = getData(requestedBlockSize)))) {
        auto onData = [&] (std::shared_ptr<const char> data, size_t len) -> size_t
            {
                if (finished)
                    return len;

                size_t myBlockNumber = blockNumber++;
                size_t myOffset = currentOffset;

                auto doBlock = [myBlockNumber, myOffset, data = std::move(data),
                                len, &finished, &onBlock] ()
                {
                    if (finished)
                        return;
                    if (!onBlock(myBlockNumber, myOffset, std::move(data), len)) {
                        finished = true;
                    }
                };

                if (maxParallelism > 0) {
                    tp.add(std::move(doBlock));
                }
                else {
                    doBlock();
                }

                currentOffset += len;
                return len;
            };

        decompress(buf, numChars, onData, allocate);
    }

    tp.waitForAll();

    return !finished;
}

Decompressor *
Decompressor::
create(const std::string & decompression)
{
    std::unique_lock<std::mutex> guard(mutex);
    auto it = decompressors.find(decompression);
    if (it == decompressors.end()) {
        throw Exception("unknown decompression %s", decompression.c_str());
    }
    return it->second.create();
}

std::shared_ptr<void>
Decompressor::
registerDecompressor(const std::string & name,
                     const std::vector<std::string> & compressorExtensions,
                     std::function<Decompressor * ()> create)
{
    Info info{ name, compressorExtensions, std::move(create)};
    std::unique_lock<std::mutex> guard(mutex);
    if (!decompressors.emplace(name, info).second) {
        throw Exception("Attempt to double register compressor " + name);
    }

    for (auto & ex: compressorExtensions) {
        extensions.emplace(ex, name);
    }

    return nullptr;
}

const Decompressor::Info &
Decompressor::
getDecompressorInfo(const std::string & decompressor)
{
    std::unique_lock<std::mutex> guard(mutex);
    auto it = decompressors.find(decompressor);
    if (it == decompressors.end()) {
        throw Exception("Unknown decompressor " + decompressor);
    }
    return it->second;
}

/*****************************************************************************/
/* NULL COMPRESSOR                                                           */
/*****************************************************************************/

struct NullCompressor : public Compressor {

    NullCompressor(int level = 0);

    virtual ~NullCompressor();

    virtual void compress(const char * data, size_t len,
                          const OnData & onData) override;

    virtual void flush(FlushLevel flushLevel, const OnData & onData) override;

    virtual void finish(const OnData & onData) override;
};

NullCompressor::
NullCompressor(int level)
{
}

NullCompressor::
~NullCompressor()
{
}

void
NullCompressor::
compress(const char * data, size_t len, const OnData & onData)
{
    size_t done = 0;

    while (done < len)
        done += onData(data + done, len - done);

    ExcAssertEqual(done, len);
}

void
NullCompressor::
flush(FlushLevel flushLevel, const OnData & onData)
{
}

void
NullCompressor::
finish(const OnData & onData)
{
}

static Compressor::Register<NullCompressor>
registerNullCompressor("null", {});
static Compressor::Register<NullCompressor>
registerNoneCompressor("none", {});

/*****************************************************************************/
/* NULL DECOMPRESSOR                                                           */
/*****************************************************************************/

struct NullDecompressor : public Decompressor {

    virtual ~NullDecompressor();

    virtual int64_t decompressedSize(const char * block, size_t blockLen,
                                     int64_t totalLen) const override;

    virtual void decompress(const char * data, size_t len,
                              const OnData & onData) override;

    virtual void finish(const OnData & onData) override;

    using Decompressor::decompress;
    using Decompressor::finish;
};

NullDecompressor::
~NullDecompressor()
{
}

int64_t
NullDecompressor::
decompressedSize(const char * block, size_t blockLen,
                 int64_t totalLen) const
{
    return totalLen;
}

void
NullDecompressor::
decompress(const char * data, size_t len, const OnData & onData)
{
    size_t done = 0;

    while (done < len)
        done += onData(data + done, len - done);

    ExcAssertEqual(done, len);
}

void
NullDecompressor::
finish(const OnData & onData)
{
}

static Decompressor::Register<NullDecompressor>
registerNullDecompressor("null", {});
static Decompressor::Register<NullDecompressor>
registerNoneDecompressor("none", {});

} // namespace MLDB


text:
/*
	vgareg.h : VGA register operations.
	(C)2012-2013 Marisa Kirisame, UnSX Team.
	Part of AliceOS, the Alice Operating System.
	Released under the MIT License.
*/
/* Attribute Controller ports */
#define VGA_AC_I 0x3C0 /* Address */
#define VGA_AC_W 0x3C0 /* Write */
#define VGA_AC_R 0x3C1 /* Read */
/* Attribute Controller registers */
#define VGA_AC_PAL0 0x00 /* Palette Index 0 */
#define VGA_AC_PAL1 0x01 /* Palette Index 1 */
#define VGA_AC_PAL2 0x02 /* Palette Index 2 */
#define VGA_AC_PAL3 0x03 /* Palette Index 3 */
#define VGA_AC_PAL4 0x04 /* Palette Index 4 */
#define VGA_AC_PAL5 0x05 /* Palette Index 5 */
#define VGA_AC_PAL6 0x06 /* Palette Index 6 */
#define VGA_AC_PAL7 0x07 /* Palette Index 7 */
#define VGA_AC_PAL8 0x08 /* Palette Index 8 */
#define VGA_AC_PAL9 0x09 /* Palette Index 9 */
#define VGA_AC_PALA 0x0A /* Palette Index A */
#define VGA_AC_PALB 0x0B /* Palette Index B */
#define VGA_AC_PALC 0x0C /* Palette Index C */
#define VGA_AC_PALD 0x0D /* Palette Index D */
#define VGA_AC_PALE 0x0E /* Palette Index E */
#define VGA_AC_PALF 0x0F /* Palette Index F */
#define VGA_AC_ATRM 0x10 /* Attribute Mode Control */
#define VGA_AC_OVSC 0x11 /* Overscan Color */
#define VGA_AC_CPLE 0x12 /* Color Plane Enable */
#define VGA_AC_HPXP 0x13 /* Horizontal Pixel Panning */
#define VGA_AC_PXSC 0x14 /* Color Select */
/* DAC ports */
#define VGA_DAC_ADWM 0x3C8 /* Address Write Mode */
#define VGA_DAC_ADRM 0x3C7 /* Address Read Mode */
#define VGA_DAC_DATA 0x3C9 /* Data */
#define VGA_DAC_STAT 0x3C7 /* State */
/* Sequencer address port (add 1 for data port) */
#define VGA_SEQ 0x3C4
/* Sequencer registers */
#define VGA_SEQ_RESET 0x00 /* Reset */
#define VGA_SEQ_CMODE 0x01 /* Clocking Mode */
#define VGA_SEQ_MMASK 0x02 /* Map Mask */
#define VGA_SEQ_CMSEL 0x03 /* Character Map Select */
#define VGA_SEQ_SMMOD 0x04 /* Sequencer Memory Mode */
/* Graphics Controller address port (add 1 for data port */
#define VGA_GC 0x3CE
/* Grapcis Controller registers */
#define VGA_GC_SETRST 0x00 /* Set/Reset */
#define VGA_GC_ESTRST 0x01 /* Enable Set/Reset */
#define VGA_GC_CLRCMP 0x02 /* Color Compare */
#define VGA_GC_DATROT 0x03 /* Data Rotate */
#define VGA_GC_RDMSEL 0x04 /* Read Map Select */
#define VGA_GC_GFXMOD 0x05 /* Graphics Mode */
#define VGA_GC_MSCGFX 0x06 /* Miscellaneous Graphics */
#define VGA_GC_CDNTCR 0x07 /* Color Don't Care */
#define VGA_GC_BTMASK 0x08 /* Bit Mask */
/* CRT Controller address port (add 1 for data port) */
#define VGA_CRTC 0x3D4
/* CRT Controller registers */
#define VGA_CRTC_HTOTAL 0x00 /* Horizontal Total */
#define VGA_CRTC_EHDISP 0x01 /* End Horizontal Display */
#define VGA_CRTC_SHBLNK 0x02 /* Start Horizontal Blanking */
#define VGA_CRTC_EHBLNK 0x03 /* End Horizontal Blanking */
#define VGA_CRTC_SHRTRC 0x04 /* Start Horizontal Retrace */
#define VGA_CRTC_EHRTRC 0x05 /* End Horizontal Retrace */
#define VGA_CRTC_VTOTAL 0x06 /* Vertical Total */
#define VGA_CRTC_OVRFLW 0x07 /* Overflow */
#define VGA_CRTC_PTRWSC 0x08 /* Preset Row Scan */
#define VGA_CRTC_MXSCLN 0x09 /* Maximum Scan Line */
#define VGA_CRTC_CSRSTR 0x0A /* Cursor Start */
#define VGA_CRTC_CSREND 0x0B /* Cursor End */
#define VGA_CRTC_STADRH 0x0C /* Start Address High */
#define VGA_CRTC_STADRL 0x0D /* Start Address Low */
#define VGA_CRTC_CSRLCH 0x0E /* Cursor Location High */
#define VGA_CRTC_CSRLCL 0x0F /* Cursor Location Low */
#define VGA_CRTC_VTRTST 0x10 /* Vertical Retrace Start */
#define VGA_CRTC_VTRTEN 0x11 /* Vertical Retrace End */
#define VGA_CRTC_VDSPEN 0x12 /* Vertical Display End */
#define VGA_CRTC_OFFSET 0x13 /* Offset */
#define VGA_CRTC_ULNLOC 0x14 /* Underline Location */
#define VGA_CRTC_SVBLNK 0x15 /* Start Vertical Blanking */
#define VGA_CRTC_EVBLNK 0x16 /* End Vertical Blanking */
#define VGA_CRTC_CRTCMC 0x17 /* CRTC Mode Control */
#define VGA_CRTC_LNCOMP 0x18 /* Line Compare */
/* Miscellaneous Output ports */
#define VGA_MSCOUTR 0x3CC /* Read */
#define VGA_MSCOUTW 0x3C2 /* Write */
/* Feature Control ports */
#define VGA_FTCNTLR 0x3CA /* Read */
#define VGA_FTCNTLW 0x3DA /* Write */
/* Input Status ports */
#define VGA_INSTAT0 0x3C2 /* 0 */
#define VGA_INSTAT1 0x3DA /* 1 */
/* set the value of a VGA register, return previous value */
uint8_t setvgareg( uint16_t port, uint8_t index, uint8_t value );
/* get the value of a VGA register */
uint8_t getvgareg( uint16_t port, uint8_t index );


text:
#include <windows.h>

#include "layout/LETypes.h"
#include "layout/LESwaps.h"
#include "layout/LEFontInstance.h"

#include "GDIFontInstance.h"
#include "sfnt.h"
#include "cmaps.h"

GDISurface::GDISurface(HDC theHDC)
    : fHdc(theHDC), fCurrentFont(NULL)
{
    // nothing else to do
}

GDISurface::~GDISurface()
{
    // nothing to do
}

void GDISurface::setHDC(HDC theHDC)
{
    fHdc         = theHDC;
    fCurrentFont = NULL;
}

void GDISurface::setFont(const GDIFontInstance *font)
{
#if 0
    if (fCurrentFont != font) {
        fCurrentFont = font;
        SelectObject(fHdc, font->getFont());
    }
#else
    SelectObject(fHdc, font->getFont());
#endif
}

void GDISurface::drawGlyphs(const LEFontInstance *font, const LEGlyphID *glyphs, le_int32 count, const float *positions,
    le_int32 x, le_int32 y, le_int32 width, le_int32 height)
{
    TTGlyphID *ttGlyphs = LE_NEW_ARRAY(TTGlyphID, count);
    le_int32  *dx = LE_NEW_ARRAY(le_int32, count);
    float     *ps = LE_NEW_ARRAY(float, count * 2 + 2);
    le_int32   out = 0;
    RECT clip;

    clip.top    = 0;
    clip.left   = 0;
    clip.bottom = height;
    clip.right  = width;

    for (le_int32 g = 0; g < count; g += 1) {
        TTGlyphID ttGlyph = (TTGlyphID) LE_GET_GLYPH(glyphs[g]);

        if (ttGlyph < 0xFFFE) {
            ttGlyphs[out] = ttGlyph;
            dx[out] = (le_int32) (positions[g * 2 + 2] - positions[g * 2]);
            ps[out * 2] = positions[g * 2];
            ps[out * 2 + 1] = positions[g * 2 + 1];
            out += 1;
        }
    }

    le_int32 dyStart, dyEnd;

    setFont((GDIFontInstance *) font);

    dyStart = dyEnd = 0;

    while (dyEnd < out) {
        float yOffset = ps[dyStart * 2 + 1];
        float xOffset = ps[dyStart * 2];

        while (dyEnd < out && yOffset == ps[dyEnd * 2 + 1]) {
            dyEnd += 1;
        }

        ExtTextOut(fHdc, x + (le_int32) xOffset, y + (le_int32) yOffset - font->getAscent(), ETO_CLIPPED | ETO_GLYPH_INDEX, &clip,
            (LPCWSTR) &ttGlyphs[dyStart], dyEnd - dyStart, (INT *) &dx[dyStart]);

        dyStart = dyEnd;
    }

    LE_DELETE_ARRAY(ps);
    LE_DELETE_ARRAY(dx);
    LE_DELETE_ARRAY(ttGlyphs);
}

GDIFontInstance::GDIFontInstance(GDISurface *surface, TCHAR *faceName, le_int16 pointSize, LEErrorCode &status)
    : FontTableCache(), fSurface(surface), fFont(NULL),
      fPointSize(pointSize), fUnitsPerEM(0), fAscent(0), fDescent(0), fLeading(0),
      fDeviceScaleX(1), fDeviceScaleY(1), fMapper(NULL)
{
    LOGFONT lf;
    FLOAT dpiX, dpiY;
    POINT pt;
    OUTLINETEXTMETRIC otm;
    HDC hdc = surface->getHDC();

    if (LE_FAILURE(status)) {
        return;
    }

    SaveDC(hdc);

    SetGraphicsMode(hdc, GM_ADVANCED);
    ModifyWorldTransform(hdc, NULL, MWT_IDENTITY);
    SetViewportOrgEx(hdc, 0, 0, NULL);
    SetWindowOrgEx(hdc, 0, 0, NULL);

    dpiX = (FLOAT) GetDeviceCaps(hdc, LOGPIXELSX);
    dpiY = (FLOAT) GetDeviceCaps(hdc, LOGPIXELSY);

#if 1
    pt.x = (int) (pointSize * dpiX / 72);
    pt.y = (int) (pointSize * dpiY / 72);

    DPtoLP(hdc, &pt, 1);
#else
    pt.x = pt.y = pointSize;
#endif

    lf.lfHeight = - pt.y;
    lf.lfWidth = 0;
    lf.lfEscapement = 0;
    lf.lfOrientation = 0;
    lf.lfWeight = 0;
    lf.lfItalic = 0;
    lf.lfUnderline = 0;
    lf.lfStrikeOut = 0;
    lf.lfCharSet = DEFAULT_CHARSET;
    lf.lfOutPrecision = 0;
    lf.lfClipPrecision = 0;
    lf.lfQuality = 0;
    lf.lfPitchAndFamily = 0;

    lstrcpy(lf.lfFaceName, faceName);

    fFont = CreateFontIndirect(&lf);

    if (fFont == NULL) {
        status = LE_FONT_FILE_NOT_FOUND_ERROR;
        return;
    }

    SelectObject(hdc, fFont);

    UINT ret = GetOutlineTextMetrics(hdc, sizeof otm, &otm);

    if (ret == 0) {
        status = LE_MISSING_FONT_TABLE_ERROR;
        goto restore;
    }

    fUnitsPerEM = otm.otmEMSquare;
    fAscent  = otm.otmTextMetrics.tmAscent;
    fDescent = otm.otmTextMetrics.tmDescent;
    fLeading = otm.otmTextMetrics.tmExternalLeading;

    status = initMapper();

    if (LE_FAILURE(status)) {
        goto restore;
    }

#if 0
    status = initFontTableCache();
#endif

restore:
    RestoreDC(hdc, -1);
}

GDIFontInstance::GDIFontInstance(GDISurface *surface, const char *faceName, le_int16 pointSize, LEErrorCode &status)
    : FontTableCache(), fSurface(surface), fFont(NULL),
      fPointSize(pointSize), fUnitsPerEM(0), fAscent(0), fDescent(0), fLeading(0),
      fDeviceScaleX(1), fDeviceScaleY(1), fMapper(NULL)
{
    LOGFONTA lf;
    FLOAT dpiX, dpiY;
    POINT pt;
    OUTLINETEXTMETRIC otm;
    HDC hdc = surface->getHDC();

    if (LE_FAILURE(status)) {
        return;
    }

    SaveDC(hdc);

    SetGraphicsMode(hdc, GM_ADVANCED);
    ModifyWorldTransform(hdc, NULL, MWT_IDENTITY);
    SetViewportOrgEx(hdc, 0, 0, NULL);
    SetWindowOrgEx(hdc, 0, 0, NULL);

    dpiX = (FLOAT) GetDeviceCaps(hdc, LOGPIXELSX);
    dpiY = (FLOAT) GetDeviceCaps(hdc, LOGPIXELSY);

    fDeviceScaleX = dpiX / 72;
    fDeviceScaleY = dpiY / 72;

#if 1
    pt.x = (int) (pointSize * fDeviceScaleX);
    pt.y = (int) (pointSize * fDeviceScaleY);

    DPtoLP(hdc, &pt, 1);
#else
    pt.x = pt.y = pointSize;
#endif

    lf.lfHeight = - pt.y;
    lf.lfWidth = 0;
    lf.lfEscapement = 0;
    lf.lfOrientation = 0;
    lf.lfWeight = 0;
    lf.lfItalic = 0;
    lf.lfUnderline = 0;
    lf.lfStrikeOut = 0;
    lf.lfCharSet = DEFAULT_CHARSET;
    lf.lfOutPrecision = 0;
    lf.lfClipPrecision = 0;
    lf.lfQuality = 0;
    lf.lfPitchAndFamily = 0;

    strcpy(lf.lfFaceName, faceName);

    fFont = CreateFontIndirectA(&lf);

    if (fFont == NULL) {
        status = LE_FONT_FILE_NOT_FOUND_ERROR;
        return;
    }

    SelectObject(hdc, fFont);

    UINT ret = GetOutlineTextMetrics(hdc, sizeof otm, &otm);

    if (ret != 0) {
        fUnitsPerEM = otm.otmEMSquare;
        fAscent  = otm.otmTextMetrics.tmAscent;
        fDescent = otm.otmTextMetrics.tmDescent;
        fLeading = otm.otmTextMetrics.tmExternalLeading;
    } else {
        const HEADTable *headTable = NULL;
        const HHEATable *hheaTable = NULL;

        // read unitsPerEm from 'head' table
        headTable = (const HEADTable *) readFontTable(LE_HEAD_TABLE_TAG);

        if (headTable == NULL) {
            status = LE_MISSING_FONT_TABLE_ERROR;
            goto restore;
        }

        fUnitsPerEM   = SWAPW(headTable->unitsPerEm);
        freeFontTable((const void *)headTable);

        hheaTable = (HHEATable *) readFontTable(LE_HHEA_TABLE_TAG);

        if (hheaTable == NULL) {
            status = LE_MISSING_FONT_TABLE_ERROR;
            goto restore;
        }

        fAscent  = (le_int32) yUnitsToPoints((float) SWAPW(hheaTable->ascent));
        fDescent = (le_int32) yUnitsToPoints((float) SWAPW(hheaTable->descent));
        fLeading = (le_int32) yUnitsToPoints((float) SWAPW(hheaTable->lineGap));

        freeFontTable((const void *) hheaTable);
    }

    status = initMapper();

    if (LE_FAILURE(status)) {
        goto restore;
    }

#if 0
    status = initFontTableCache();
#endif

restore:
    RestoreDC(hdc, -1);
}

GDIFontInstance::~GDIFontInstance()
{
#if 0
    flushFontTableCache();
    delete[] fTableCache;
#endif

    if (fFont != NULL) {
        // FIXME: call RemoveObject first?
        DeleteObject(fFont);
    }

    delete fMapper;
    fMapper = NULL;
}

LEErrorCode GDIFontInstance::initMapper()
{
    LETag cmapTag = LE_CMAP_TABLE_TAG;
    const CMAPTable *cmap = (const CMAPTable *) readFontTable(cmapTag);

    if (cmap == NULL) {
        return LE_MISSING_FONT_TABLE_ERROR;
    }

    fMapper = CMAPMapper::createUnicodeMapper(cmap);

    if (fMapper == NULL) {
        return LE_MISSING_FONT_TABLE_ERROR;
    }

    return LE_NO_ERROR;
}

const void *GDIFontInstance::getFontTable(LETag tableTag) const
{
    return FontTableCache::find(tableTag);
}

const void *GDIFontInstance::readFontTable(LETag tableTag) const
{
    fSurface->setFont(this);

    HDC   hdc    = fSurface->getHDC();
    DWORD stag   = SWAPL(tableTag);
    DWORD len    = GetFontData(hdc, stag, 0, NULL, 0);
    void *result = NULL;

    if (len != GDI_ERROR) {
        result = LE_NEW_ARRAY(char, len);
        GetFontData(hdc, stag, 0, result, len);
    }

    return result;
}

void GDIFontInstance::getGlyphAdvance(LEGlyphID glyph, LEPoint &advance) const
{
    advance.fX = 0;
    advance.fY = 0;

    if (glyph == 0xFFFE || glyph == 0xFFFF) {
        return;
    }

    GLYPHMETRICS metrics;
    DWORD result;
    MAT2 identity = {{0, 1}, {0, 0}, {0, 0}, {0, 1}};
    HDC hdc = fSurface->getHDC();

    fSurface->setFont(this);

    result = GetGlyphOutline(hdc, glyph, GGO_GLYPH_INDEX | GGO_METRICS, &metrics, 0, NULL, &identity);

    if (result == GDI_ERROR) {
        return;
    }

    advance.fX = metrics.gmCellIncX;
    return;
}

le_bool GDIFontInstance::getGlyphPoint(LEGlyphID glyph, le_int32 pointNumber, LEPoint &point) const
{
#if 0
    hsFixedPoint2 pt;
    le_bool result;

    result = fFontInstance->getGlyphPoint(glyph, pointNumber, pt);

    if (result) {
        point.fX = xUnitsToPoints(pt.fX);
        point.fY = yUnitsToPoints(pt.fY);
    }

    return result;
#else
    return FALSE;
#endif
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.wikidata.wdtk</groupId>
    <artifactId>wdtk-parent</artifactId>
    <version>0.5.0-SNAPSHOT</version>
  </parent>
  <artifactId>wdtk-enums</artifactId>
</project>


text:
package vos;

import org.codehaus.jackson.annotate.JsonProperty;

public class Restaurante {

	//// Atributos

	/**
	 * Nombre del usuario
	 */
	@JsonProperty(value = "id")
	private Long id;

	/**
	 * Identificador del usuario
	 */
	@JsonProperty(value = "nombre")
	private String nombre;

	/**
	 * Identificador del usuario
	 */
	@JsonProperty(value = "tipo")
	private String tipo;

	/**
	 * Correo electronico del usuario
	 */
	@JsonProperty(value = "representante")
	private String representante;

	/**
	 * Rol del usuario
	 */
	@JsonProperty(value = "paginaWeb")
	private String paginaWeb;

	/**
	 * Pass del usuario
	 */
	@JsonProperty(value = "balancePrecio")
	private Double balancePrecio;

	/**
	 * Pass del usuario
	 */
	@JsonProperty(value = "balanceCosto")
	private Double balanceCosto;

	/**
	 * Pass del usuario
	 */
	@JsonProperty(value = "usuario")
	private String usuario;

	/**
	 * Pass del usuario
	 */
	@JsonProperty(value = "nombreZona")
	private String nombreZona;

	/**
	 * Metodo constructor de la clase video
	 * <b>post: </b> Crea el video con los valores que entran como parametro
	 * @param id - Id del video.
	 * @param name - Nombre del video. name != null
	 * @param duration - Duracion en minutos del video.
	 */
	public Restaurante(@JsonProperty(value="id")Long id, @JsonProperty(value="nombre")String nombre,@JsonProperty(value="tipo")String tipo,
			@JsonProperty(value = "representante") String representante, @JsonProperty(value="paginaWeb")String paginaWeb,
			@JsonProperty(value="balancePrecio")Double balancePrecio, @JsonProperty(value="balanceCosto")Double balanceCosto,
			@JsonProperty(value="usuario")String usuario, @JsonProperty(value="nombreZona")String nombreZona ) {
		super();
		this.id = id;
		this.nombre = nombre;
		this.representante= representante;
		this.paginaWeb = paginaWeb;
		this.balancePrecio = balancePrecio;
		this.balanceCosto = balanceCosto;
		this.usuario = usuario;
		this.nombreZona = nombreZona;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

	public String getTipo() {
		return tipo;
	}

	public void setTipo(String tipo) {
		this.tipo = tipo;
	}

	public String getRepresentante() {
		return representante;
	}

	public void setRepresentante(String representante) {
		this.representante = representante;
	}

	public String getPaginaWeb() {
		return paginaWeb;
	}

	public void setPaginaWeb(String paginaWeb) {
		this.paginaWeb = paginaWeb;
	}

	public Double getBalancePrecio() {
		return balancePrecio;
	}

	public void setBalancePrecio(Double balancePrecio) {
		this.balancePrecio = balancePrecio;
	}

	public Double getBalanceCosto() {
		return balanceCosto;
	}

	public void setBalanceCosto(Double balanceCosto) {
		this.balanceCosto = balanceCosto;
	}

	public String getUsuario() {
		return usuario;
	}

	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}

	public String getNombreZona() {
		return nombreZona;
	}

	public void setNombreZona(String nombreZona) {
		this.nombreZona = nombreZona;
	}

}


text:
const {
  jsExtensions,
  tsExtensions,
  platformSubextensions,
  computeExpoExtensions,
} = require('./shared/extensions');

const allExtensions = computeExpoExtensions(
  [...jsExtensions, ...tsExtensions],
  platformSubextensions
);

module.exports = {
  extends: [
    './shared/core.js',
    './shared/typescript.js',
    './shared/react.js',
    './shared/prettier.js',
  ],
  globals: {
    __DEV__: false,
    Atomics: false,
    ErrorUtils: false,
    FormData: false,
    SharedArrayBuffer: false,
    XMLHttpRequest: false,
    alert: false,
    cancelAnimationFrame: false,
    cancelIdleCallback: false,
    clearImmediate: false,
    clearInterval: false,
    clearTimeout: false,
    fetch: false,
    navigator: false,
    process: false,
    requestAnimationFrame: false,
    requestIdleCallback: false,
    setImmediate: false,
    setInterval: false,
    setTimeout: false,
    window: false,
  },
  settings: {
    'import/extensions': allExtensions,
    'import/resolver': {
      node: { extensions: allExtensions },
    },
  },
  overrides: [
    {
      files: ['*.web.*'],
      env: { browser: true },
    },
  ],
};


text:
import Comment from '../models/comment';

class CommentCtrl {

  async get(request, reply) {
    const comment = await Comment.get(request.params.id).getJoin().run();
    reply(comment);
  }

  async create(request, reply) {
    const comment = await new Comment({
      body: request.payload.body,
      postId: request.params.id,
      accountId: request.auth.credentials.account.id
    }).save();

    reply(comment).code(201);
  }

  async update(request, reply) {
    const comment = await Comment.get(request.params.id).run();

    if (request.payload.body) {
      comment.body = request.payload.body;
    }

    reply(await comment.save());
  }

  async delete(request, reply) {
    const comment = await Comment.get(request.params.id).run();
    await comment.deleteAll();
    reply().code(204);
  }

}

export default CommentCtrl;


text:
/*添加收藏*/
function addFavorite(name, site) {
	try { window.external.addFavorite(site, name) } catch(e) {
		try { window.sidebar.addPanel(name, site, "") } catch(e) { alert("加入收藏失败,请使用Ctrl+D进行添加") }
	}
}

$(document).ready(function () {
    /*通过地址栏url激活菜单状态*/
    $(".w_menu li a").each(function () {
        if (String(window.location).startWith($($(this))[0].href)) {
            $(this).removeAttr("data-hover");
            $(this).parent().addClass('active').siblings().removeClass("active");
        }
    });
})

String.prototype.startWith=function(str){
    var reg=new RegExp("^"+str);
    return reg.test(this);
}


text:
#include "local.h"

/* Module (global) data. Placed in struct to be easier to find by GDB. Must
 * be global as several c-files belonging to the same module shares this */
struct mlistmod_struct mlistmod_data = {
    .isinit = 0,
    .nlists = 0,
    .mlists = NULL,
};

struct mlistmod_settings mlistmod_settings = {
    .isinit = 0,
    .debuglevel = -1,
    .verbose = 0,
};


text:
local KeyPressed = class("KeyPressed")

function KeyPressed:initialize(key, isrepeat)
    self.key = key
    self.isrepeat = isrepeat
end

return KeyPressed