text:
namespace remoting {

namespace {

void SetOrClearBit(uint64_t &value, uint64_t bit, bool set_bit) {
  value = set_bit ? (value | bit) : (value & ~bit);
}

// This value is not defined. Give it the obvious name so that if it is ever
// added there will be a handy compilation error to remind us to remove this
// definition.
const int kVK_RightCommand = 0x36;

using protocol::ClipboardEvent;
using protocol::KeyEvent;
using protocol::MouseEvent;

// A class to generate events on Mac.
class InputInjectorMac : public InputInjector {
 public:
  explicit InputInjectorMac(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner);
  virtual ~InputInjectorMac();

  // ClipboardStub interface.
  virtual void InjectClipboardEvent(const ClipboardEvent& event) OVERRIDE;

  // InputStub interface.
  virtual void InjectKeyEvent(const KeyEvent& event) OVERRIDE;
  virtual void InjectMouseEvent(const MouseEvent& event) OVERRIDE;

  // InputInjector interface.
  virtual void Start(
      scoped_ptr<protocol::ClipboardStub> client_clipboard) OVERRIDE;

 private:
  // The actual implementation resides in InputInjectorMac::Core class.
  class Core : public base::RefCountedThreadSafe<Core> {
   public:
    explicit Core(scoped_refptr<base::SingleThreadTaskRunner> task_runner);

    // Mirrors the ClipboardStub interface.
    void InjectClipboardEvent(const ClipboardEvent& event);

    // Mirrors the InputStub interface.
    void InjectKeyEvent(const KeyEvent& event);
    void InjectMouseEvent(const MouseEvent& event);

    // Mirrors the InputInjector interface.
    void Start(scoped_ptr<protocol::ClipboardStub> client_clipboard);

    void Stop();

   private:
    friend class base::RefCountedThreadSafe<Core>;
    virtual ~Core();

    scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
    webrtc::DesktopVector mouse_pos_;
    uint32 mouse_button_state_;
    scoped_ptr<Clipboard> clipboard_;
    CGEventFlags left_modifiers_;
    CGEventFlags right_modifiers_;

    DISALLOW_COPY_AND_ASSIGN(Core);
  };

  scoped_refptr<Core> core_;

  DISALLOW_COPY_AND_ASSIGN(InputInjectorMac);
};

InputInjectorMac::InputInjectorMac(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
  core_ = new Core(task_runner);
}

InputInjectorMac::~InputInjectorMac() {
  core_->Stop();
}

void InputInjectorMac::InjectClipboardEvent(const ClipboardEvent& event) {
  core_->InjectClipboardEvent(event);
}

void InputInjectorMac::InjectKeyEvent(const KeyEvent& event) {
  core_->InjectKeyEvent(event);
}

void InputInjectorMac::InjectMouseEvent(const MouseEvent& event) {
  core_->InjectMouseEvent(event);
}

void InputInjectorMac::Start(
    scoped_ptr<protocol::ClipboardStub> client_clipboard) {
  core_->Start(client_clipboard.Pass());
}

InputInjectorMac::Core::Core(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : task_runner_(task_runner),
      mouse_button_state_(0),
      clipboard_(Clipboard::Create()),
      left_modifiers_(0),
      right_modifiers_(0) {
  // Ensure that local hardware events are not suppressed after injecting
  // input events.  This allows LocalInputMonitor to detect if the local mouse
  // is being moved whilst a remote user is connected.
  // This API is deprecated, but it is needed when using the deprecated
  // injection APIs.
  // If the non-deprecated injection APIs were used instead, the equivalent of
  // this line would not be needed, as OS X defaults to _not_ suppressing local
  // inputs in that case.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
  CGSetLocalEventsSuppressionInterval(0.0);
#pragma clang diagnostic pop
}

void InputInjectorMac::Core::InjectClipboardEvent(const ClipboardEvent& event) {
  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE, base::Bind(&Core::InjectClipboardEvent, this, event));
    return;
  }

  // |clipboard_| will ignore unknown MIME-types, and verify the data's format.
  clipboard_->InjectClipboardEvent(event);
}

void InputInjectorMac::Core::InjectKeyEvent(const KeyEvent& event) {
  // HostEventDispatcher should filter events missing the pressed field.
  if (!event.has_pressed() || !event.has_usb_keycode())
    return;

  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  int keycode = key_converter->UsbKeycodeToNativeKeycode(event.usb_keycode());

  VLOG(3) << "Converting USB keycode: " << std::hex << event.usb_keycode()
          << " to keycode: " << keycode << std::dec;

  // If we couldn't determine the Mac virtual key code then ignore the event.
  if (keycode == key_converter->InvalidNativeKeycode())
    return;

  // If this is a modifier key, remember its new state so that it can be
  // correctly applied to subsequent events.
  if (keycode == kVK_Command) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskCommand, event.pressed());
  } else if (keycode == kVK_Shift) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskShift, event.pressed());
  } else if (keycode == kVK_Control) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskControl, event.pressed());
  } else if (keycode == kVK_Option) {
    SetOrClearBit(left_modifiers_, kCGEventFlagMaskAlternate, event.pressed());
  } else if (keycode == kVK_RightCommand) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskCommand, event.pressed());
  } else if (keycode == kVK_RightShift) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskShift, event.pressed());
  } else if (keycode == kVK_RightControl) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskControl, event.pressed());
  } else if (keycode == kVK_RightOption) {
    SetOrClearBit(right_modifiers_, kCGEventFlagMaskAlternate, event.pressed());
  }

  base::ScopedCFTypeRef<CGEventRef> eventRef(
      CGEventCreateKeyboardEvent(NULL, keycode, event.pressed()));

  if (eventRef) {
    // In addition to the modifier keys pressed right now, we also need to set
    // AlphaShift if caps lock was active at the client (Mac ignores NumLock).
    uint64_t flags = left_modifiers_ | right_modifiers_;
    if (event.lock_states() & protocol::KeyEvent::LOCK_STATES_CAPSLOCK)
      flags |= kCGEventFlagMaskAlphaShift;
    CGEventSetFlags(eventRef, flags);

    // Post the event to the current session.
    CGEventPost(kCGSessionEventTap, eventRef);
  }
}

void InputInjectorMac::Core::InjectMouseEvent(const MouseEvent& event) {
  if (event.has_x() && event.has_y()) {
    // On multi-monitor systems (0,0) refers to the top-left of the "main"
    // display, whereas our coordinate scheme places (0,0) at the top-left of
    // the bounding rectangle around all the displays, so we need to translate
    // accordingly.

    // Set the mouse position assuming single-monitor.
    mouse_pos_.set(event.x(), event.y());

    // Fetch the desktop configuration.
    // TODO(wez): Optimize this out, or at least only enumerate displays in
    // response to display-changed events. VideoFrameCapturer's VideoFrames
    // could be augmented to include native cursor coordinates for use by
    // MouseClampingFilter, removing the need for translation here.
    webrtc::MacDesktopConfiguration desktop_config =
        webrtc::MacDesktopConfiguration::GetCurrent(
            webrtc::MacDesktopConfiguration::TopLeftOrigin);

    // Translate the mouse position into desktop coordinates.
    mouse_pos_.add(webrtc::DesktopVector(desktop_config.pixel_bounds.left(),
                                         desktop_config.pixel_bounds.top()));

    // Constrain the mouse position to the desktop coordinates.
    mouse_pos_.set(
       std::max(desktop_config.pixel_bounds.left(),
           std::min(desktop_config.pixel_bounds.right(), mouse_pos_.x())),
       std::max(desktop_config.pixel_bounds.top(),
           std::min(desktop_config.pixel_bounds.bottom(), mouse_pos_.y())));

    // Convert from pixel to Density Independent Pixel coordinates.
    mouse_pos_.set(mouse_pos_.x() / desktop_config.dip_to_pixel_scale,
                   mouse_pos_.y() / desktop_config.dip_to_pixel_scale);

    VLOG(3) << "Moving mouse to " << mouse_pos_.x() << "," << mouse_pos_.y();
  }
  if (event.has_button() && event.has_button_down()) {
    if (event.button() >= 1 && event.button() <= 3) {
      VLOG(2) << "Button " << event.button()
              << (event.button_down() ? " down" : " up");
      int button_change = 1 << (event.button() - 1);
      if (event.button_down())
        mouse_button_state_ |= button_change;
      else
        mouse_button_state_ &= ~button_change;
    } else {
      VLOG(1) << "Unknown mouse button: " << event.button();
    }
  }
  // We use the deprecated CGPostMouseEvent API because we receive low-level
  // mouse events, whereas CGEventCreateMouseEvent is for injecting higher-level
  // events. For example, the deprecated APIs will detect double-clicks or drags
  // in a way that is consistent with how they would be generated using a local
  // mouse, whereas the new APIs expect us to inject these higher-level events
  // directly.
  CGPoint position = CGPointMake(mouse_pos_.x(), mouse_pos_.y());
  enum {
    LeftBit = 1 << (MouseEvent::BUTTON_LEFT - 1),
    MiddleBit = 1 << (MouseEvent::BUTTON_MIDDLE - 1),
    RightBit = 1 << (MouseEvent::BUTTON_RIGHT - 1)
  };
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
  CGError error = CGPostMouseEvent(position, true, 3,
                                   (mouse_button_state_ & LeftBit) != 0,
                                   (mouse_button_state_ & RightBit) != 0,
                                   (mouse_button_state_ & MiddleBit) != 0);
#pragma clang diagnostic pop
  if (error != kCGErrorSuccess)
    LOG(WARNING) << "CGPostMouseEvent error " << error;

  if (event.has_wheel_delta_x() && event.has_wheel_delta_y()) {
    int delta_x = static_cast<int>(event.wheel_delta_x());
    int delta_y = static_cast<int>(event.wheel_delta_y());
    base::ScopedCFTypeRef<CGEventRef> event(CGEventCreateScrollWheelEvent(
        NULL, kCGScrollEventUnitPixel, 2, delta_y, delta_x));
    if (event)
      CGEventPost(kCGSessionEventTap, event);
  }
}

void InputInjectorMac::Core::Start(
    scoped_ptr<protocol::ClipboardStub> client_clipboard) {
  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&Core::Start, this, base::Passed(&client_clipboard)));
    return;
  }

  clipboard_->Start(client_clipboard.Pass());
}

void InputInjectorMac::Core::Stop() {
  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(FROM_HERE, base::Bind(&Core::Stop, this));
    return;
  }

  clipboard_->Stop();
}

InputInjectorMac::Core::~Core() {
}

}  // namespace

scoped_ptr<InputInjector> InputInjector::Create(
    scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) {
  return scoped_ptr<InputInjector>(new InputInjectorMac(main_task_runner));
}

}  // namespace remoting


text:
<?php

namespace RedKiteLabs\RedKiteCms\TwitterBootstrapBundle\Core\Form\Base;

use RedKiteLabs\RedKiteCms\RedKiteCmsBaseBlocksBundle\Core\Form\Base\BaseType as BaseJson;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Implements a base form to defines the translation domain for this bundle
 *
 * @author RedKite Labs <info@redkite-labs.com>
 */
abstract class BaseType extends BaseJson
{
    /**
     * Sets the default options for this type
     *
     * @param OptionsResolverInterface $resolver The resolver for the options
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'translation_domain' => 'TwitterBootstrapBundle',
            'csrf_protection' => false,
        ));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<form class="form-horizontal email-IDs-tab"
      ng-controller="EmailIDsController"
      ng-class="{'form-group-sm': $storage.displayDensity === pipelineConstant.DENSITY_COZY || $storage.displayDensity === pipelineConstant.DENSITY_COMPACT}"
      role="form" name="emailIDsForm">

    Email IDs

          <input type="text" class="form-control input-sm"
                 required
                 name="{{'emailId' + $index}}"
                 ng-readonly="isPipelineRulesReadOnly"
                 ng-model="pipelineRules.emailIds[$index]"/>

          <button type="button" class="btn btn-default btn-sm"
                  ng-click="removeFromList(pipelineRules.emailIds, $index)">

          </button>
          <button type="button" class="btn btn-default btn-sm"
                  ng-show="$last"
                  ng-click="addToList(pipelineRules.emailIds)">

          </button>

          <button type="button" class="btn btn-default btn-sm"
                  ng-click="addToList(pipelineRules.emailIds)">

          </button>

</form>


text:
@implementation BIKeyboardAppearance
+ (void)load {
    [super load];
    BIRegisterSelfAsEnum(UIKeyboardAppearance);
}

- (void)defineEnum {
    BIEnumDefine(UIKeyboardAppearance,
            UIKeyboardAppearanceDefault,
            UIKeyboardAppearanceDark,
            UIKeyboardAppearanceLight,
            UIKeyboardAppearanceAlert);
}

@end


text:
layout: example
categories: example/v1.0.0
version: v1.0.0
title: Load GeoJSON from a URL
description: Loading GeoJSON that contains a simple marker from a URL source.
tags:
  - markers
---


text:
package challenge8a

import core._, Syntax._

class Challenge8aSpec extends test.Spec {
  import Laws._
  import HttpArbitraries._

  "Http" should {
    "satisfy monad laws" ! monad.laws[Http]
  }

  implicit def HttpWriteEqual =
    Equal.derived[HttpWrite]

  implicit def HttpStateEqual =
    Equal.derived[HttpState]

  implicit def HttpValueEqual[A: Equal]: Equal[HttpValue[A]] =
    Equal.from[HttpValue[A]]((a, b) => a.fold(
      t => b.fold(_ === t, _ => false, _ => false),
      m => b.fold(_ => false, _ === m, _ => false),
      a => b.fold(_ => false, _ => false, _ === a)
    ))

  implicit def HttpEqual[A: Equal]: Equal[Http[A]] =
    Equal.from[Http[A]]((a, b) => {
      val r = HttpRead(Get, "abc", Headers(Vector("accept" -> "application/json")))
      val s = HttpState(Headers(Vector("loggedin" -> "fred")))
      a.run(r, s) === b.run(r, s)
    })

  "Echo service" should {
    val echo: Http[String] = HttpExample.echo
    "return body as string" ! prop((r: HttpRead, s: HttpState) =>
      echo.run(r, s)._3 must_== HttpValue.ok(r.body)
    )

    "add 'content-type' header of 'text/plain'" ! prop((r: HttpRead, s: HttpState) =>
      echo.run(r, s)._2.resheaders.headers must contain ("content-type" -> "text/plain")
    )

    "log a message with the length of the body in characters" ! prop((r: HttpRead, s: HttpState) =>
      echo.run(r, s)._1.log must contain (r.body.length.toString)
    )
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Core2D.UI.Zoom.Input;
using Draw2D.ViewModels.Shapes;
using Spatial;

namespace Draw2D.ViewModels.Bounds
{
    [DataContract(IsReference = true)]
    public class GroupBounds : ViewModelBase, IBounds
    {
        public IPointShape TryToGetPoint(IBaseShape shape, Point2 target, double radius, IHitTest hitTest, Modifier modifier)
        {
            if (!(shape is GroupShape group))
            {
                throw new ArgumentNullException("shape");
            }

            if (modifier.HasFlag(Modifier.Shift))
            {
                foreach (var groupShape in group.Shapes.Reverse())
                {
                    var result = groupShape.Bounds?.TryToGetPoint(groupShape, target, radius, hitTest, modifier);
                    if (result != null)
                    {
                        return result;
                    }
                }
            }
            else
            {
                foreach (var groupPoint in group.Points)
                {
                    if (groupPoint.Bounds?.TryToGetPoint(groupPoint, target, radius, hitTest, modifier) != null)
                    {
                        return groupPoint;
                    }
                }
            }

            return null;
        }

        public IBaseShape Contains(IBaseShape shape, Point2 target, double radius, IHitTest hitTest, Modifier modifier)
        {
            if (!(shape is GroupShape group))
            {
                throw new ArgumentNullException("shape");
            }

            foreach (var groupShape in group.Shapes.Reverse())
            {
                var result = groupShape.Bounds?.Contains(groupShape, target, radius, hitTest, modifier);
                if (result != null)
                {
                    if (modifier.HasFlag(Modifier.Shift))
                    {
                        return result;
                    }
                    else
                    {
                        return group;
                    }
                }
            }

            var points = new List<IPointShape>();
            group.GetPoints(points);

            if (points.Count == 0)
            {
                return null;
            }

            return HitTestHelper.Contains(points, target) ? shape : null;
        }

        public IBaseShape Overlaps(IBaseShape shape, Rect2 target, double radius, IHitTest hitTest, Modifier modifier)
        {
            if (!(shape is GroupShape group))
            {
                throw new ArgumentNullException("shape");
            }

            foreach (var groupShape in group.Shapes)
            {
                var result = groupShape.Bounds?.Overlaps(groupShape, target, radius, hitTest, modifier);
                if (result != null)
                {
                    return group;
                }
            }
            return null;
        }
    }
}


text:
$cd = Get-Location
$sourcedir = "$cd\Source"
$builddir = "$cd\Build"
$tempdir = "$cd\Temp"
$buildout = $tempdir+"\DSTEd-*-*-*"
$engineVer = Read-Host "Input Electron Version"

#echo "Build requires NPM"
echo "Cleaning"
del -Recurse "$tempdir\*"
del -Recurse "$builddir\*"
md -Confirm $builddir
md -Confirm $tempdir
echo "copy items to temp"
Copy-Item -Recurse  "$sourcedir\*" "$tempdir\"

cd $tempdir
echo "install necessary javascript modules"
npm install
copy "$tempdir\build\Release\*.node" "$tempdir\Library\win64"
echo "Build Start"
$temp = """$tempdir"""
electron-packager.cmd $temp DSTEd --electronVersion=$engineVer --asar --overwrite --arch=x64  --icon="$tempdir\Resources\window_icon.ico" --app-version="1.0.0" --win32metadata.CompanyName="DSTEd - OpenSource" --win32metadata.ProductName="DSTEd" --win32metadata.OriginalFilename="DSTEd.exe"
#echo "delete unused files"
cd $cd
copy -Recurse $buildout $builddir
#foreach($file in $unused)
#{
#    del -Confirm "$builddir\$file"
#}
echo "delete temp files"
del "$tempdir\*"
pause
cls


text:
package edu.buffalo.fusim;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import net.sf.picard.sam.MergeSamFiles;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Fusim
 *
 * @author Andrew E. Bruno
 *
 */
public class Fusim {
    private static Log logger = LogFactory.getLog(Fusim.class);
    private Options options;

    public static void main(String[] args) {
        Fusim fusim = new Fusim();

        try {
            fusim.run(args);
        } catch (Exception e) {
            logger.fatal("Execution failed: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void run(String[] args) throws IOException, InterruptedException {
        buildOptions();

        CommandLineParser clParser = new PosixParser();
        CommandLine cmd = null;
        try {
            cmd = clParser.parse(options, args);
        } catch (ParseException e) {
            printHelpAndExit(options, e.getMessage());
        }

        if (cmd.hasOption("v")) {
            printVersionAndExit();
        }

        if (cmd.hasOption("h") || cmd.getOptions().length == 0) {
            printHelpAndExit(options);
        }

        if(cmd.hasOption("z")) {
            if(!cmd.hasOption("i")) {
                printHelpAndExit(options, "Please specify a path to a GTF/GFF file for conversion with option -i");
            }
            if(!cmd.hasOption("o")) {
                printHelpAndExit(options, "Please specify an output filename with option -O");
            }

            File outFile = new File(cmd.getOptionValue("o"));
            File gtfFile = new File(cmd.getOptionValue("i"));
            if(!gtfFile.canRead()) {
                printHelpAndExit(options, "Can't read input GTF file");
            }

            GTF2RefFlat gtf2Flat = new GTF2RefFlat();

            gtf2Flat.convert(gtfFile, outFile);
            System.exit(0);
        }

        if(!cmd.hasOption("g")) {
            printHelpAndExit(options, "Please specify a path to a gene model file with option -g");
        }

        File geneModelFile = new File(cmd.getOptionValue("g"));
        if(!geneModelFile.canRead()) {
            printHelpAndExit(options, "Can't read Gene Model file");
        }

        PrintWriter textOutput = null;
        if(cmd.hasOption("t")) {
            if("-".equals(cmd.getOptionValue("t"))) {
                textOutput = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
            } else {
                textOutput = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cmd.getOptionValue("t")), "UTF-8"));
            }
        }

        PrintWriter fastaOutput = null;
        if(cmd.hasOption("f")) {
            if("-".equals(cmd.getOptionValue("f"))) {
                fastaOutput = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
            } else {
                fastaOutput = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cmd.getOptionValue("f")), "UTF-8"));
            }
        }

        // Default to TXT output
        if(fastaOutput == null && textOutput == null) {
            textOutput = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
        }

        if(cmd.hasOption("f") && !cmd.hasOption("r")) {
            printHelpAndExit(options, "You must provide an indexed (.fai) genome reference file for FASTA output using option \"-r\".");
        }

        File referenceFile = null;
        if(cmd.hasOption("r")) {
            referenceFile = new File(cmd.getOptionValue("r"));
        }
        if(cmd.hasOption("f") && !referenceFile.canRead()) {
            printHelpAndExit(options, "Please provide a valid reference file in fasta format");
        }
        if(cmd.hasOption("f")) {
            File referenceIndexFile = new File(referenceFile.getAbsolutePath() + ".fai");
            if(!referenceIndexFile.canRead()) {
                fatalError("Missing index file. Please index your fasta file with: samtools faidx my_genome.fa");
            }
        }

        int nFusions = 0;
        if(cmd.hasOption("n")) {
            try {
                nFusions = Integer.parseInt(cmd.getOptionValue("n"));
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Number of fusions (-n) must be a number");
            }
        }

        int nReadThrough = 0;
        if(cmd.hasOption("x")) {
            try {
                nReadThrough = Integer.parseInt(cmd.getOptionValue("x"));
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Number of read through fusion genes (-x) must be a number");
            }
        }

        int nTriFusion = 0;
        if(cmd.hasOption("j")) {
            try {
                nTriFusion = Integer.parseInt(cmd.getOptionValue("j"));
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Number of tri-fusions (-j) must be a number");
            }
        }

        int nIntraChromFusion = 0;
        if(cmd.hasOption("y")) {
            try {
                nIntraChromFusion = Integer.parseInt(cmd.getOptionValue("y"));
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Number of intra-chromosome fusions (-y) must be a number");
            }
        }

        int nSelfFusion = 0;
        if(cmd.hasOption("s")) {
            try {
                nSelfFusion = Integer.parseInt(cmd.getOptionValue("s"));
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Number of self-fusions (-s) must be a number");
            }
        }

        int foreignInsertionLen = 0;
        if(cmd.hasOption("u")) {
            try {
                foreignInsertionLen = Integer.parseInt(cmd.getOptionValue("u"));
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Foreign insertion length (-u) must be a number");
            }
        }

        int nThreads = Runtime.getRuntime().availableProcessors();
        if(cmd.hasOption("p")) {
            try {
                nThreads = Integer.parseInt(cmd.getOptionValue("p"));
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Number of threads to spawn (-p) must be a number");
            }
        }

        double rpkmCutoff = 0.2;
        if(cmd.hasOption("k")) {
            try {
                rpkmCutoff = Double.parseDouble(cmd.getOptionValue("k"));
                if(rpkmCutoff < 0 || rpkmCutoff > 1) throw new NumberFormatException();
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "RPKM cutoff (-k) must be 0 < cutoff < 1");
            }
        }

        double foreignInsertionPct = 0.0;
        if(cmd.hasOption("w")) {
            try {
                foreignInsertionPct = Double.parseDouble(cmd.getOptionValue("w"));
                if(foreignInsertionPct < 0 || foreignInsertionPct > 1) throw new NumberFormatException();
            } catch(NumberFormatException e) {
                printHelpAndExit(options, "Foreign insertion percent (-w) must be 0 < x < 1");
            }
        }

        GeneSelectionMethod geneSelectioMethod = GeneSelectionMethod.UNIFORM;
        if(cmd.hasOption("m")) {
            GeneSelectionMethod sm = GeneSelectionMethod.fromString(cmd.getOptionValue("m"));
            if(sm == null) {
                printHelpAndExit(options, "Invalid gene selection method: "+cmd.getOptionValue("m"));
            }
            geneSelectioMethod = sm;
        }

        Map<String, Boolean> limit = null;
        if(cmd.hasOption("l")) {
            limit = new HashMap<String,Boolean>();
            String[] limits = cmd.getOptionValue("l").split(",");
            if(limits.length < 1) {
                printHelpAndExit(options, "Must provide a limit of at least one genes (ex. gene1,gene2,..): "+cmd.getOptionValue("l"));
            }
            for(int i = 0; i < limits.length; i++) {
                limit.put(limits[i], true);
            }
        }

        List<String[]> filters = new ArrayList<String[]>();
        for(String filterOption : new String[]{"1","2","3"}) {
            if(cmd.hasOption(filterOption)) {
                filters.add(cmd.getOptionValue(filterOption).split(","));
            } else {
                filters.add(null);
            }
        }

        File bamFile = null;
        if(cmd.hasOption("b")) {
            bamFile = new File(cmd.getOptionValue("b"));

            if(!bamFile.canRead()) {
                printHelpAndExit(options, "Please provide a valid BAM file");
            }
        }

        logger.info("========================================================================");
        logger.info("Running Fusim with the following settings:");
        logger.info("========================================================================");
        logger.info("Reference Gene Model: "+geneModelFile.getAbsolutePath());
        if(cmd.hasOption("t")) {
            logger.info("Text Output: "+("-".equals(cmd.getOptionValue("t")) ? "<stdout>" : cmd.getOptionValue("t")));
        }
        if(cmd.hasOption("f")) {
            logger.info("Fasta Output: "+("-".equals(cmd.getOptionValue("f")) ? "<stdout>" : cmd.getOptionValue("f")));
        }
        if(!cmd.hasOption("f") && !cmd.hasOption("t")) {
            logger.info("Text Output: <stdout>");
        }
        logger.info("");
        logger.info("------------------");
        logger.info("Gene Selection");
        logger.info("------------------");
        if(cmd.hasOption("b")) {
            logger.info("Mode: background reads");
            logger.info("BAM file: "+bamFile.getAbsolutePath());
            logger.info("RPKM cutoff: "+rpkmCutoff);
            logger.info("Number of threads: "+nThreads);
            logger.info("Gene selection method: "+geneSelectioMethod.toString());
        } else {
            logger.info("Mode: gene model");
        }
        logger.info("");
        logger.info("------------------");
        logger.info("Type of fusions");
        logger.info("------------------");
        logger.info("Hybrid: "+nFusions);
        logger.info("Self: "+nSelfFusion);
        logger.info("Complex: "+nTriFusion);
        logger.info("Intra-chromosome: "+nIntraChromFusion);
        logger.info("Read through: "+nReadThrough);
        logger.info("");
        logger.info("------------------");
        logger.info("Fusion options");
        logger.info("------------------");
        logger.info("CDS only: "+(cmd.hasOption("c") ? "yes" : "no"));
        logger.info("Auto-correct orientation: "+(cmd.hasOption("a") ? "yes" : "no"));
        logger.info("Allow fusions outside of ORF: "+(cmd.hasOption("d") ? "yes" : "no"));
        logger.info("Force fusion breaks on exon boundries: "+(cmd.hasOption("e") ? "yes" : "no"));
        if(cmd.hasOption("u")) {
            logger.info("Foreign insertion max length: "+foreignInsertionLen);
            logger.info("Foreign insertion percent: "+foreignInsertionPct);
        }
        logger.info("========================================================================");

        GeneModelParser parser = new UCSCRefFlatParser(cmd.hasOption("e"), cmd.hasOption("c"), limit);
        GeneSelector selector = null;
        FusionGenerator fg = null;

        if(cmd.hasOption("b")) {
            selector = new BackgroundSelector(bamFile, rpkmCutoff, nThreads);
            fg = new BackgroundGenerator();
        } else {
            selector = new StaticSelector();
            fg = new RandomGenerator();
        }

        selector.setGeneModelFile(geneModelFile);
        selector.setGeneModelParser(parser);

        fg.setGeneSelector(selector);
        fg.setGeneSelectionMethod(geneSelectioMethod);
        fg.setFilters(filters);

        List<FusionGene> fusions = new ArrayList<FusionGene>();

        if(nFusions > 0) {
            fusions.addAll(fg.generate(nFusions, 2));
        }

        // Generate any read through fusion genes
        if(nReadThrough > 0) {
            logger.info("Generating read through genes...");
            ReadThroughGenerator rt = new ReadThroughGenerator();
            rt.setGeneSelector(selector);
            rt.setGeneSelectionMethod(geneSelectioMethod);

            List<FusionGene> rtFusions = rt.generate(nReadThrough, 2);
            for(FusionGene g : rtFusions) {
                g.setFusionType(FusionType.READ_THROUGH);
            }
            fusions.addAll(rtFusions);
        }

        // Generate any tri-fusions
        if(nTriFusion > 0) {
            logger.info("Generating tri-fusion genes...");
            List<FusionGene> tfusions = fg.generate(nTriFusion, 3);
            for(FusionGene g : tfusions) {
                g.setFusionType(FusionType.TRI_FUSION);
            }
            fusions.addAll(tfusions);
        }

        // Generate any intra chromosome fusions
        if(nIntraChromFusion > 0) {
            logger.info("Generating intra-chromosome fusions...");
            IntraChromGenerator ig = new IntraChromGenerator();
            ig.setGeneSelector(selector);
            ig.setGeneSelectionMethod(geneSelectioMethod);

            List<FusionGene> ifusions = ig.generate(nIntraChromFusion, 2);
            for(FusionGene g : ifusions) {
                g.setFusionType(FusionType.INTRA_CHROMOSOME);
            }
            fusions.addAll(ifusions);
        }

        // Generate any self-fusions
        if(nSelfFusion > 0) {
            logger.info("Generating self-fusion genes...");
            List<FusionGene> sfusions = fg.generate(nSelfFusion, 1);
            for(FusionGene g : sfusions) {
                g.setFusionType(FusionType.SELF_FUSION);
            }
            fusions.addAll(sfusions);
        }

        if(fusions.size() == 0) {
            fatalError("No fusions to simulate! Check to be sure you have -j,-n,-s,-x,-y specified and your filters are correct.");
        }

        if(textOutput != null) {
            textOutput.println(StringUtils.join(FusionGene.getHeader(), "\t"));
        }

        int foreignInsertionCutoff = (int)(foreignInsertionPct*fusions.size());

        Random rgen = new Random();
        for(int g = 0; g < fusions.size(); g++) {
            FusionGene f = fusions.get(g);

            //out.println(f);
            List<int []> breaks = new ArrayList<int []>();

            // First half of gene 1
            breaks.add(f.getGene(0).generateExonBreak(true, cmd.hasOption("c")));

            if(f.size() == 2) {
                // Second half of gene2
                breaks.add(f.getGene(1).generateExonBreak(false, cmd.hasOption("c")));
            } else if(f.size() == 3) {
                // Second half of gene2
                breaks.add(f.getGene(1).generateExonBreak(false, cmd.hasOption("c")));

                // Second half of gene3
                breaks.add(f.getGene(2).generateExonBreak(false, cmd.hasOption("c")));
            }

            // Keep ORF (don't allow out of frame) and allow splitting of exons
            if(!cmd.hasOption("d") && !cmd.hasOption("e")) {
                // Split last exon in half and ensure within ORF
                for(int i = 0; i < breaks.size(); i++) {
                    int[] exons = breaks.get(i);
                    int[] lastExon = f.getGene(i).getExons(cmd.hasOption("c")).get(exons[exons.length-1]);
                    int randIndex = rgen.nextInt(lastExon[1]-lastExon[0]);
                    while(randIndex % 3 != 0) {
                        randIndex--;
                    }
                    f.getGene(i).getExons(cmd.hasOption("c")).get(exons[exons.length-1])[1] -= randIndex;
                }
            } else if(cmd.hasOption("e") && !cmd.hasOption("d")) {
                breaks.clear();
                // Keep ORF (don't allow out of frame) and don't allow splitting of exons (keep exon boundries)
                // Break genes on exons boundries
                breaks.add(f.getGene(0).generateExonBoundryBreak(cmd.hasOption("c")));

                if(f.size() == 2) {
                    breaks.add(f.getGene(1).generateExonBoundryBreak(cmd.hasOption("c")));
                } else if(f.size() == 3) {
                    breaks.add(f.getGene(2).generateExonBoundryBreak(cmd.hasOption("c")));
                    breaks.add(f.getGene(3).generateExonBoundryBreak(cmd.hasOption("c")));
                }
            }

            // Set options for output
            if(cmd.hasOption("a")) {
                f.addOption(FusionOption.AUTO_CORRECT_ORIENTATION);
            }
            if(cmd.hasOption("c")) {
                f.addOption(FusionOption.CDS_ONLY);
            }
            if(cmd.hasOption("d")) {
                f.addOption(FusionOption.OUT_OF_FRAME);
            } else {
                f.addOption(FusionOption.SYMMETRICAL_EXONS);
            }
            if(cmd.hasOption("e")) {
                f.addOption(FusionOption.KEEP_EXON_BOUNDRY);
            }

            if(textOutput != null) {
                textOutput.print(f.outputText(breaks, cmd.hasOption("c")));
            }

            if(fastaOutput != null) {
                if(foreignInsertionLen > 0 && foreignInsertionCutoff > 0 && g <= foreignInsertionCutoff) {
                    f.addOption(FusionOption.FOREIGN_INSERTION);
                    fastaOutput.println(f.outputFasta(breaks, referenceFile, cmd.hasOption("c"), cmd.hasOption("a"), foreignInsertionLen));
                } else {
                    fastaOutput.println(f.outputFasta(breaks, referenceFile, cmd.hasOption("c"), cmd.hasOption("a")));
                }
            }
        }

        if(textOutput != null) textOutput.flush();
        if(fastaOutput != null) fastaOutput.flush();

        logger.info("Fusim run complete. Goodbye!");
    }

    @SuppressWarnings("static-access")
    private void buildOptions() {
        options = new Options();

        options.addOption(
                OptionBuilder.withLongOpt("help")
                             .withDescription("print usage info")
                             .create("h")
            );
        options.addOption(
            OptionBuilder.withLongOpt("gene-model")
                         .withDescription("Path to gene model file in refFlat format")
                         .hasArg()
                         .create("g")
        );
        options.addOption(
                OptionBuilder.withLongOpt("reference")
                             .withDescription("Path to indexed reference genome fasta file (.fai)")
                             .hasArg()
                             .create("r")
            );
        options.addOption(
                OptionBuilder.withLongOpt("background-reads")
                             .withDescription("Path to BAM file containing background reads. Genes will be selected for fusions according to the read profile of the background reads.")
                             .hasArg()
                             .create("b")
            );
        options.addOption(
                OptionBuilder.withLongOpt("fusions")
                             .withDescription("Number of fusions to generate using two randomly selected genes")
                             .hasArg()
                             .create("n")
            );
        options.addOption(
                OptionBuilder.withLongOpt("text-output")
                             .withDescription("File name of text output")
                             .hasArg()
                             .create("t")
            );
        options.addOption(
                OptionBuilder.withLongOpt("fasta-output")
                             .withDescription("File name of FASTA output")
                             .hasArg()
                             .create("f")
            );
        options.addOption(
                OptionBuilder.withLongOpt("cds-only")
                             .withDescription("Only include CDS exons")
                             .create("c")
            );
        options.addOption(
                OptionBuilder.withLongOpt("read-through")
                             .withDescription("Number of read through fusions")
                             .hasArg()
                             .create("x")
            );
        options.addOption(
                OptionBuilder.withLongOpt("tri-fusion")
                             .withDescription("Number of fusions with three genes")
                             .hasArg()
                             .create("j")
            );
        options.addOption(
                OptionBuilder.withLongOpt("self-fusion")
                             .withDescription("Number of self-fusions (fusions with single gene)")
                             .hasArg()
                             .create("s")
            );
        options.addOption(
                OptionBuilder.withLongOpt("intra-chrom")
                             .withDescription("Number of intra-chromosome fusions (fusions within single chrom)")
                             .hasArg()
                             .create("y")
            );
        options.addOption(
                OptionBuilder.withLongOpt("rpkm-cutoff")
                             .withDescription("RPKM cutoff when using background BAM file. Genes below the cutoff will be ignored")
                             .hasArg()
                             .create("k")
            );
        options.addOption(
                OptionBuilder.withLongOpt("threads")
                             .withDescription("Number of threads to spawn when processing background BAM file")
                             .hasArg()
                             .create("p")
            );
        options.addOption(
                OptionBuilder.withLongOpt("convert")
                             .withDescription("Convert GTF/GFF to refFlat (genePred) format")
                             .create("z")
            );
        options.addOption(
                OptionBuilder.withLongOpt("gtf")
                             .withDescription("Input GTF file for conversion")
                             .hasArg()
                             .create("i")
            );
        options.addOption(
                OptionBuilder.withLongOpt("output")
                             .withDescription("Output refFlat file for conversion")
                             .hasArg()
                             .create("o")
            );
        options.addOption(
                OptionBuilder.withLongOpt("gene-selection-method")
                             .withDescription("Method to use when selecting genes for fusions: uniform|binned|empirical|empirical-sturges")
                             .hasArg()
                             .create("m")
            );
        options.addOption(
                OptionBuilder.withLongOpt("auto-correct-orientation")
                             .withDescription("Auto correct orientation of fusion sequence if genes are located on different strands")
                             .create("a")
            );
        options.addOption(
                OptionBuilder.withLongOpt("out-of-frame")
                             .withDescription("Allow fusions outside of reading frames. By default the reading frame is preserved")
                             .create("d")
            );
        options.addOption(
                OptionBuilder.withLongOpt("keep-exon-boundary")
                             .withDescription("Generate fusion breaks on exon boundaries only")
                             .create("e")
            );
        options.addOption(
                OptionBuilder.withLongOpt("limit")
                             .withDescription("Limit all fusions to specific geneId, transcriptId, or chrom")
                             .hasArg()
                             .create("l")
            );
        options.addOption(
                OptionBuilder.withLongOpt("gene1")
                             .withDescription("Filter for gene1")
                             .hasArg()
                             .create("1")
            );
        options.addOption(
                OptionBuilder.withLongOpt("gene2")
                             .withDescription("Filter for gene2")
                             .hasArg()
                             .create("2")
            );
        options.addOption(
                OptionBuilder.withLongOpt("gene3")
                             .withDescription("Filter for gene3")
                             .hasArg()
                             .create("3")
            );
        options.addOption(
                OptionBuilder.withLongOpt("foreign-insertion-length")
                             .withDescription("Maxium length of randomly generated sequence to insert between fusion breakpoints")
                             .hasArg()
                             .create("u")
            );
        options.addOption(
                OptionBuilder.withLongOpt("foreign-insertion-perecent")
                             .withDescription("Percent of fusions to insert foreign sequence between fusion breakpoints")
                             .hasArg()
                             .create("w")
            );
        options.addOption(
                OptionBuilder.withLongOpt("version")
                             .withDescription("Display version info")
                             .create("v")
            );
    }

    public void fatalError(String message) {
        if (message != null) logger.fatal("Fatal error: " + message);

        System.exit(1);
    }

    public void printHelpAndExit(Options options, String message) {
        if (message != null)
            logger.fatal("Usage error: " + message + "\n");
        // Print CLI options
        //HelpFormatter formatter = new HelpFormatter();
        //formatter.printHelp("fusim", options);
        try {
            System.out.print(
                IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("fusim.options"))
            );
        } catch (Exception e){
            logger.fatal("Failed to load options help file: "+e.getMessage());
        }
        if (message != null) {
            System.exit(1);
        } else {
            System.exit(0);
        }
    }

    public void printHelpAndExit(Options options) {
        printHelpAndExit(options, null);
    }

    private void printVersionAndExit() {
        Properties properties = new Properties();
        try {
            InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("version.properties");
            properties.load(inStream);
        } catch (Exception e){
            logger.fatal("Failed to load version data: "+e.getMessage());
        }
        System.out.println("v"+properties.getProperty("fusim.version"));
        System.exit(0);
    }
}


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* RecordStateComparer.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System.Collections.Generic;

using JetBrains.Annotations;

using MoonSharp.Interpreter;

#endregion

namespace ManagedIrbis.Client
{
    /// <summary>
    ///
    /// </summary>
    [PublicAPI]
    [MoonSharpUserData]
    public sealed class RecordStateComparer
    {
        #region Nested classes

        /// <summary>
        /// Compares <see cref="RecordState"/>
        /// by <see cref="RecordState.Id"/>
        /// </summary>
        public sealed class ById
            : IEqualityComparer<RecordState>
        {
            #region IEqualityComparer<T> members

            /// <inheritdoc cref="IEqualityComparer{T}.Equals(T,T)"/>
            public bool Equals
                (
                    RecordState x,
                    RecordState y
                )
            {
                return x.Id == y.Id;
            }

            /// <inheritdoc cref="IEqualityComparer{T}.GetHashCode(T)"/>
            public int GetHashCode
                (
                    RecordState obj
                )
            {
                return obj.Id;
            }

            #endregion
        }

        /// <summary>
        /// Compares <see cref="RecordState"/>
        /// by <see cref="RecordState.Mfn"/>
        /// </summary>
        public sealed class ByMfn
            : IEqualityComparer<RecordState>
        {
            #region IEqualityComparer<T> members

            /// <inheritdoc cref="IEqualityComparer{T}.Equals(T,T)"/>
            public bool Equals
                (
                    RecordState x,
                    RecordState y
                )
            {
                return x.Mfn == y.Mfn;
            }

            /// <inheritdoc cref="IEqualityComparer{T}.GetHashCode(T)"/>
            public int GetHashCode
                (
                    RecordState obj
                )
            {
                return obj.Mfn;
            }

            #endregion
        }

        /// <summary>
        /// Compares <see cref="RecordState"/>
        /// by <see cref="RecordState.Mfn"/> and
        /// <see cref="RecordState.Version"/>.
        /// </summary>
        public sealed class ByVersion
            : IEqualityComparer<RecordState>
        {
            #region IEqualityComparer<T> members

            /// <inheritdoc cref="IEqualityComparer{T}.Equals(T,T)"/>
            public bool Equals
                (
                    RecordState x,
                    RecordState y
                )
            {
                return x.Mfn == y.Mfn
                    && x.Version == y.Version;
            }

            /// <inheritdoc cref="IEqualityComparer{T}.GetHashCode(T)"/>
            public int GetHashCode
                (
                    RecordState obj
                )
            {
                return unchecked (obj.Mfn * 37 + obj.Version);
            }

            #endregion
        }

        #endregion
    }
}


text:
module Data.Endianness where

data Endianness = LittleEndian | BigEndian
                  deriving (Prelude.Eq)

{- Discussion of endianness

Due to the nuances of the languages, endianness can mean something different in
Verilog and Haskell.

The verilog definition of endianness is the standard, but we are prescribing the
Haskell definition.

  * In Verilog bit-vectors, endianness determines how we index into the vector.

  * In Haskell lists, endianness determines which side of the list the least
    significant bit is.

== Verilog ==

In Verilog, words are always written with the least significant on the right.
The word {0,0,1,0} corresponds to the number 2 regardless of endianness.

Endianness simply determines how we index into a word.  In little endian, index
0 is on the right, and in big endian, it is on the left.  Thus, in the
bit-vector {0,0,1,0}, the 1 is at index 1 if it is little endian and index 2 if
it is big endian.

The endianness of a bit-vector is determined by its declaration:

  wire [3:0] x;  // little endian
  wire [0:3] y;  // big endian

Index ranges must follow the same direction as the declaration.  Given the above
declarations, x[1:0] would be a valid slice, but x[0:1] would not.

== Haskell ==

In Haskell, lists are written left to right, with index 0 being on the left.  We
say that a list of bits is little endian if the least significant is first (at
index 0), and big endian if the most significant is first.  So, the list
[0,1,0,0] represents 2 if it is little endian and 4 if it is big endian, but the
1 is always at index 1, regardless of endianness.

This definition of endianness is different than the Verilog notion of
endianness.  In fact, Verilog bit-vectors are most like big-endian Haskell
lists, because all Verilog bit-vectors have the least significant bit on the
right.

-}


text:
package endorser

import (
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"testing"
	"time"

	"path/filepath"

	"errors"

	"github.com/golang/protobuf/proto"
	mockpolicies "github.com/hyperledger/fabric/common/mocks/policies"
	"github.com/hyperledger/fabric/common/policies"
	"github.com/hyperledger/fabric/common/util"
	"github.com/hyperledger/fabric/core/chaincode"
	"github.com/hyperledger/fabric/core/common/ccprovider"
	"github.com/hyperledger/fabric/core/config"
	"github.com/hyperledger/fabric/core/container"
	"github.com/hyperledger/fabric/core/peer"
	syscc "github.com/hyperledger/fabric/core/scc"
	"github.com/hyperledger/fabric/msp"
	mspmgmt "github.com/hyperledger/fabric/msp/mgmt"
	"github.com/hyperledger/fabric/msp/mgmt/testtools"
	"github.com/hyperledger/fabric/protos/common"
	pb "github.com/hyperledger/fabric/protos/peer"
	pbutils "github.com/hyperledger/fabric/protos/utils"
	"github.com/spf13/viper"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

var endorserServer pb.EndorserServer
var signer msp.SigningIdentity

type testEnvironment struct {
	tempDir  string
	listener net.Listener
}

//initialize peer and start up. If security==enabled, login as vp
func initPeer(chainID string) (*testEnvironment, error) {
	//start clean
	// finitPeer(nil)
	var opts []grpc.ServerOption
	if viper.GetBool("peer.tls.enabled") {
		creds, err := credentials.NewServerTLSFromFile(config.GetPath("peer.tls.cert.file"), config.GetPath("peer.tls.key.file"))
		if err != nil {
			return nil, fmt.Errorf("Failed to generate credentials %v", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	grpcServer := grpc.NewServer(opts...)

	tempDir := newTempDir()
	viper.Set("peer.fileSystemPath", filepath.Join(tempDir, "hyperledger", "production"))

	peerAddress, err := peer.GetLocalAddress()
	if err != nil {
		return nil, fmt.Errorf("Error obtaining peer address: %s", err)
	}
	lis, err := net.Listen("tcp", peerAddress)
	if err != nil {
		return nil, fmt.Errorf("Error starting peer listener %s", err)
	}

	//initialize ledger
	peer.MockInitialize()

	mspGetter := func(cid string) []string {
		return []string{"DEFAULT"}
	}

	peer.MockSetMSPIDGetter(mspGetter)

	getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
		return &pb.PeerEndpoint{Id: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil
	}

	ccStartupTimeout := time.Duration(30000) * time.Millisecond
	pb.RegisterChaincodeSupportServer(grpcServer, chaincode.NewChaincodeSupport(getPeerEndpoint, false, ccStartupTimeout))

	syscc.RegisterSysCCs()

	if err = peer.MockCreateChain(chainID); err != nil {
		closeListenerAndSleep(lis)
		return nil, err
	}

	syscc.DeploySysCCs(chainID)

	go grpcServer.Serve(lis)

	return &testEnvironment{tempDir: tempDir, listener: lis}, nil
}

func finitPeer(tev *testEnvironment) {
	closeListenerAndSleep(tev.listener)
	os.RemoveAll(tev.tempDir)
}

func closeListenerAndSleep(l net.Listener) {
	if l != nil {
		l.Close()
		time.Sleep(2 * time.Second)
	}
}

// getInvokeProposal gets the proposal for the chaincode invocation
// Currently supported only for Invokes
// It returns the proposal and the transaction id associated to the proposal
func getInvokeProposal(cis *pb.ChaincodeInvocationSpec, chainID string, creator []byte) (*pb.Proposal, string, error) {
	return pbutils.CreateChaincodeProposal(common.HeaderType_ENDORSER_TRANSACTION, chainID, cis, creator)
}

// getInvokeProposalOverride allows to get a proposal for the chaincode invocation
// overriding transaction id and nonce which are by default auto-generated.
// It returns the proposal and the transaction id associated to the proposal
func getInvokeProposalOverride(txid string, cis *pb.ChaincodeInvocationSpec, chainID string, nonce, creator []byte) (*pb.Proposal, string, error) {
	return pbutils.CreateChaincodeProposalWithTxIDNonceAndTransient(txid, common.HeaderType_ENDORSER_TRANSACTION, chainID, cis, nonce, creator, nil)
}

func getDeployProposal(cds *pb.ChaincodeDeploymentSpec, chainID string, creator []byte) (*pb.Proposal, error) {
	return getDeployOrUpgradeProposal(cds, chainID, creator, false)
}

func getUpgradeProposal(cds *pb.ChaincodeDeploymentSpec, chainID string, creator []byte) (*pb.Proposal, error) {
	return getDeployOrUpgradeProposal(cds, chainID, creator, true)
}

//getDeployOrUpgradeProposal gets the proposal for the chaincode deploy or upgrade
//the payload is a ChaincodeDeploymentSpec
func getDeployOrUpgradeProposal(cds *pb.ChaincodeDeploymentSpec, chainID string, creator []byte, upgrade bool) (*pb.Proposal, error) {
	//we need to save off the chaincode as we have to instantiate with nil CodePackage
	var err error
	if err = ccprovider.PutChaincodeIntoFS(cds); err != nil {
		return nil, err
	}

	cds.CodePackage = nil

	b, err := proto.Marshal(cds)
	if err != nil {
		return nil, err
	}

	var propType string
	if upgrade {
		propType = "upgrade"
	} else {
		propType = "deploy"
	}
	sccver := util.GetSysCCVersion()
	//wrap the deployment in an invocation spec to lscc...
	lsccSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: &pb.ChaincodeSpec{Type: pb.ChaincodeSpec_GOLANG, ChaincodeId: &pb.ChaincodeID{Name: "lscc", Version: sccver}, Input: &pb.ChaincodeInput{Args: [][]byte{[]byte(propType), []byte(chainID), b}}}}

	//...and get the proposal for it
	var prop *pb.Proposal
	if prop, _, err = getInvokeProposal(lsccSpec, chainID, creator); err != nil {
		return nil, err
	}

	return prop, nil
}

func getSignedProposal(prop *pb.Proposal, signer msp.SigningIdentity) (*pb.SignedProposal, error) {
	propBytes, err := pbutils.GetBytesProposal(prop)
	if err != nil {
		return nil, err
	}

	signature, err := signer.Sign(propBytes)
	if err != nil {
		return nil, err
	}

	return &pb.SignedProposal{ProposalBytes: propBytes, Signature: signature}, nil
}

func getDeploymentSpec(context context.Context, spec *pb.ChaincodeSpec) (*pb.ChaincodeDeploymentSpec, error) {
	codePackageBytes, err := container.GetChaincodePackageBytes(spec)
	if err != nil {
		return nil, err
	}
	chaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: codePackageBytes}
	return chaincodeDeploymentSpec, nil
}

func deploy(endorserServer pb.EndorserServer, chainID string, spec *pb.ChaincodeSpec, f func(*pb.ChaincodeDeploymentSpec)) (*pb.ProposalResponse, *pb.Proposal, error) {
	return deployOrUpgrade(endorserServer, chainID, spec, f, false)
}

func upgrade(endorserServer pb.EndorserServer, chainID string, spec *pb.ChaincodeSpec, f func(*pb.ChaincodeDeploymentSpec)) (*pb.ProposalResponse, *pb.Proposal, error) {
	return deployOrUpgrade(endorserServer, chainID, spec, f, true)
}

func deployOrUpgrade(endorserServer pb.EndorserServer, chainID string, spec *pb.ChaincodeSpec, f func(*pb.ChaincodeDeploymentSpec), upgrade bool) (*pb.ProposalResponse, *pb.Proposal, error) {
	var err error
	var depSpec *pb.ChaincodeDeploymentSpec

	ctxt := context.Background()
	depSpec, err = getDeploymentSpec(ctxt, spec)
	if err != nil {
		return nil, nil, err
	}

	if f != nil {
		f(depSpec)
	}

	creator, err := signer.Serialize()
	if err != nil {
		return nil, nil, err
	}

	var prop *pb.Proposal
	if upgrade {
		prop, err = getUpgradeProposal(depSpec, chainID, creator)
	} else {
		prop, err = getDeployProposal(depSpec, chainID, creator)
	}
	if err != nil {
		return nil, nil, err
	}

	var signedProp *pb.SignedProposal
	signedProp, err = getSignedProposal(prop, signer)
	if err != nil {
		return nil, nil, err
	}

	var resp *pb.ProposalResponse
	resp, err = endorserServer.ProcessProposal(context.Background(), signedProp)

	return resp, prop, err
}

func invoke(chainID string, spec *pb.ChaincodeSpec) (*pb.Proposal, *pb.ProposalResponse, string, []byte, error) {
	invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	creator, err := signer.Serialize()
	if err != nil {
		return nil, nil, "", nil, err
	}

	var prop *pb.Proposal
	prop, txID, err := getInvokeProposal(invocation, chainID, creator)
	if err != nil {
		return nil, nil, "", nil, fmt.Errorf("Error creating proposal  %s: %s\n", spec.ChaincodeId, err)
	}

	nonce, err := pbutils.GetNonce(prop)
	if err != nil {
		return nil, nil, "", nil, fmt.Errorf("Failed getting nonce  %s: %s\n", spec.ChaincodeId, err)
	}

	var signedProp *pb.SignedProposal
	signedProp, err = getSignedProposal(prop, signer)
	if err != nil {
		return nil, nil, "", nil, err
	}

	resp, err := endorserServer.ProcessProposal(context.Background(), signedProp)
	if err != nil {
		return nil, nil, "", nil, fmt.Errorf("Error endorsing %s: %s\n", spec.ChaincodeId, err)
	}

	return prop, resp, txID, nonce, err
}

func invokeWithOverride(txid string, chainID string, spec *pb.ChaincodeSpec, nonce []byte) (*pb.ProposalResponse, error) {
	invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	creator, err := signer.Serialize()
	if err != nil {
		return nil, err
	}

	var prop *pb.Proposal
	prop, _, err = getInvokeProposalOverride(txid, invocation, chainID, nonce, creator)
	if err != nil {
		return nil, fmt.Errorf("Error creating proposal with override  %s %s: %s\n", txid, spec.ChaincodeId, err)
	}

	var signedProp *pb.SignedProposal
	signedProp, err = getSignedProposal(prop, signer)
	if err != nil {
		return nil, err
	}

	resp, err := endorserServer.ProcessProposal(context.Background(), signedProp)
	if err != nil {
		return nil, fmt.Errorf("Error endorsing %s %s: %s\n", txid, spec.ChaincodeId, err)
	}

	return resp, err
}

func deleteChaincodeOnDisk(chaincodeID string) {
	os.RemoveAll(filepath.Join(config.GetPath("peer.fileSystemPath"), "chaincodes", chaincodeID))
}

//begin tests. Note that we rely upon the system chaincode and peer to be created
//once and be used for all the tests. In order to avoid dependencies / collisions
//due to deployed chaincodes, trying to use different chaincodes for different
//tests

//TestDeploy deploy chaincode example01
func TestDeploy(t *testing.T) {
	chainID := util.GetTestChainID()
	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: &pb.ChaincodeID{Name: "ex01", Path: "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01", Version: "0"}, Input: &pb.ChaincodeInput{Args: [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}}}
	defer deleteChaincodeOnDisk("ex01.0")

	cccid := ccprovider.NewCCContext(chainID, "ex01", "0", "", false, nil, nil)

	_, _, err := deploy(endorserServer, chainID, spec, nil)
	if err != nil {
		t.Fail()
		t.Logf("Deploy-error in deploy %s", err)
		chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
		return
	}
	chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
}

//REMOVE WHEN JAVA CC IS ENABLED
func TestJavaDeploy(t *testing.T) {
	chainID := util.GetTestChainID()
	//pretend this is a java CC (type 4)
	spec := &pb.ChaincodeSpec{Type: 4, ChaincodeId: &pb.ChaincodeID{Name: "javacc", Path: "../../examples/chaincode/java/chaincode_example02", Version: "0"}, Input: &pb.ChaincodeInput{Args: [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}}}
	defer deleteChaincodeOnDisk("javacc.0")

	cccid := ccprovider.NewCCContext(chainID, "javacc", "0", "", false, nil, nil)

	_, _, err := deploy(endorserServer, chainID, spec, nil)
	if err == nil {
		t.Fail()
		t.Logf("expected java CC deploy to fail")
		chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
		return
	}
	chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
}

//TestRedeploy - deploy two times, second time should fail but example02 should remain deployed
func TestRedeploy(t *testing.T) {
	chainID := util.GetTestChainID()

	//invalid arguments
	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: &pb.ChaincodeID{Name: "ex02", Path: "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", Version: "0"}, Input: &pb.ChaincodeInput{Args: [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}}}

	defer deleteChaincodeOnDisk("ex02.0")

	cccid := ccprovider.NewCCContext(chainID, "ex02", "0", "", false, nil, nil)

	_, _, err := deploy(endorserServer, chainID, spec, nil)
	if err != nil {
		t.Fail()
		t.Logf("error in endorserServer.ProcessProposal %s", err)
		chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
		return
	}

	deleteChaincodeOnDisk("ex02.0")

	//second time should not fail as we are just simulating
	_, _, err = deploy(endorserServer, chainID, spec, nil)
	if err != nil {
		t.Fail()
		t.Logf("error in endorserServer.ProcessProposal %s", err)
		chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
		return
	}
	chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
}

// TestDeployAndInvoke deploys and invokes chaincode_example01
func TestDeployAndInvoke(t *testing.T) {
	chainID := util.GetTestChainID()
	var ctxt = context.Background()

	url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
	chaincodeID := &pb.ChaincodeID{Path: url, Name: "ex01", Version: "0"}

	defer deleteChaincodeOnDisk("ex01.0")

	args := []string{"10"}

	f := "init"
	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: argsDeploy}}

	cccid := ccprovider.NewCCContext(chainID, "ex01", "0", "", false, nil, nil)

	resp, prop, err := deploy(endorserServer, chainID, spec, nil)
	chaincodeID1 := spec.ChaincodeId.Name
	if err != nil {
		t.Fail()
		t.Logf("Error deploying <%s>: %s", chaincodeID1, err)
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}
	var nextBlockNumber uint64 = 1 // first block needs to be block number = 1. Genesis block is block 0
	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
	if err != nil {
		t.Fail()
		t.Logf("Error committing deploy <%s>: %s", chaincodeID1, err)
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}

	f = "invoke"
	invokeArgs := append([]string{f}, args...)
	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
	prop, resp, txid, nonce, err := invoke(chainID, spec)
	if err != nil {
		t.Fail()
		t.Logf("Error invoking transaction: %s", err)
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}
	// Commit invoke
	nextBlockNumber++
	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
	if err != nil {
		t.Fail()
		t.Logf("Error committing first invoke <%s>: %s", chaincodeID1, err)
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}

	// Now test for an invalid TxID
	f = "invoke"
	invokeArgs = append([]string{f}, args...)
	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
	_, err = invokeWithOverride("invalid_tx_id", chainID, spec, nonce)
	if err == nil {
		t.Fail()
		t.Log("Replay attack protection faild. Transaction with invalid txid passed")
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}

	// Now test for duplicated TxID
	f = "invoke"
	invokeArgs = append([]string{f}, args...)
	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
	_, err = invokeWithOverride(txid, chainID, spec, nonce)
	if err == nil {
		t.Fail()
		t.Log("Replay attack protection faild. Transaction with duplicaged txid passed")
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}

	fmt.Printf("Invoke test passed\n")
	t.Logf("Invoke test passed")

	chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
}

// TestUpgradeAndInvoke deploys chaincode_example01, upgrade it with chaincode_example02, then invoke it
func TestDeployAndUpgrade(t *testing.T) {
	chainID := util.GetTestChainID()
	var ctxt = context.Background()

	url1 := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
	url2 := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
	chaincodeID1 := &pb.ChaincodeID{Path: url1, Name: "upgradeex01", Version: "0"}
	chaincodeID2 := &pb.ChaincodeID{Path: url2, Name: "upgradeex01", Version: "1"}

	defer deleteChaincodeOnDisk("upgradeex01.0")
	defer deleteChaincodeOnDisk("upgradeex01.1")

	f := "init"
	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID1, Input: &pb.ChaincodeInput{Args: argsDeploy}}

	cccid1 := ccprovider.NewCCContext(chainID, "upgradeex01", "0", "", false, nil, nil)
	cccid2 := ccprovider.NewCCContext(chainID, "upgradeex01", "1", "", false, nil, nil)

	resp, prop, err := deploy(endorserServer, chainID, spec, nil)

	chaincodeName := spec.ChaincodeId.Name
	if err != nil {
		t.Fail()
		chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
		chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
		t.Logf("Error deploying <%s>: %s", chaincodeName, err)
		return
	}

	var nextBlockNumber uint64 = 3 // something above created block 0
	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
	if err != nil {
		t.Fail()
		chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
		chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
		t.Logf("Error committing <%s>: %s", chaincodeName, err)
		return
	}

	argsUpgrade := util.ToChaincodeArgs(f, "a", "150", "b", "300")
	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID2, Input: &pb.ChaincodeInput{Args: argsUpgrade}}
	_, _, err = upgrade(endorserServer, chainID, spec, nil)
	if err != nil {
		t.Fail()
		chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
		chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
		t.Logf("Error upgrading <%s>: %s", chaincodeName, err)
		return
	}

	fmt.Printf("Upgrade test passed\n")
	t.Logf("Upgrade test passed")

	chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
	chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
}

// TestWritersACLFail deploys a chaincode and then tries to invoke it;
// however we inject a special policy for writers to simulate
// the scenario in which the creator of this proposal is not among
// the writers for the chain
func TestWritersACLFail(t *testing.T) {
	//skip pending FAB-2457 fix
	t.Skip()
	chainID := util.GetTestChainID()
	var ctxt = context.Background()

	url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
	chaincodeID := &pb.ChaincodeID{Path: url, Name: "ex01-fail", Version: "0"}

	defer deleteChaincodeOnDisk("ex01-fail.0")

	args := []string{"10"}

	f := "init"
	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: argsDeploy}}

	cccid := ccprovider.NewCCContext(chainID, "ex01-fail", "0", "", false, nil, nil)

	resp, prop, err := deploy(endorserServer, chainID, spec, nil)
	chaincodeID1 := spec.ChaincodeId.Name
	if err != nil {
		t.Fail()
		t.Logf("Error deploying <%s>: %s", chaincodeID1, err)
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}
	var nextBlockNumber uint64 = 3 // The tests that ran before this test created blocks 0-2
	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
	if err != nil {
		t.Fail()
		t.Logf("Error committing deploy <%s>: %s", chaincodeID1, err)
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}

	// here we inject a reject policy for writers
	// to simulate the scenario in which the invoker
	// is not authorized to issue this proposal
	rejectpolicy := &mockpolicies.Policy{
		Err: errors.New("The creator of this proposal does not fulfil the writers policy of this chain"),
	}
	pm := peer.GetPolicyManager(chainID)
	pm.(*mockpolicies.Manager).PolicyMap = map[string]policies.Policy{policies.ChannelApplicationWriters: rejectpolicy}

	f = "invoke"
	invokeArgs := append([]string{f}, args...)
	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
	prop, resp, _, _, err = invoke(chainID, spec)
	if err == nil {
		t.Fail()
		t.Logf("Invocation should have failed")
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}

	fmt.Println("TestWritersACLFail passed")
	t.Logf("TestWritersACLFail passed")

	chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
}

// TestAdminACLFail deploys tried to deploy a chaincode;
// however we inject a special policy for admins to simulate
// the scenario in which the creator of this proposal is not among
// the admins for the chain
func TestAdminACLFail(t *testing.T) {
	//skip pending FAB-2457 fix
	t.Skip()
	chainID := util.GetTestChainID()

	// here we inject a reject policy for admins
	// to simulate the scenario in which the invoker
	// is not authorized to issue this proposal
	rejectpolicy := &mockpolicies.Policy{
		Err: errors.New("The creator of this proposal does not fulfil the writers policy of this chain"),
	}
	pm := peer.GetPolicyManager(chainID)
	pm.(*mockpolicies.Manager).PolicyMap = map[string]policies.Policy{policies.ChannelApplicationAdmins: rejectpolicy}

	var ctxt = context.Background()

	url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
	chaincodeID := &pb.ChaincodeID{Path: url, Name: "ex01-fail1", Version: "0"}

	defer deleteChaincodeOnDisk("ex01-fail1.0")

	f := "init"
	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: argsDeploy}}

	cccid := ccprovider.NewCCContext(chainID, "ex01-fail1", "0", "", false, nil, nil)

	_, _, err := deploy(endorserServer, chainID, spec, nil)
	if err == nil {
		t.Fail()
		t.Logf("Deploying chaincode should have failed!")
		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
		return
	}

	fmt.Println("TestAdminACLFail passed")
	t.Logf("TestATestAdminACLFailCLFail passed")

	chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
}

// TestInvokeSccFail makes sure that invoking a system chaincode fails
func TestInvokeSccFail(t *testing.T) {
	chainID := util.GetTestChainID()

	chaincodeID := &pb.ChaincodeID{Name: "escc"}
	args := util.ToChaincodeArgs("someFunc", "someArg")
	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: args}}
	_, _, _, _, err := invoke(chainID, spec)
	if err == nil {
		t.Logf("Invoking escc should have failed!")
		t.Fail()
		return
	}
}

func newTempDir() string {
	tempDir, err := ioutil.TempDir("", "fabric-")
	if err != nil {
		panic(err)
	}
	return tempDir
}

func TestMain(m *testing.M) {
	SetupTestConfig()

	chainID := util.GetTestChainID()
	tev, err := initPeer(chainID)
	if err != nil {
		os.Exit(-1)
		fmt.Printf("Could not initialize tests")
		finitPeer(tev)
		return
	}

	endorserServer = NewEndorserServer()

	// setup the MSP manager so that we can sign/verify
	err = msptesttools.LoadMSPSetupForTesting()
	if err != nil {
		fmt.Printf("Could not initialize msp/signer, err %s", err)
		finitPeer(tev)
		os.Exit(-1)
		return
	}
	signer, err = mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
	if err != nil {
		fmt.Printf("Could not initialize msp/signer")
		finitPeer(tev)
		os.Exit(-1)
		return
	}

	retVal := m.Run()

	finitPeer(tev)

	os.Exit(retVal)
}


text:
// userFormCompoment

UserForm.$inject = [ '$scope', '$location' ];
function UserForm($scope, $location) {
  this.$location = $location;
  this.submitAllowed = function () {
    return $scope.userForm.$valid && $scope.userForm.$dirty;
  }
}

UserForm.controller = UserForm;
UserForm.bindings = {
  "user": "<",
  "onUpdate": "<",
  "backTo": "@"
}
UserForm.template = '#include("./build/user-form.html")';

UserForm.prototype.cancel = function () {
  this.goBack();
}

UserForm.prototype.accept = function () {
  if (this.submitAllowed()) {
    this.onUpdate && this.onUpdate(this.user);
    this.goBack();
  }
}

UserForm.prototype.goBack = function () {
  this.backTo && this.$location.path(this.backTo);
}

angular
  .module('userFormCompoment', [])
  .component('userForm', UserForm);


text:
@implementation HistoryViewController

-(void)viewDidAppear:(BOOL)animated{
    NSMutableAttributedString *logs = [[NSMutableAttributedString alloc]init];
    for (NSAttributedString *log in self.history){
        [logs appendAttributedString:log];
        [logs appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n" attributes:nil]];
    }

    self.historyTextView.attributedText=logs;
}
@end


text:
<?php

namespace Graze\Supervisor;

interface SupervisorInterface
{
    /**
     * @return bool
     */
    public function ping();

    /**
     * @param callable $fn
     * @return SupervisorInterface
     */
    public function restart(callable $fn = null);

    /**
     * @param callable $fn
     * @return SupervisorInterface
     */
    public function start(callable $fn = null);

    /**
     * @param int $signal
     * @return SupervisorInterface
     */
    public function stop($signal = null);

    /**
     * @param float $delay
     * @return SupervisorInterface
     */
    public function supervise($delay = 0.001);
}


text:
import { parentPort, workerData } from "worker_threads";
import { Scanner, workerThreadData } from "./cobscanner";
import { ScanStats } from "./cobscannerdata";
import { IExternalFeatures } from "./externalfeatures";

import * as fs from "fs";
import * as path from "path";
import util from "util";
import { ICOBOLSettings } from "./iconfiguration";
import { ICOBOLSourceScannerEventer } from "./cobolsourcescanner";
import { COBOLFileUtils } from "./fileutils";

export class ThreadConsoleExternalFeatures implements IExternalFeatures {
    public static readonly Default = new ThreadConsoleExternalFeatures();

    public workspaceFolders: string[] = [];

    public logMessage(message: string): void {
        if (parentPort !== null) {
            parentPort.postMessage(message);
        }

        return;
    }

    public logException(message: string, ex: Error): void {
        this.logMessage(ex.name + ": " + message);
        if (ex !== undefined && ex.stack !== undefined) {
            this.logMessage(ex.stack);
        }
        return;
    }

    readonly logTimeThreshold = 500;

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    public logTimedMessage(timeTaken: number, message: string, ...parameters: any[]): boolean {
        const fixedTimeTaken = " (" + timeTaken.toFixed(2) + "ms)";

        if (timeTaken < this.logTimeThreshold) {
            return false;
        }

        if ((parameters !== undefined || parameters !== null) && parameters.length !== 0) {
            const m: string = util.format(message, parameters);
            this.logMessage(m.padEnd(60) + fixedTimeTaken);
        } else {
            this.logMessage(message.padEnd(60) + fixedTimeTaken);
        }

        return true;

    }

    public performance_now(): number {
        return Date.now();
    }

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    public expandLogicalCopyBookToFilenameOrEmpty(filename: string, inDirectory: string, config: ICOBOLSettings): string {
        return "";
    }

    public setWorkspaceFolders(folders: string[]):void {
        this.workspaceFolders = folders;
    }

    public getWorkspaceFolders(): string[] {
        return this.workspaceFolders;
    }

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    public getFullWorkspaceFilename(sdir: string, sdirMs: BigInt): string | undefined {
        for (const folder of this.workspaceFolders) {
            const possibleFile = path.join(folder, sdir);
            if (this.isFile(possibleFile)) {
                const stat4src = fs.statSync(possibleFile, { bigint: true });
                if (sdirMs === stat4src.mtimeMs) {
                    return possibleFile;
                }
            }
        }

        return undefined;
    }

    public isFile(possibleFilename:string): boolean {
        try {
            if (fs.existsSync(possibleFilename)) {
                // not on windows, do extra check for +x perms (protects exe & dirs)
                // if (!COBOLFileUtils.isWin32) {
                //     try {
                //         fs.accessSync(sdir, fs.constants.F_OK | fs.constants.X_OK);
                //         return false;
                //     }
                //     catch {
                //         return true;
                //     }
                // }

                return true;
            }
        }
        catch {
            return false;
        }
        return false;
    }

    public isDirectory(possibleDirectory: string) : boolean {
        return COBOLFileUtils.isDirectory(possibleDirectory);
    }

    public getFileModTimeStamp(filename: string):BigInt {
        try {
            return (BigInt)(fs.statSync(filename, {bigint: true }).mtimeMs);
        } catch {
            //
        }

        return (BigInt)(0);
    }

    private fileSearchDirectory: string[] = [];

    public getCombinedCopyBookSearchPath(): string[] {
        return this.fileSearchDirectory;
    }

    public setCombinedCopyBookSearchPath(fileSearchDirectory: string[]):void {
        this.fileSearchDirectory = fileSearchDirectory;
    }

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    public getSourceTimeout(config: ICOBOLSettings): number {
        return Number.MAX_VALUE;
    }

    private URLSearchDirectory: string[] = [];

    public getURLCopyBookSearchPath(): string[] {
        return this.URLSearchDirectory;
    }

    public setURLCopyBookSearchPath(fileSearchDirectory: string[]): void {
        this.URLSearchDirectory = fileSearchDirectory;
    }

     public async isFileASync(possibleFilename: string): Promise<boolean> {
        return false;
     }
}

class threadSender implements ICOBOLSourceScannerEventer {
    public static Default = new threadSender();

    sendMessage(message: string): void {
        if (parentPort !== null) {
            parentPort.postMessage(message);
        }
    }
}

if (parentPort !== null) {
    try {
        const features = ThreadConsoleExternalFeatures.Default;
        const wd: workerThreadData = workerData as workerThreadData;
        const scanData = wd.scanData;
        scanData.showStats = false;
        const sd = new ScanStats();
        Scanner.transferScanDataToGlobals(scanData, features);
        Scanner.processFiles(scanData,features, threadSender.Default, sd);
        parentPort.postMessage(`++${JSON.stringify(sd)}`);
    } catch (e) {
        threadSender.Default.sendMessage((e as Error).message);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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.scijava</groupId>
		<artifactId>pom-scijava</artifactId>
		<version>12.0.0</version>
		<relativePath />
	</parent>

	<groupId>net.imagej</groupId>
	<artifactId>pom-imagej</artifactId>
	<version>17.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<name>ImageJ Projects</name>
	<description>Obsolete parent POM. Extend scijava:pom-scijava instead!</description>
	<url>http://imagej.net/</url>
	<inceptionYear>2009</inceptionYear>
	<organization>
		<name>ImageJ</name>
		<url>http://imagej.net/</url>
	</organization>
	<licenses>
		<license>
			<name>Simplified BSD License</name>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<build>
			<plugins>
				<plugin>
					<artifactId>maven-enforcer-plugin</artifactId>
					<configuration>
						<rules combine.self="override">
							<requireProperty>
								<property>project.artifactId</property>
								<regex>pom-imagej</regex>
								<regexMessage>~
+-----------------------------------------------------------------------+
| The pom-imagej parent is obsolete. Please extend pom-scijava instead! |
+-----------------------------------------------------------------------+
~</regexMessage>
							</requireProperty>
						</rules>
					</configuration>
				</plugin>
			</plugins>
	</build>

	<developers>
		<developer>
			<id>ctrueden</id>
			<name>Curtis Rueden</name>
			<url>http://imagej.net/User:Rueden</url>
			<roles>
				<role>founder</role>
				<role>lead</role>
				<role>maintainer</role>
			</roles>
		</developer>
	</developers>
	<contributors>
		<contributor>
			<name>Johannes Schindelin</name>
			<url>http://imagej.net/User:Schindelin</url>
			<roles><role>founder</role></roles>
			<properties><id>dscho</id></properties>
		</contributor>
		<contributor>
			<name>Mark Hiner</name>
			<url>http://imagej.net/User:Hinerm</url>
			<properties><id>hinerm</id></properties>
		</contributor>
		<contributor>
			<name>Tobias Pietzsch</name>
			<url>http://imagej.net/User:Pietzsch</url>
			<properties><id>tpietzsch</id></properties>
		</contributor>
	</contributors>

	<mailingLists>
		<mailingList>
			<name>ImageJ Forum</name>
			<archive>http://forum.imagej.net/</archive>
		</mailingList>
	</mailingLists>

	<scm>
		<connection>scm:git:git://github.com/imagej/pom-imagej</connection>
		<developerConnection>scm:git:git@github.com:imagej/pom-imagej</developerConnection>
		<tag>HEAD</tag>
		<url>https://github.com/imagej/pom-imagej</url>
	</scm>
	<issueManagement>
		<system>GitHub Issues</system>
		<url>https://github.com/imagej/pom-imagej/issues</url>
	</issueManagement>
	<ciManagement>
		<system>Jenkins</system>
		<url>http://jenkins.imagej.net/job/pom-imagej/</url>
	</ciManagement>

	<properties>
		<license.licenseName>bsd_2</license.licenseName>
		<license.copyrightOwners>Board of Regents of the University of
Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
Institute of Molecular Cell Biology and Genetics.</license.copyrightOwners>
		<license.projectName>ImageJ software for multidimensional image processing and analysis.</license.projectName>
	</properties>

</project>


text:
require_relative 'version'

# Kubernetes
class Kubernetes < FPM::Cookery::Recipe
  name 'kubernetes'
  version VERSION

  chain_package true
  chain_recipes %w(
    hyperkube
    kube-aggregator
    kube-apiserver
    kube-controller-manager
    kube-proxy
    kube-scheduler
    kubectl
    kubelet
  )

  def build; end
  def install; end
end


text:
<SpawnConfig>
<!-- Enabling this section will stop all slime spawns
  <entry id="Slime" mobName="slime" creatureType="MONSTER" rate="80" remove="true">
    <biomeFilter type="any">
      <biome type="BASE_LAND_TYPES" />
    </biomeFilter>
  </entry>
 -->

<!-- Enabling this section will remove the default wither witch spawn config and replace it with
     a new config with a higher spawn rate
 <entry id="WitherWitch" mobName="witherwitch" rate="5" remove="true">
    <biomeFilter type="any">
      <biome type="FOREST" />
      <biome type="SWAMP" />
      <biome type="PLAINS" />
      <biome type="HILLS" />
      <biome type="MOUNTAIN" />
      <biome type="NETHER" exclude="true" />
      <biome type="END" exclude="true" />
    </biomeFilter>
    <dimensionExclude name="Twilight Forest"/>
  </entry>

   <entry id="WitherWitch" mobName="witherwitch" rate="20" minGroupSize="1" maxGroupSize="1">
    <biomeFilter type="any">
      <biome type="FOREST" />
      <biome type="SWAMP" />
      <biome type="PLAINS" />
      <biome type="HILLS" />
      <biome type="MOUNTAIN" />
      <biome type="NETHER" exclude="true" />
      <biome type="END" exclude="true" />
    </biomeFilter>
    <dimensionExclude name="Twilight Forest"/>
  </entry>
-->

</SpawnConfig>


text:
py-shm-manager
==============

Little python scripts showing the share of memory via a server.

The three scripts are in python 3.

The server create a empty queue and shared this one to clients.

One client is a productor and write numbers from 1 to 1337 inside the queue
(just an exemple of use). Then this client exit.

The second client is a consumer and try to read constantly into the queue. Then
it's just print the read numbers into stdin. This one continue to try to read
until an SIGINT is send (by ^C or kill).

Usage
-----

Start the server :

```
python server.py
```

Then start the consumer and productor :

```
python ./consumer.py &
python ./productor.py &
```

Many productor and consumer can be launched at the same time. For example :
```sh
python ./consumer.py &
for i in `seq 1 100`; python ./productor.py &; done
```


text:
[![Build Status](https://travis-ci.org/jvnill/track_me.png)](https://travis-ci.org/jvnill/track_me)

This is a gem that allows you to easily add javascript based metric systems like kissmetrics and mixpanel to your application.

## Installation

Add this line to your application's Gemfile:

    gem 'track_me'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install track_me

After installing the gem, you need to run the generator that will install a few files.

    $ rails g track_me:install

## Usage

In your controllers, call trackme and pass in the name of the action and the string that will be used to describe the action.  You can also pass in a hash with a key called 'object' which will be used for sending the details of the object.

```ruby
class CommentsController < ActionController::Base
  trackme index: ['Visited the comments index page'],
         create: ['Created a comment', object: 'comment']

  def index
  end

  def create
    @comment = ...
  end
end
```

## 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