text:
#include "SkCanvasStateUtils.h"

#include "SkBitmapDevice.h"
#include "SkCanvas.h"
#include "SkCanvasStack.h"
#include "SkErrorInternals.h"
#include "SkWriter32.h"

#define CANVAS_STATE_VERSION 1
/*
 * WARNING: The structs below are part of a stable ABI and as such we explicitly
 * use unambigious primitives (e.g. int32_t instead of an enum).
 *
 * ANY CHANGES TO THE STRUCTS BELOW THAT IMPACT THE ABI SHOULD RESULT IN AN
 * UPDATE OF THE CANVAS_STATE_VERSION. SUCH CHANGES SHOULD ONLY BE MADE IF
 * ABSOLUTELY NECESSARY!
 */
enum RasterConfigs {
  kUnknown_RasterConfig   = 0,
  kRGB_565_RasterConfig   = 1,
  kARGB_8888_RasterConfig = 2
};
typedef int32_t RasterConfig;

enum CanvasBackends {
    kUnknown_CanvasBackend = 0,
    kRaster_CanvasBackend  = 1,
    kGPU_CanvasBackend     = 2,
    kPDF_CanvasBackend     = 3
};
typedef int32_t CanvasBackend;

struct ClipRect {
    int32_t left, top, right, bottom;
};

struct SkMCState {
    float matrix[9];
    // NOTE: this only works for non-antialiased clips
    int32_t clipRectCount;
    ClipRect* clipRects;
};

// NOTE: If you add more members, bump CanvasState::version.
struct SkCanvasLayerState {
    CanvasBackend type;
    int32_t x, y;
    int32_t width;
    int32_t height;

    SkMCState mcState;

    union {
        struct {
            RasterConfig config; // pixel format: a value from RasterConfigs.
            size_t rowBytes;     // Number of bytes from start of one line to next.
            void* pixels;        // The pixels, all (height * rowBytes) of them.
        } raster;
        struct {
            int32_t textureID;
        } gpu;
    };
};

class SkCanvasState {
public:
    SkCanvasState(SkCanvas* canvas) {
        SkASSERT(canvas);
        version = CANVAS_STATE_VERSION;
        width = canvas->getDeviceSize().width();
        height = canvas->getDeviceSize().height();
        layerCount = 0;
        layers = NULL;
        originalCanvas = SkRef(canvas);

        mcState.clipRectCount = 0;
        mcState.clipRects = NULL;
    }

    ~SkCanvasState() {
        // loop through the layers and free the data allocated to the clipRects
        for (int i = 0; i < layerCount; ++i) {
            sk_free(layers[i].mcState.clipRects);
        }

        sk_free(mcState.clipRects);
        sk_free(layers);

        // it is now safe to free the canvas since there should be no remaining
        // references to the content that is referenced by this canvas (e.g. pixels)
        originalCanvas->unref();
    }

    /**
     * The version this struct was built with.  This field must always appear
     * first in the struct so that when the versions don't match (and the
     * remaining contents and size are potentially different) we can still
     * compare the version numbers.
     */
    int32_t version;

    int32_t width;
    int32_t height;

    SkMCState mcState;

    int32_t layerCount;
    SkCanvasLayerState* layers;

private:
    SkCanvas* originalCanvas;
};

////////////////////////////////////////////////////////////////////////////////

class ClipValidator : public SkCanvas::ClipVisitor {
public:
    ClipValidator() : fFailed(false) {}
    bool failed() { return fFailed; }

    // ClipVisitor
    virtual void clipRect(const SkRect& rect, SkRegion::Op op, bool antialias) SK_OVERRIDE {
        fFailed |= antialias;
    }

    virtual void clipPath(const SkPath&, SkRegion::Op, bool antialias) SK_OVERRIDE {
        fFailed |= antialias;
    }

private:
    bool fFailed;
};

static void setup_MC_state(SkMCState* state, const SkMatrix& matrix, const SkRegion& clip) {
    // initialize the struct
    state->clipRectCount = 0;

    // capture the matrix
    for (int i = 0; i < 9; i++) {
        state->matrix[i] = matrix.get(i);
    }

    /*
     * capture the clip
     *
     * storage is allocated on the stack for the first 4 rects. This value was
     * chosen somewhat arbitrarily, but does allow us to represent simple clips
     * and some more common complex clips (e.g. a clipRect with a sub-rect
     * clipped out of its interior) without needing to malloc any additional memory.
     */
    const int clipBufferSize = 4 * sizeof(ClipRect);
    char clipBuffer[clipBufferSize];
    SkWriter32 clipWriter(sizeof(ClipRect), clipBuffer, clipBufferSize);

    if (!clip.isEmpty()) {
        // only returns the b/w clip so aa clips fail
        SkRegion::Iterator clip_iterator(clip);
        for (; !clip_iterator.done(); clip_iterator.next()) {
            // this assumes the SkIRect is stored in l,t,r,b ordering which
            // matches the ordering of our ClipRect struct
            clipWriter.writeIRect(clip_iterator.rect());
            state->clipRectCount++;
        }
    }

    // allocate memory for the clip then and copy them to the struct
    state->clipRects = (ClipRect*) sk_malloc_throw(clipWriter.bytesWritten());
    clipWriter.flatten(state->clipRects);
}

SkCanvasState* SkCanvasStateUtils::CaptureCanvasState(SkCanvas* canvas) {
    SkASSERT(canvas);

    // Check the clip can be decomposed into rectangles (i.e. no soft clips).
    ClipValidator validator;
    canvas->replayClips(&validator);
    if (validator.failed()) {
        SkErrorInternals::SetError(kInvalidOperation_SkError,
                "CaptureCanvasState does not support canvases with antialiased clips.\n");
        return NULL;
    }

    SkAutoTDelete<SkCanvasState> canvasState(SkNEW_ARGS(SkCanvasState, (canvas)));

    // decompose the total matrix and clip
    setup_MC_state(&canvasState->mcState, canvas->getTotalMatrix(), canvas->getTotalClip());

    /*
     * decompose the layers
     *
     * storage is allocated on the stack for the first 3 layers. It is common in
     * some view systems (e.g. Android) that a few non-clipped layers are present
     * and we will not need to malloc any additional memory in those cases.
     */
    const int layerBufferSize = 3 * sizeof(SkCanvasLayerState);
    char layerBuffer[layerBufferSize];
    SkWriter32 layerWriter(sizeof(SkCanvasLayerState), layerBuffer, layerBufferSize);
    int layerCount = 0;
    for (SkCanvas::LayerIter layer(canvas, true/*skipEmptyClips*/); !layer.done(); layer.next()) {

        // we currently only work for bitmap backed devices
        const SkBitmap& bitmap = layer.device()->accessBitmap(true/*changePixels*/);
        if (bitmap.empty() || bitmap.isNull() || !bitmap.lockPixelsAreWritable()) {
            return NULL;
        }

        SkCanvasLayerState* layerState =
                (SkCanvasLayerState*) layerWriter.reserve(sizeof(SkCanvasLayerState));
        layerState->type = kRaster_CanvasBackend;
        layerState->x = layer.x();
        layerState->y = layer.y();
        layerState->width = bitmap.width();
        layerState->height = bitmap.height();

        switch (bitmap.config()) {
            case SkBitmap::kARGB_8888_Config:
                layerState->raster.config = kARGB_8888_RasterConfig;
                break;
            case SkBitmap::kRGB_565_Config:
                layerState->raster.config = kRGB_565_RasterConfig;
                break;
            default:
                return NULL;
        }
        layerState->raster.rowBytes = bitmap.rowBytes();
        layerState->raster.pixels = bitmap.getPixels();

        setup_MC_state(&layerState->mcState, layer.matrix(), layer.clip());
        layerCount++;
    }

    // allocate memory for the layers and then and copy them to the struct
    SkASSERT(layerWriter.bytesWritten() == layerCount * sizeof(SkCanvasLayerState));
    canvasState->layerCount = layerCount;
    canvasState->layers = (SkCanvasLayerState*) sk_malloc_throw(layerWriter.bytesWritten());
    layerWriter.flatten(canvasState->layers);

    // for now, just ignore any client supplied DrawFilter.
    if (canvas->getDrawFilter()) {
//        SkDEBUGF(("CaptureCanvasState will ignore the canvases draw filter.\n"));
    }

    return canvasState.detach();
}

////////////////////////////////////////////////////////////////////////////////

static void setup_canvas_from_MC_state(const SkMCState& state, SkCanvas* canvas) {
    // reconstruct the matrix
    SkMatrix matrix;
    for (int i = 0; i < 9; i++) {
        matrix.set(i, state.matrix[i]);
    }

    // reconstruct the clip
    SkRegion clip;
    for (int i = 0; i < state.clipRectCount; ++i) {
        clip.op(SkIRect::MakeLTRB(state.clipRects[i].left,
                                  state.clipRects[i].top,
                                  state.clipRects[i].right,
                                  state.clipRects[i].bottom),
                SkRegion::kUnion_Op);
    }

    canvas->setMatrix(matrix);
    canvas->setClipRegion(clip);
}

static SkCanvas* create_canvas_from_canvas_layer(const SkCanvasLayerState& layerState) {
    SkASSERT(kRaster_CanvasBackend == layerState.type);

    SkBitmap bitmap;
    SkBitmap::Config config =
        layerState.raster.config == kARGB_8888_RasterConfig ? SkBitmap::kARGB_8888_Config :
        layerState.raster.config == kRGB_565_RasterConfig ? SkBitmap::kRGB_565_Config :
        SkBitmap::kNo_Config;

    if (config == SkBitmap::kNo_Config) {
        return NULL;
    }

    bitmap.setConfig(config, layerState.width, layerState.height,
                     layerState.raster.rowBytes);
    bitmap.setPixels(layerState.raster.pixels);

    SkASSERT(!bitmap.empty());
    SkASSERT(!bitmap.isNull());

    // create a device & canvas
    SkAutoTUnref<SkBitmapDevice> device(SkNEW_ARGS(SkBitmapDevice, (bitmap)));
    SkAutoTUnref<SkCanvas> canvas(SkNEW_ARGS(SkCanvas, (device.get())));

    // setup the matrix and clip
    setup_canvas_from_MC_state(layerState.mcState, canvas.get());

    return canvas.detach();
}

SkCanvas* SkCanvasStateUtils::CreateFromCanvasState(const SkCanvasState* state) {
    SkASSERT(state);

    // check that the versions match
    if (CANVAS_STATE_VERSION != state->version) {
        SkDebugf("CreateFromCanvasState version does not match the one use to create the input");
        return NULL;
    }

    if (state->layerCount < 1) {
        return NULL;
    }

    SkAutoTUnref<SkCanvasStack> canvas(SkNEW_ARGS(SkCanvasStack, (state->width, state->height)));

    // setup the matrix and clip on the n-way canvas
    setup_canvas_from_MC_state(state->mcState, canvas);

    // Iterate over the layers and add them to the n-way canvas
    for (int i = state->layerCount - 1; i >= 0; --i) {
        SkAutoTUnref<SkCanvas> canvasLayer(create_canvas_from_canvas_layer(state->layers[i]));
        if (!canvasLayer.get()) {
            return NULL;
        }
        canvas->pushCanvas(canvasLayer.get(), SkIPoint::Make(state->layers[i].x,
                                                             state->layers[i].y));
    }

    return canvas.detach();
}

////////////////////////////////////////////////////////////////////////////////

void SkCanvasStateUtils::ReleaseCanvasState(SkCanvasState* state) {
    SkDELETE(state);
}


text:
require "spec_helper"
require "crawler/api/scheduler"
module Crawler
  module Api
    describe Scheduler do

      before (:all) do
        @server=Celluloid::IO::TCPServer.new("localhost", 9001)
      end

      before :each do
        @socket=Celluloid::IO::TCPSocket.new("localhost", 9001)
        @peer=@server.accept
        @queue=Queue.new
        @scheduler=Scheduler.new queue: @queue, timeout: 0.5
        @scheduler.async.push socket: @peer
      end

      after :each do
        @socket.close unless @socket.closed?
        @peer.close unless @peer.closed?
      end

      describe "#push" do
        it "reads in the infinite loop incoming json from socket and pushes request string into the queue"  do
          payload={method: "users.get", params: {id: 1, v: 5}}
          @socket.puts payload.to_json
          sleep 0.05
          @queue.pop(true).should=={socket: @peer, request:"https://api.vk.com/method/users.get?id=1&v=5&",
                                    incoming: payload}
        end

        context "when it doesn't receive any message in #{Scheduler::CONNECTION_TIMEOUT} seconds" do
          it "closes the connection" do
            @scheduler.wrapped_object.should_receive(:shutdown)
            sleep 1
          end
        end

        context "when invalid json received" do
          before :each do
            @socket.puts "{{1"
            @socket.puts "1"
            @socket.puts "{\"method\":1, \"params\":{{}"
          end

          it "responds with error \"Unable to parse request\" " do
            3.times {@socket.gets.chomp.should=={error: "Unable to parse request"}.to_json}
          end
        end

        context "when valid json received" do
          context "when method key is not specified" do
            it "responds with error \"Method is not specified\" " do
              @socket.puts({params:{uid:1}}.to_json)
              @socket.gets.chomp.should=={error: "Method is not specified"}.to_json
            end
          end

          context "when params are not hash" do
            it "responds with error \"Params must be a hash\" " do
              @socket.puts({method: "users.get", params: [1,2]}.to_json)
              @socket.gets.chomp.should=={error: "Params must be a hash"}.to_json
            end
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Apresentacao extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		//Load Dependencies

	}

	// List all your items
	public function index( $offset = 0 )
	{
		$this->load->view("apresentacao");
	}

}

/* End of file Apresentacao.php */
/* Location: ./application/controllers/Apresentacao.php */


text:
FROM billyzhang2010/python-pip:latest

RUN apt-get update && apt-get install -y python-dev && pip install simiki

RUN apt install git -y

RUN cd /home

#RUN git clone https://hustbill@github.com/hustbill/goWiki.git demo

EXPOSE 8000

#CMD cd demo/mywiki && simiki g  && simiki p -w  --host 0.0.0.0 --port 8000

#CMD ["/bin/bash"]


text:
<!DOCTYPE html>

<html lang="en" dir="ltr">

	<head>
		<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Intuit Boot Camp Demonstrations</title>
		<link href='libs/bootstrap/dist/css/bootstrap.min.css' rel="stylesheet">
		<link href='libs/bootstrap/dist/css/bootstrap-theme.min.css' rel="stylesheet">
		<link href="libs/dijit/themes/claro/claro.css" rel="stylesheet">
		<link href="css/site.css" rel="stylesheet">
	</head>

	<body class="claro">
		<input id="calendar5" data-dojo-type="dijit/Calendar">

		<script src="js/dojo/dojo-config.js"></script>
		<script src="libs/dojo/dojo.js"></script>

		<script>

		require(["dojo/parser","dijit/Calendar", "ready!"],
			function(parser) {
				parser.parse();
			});

		</script>

	</body>

</html>


text:
#include <linux/clk-provider.h>
#include <linux/mfd/dbx500-prcmu.h>
#include <linux/platform_data/clk-ux500.h>
#include "clk.h"

void u9540_clk_init(void)
{
	/* register clocks here */
}


text:
package org.jkiss.dbeaver.ext.oracle.edit;

import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.oracle.model.OracleQueue;
import org.jkiss.dbeaver.ext.oracle.model.OracleSchema;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.edit.DBECommandContext;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.cache.DBSObjectCache;
import org.jkiss.utils.CommonUtils;

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

public class OracleQueueManager extends SQLObjectEditor<OracleQueue, OracleSchema> {

    @Override
    public long getMakerOptions(DBPDataSource dataSource) {
        return FEATURE_EDITOR_ON_CREATE;
    }

    @Override
    public boolean canCreateObject(Object container) {
        return false;
    }

    @Override
    protected void validateObjectProperties(DBRProgressMonitor monitor, ObjectChangeCommand command, Map<String, Object> options) throws DBException {
        if (CommonUtils.isEmpty(command.getObject().getName())) {
            throw new DBException("Queue name cannot be empty");
        }
    }

    @Nullable
    @Override
    public DBSObjectCache<? extends DBSObject, OracleQueue> getObjectsCache(OracleQueue object) {
        return object.getSchema().queueCache;
    }

    @Override
    protected OracleQueue createDatabaseObject(
        DBRProgressMonitor monitor, DBECommandContext context,
        final Object container,
        Object copyFrom, Map<String, Object> options) {
        OracleSchema schema = (OracleSchema) container;
        return new OracleQueue(schema, "NEW_QUEUE");
    }

    @Override
    protected void addObjectCreateActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectCreateCommand command, Map<String, Object> options) {

    }

    @Override
    protected void addObjectModifyActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actionList, ObjectChangeCommand command, Map<String, Object> options) {

    }

    @Override
    protected void addObjectDeleteActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectDeleteCommand command, Map<String, Object> options) {

    }
}


text:
title: Join / Contribute
order: 4
---

Come join us at UtahJS activities! UtahJS is a thriving community of JavaScript enthusiasts.

##Everyone is Welcome##

Experts and noobs alike are invited to our activities:

* Monthly meetings are on the first Thursday of every month at the Domo offices in Lindon (Map). Monthly meetings consist of short and long presentations for all experience levels.
* Weekly lunches. Every Wednesday we get together for lunch. Come to get out of the office and make friends. Bring your tech talk.
* Mailing List. Participate in the UtahJS community via our Google Groups mailing list.
* Chat room. For quick conversations, join us in #utahjs on freenode.
* Hack nights. Periodically we get together and help each other hack together cool web apps. Dates and locations are announced on the UtahJS mailing list.
* Learn together by contributing to our github repositories.
* Conferences. UtahJS is holding its first annual conference in June 2012. Stay tuned for details!
* Access to O'Reilly books and discounts. Periodically O'Reilly sends books for free, asking only for a public book review. Members also get a 35% discount on all O'Reilly books and e-books.
* Web site. Fork the github repository for the utahjs.com web site and add articles, book reviews and how-tos. Send a pull request to get your content added. If you're uncomfortable with git or github, send an email to rpflorence at gmail dot com and he'll either help you figure it out, or simply add the content you'd like to contribute for you. Don't be shy!

##Membership##

UtahJS has extra perks for those who pay $10 yearly membership dues:

* you.utahjs.com subdomain to point to your personal web site
* you@utahjs.com personalized email address
* utahjs.com/members/you page to advertise yourself or your work
* Discount on early-bird UtahJS Conference tickets
* Admission to special speaking events. Speakers, dates and locations are announced on the UtahJS mailing list. We intend to hold these special speaking events semi-annually.

Memberships also help UtahJS get recognition and sponsorships in the community. Send cash or make a check out to UtahJS to sign up today! Submit dues to Ken Snyder:

**UtahJS**

c/o Ken Snyder

8332 S 1890 W

West Jordan, UT 84088

ken@utahjs.com

801-368-8434


text:
network_tools
=============

#HTTP Server (Step 1)

##Authors:
* Perry Hook
* Mike Delaney
* Larry Fritts

Implemented basic HTTP Server which responds to GET requests using HTTP 1.1 protocol.  Methods other than GET and protocols other than HTTP 1.1 will return HTTP errors.

Used http://www.jmarshall.com/easy/http/#http1.1s5 to get clarification of what an error message actually looks like.

Used various posts on Stack Overflow for information on splitting strings.

#HTTP Server (Step 2)

##Authors:
* Perry Hook
* Mike Delaney
* Larry Fritts

Upgraded basic HTTP Server to serve basic content based on the URI.  Displays
contents of directory if URI is a directory, otherwise it serves the file.

Also will not allow URIs with .. (up a directory).  Responds with 505 Forbidden
Error.  Other additional errors include a 500 Internal Server Error and 404 Not
Found error.

#HTTP Server (Final Step)

##Authors:
* Perry Hook
* Mike Delaney
* Larry Fritts

Upgraded HTTP server to concurrent services using Twisted.  Had to refactor code from previous steps because many of our functions were implemented in twisted.  Our server is still set to respond to bad requests with appropriate messages.  Added links to the pages.

While the documentation for twisted was minimal, a useful website was http://codereview.stackexchange.com/questions/2315/file-serving-twisted-resource. A less useful wesite was found at  was a useful resource for helping to setup twisted.  A less useful website was found at http://twistedmatrix.com/documents/current/web/howto/web-in-60/error-handling.html.


text:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    LogViewerWindow viewer(ui->lineEdit_IP->text(), ui->lineEdit_Port->text().toInt());

    this->close();
    viewer.exec();
}


text:
import { IBoxComponentProps } from '../Box/model';

export interface IGridProps extends IBoxComponentProps {
	children?: Array<React.ReactElement<IRowProps>> | React.ReactElement<IRowProps>;
}

export interface IRowProps extends IBoxComponentProps {
	children?: Array<React.ReactElement<IColProps>> | React.ReactElement<IColProps>;
}

export type ColWidth = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;

export interface IColWidths {
	lg?: ColWidth | 'hidden';
	md?: ColWidth | 'hidden';
	sm?: ColWidth | 'hidden';
	xs?: ColWidth | 'hidden';
}

export interface IColProps extends IColWidths, IBoxComponentProps {
	children?: any;
}


text:
<?php

namespace Musonza\Groups\Models;

use Illuminate\Database\Eloquent\Model;

class GroupUser extends Model
{
    protected $table = 'group_user';

    public function group()
    {
        return $this->belongsTo(Group::class, 'group_id');
    }
}


text:
class RenameHeaters < ActiveRecord::Migration[5.0]
  RENAMED_KEYS = {
    'input_energy_heater_for_heat_network_crude_oil_production' => 'input_energy_heat_burner_crude_oil_production',
    'input_energy_heater_for_heat_network_coal_production' => 'input_energy_heat_burner_coal_production',
    'input_energy_heater_for_heat_network_waste_mix_production' => 'input_energy_heat_burner_waste_mix_production',
    'input_energy_heater_for_heat_network_wood_pellets_production' => 'input_energy_heat_burner_wood_pellets_production'
  }.freeze

  def up
    say "Checking and migrating #{Dataset.count} datasets"
    changed = 0

    Dataset.find_each.with_index do |dataset, index|
      if index.positive? && (index % 500).zero?
        say "Done #{index} (#{changed} updated)"
      end

      key_altered = false

      RENAMED_KEYS.each do |old_key, new_key|
        edit = find_edit(dataset, old_key)

        if edit
          edit.key = new_key
          edit.save(validate: false, touch: false)
          destroy_edits(dataset, old_key)

          key_altered = true
        end
      end

      if key_altered
        changed += 1
      end
    end

    say "Finished (#{changed} updated)"
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end

  private

  # Create a new dataset edit
  def create_edit(commit, key, value)
    ActiveRecord::Base.transaction do
      DatasetEdit.create!(
        commit_id: commit.id,
        key: key,
        value: value
      )
    end
  end

  # Finds all commits belonging to a dataset with an edit to the given key.
  def find_commits(dataset, edit_key)
    dataset.commits
           .joins(:dataset_edits)
           .where(dataset_edits: { key: edit_key })
           .order(updated_at: :desc)
  end

  # Finds the most recent edit of a key belonging to a dataset.
  def find_edit(dataset, edit_key)
    commits = find_commits(dataset, edit_key)

    return nil unless commits.any?

    DatasetEdit
      .where(commit_id: commits.pluck(:id), key: edit_key)
      .order(updated_at: :desc)
      .first
  end

  # Removes all dataset edits matching the `edit_key`. If the key is the only
  # dataset belonging to the commit, the commit will also be removed.
  def destroy_edits(dataset, edit_key)
    commits = find_commits(dataset, edit_key)

    return if commits.none?

    commits.each do |commit|
      if commit.dataset_edits.one?
        commit.destroy
      else
        commit.dataset_edits.find_by_key(edit_key).destroy
      end
    end
  end
end


text:
FROM fedora:23
MAINTAINER Robpol86 <robpol86@gmail.com>

RUN dnf update -y && \
    dnf install -y @development-tools fedora-packager rpmdevtools dnf-plugins-core

VOLUME ["/RPMS", "/SRPMS", "/SOURCES", "/SPECS"]
ADD build.sh build.sh

ENTRYPOINT ["bash", "build.sh"]


text:
require 'test/unit'
require 'concourse'
require 'date'

class TestUtils < Test::Unit::TestCase

    def test_convert_string_round_trip
        orig = "foo"
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

    def test_convert_tag_round_trip
        orig = Concourse::Tag.create "foo"
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

    def test_convert_link_round_trip
        orig = Concourse::Link.to 2147483648
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

    def test_convert_int_round_trip
        orig = 10
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

    def test_convert_long_round_trip
        orig = 2147483649
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

    def test_convert_boolean_round_trip
        orig = false
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

    def test_convert_float_round_trip
        orig = 3.14353
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

    def test_convert_datetime_round_trip
        orig = DateTime.now
        assert_equal(orig, Concourse::Utils::Convert::thrift_to_ruby(Concourse::Utils::Convert::ruby_to_thrift(orig)))
    end

end


text:
var ReactElement = require('react/lib/ReactElement');
var ReactInstanceHandles = require('react/lib/ReactInstanceHandles');
var ReactMarkupChecksum = require('react/lib/ReactMarkupChecksum');
var ReactServerRenderingTransaction = require('react/lib/ReactServerRenderingTransaction');

var cloneWithProps = require('react/lib/cloneWithProps');
var objectAssign = require('react/lib/Object.assign');
var instantiateReactComponent = require('react/lib/instantiateReactComponent');
var invariant = require('react/lib/invariant');

function cloneRoutesForServerRendering(routes) {
  return cloneWithProps(routes, {
    location: 'none',
    scrollBehavior: 'none'
  });
}

function mergeStateIntoInitialProps(state, props) {
  objectAssign(props, {
    initialPath: state.path,
    initialMatches: state.matches,
    initialActiveRoutes: state.activeRoutes,
    initialActiveParams: state.activeParams,
    initialActiveQuery: state.activeQuery
  });
}

/**
 * Renders a <Routes> component to a string of HTML at the given URL
 * path and calls callback(error, abortReason, html) when finished.
 *
 * If there was an error during the transition, it is passed to the
 * callback. Otherwise, if the transition was aborted for some reason,
 * it is given in the abortReason argument (with the exception of
 * internal redirects which are transparently handled for you).
 *
 * TODO: <NotFoundRoute> should be handled specially so servers know
 * to use a 404 status code.
 */
function renderRoutesToString(routes, path, callback) {
  invariant(
    ReactElement.isValidElement(routes),
    'You must pass a valid ReactComponent to renderRoutesToString'
  );

  var component = instantiateReactComponent(
    cloneRoutesForServerRendering(routes)
  );

  component.dispatch(path, function (error, abortReason, nextState) {
    if (error || abortReason)
      return callback(error, abortReason);

    mergeStateIntoInitialProps(nextState, component.props);

    var transaction;
    try {
      var id = ReactInstanceHandles.createReactRootID();
      transaction = ReactServerRenderingTransaction.getPooled(false);

      transaction.perform(function () {
        var markup = component.mountComponent(id, transaction, 0);
        callback(null, null, ReactMarkupChecksum.addChecksumToMarkup(markup));
      }, null);
    } finally {
      ReactServerRenderingTransaction.release(transaction);
    }
  });
}

/**
 * Renders a <Routes> component to static markup at the given URL
 * path and calls callback(error, abortReason, markup) when finished.
 */
function renderRoutesToStaticMarkup(routes, path, callback) {
  invariant(
    ReactElement.isValidElement(routes),
    'You must pass a valid ReactComponent to renderRoutesToStaticMarkup'
  );

  var component = instantiateReactComponent(
    cloneRoutesForServerRendering(routes)
  );

  component.dispatch(path, function (error, abortReason, nextState) {
    if (error || abortReason)
      return callback(error, abortReason);

    mergeStateIntoInitialProps(nextState, component.props);

    var transaction;
    try {
      var id = ReactInstanceHandles.createReactRootID();
      transaction = ReactServerRenderingTransaction.getPooled(false);

      transaction.perform(function () {
        callback(null, null, component.mountComponent(id, transaction, 0));
      }, null);
    } finally {
      ReactServerRenderingTransaction.release(transaction);
    }
  });
}

module.exports = {
  renderRoutesToString: renderRoutesToString,
  renderRoutesToStaticMarkup: renderRoutesToStaticMarkup
};


text:
package cz.crcs.ectester.standalone.libs.jni;

import cz.crcs.ectester.common.util.ECUtil;

import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.InvalidParameterSpecException;

/**
 * @author Jan Jancar johny@neuromancer.sk
 */
public abstract class NativeSignatureSpi extends SignatureSpi {
    ECPublicKey verifyKey;
    ECPrivateKey signKey;
    ECParameterSpec params;

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    @Override
    protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
        if (!(publicKey instanceof ECPublicKey)) {
            throw new InvalidKeyException
                    ("Key must be an instance of ECPublicKey");
        }
        verifyKey = (ECPublicKey) publicKey;
        params = verifyKey.getParams();
        buffer.reset();
    }

    @Override
    protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
        if (!(privateKey instanceof ECPrivateKey)) {
            throw new InvalidKeyException
                    ("Key must be an instance of ECPrivateKey");
        }
        signKey = (ECPrivateKey) privateKey;
        params = signKey.getParams();
        buffer.reset();
    }

    @Override
    protected void engineUpdate(byte b) throws SignatureException {
        buffer.write(b);
    }

    @Override
    protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
        buffer.write(b, off, len);
    }

    @Override
    @Deprecated
    protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
        throw new UnsupportedOperationException("setParameter() not supported");
    }

    @Override
    @Deprecated
    protected Object engineGetParameter(String param) throws InvalidParameterException {
        throw new UnsupportedOperationException("getParameter() not supported");
    }

    private abstract static class SimpleSignatureSpi extends NativeSignatureSpi {

        @Override
        protected byte[] engineSign() throws SignatureException {
            byte[] privkey;
            if (signKey instanceof NativeECPrivateKey) {
                privkey = ((NativeECPrivateKey) signKey).getData();
            } else {
                privkey = ECUtil.toByteArray(signKey.getS(), params.getOrder().bitLength());
            }
            return sign(buffer.toByteArray(), privkey, params);
        }

        @Override
        protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
            byte[] pubkey;
            if (verifyKey instanceof NativeECPublicKey) {
                pubkey = ((NativeECPublicKey) verifyKey).getData();
            } else {
                pubkey = ECUtil.toX962Uncompressed(verifyKey.getW(), params);
            }
            return verify(sigBytes, buffer.toByteArray(), pubkey, params);
        }

        abstract byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        abstract boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    private abstract static class ExtendedSignatureSpi extends NativeSignatureSpi {

        @Override
        protected byte[] engineSign() throws SignatureException {
            return sign(buffer.toByteArray(), signKey, params);
        }

        @Override
        protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
            return verify(sigBytes, buffer.toByteArray(), verifyKey, params);
        }

        abstract byte[] sign(byte[] data, ECPrivateKey privkey, ECParameterSpec params);

        abstract boolean verify(byte[] signature, byte[] data, ECPublicKey pubkey, ECParameterSpec params);
    }

    public static class TomCryptRaw extends SimpleSignatureSpi {

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public abstract static class Botan extends SimpleSignatureSpi {
        private String type;

        public Botan(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class BotanECDSAwithNONE extends Botan {

        public BotanECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public static class BotanECDSAwithSHA1 extends Botan {

        public BotanECDSAwithSHA1() {
            super("SHA1withECDSA");
        }
    }

    public static class BotanECDSAwithSHA224 extends Botan {

        public BotanECDSAwithSHA224() {
            super("SHA224withECDSA");
        }
    }

    public static class BotanECDSAwithSHA256 extends Botan {

        public BotanECDSAwithSHA256() {
            super("SHA256withECDSA");
        }
    }

    public static class BotanECDSAwithSHA384 extends Botan {

        public BotanECDSAwithSHA384() {
            super("SHA384withECDSA");
        }
    }

    public static class BotanECDSAwithSHA512 extends Botan {

        public BotanECDSAwithSHA512() {
            super("SHA512withECDSA");
        }
    }

    public static class BotanECKCDSAwithNONE extends Botan {

        public BotanECKCDSAwithNONE() {
            super("NONEwithECKCDSA");
        }
    }

    public static class BotanECKCDSAwithSHA1 extends Botan {

        public BotanECKCDSAwithSHA1() {
            super("SHA1withECKCDSA");
        }
    }

    public static class BotanECKCDSAwithSHA224 extends Botan {

        public BotanECKCDSAwithSHA224() {
            super("SHA224withECKCDSA");
        }
    }

    public static class BotanECKCDSAwithSHA256 extends Botan {

        public BotanECKCDSAwithSHA256() {
            super("SHA256withECKCDSA");
        }
    }

    public static class BotanECKCDSAwithSHA384 extends Botan {

        public BotanECKCDSAwithSHA384() {
            super("SHA384withECKCDSA");
        }
    }

    public static class BotanECKCDSAwithSHA512 extends Botan {

        public BotanECKCDSAwithSHA512() {
            super("SHA512withECKCDSA");
        }
    }

    public static class BotanECGDSAwithNONE extends Botan {

        public BotanECGDSAwithNONE() {
            super("NONEwithECGDSA");
        }
    }

    public static class BotanECGDSAwithSHA1 extends Botan {

        public BotanECGDSAwithSHA1() {
            super("SHA1withECGDSA");
        }
    }

    public static class BotanECGDSAwithSHA224 extends Botan {

        public BotanECGDSAwithSHA224() {
            super("SHA224withECGDSA");
        }
    }

    public static class BotanECGDSAwithSHA256 extends Botan {

        public BotanECGDSAwithSHA256() {
            super("SHA256withECGDSA");
        }
    }

    public static class BotanECGDSAwithSHA384 extends Botan {

        public BotanECGDSAwithSHA384() {
            super("SHA384withECGDSA");
        }
    }

    public static class BotanECGDSAwithSHA512 extends Botan {

        public BotanECGDSAwithSHA512() {
            super("SHA512withECGDSA");
        }
    }

    public abstract static class Cryptopp extends SimpleSignatureSpi {
        private String type;

        public Cryptopp(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class CryptoppECDSAwithSHA1 extends Cryptopp {

        public CryptoppECDSAwithSHA1() {
            super("SHA1withECDSA");
        }
    }

    public static class CryptoppECDSAwithSHA224 extends Cryptopp {

        public CryptoppECDSAwithSHA224() {
            super("SHA224withECDSA");
        }
    }

    public static class CryptoppECDSAwithSHA256 extends Cryptopp {

        public CryptoppECDSAwithSHA256() {
            super("SHA256withECDSA");
        }
    }

    public static class CryptoppECDSAwithSHA384 extends Cryptopp {

        public CryptoppECDSAwithSHA384() {
            super("SHA384withECDSA");
        }
    }

    public static class CryptoppECDSAwithSHA512 extends Cryptopp {

        public CryptoppECDSAwithSHA512() {
            super("SHA512withECDSA");
        }
    }

    public abstract static class Openssl extends SimpleSignatureSpi {
        private String type;

        public Openssl(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class OpensslECDSAwithNONE extends Openssl {

        public OpensslECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public abstract static class Boringssl extends SimpleSignatureSpi {
        private String type;

        public Boringssl(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class BoringsslECDSAwithNONE extends Boringssl {

        public BoringsslECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public abstract static class Gcrypt extends SimpleSignatureSpi {
        private String type;

        public Gcrypt(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class GcryptECDSAwithNONE extends Gcrypt {

        public GcryptECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public static class GcryptECDSAwithSHA1 extends Gcrypt {

        public GcryptECDSAwithSHA1() {
            super("SHA1withECDSA");
        }
    }

    public static class GcryptECDSAwithSHA224 extends Gcrypt {

        public GcryptECDSAwithSHA224() {
            super("SHA224withECDSA");
        }
    }

    public static class GcryptECDSAwithSHA256 extends Gcrypt {

        public GcryptECDSAwithSHA256() {
            super("SHA256withECDSA");
        }
    }

    public static class GcryptECDSAwithSHA384 extends Gcrypt {

        public GcryptECDSAwithSHA384() {
            super("SHA384withECDSA");
        }
    }

    public static class GcryptECDSAwithSHA512 extends Gcrypt {

        public GcryptECDSAwithSHA512() {
            super("SHA512withECDSA");
        }
    }

    public static class GcryptECDDSAwithSHA1 extends Gcrypt {

        public GcryptECDDSAwithSHA1() {
            super("SHA1withECDDSA");
        }
    }

    public static class GcryptECDDSAwithSHA224 extends Gcrypt {

        public GcryptECDDSAwithSHA224() {
            super("SHA224withECDDSA");
        }
    }

    public static class GcryptECDDSAwithSHA256 extends Gcrypt {

        public GcryptECDDSAwithSHA256() {
            super("SHA256withECDDSA");
        }
    }

    public static class GcryptECDDSAwithSHA384 extends Gcrypt {

        public GcryptECDDSAwithSHA384() {
            super("SHA384withECDDSA");
        }
    }

    public static class GcryptECDDSAwithSHA512 extends Gcrypt {

        public GcryptECDDSAwithSHA512() {
            super("SHA512withECDDSA");
        }
    }

    public abstract static class MbedTLS extends SimpleSignatureSpi {
        private String type;

        public MbedTLS(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class MbedTLSECDSAwithNONE extends MbedTLS {

        public MbedTLSECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public abstract static class Ippcp extends SimpleSignatureSpi {
        private String type;

        public Ippcp(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class IppcpECDSAwithNONE extends Ippcp {

        public IppcpECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public abstract static class Libressl extends SimpleSignatureSpi {
        private String type;

        public Libressl(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class LibresslECDSAwithNONE extends Libressl {

        public LibresslECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public abstract static class Matrixssl extends SimpleSignatureSpi {
        private String type;

        public Matrixssl(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, byte[] privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params);
    }

    public static class MatrixsslECDSAwithNONE extends Matrixssl {

        public MatrixsslECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

    public abstract static class Mscng extends ExtendedSignatureSpi {
        private String type;

        public Mscng(String type) {
            this.type = type;
        }

        @Override
        native byte[] sign(byte[] data, ECPrivateKey privkey, ECParameterSpec params);

        @Override
        native boolean verify(byte[] signature, byte[] data, ECPublicKey pubkey, ECParameterSpec params);
    }

    public static class MscngECDSAwithSHA1 extends Mscng {

        public MscngECDSAwithSHA1() {
            super("SHA1withECDSA");
        }
    }

    public static class MscngECDSAwithSHA256 extends Mscng {

        public MscngECDSAwithSHA256() {
            super("SHA256withECDSA");
        }
    }

    public static class MscngECDSAwithSHA384 extends Mscng {

        public MscngECDSAwithSHA384() {
            super("SHA384withECDSA");
        }
    }

    public static class MscngECDSAwithSHA512 extends Mscng {

        public MscngECDSAwithSHA512() {
            super("SHA512withECDSA");
        }
    }

    public abstract static class Nettle extends SimpleSignatureSpi {
        private String type;

        public Nettle(String type) {
            this.type = type;
        }

        @Override
        byte[] sign(byte[] data, byte[] privKey, ECParameterSpec params) {
            try {
                AlgorithmParameters tmp = AlgorithmParameters.getInstance("EC");
                tmp.init(params);
                ECGenParameterSpec spec = tmp.getParameterSpec(ECGenParameterSpec.class);
                switch (spec.getName()) {
                    case "1.2.840.10045.3.1.7":
                        spec = new ECGenParameterSpec("secp256r1");
                        break;
                    case "1.2.840.10045.3.1.1":
                        spec = new ECGenParameterSpec("secp192r1");
                        break;
                    case "1.3.132.0.33":
                        spec = new ECGenParameterSpec("secp224r1");
                        break;
                    case "1.3.132.0.34":
                        spec = new ECGenParameterSpec("secp384r1");
                        break;
                    case "1.3.132.0.35":
                        spec = new ECGenParameterSpec("secp521r1");
                        break;
                    default:
                        return null;

                }
                return sign(data, privKey, spec);

            } catch (NoSuchAlgorithmException | InvalidParameterSpecException e) {
                e.printStackTrace();
                return null;
            }
        }

        native byte[] sign(byte[] data, byte[] privKey, ECGenParameterSpec params);

        @Override
        boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECParameterSpec params) {
            try {
                AlgorithmParameters tmp = AlgorithmParameters.getInstance("EC");
                tmp.init(params);
                ECGenParameterSpec spec = tmp.getParameterSpec(ECGenParameterSpec.class);
                switch (spec.getName()) {
                    case "1.2.840.10045.3.1.7":
                        spec = new ECGenParameterSpec("secp256r1");
                        break;
                    case "1.2.840.10045.3.1.1":
                        spec = new ECGenParameterSpec("secp192r1");
                        break;
                    case "1.3.132.0.33":
                        spec = new ECGenParameterSpec("secp224r1");
                        break;
                    case "1.3.132.0.34":
                        spec = new ECGenParameterSpec("secp384r1");
                        break;
                    case "1.3.132.0.35":
                        spec = new ECGenParameterSpec("secp521r1");
                        break;
                    default:
                        return false;
                }
                return verify(signature, data, pubkey, spec);

            } catch (NoSuchAlgorithmException | InvalidParameterSpecException e) {
                e.printStackTrace();
                return false;
            }
        }

        native boolean verify(byte[] signature, byte[] data, byte[] pubkey, ECGenParameterSpec params);
    }

    public static class NettleECDSAwithNONE extends Nettle {

        public NettleECDSAwithNONE() {
            super("NONEwithECDSA");
        }
    }

}


text:
from io import StringIO
import unittest

import mock
import sys

import maccli.mac_cli
from tests.mock_data import *

class MacTestCase(unittest.TestCase):
    def setUp(self):
        maccli.user = MOCK_USER
        maccli.apikey = MOCK_APIKEY

    @mock.patch('maccli.command_cli.login')
    def test_dispatch_cmds_login(self, mock):
        args = Mock_args('login', None)
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)

    @mock.patch('maccli.command_cli.instance_create')
    def test_dispatch_cmds_create(self, mock):
        args = MockInstanceCreate_args('instance', 'create')
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)

    @mock.patch('maccli.command_cli.instance_destroy_help')
    def test_dispatch_cmds_destroy_help(self, mock):
        self.stderr = sys.stderr
        sys.stderr = StringIO()
        args = MockInstanceDestroy_args('instance', 'destroy', None, None)
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)

    @mock.patch('maccli.command_cli.instance_list')
    def test_dispatch_cmds_list(self, mock):
        args = Mock_args('instance', 'list')
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)

    @mock.patch('maccli.command_cli.instance_ssh_help')
    def test_dispatch_cmds_ssh_help(self, mock):
        self.stderr = sys.stderr
        sys.stderr = StringIO()
        args = MockInstanceSSH_args('instance', 'ssh', None, None)
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)

    @mock.patch('maccli.command_cli.instance_ssh')
    def test_dispatch_cmds_ssh_help_1(self, mock):
        args = MockInstanceSSH_args('instance', 'ssh', 'nameorid', None)
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)

    @mock.patch('maccli.command_cli.configuration_list')
    def test_dispatch_cmds_configuration_list(self, mock):
        args = Mock_args('configuration', 'list')
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)

    @mock.patch('maccli.command_cli.configuration_search')
    def test_dispatch_cmds_configuration_Search(self, mock):
        args = MockConfiguration_Args('configuration', 'search', None, None)
        maccli.mac_cli.dispatch_cmds(args)
        self.assertTrue(mock.called)


text:
package com.webcohesion.ofx4j.domain.data.seclist;

/**
 * Call type for debt.
 * @see "Section 13.8.5.2, OFX Spec"
 *
 * @author Jon Perlow
 */
public enum CallType {
  CALL,
  PUT,
  PREFUND,
  MATURITY;

  public static CallType fromOfx(String ofxVal) {
    if ("CALL".equals(ofxVal)) {
      return CALL;
    } else if ("PUT".equals(ofxVal)) {
      return PUT;
    } else if ("PREFUND".equals(ofxVal)) {
      return PREFUND;
    } else if ("MATURITY".equals(ofxVal)) {
      return MATURITY;
    } else {
      return null;
    }
  }
}


text:
package com.intellij.ide.impl.dataRules;

import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;

public class PsiFileRule implements GetDataRule {
  @Override
  public Object getData(DataProvider dataProvider) {
    final PsiElement element = LangDataKeys.PSI_ELEMENT.getData(dataProvider);
    if (element != null) {
      return element.getContainingFile();
    }
    Project project = PlatformDataKeys.PROJECT.getData(dataProvider);
    if (project != null) {
      VirtualFile vFile = PlatformDataKeys.VIRTUAL_FILE.getData(dataProvider);
      if (vFile != null) {
        return PsiManager.getInstance(project).findFile(vFile);
      }
    }
    return null;
  }
}


text:
package connectad

import (
	"encoding/json"
	"testing"

	"github.com/prebid/prebid-server/openrtb_ext"
)

func TestValidParams(t *testing.T) {
	validator, err := openrtb_ext.NewBidderParamsValidator("../../static/bidder-params")
	if err != nil {
		t.Fatalf("Failed to fetch the json-schemas. %v", err)
	}

	for _, validParam := range validParams {
		if err := validator.Validate(openrtb_ext.BidderConnectAd, json.RawMessage(validParam)); err != nil {
			t.Errorf("Schema rejected ConnectAd params: %s", validParam)
		}
	}
}

func TestInvalidParams(t *testing.T) {
	validator, err := openrtb_ext.NewBidderParamsValidator("../../static/bidder-params")
	if err != nil {
		t.Fatalf("Failed to fetch the json-schemas. %v", err)
	}

	for _, invalidParam := range invalidParams {
		if err := validator.Validate(openrtb_ext.BidderConnectAd, json.RawMessage(invalidParam)); err == nil {
			t.Errorf("Schema allowed unexpected params: %s", invalidParam)
		}
	}
}

var validParams = []string{
	`{"siteId": 123456, "networkId": 123456, "bidfloor": 0.10}`,
	`{"siteId": 123456, "networkId": 123456}`,
}

var invalidParams = []string{
	`{}`,
	`null`,
	`{"siteId": 123456, "networkId": "123456", "bidfloor": 0.10}`,
	`{"siteId": "123456", "networkId": 123456, "bidfloor": 0.10}`,
	`{"siteId": 123456, "networkId": 123456, "bidfloor": "0.10"}`,
	`{"siteId": "123456"}`,
	`{"networkId": 123456}`,
	`{"siteId": 123456}`,
	`{"invalid_param": "123"}`,
}


text:
package org.maera.plugin.predicate;

import org.maera.plugin.Plugin;

/**
 * Interface used to match plugins according to implementation specific rules.
 *
 * @since 0.17
 */
public interface PluginPredicate {
    /**
     *
Will match a plugin according to implementation rules.

     *
This method must not change the state of the plugin.

     *
     * @param plugin the plugin to test against.
     * @return true if the plugin matches the predicate, false otherwise.
     */
    boolean matches(final Plugin plugin);
}


text:
package config

import (
	"io"

	"github.com/scionproto/scion/go/lib/config"
	"github.com/scionproto/scion/go/lib/env"
	"github.com/scionproto/scion/go/lib/log"
)

const idSample = "router-1"

type Config struct {
	General  env.General  `toml:"general,omitempty"`
	Features env.Features `toml:"features,omitempty"`
	Logging  log.Config   `toml:"log,omitempty"`
	Metrics  env.Metrics  `toml:"metrics,omitempty"`
}

func (cfg *Config) InitDefaults() {
	config.InitAll(
		&cfg.General,
		&cfg.Features,
		&cfg.Logging,
		&cfg.Metrics,
	)
}

func (cfg *Config) Validate() error {
	return config.ValidateAll(
		&cfg.General,
		&cfg.Features,
		&cfg.Logging,
		&cfg.Metrics,
	)
}

func (cfg *Config) Sample(dst io.Writer, path config.Path, _ config.CtxMap) {
	config.WriteSample(dst, path, config.CtxMap{config.ID: idSample},
		&cfg.General,
		&cfg.Features,
		&cfg.Logging,
		&cfg.Metrics,
	)
}


text:
SET gp_create_table_random_default_distribution=off;
-- end_ignore
CREATE SEQUENCE ck_sync1_seq1  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;
CREATE SEQUENCE ck_sync1_seq2  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;
CREATE SEQUENCE ck_sync1_seq3  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;
CREATE SEQUENCE ck_sync1_seq4  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;
CREATE SEQUENCE ck_sync1_seq5  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;
CREATE SEQUENCE ck_sync1_seq6  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;
CREATE SEQUENCE ck_sync1_seq7  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;

DROP SEQUENCE sync1_seq2;
DROP SEQUENCE ck_sync1_seq1;

-- SEQUENCE USAGE

CREATE TABLE ck_sync1_tbl1 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO ck_sync1_tbl1 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE ck_sync1_seq11 START 101 OWNED BY ck_sync1_tbl1.col1;
INSERT INTO ck_sync1_tbl1 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

CREATE TABLE ck_sync1_tbl2 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO ck_sync1_tbl2 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE ck_sync1_seq22 START 101 OWNED BY ck_sync1_tbl2.col1;
INSERT INTO ck_sync1_tbl2 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

CREATE TABLE ck_sync1_tbl3 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO ck_sync1_tbl3 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE ck_sync1_seq33 START 101 OWNED BY ck_sync1_tbl3.col1;
INSERT INTO ck_sync1_tbl3 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

CREATE TABLE ck_sync1_tbl4 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO ck_sync1_tbl4 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE ck_sync1_seq44 START 101 OWNED BY ck_sync1_tbl4.col1;
INSERT INTO ck_sync1_tbl4 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

CREATE TABLE ck_sync1_tbl5 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO ck_sync1_tbl5 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE ck_sync1_seq55 START 101 OWNED BY ck_sync1_tbl5.col1;
INSERT INTO ck_sync1_tbl5 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

CREATE TABLE ck_sync1_tbl6 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO ck_sync1_tbl6 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE ck_sync1_seq66 START 101 OWNED BY ck_sync1_tbl6.col1;
INSERT INTO ck_sync1_tbl6 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

CREATE TABLE ck_sync1_tbl7 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO ck_sync1_tbl7 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE ck_sync1_seq77 START 101 OWNED BY ck_sync1_tbl7.col1;
INSERT INTO ck_sync1_tbl7 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

DROP SEQUENCE sync1_seq22;
DROP SEQUENCE ck_sync1_seq11;


text:
This is an extension of Hash, and enable to use key-value like method.

## Installation

Add this line to your application's Gemfile:

    gem 'methodable_hash'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install methodable_hash

## Usage

    require 'methodable_hash'

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
Featured

        Offers

      Start your search with a look at the best rates on our site.

                      <?php
                            if(isset($featuredOffers) && !empty($featuredOffers)){
                                foreach($featuredOffers as $featurePackage){
//                                    var_dump($featurePackage); die();
                      ?>

                            <a href="<?php echo site_url('packages/'.$featurePackage->package_slug); ?>" >
                                <img src="<?php echo 'assets/uploads/packages/'.$featurePackage->package_image; ?>" alt="" style="height: 178px; width: 255px; overflow: hidden;" />

<?php echo character_limiter($featurePackage->package_title,10); ?>

<?php echo character_limiter($featurePackage->package_location,10); ?>

                                    <?php
                                    if($featurePackage->discount_percentage>0) {
                                        ?>
                                    save upto <?php echo round($featurePackage->discount_percentage).'%' ?>
                                    <?php
                                            }
                                    ?>

From

                                           <?php
                                    if($featurePackage->discount_percentage>0) {
                                    ?>

                                                <?php
                          echo '$'.$featurePackage->package_basic_price;
                          ?>

                                            <?php } ?>

                                              <?php
                                    $price = $featurePackage->package_basic_price-$featurePackage->package_basic_discount;
                                    echo '$'.$price;
                                    ?>

                        <?php
                        }
                          }
                        ?>

                     <img src="<?php echo base_url('assets');?>/images/spacer.png" alt=""/>

                     <img src="<?php echo base_url('assets');?>/images/spacer.png" alt=""/>


text:
package tests

import (
	"fmt"
	"os/exec"
	"runtime"
	"testing"
)

func TestLxdSimple(t *testing.T) {
	if runtime.GOARCH == "ppc64le" {
		t.Skip("lxd won't run on ppc64le")
	}
	if exec.Command("grep", "Red Hat Enterprise Linux", "/etc/os-release").Run() == nil {
		t.Skip("lxd won't run on RHEL")
	}

	test := &Test{
		setupCmds: []Cmd{
			{"lxc launch images:ubuntu/bionic test-skydive-lxd-simple", false},
		},

		tearDownCmds: []Cmd{
			{"lxc delete --force test-skydive-lxd-simple", false},
		},

		mode: Replay,

		checks: []CheckFunction{func(c *CheckContext) error {
			gremlin := c.gremlin.V().Has("Type", "netns", "Manager", "lxd")
			gremlin = gremlin.Out("Type", "container", "Name", "test-skydive-lxd-simple")

			nodes, err := c.gh.GetNodes(gremlin)
			if err != nil {
				return err
			}

			if len(nodes) != 1 {
				return fmt.Errorf("Expected 1 node, got %+v", nodes)
			}

			return nil
		}},
	}

	RunTest(t, test)
}


text:
namespace Img {
	ImageComposer::Ptr StaticCodec::RequestImageComposer() {
		return m_composer;
	}

	StaticCodec::StaticCodec():m_surface(CreateNewSurface()), m_fastSurface(CreateNewSurface()), m_doFast(false) {
		m_composer = std::make_shared<ImageComposerStatic>(m_surface, m_fastSurface);
	}

	StaticCodec::~StaticCodec() {}

	void StaticCodec::UseFastSurface( bool doFastSurface ) {
		m_doFast = doFastSurface;
		if (doFastSurface) {
			m_composer->UseFastSurface(true);
		}
	}

	void StaticCodec::FinalizeSurface() {
		if (!m_doFast) {
			m_composer->UseFastSurface(false);
		}
	}

	Surface::Ptr StaticCodec::GetSurface() {
		return m_doFast ? m_fastSurface : m_surface;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         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>

    <groupId>org.opencompare</groupId>
    <artifactId>stats</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <scala.version>2.11.6</scala.version>
        <sqlite4java.version>1.0.392</sqlite4java.version>
        <sqlite4java.debug>true</sqlite4java.debug>
        <sqlite4java.library.path>${project.build.directory}/lib</sqlite4java.library.path>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.opencompare</groupId>
            <artifactId>api-java</artifactId>
            <version>0.6-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.opencompare</groupId>
            <artifactId>api-java-impl</artifactId>
            <version>0.6-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.opencompare.io</groupId>
            <artifactId>io-wikipedia</artifactId>
            <version>0.6-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-xml</artifactId>
            <version>2.11.0-M4</version>
        </dependency>
        <dependency>
            <groupId>org.scalaj</groupId>
            <artifactId>scalaj-http_2.11</artifactId>
            <version>1.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.github.tototoshi</groupId>
            <artifactId>scala-csv_2.11</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.typesafe.play</groupId>
            <artifactId>play-json_2.11</artifactId>
            <version>2.4.1</version>
            <exclusions>
                <exclusion> <!-- different version of scala -->
                    <groupId>org.scala-stm</groupId>
                    <artifactId>scala-stm_2.11</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.almworks.sqlite4java</groupId>
            <artifactId>sqlite4java</artifactId>
            <version>${sqlite4java.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.10</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>2.9.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>org.opencompare.stats.Launcher</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>com.almworks.sqlite4java</groupId>
                                    <artifactId>libsqlite4java-linux-amd64</artifactId>
                                    <version>${sqlite4java.version}</version>
                                    <type>so</type>
                                    <overWrite>true</overWrite>
                                    <outputDirectory>${project.build.directory}/lib</outputDirectory>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
/*
  @author: Seven Lju
  @date: 2016-03-18

  DOM Event Monitor by Overriding
    EventTarget.prototype.addEventListener
  with global object identifier feature via defining
    Object.prototype.__oid__
 */
var $petal;
if(!$petal) $petal = {};

(function ($petal) {

(function() {
    var _id = 1;
    Object.defineProperty(Object.prototype, "__oid_w__", {
      writable: true
    });
    Object.defineProperty(Object.prototype, "__oid__", {
      get: function() {
        if (!this.__oid_w__)
          this.__oid_w__ = _id++;
        return this.__oid_w__;
      },
    });
})();

var original_addEventListener = EventTarget.prototype.addEventListener;
var map_listener = {
  config: {
    count: true
  }
};

function new_addEventListener(type, listener, options) {
  return original_addEventListener.call(
    this,
    type,
    wrapper(this, listener, type, map_listener),
    options
  );
}

function mapid(obj, listener) {
  return obj.__oid__ + '_' + listener.__oid__;
}

function wrapper(target, listener, type, __map__) {
  var __id__ = mapid(target, listener);
  var __item__ = __map__[__id__];
  if (!__item__) {
    __item__ = {};
    __map__[__id__] = __item__;
  }
  __item__.count = 0;
  __item__.type = type;
  return function (evt) {
    if (__item__.callback) __item__.callback(evt);
    if (__map__.config.count) __item__.count ++;
    listener(evt);
  };
}

function switch_off() {
  EventTarget.prototype.addEventListener = original_addEventListener;
  // TODO registered wrapper(listener)=>listener
}

function switch_on() {
  EventTarget.prototype.addEventListener = new_addEventListener;
  // TODO registered listener=>wrapper(listener)
}

$petal.evtmonitor = {
  config: function () {
    return map_listener.config;
  },
  count: function (target, listener) {
    var item = map_listener[mapid(target, listener)];
    if (!item) return -1;
    return item.count;
  },
  type: function (target, listener) {
    var item = map_listener[mapid(target, listener)];
    if (!item) return null;
    return item.type;
  },
  addCleanEventListener: function (target, type, listener, options) {
    return original_addEventListener.call(
      target,
      type,
      listener,
      options
    );
  },
  switchOn: switch_on,
  switchOff: switch_off
};

})($petal);


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DocumentFormat.OpenXml.Packaging
{
    /// <summary>
    /// Defines CustomPropertyPartType - types of CustomPropertyPart.
    /// </summary>
    public enum CustomPropertyPartType
    {
        /// <summary>
        /// application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty.
        /// </summary>
        Spreadsheet,

        /// <summary>
        /// application/xml.
        /// </summary>
        Xml,
    }
}


text:
using UnityEngine;

/// Resonance Audio material mapper updater. This class is used to receive Update events during Edit
/// Mode (which are triggered whenever the scene is modified and the material mappings are changed
/// etc.), then calls a delegate to refresh the material mapper.
[AddComponentMenu("")]
[ExecuteInEditMode]
public class ResonanceAudioMaterialMapperUpdater : MonoBehaviour {
  /// The delegate to call to refresh the material mapper.
  public delegate void RefreshMaterialMapperDelegate();
  public RefreshMaterialMapperDelegate RefreshMaterialMapper = null;

  void Update() {
    if (Application.isEditor && !Application.isPlaying && RefreshMaterialMapper != null) {
      RefreshMaterialMapper();
    }
  }
}


text:
<?php
return array (
  '%displayName% joined the space %spaceName%' => '%displayName%さんは、%spaceName% スペースに参加しました',
  '%displayName% joined this space.' => '%displayName%さんが、このスペースに参加しました。',
);


text:
class QNiTE;

class QNiTETrackerRenderer : public QQuickPaintedItem
{
    Q_OBJECT
    Q_PROPERTY(QObject* kinect READ kinect WRITE setKinect NOTIFY kinectChanged)
    Q_PROPERTY(bool initialized READ initialized WRITE setInitialized NOTIFY initializedChanged)
    Q_PROPERTY(bool keepHistogram READ keepHistogram WRITE setKeepHistogram NOTIFY keepHistogramChanged)
public:
    explicit QNiTETrackerRenderer(QQuickItem *parent = 0);
    ~QNiTETrackerRenderer();

    bool initialized() const
    {
        return m_initialized;
    }

    virtual void paint(QPainter *painter);

    QObject* kinect() const
    {
        return m_kinect;
    }

    bool keepHistogram() const
    {
        return m_keepHistogram;
    }

signals:

    void initializedChanged(bool arg);
    void newFrameAvailable();

    void kinectChanged(QObject* arg);

    void keepHistogramChanged(bool arg);

public slots:

    void initialize();
    void onNewFrame();
    void setInitialized(bool arg)
    {
        if (m_initialized == arg)
            return;

        m_initialized = arg;
        emit initializedChanged(arg);
    }

    void setKinect(QObject* arg)
    {
        if (m_kinect == arg)
            return;

        m_kinect = arg;
        emit kinectChanged(arg);
    }

    void setKeepHistogram(bool arg)
    {
        if (m_keepHistogram == arg)
            return;

        m_keepHistogram = arg;
        emit keepHistogramChanged(arg);
    }

private:
    void DrawSkeleton(nite::UserTracker* pUserTracker, const nite::UserData& userData, QPainter *painter);
    void DrawLimb(nite::UserTracker* pUserTracker, const nite::SkeletonJoint& joint1, const nite::SkeletonJoint& joint2, QPainter *painter);

    QNiTE *m_qnite;

    openni::Device * m_device;
    nite::UserTracker * m_userTracker;
    bool m_initialized;

    int m_nTexMapX;
    int m_nTexMapY;
    int g_nXRes;
    int g_nYRes;
    openni::RGB888Pixel * m_pTexMap;

    float m_pDepthHist[MAX_DEPTH];
    bool m_hasHistogram;
    QObject* m_kinect;
    bool m_keepHistogram;
};

#endif // QNiTETrackerRendererTRACKERRENDERER_H