text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004-2007, Clay Loveless                               |
// | All rights reserved.                                                 |
// +----------------------------------------------------------------------+
// | This LICENSE is in the BSD license style.                            |
// | http://www.opensource.org/licenses/bsd-license.php                   |
// |                                                                      |
// | Redistribution and use in source and binary forms, with or without   |
// | modification, are permitted provided that the following conditions   |
// | are met:                                                             |
// |                                                                      |
// |  * Redistributions of source code must retain the above copyright    |
// |    notice, this list of conditions and the following disclaimer.     |
// |                                                                      |
// |  * Redistributions in binary form must reproduce the above           |
// |    copyright notice, this list of conditions and the following       |
// |    disclaimer in the documentation and/or other materials provided   |
// |    with the distribution.                                            |
// |                                                                      |
// |  * Neither the name of Clay Loveless nor the names of contributors   |
// |    may be used to endorse or promote products derived from this      |
// |    software without specific prior written permission.               |
// |                                                                      |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
// | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;     |
// | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER     |
// | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT   |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN    |
// | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE      |
// | POSSIBILITY OF SUCH DAMAGE.                                          |
// +----------------------------------------------------------------------+
// | Author: Clay Loveless <clay@killersoft.com>                          |
// +----------------------------------------------------------------------+
//
// $Id: Cleanup.php 286753 2009-08-03 19:37:03Z mrook $
//

/**
 * @package     VersionControl_SVN
 * @category    VersionControl
 * @author      Clay Loveless <clay@killersoft.com>
 */

/**
 * Subversion Cleanup command manager class
 *
 * Recursively clean up the working copy indicated by PATH, removing
 * locks, resuming unfinished operations, etc.
 *
 * $options is an array containing one or more options
 * defined by the following associative keys:
 *
 *
 *
 * $switches = array(
 *  'config-dir'    =>  'Path to a Subversion configuration directory',
 *  'diff3-cmd'     =>  'ARG'
 *                      // Use ARG as merge command.
 * );
 *
 *
 *
 * If a path is not used in the $args array, the default path of '.' will
 * be assumed.
 *
 * Note: Subversion does not offer an XML output option for this subcommand
 *
 * Note: There is no output from the svn cleanup command!
 *
 * Usage example:
 *
 * <?php
 * require_once 'VersionControl/SVN.php';
 *
 * // Setup error handling -- always a good idea!
 * $svnstack = &PEAR_ErrorStack::singleton('VersionControl_SVN');
 *
 * // Pass array of subcommands we need to factory
 * $svn = VersionControl_SVN::factory(array('cleanup'), $options);
 *
 * // Define any switches and aguments we may need
 * $args = array('/path/to/working_copy');
 *
 * // Run command
 * if ($output = $svn->cleanup->run($args)) {
 *     print_r($output);
 * } else {
 *     if (count($errs = $svnstack->getErrors())) {
 *         foreach ($errs as $err) {
 *             echo '
'.$err['message']."
\n";
 *             echo "Command used: " . $err['params']['cmd'];
 *         }
 *     }
 * }
 * ?>
 *
 *
 * @package  VersionControl_SVN
 * @version  0.4.0
 * @category SCM
 * @author   Clay Loveless <clay@killersoft.com>
 */
class VersionControl_SVN_Cleanup extends VersionControl_SVN
{
    /**
     * Valid switches for svn cleanup
     *
     * @var     array
     * @access  public
     */
    var $valid_switches = array('config-dir',
                                'config_dir',
                                'diff3-cmd'
                                );

    /**
     * Command-line arguments that should be passed
     * outside of those specified in {@link switches}.
     *
     * @var     array
     * @access  public
     */
    var $args = array();

    /**
     * Minimum number of args required by this subcommand.
     * See {@link http://svnbook.red-bean.com/svnbook/ Version Control with Subversion},
     * Subversion Complete Reference for details on arguments for this subcommand.
     * @var     int
     * @access  public
     */
    var $min_args = 0;

    /**
     * Switches required by this subcommand.
     * See {@link http://svnbook.red-bean.com/svnbook/ Version Control with Subversion},
     * Subversion Complete Reference for details on arguments for this subcommand.
     * @var     array
     * @access  public
     */
    var $required_switches = array();

    /**
     * Use exec or passthru to get results from command.
     * @var     bool
     * @access  public
     */
    var $passthru = false;

    /**
     * Prepare the svn subcommand switches.
     *
     * @param   void
     * @return  int    true on success, false on failure. Check PEAR_ErrorStack
     *                 for error details, if any.
     */
    function prepare()
    {

        $meets_requirements = $this->checkCommandRequirements();
        if (!$meets_requirements) {
            return false;
        }

        $valid_switches     = $this->valid_switches;
        $switches           = $this->switches;
        $args               = $this->args;
        $fetchmode          = $this->fetchmode;
        $invalid_switches   = array();
        $_switches          = '';

        foreach ($switches as $switch => $val) {
            if (in_array($switch, $valid_switches)) {
                $switch = str_replace('_', '-', $switch);
                switch ($switch) {
                    case 'config-dir':
                    case 'diff3-cmd':
                        $_switches .= "--$switch $val ";
                        break;
                    default:
                        // that's all, folks!
                        break;
                }
            } else {
                $invalid_switches[] = $switch;
            }
        }

        $_switches = trim($_switches);
        $this->_switches = $_switches;

        $cmd = "$this->svn_path $this->_svn_cmd $_switches";
        if (!empty($args)) {
            $cmd .= ' '. join(' ', $args);
        }
        $this->_prepped_cmd = $cmd;
        $this->prepared = true;

        $invalid = count($invalid_switches);
        if ($invalid > 0) {
            $params['was'] = 'was';
            $params['is_invalid_switch'] = 'is an invalid switch';
            if ($invalid > 1) {
                $params['was'] = 'were';
                $params['is_invalid_switch'] = 'are invalid switches';
            }
            $params['list'] = $invalid_switches;
            $params['switches'] = $switches;
            $params['_svn_cmd'] = ucfirst($this->_svn_cmd);
            $this->_stack->push(VERSIONCONTROL_SVN_NOTICE_INVALID_SWITCH, 'notice', $params);
        }
        return true;
    }

    /// }}}
}

/// }}}
?>


text:
// Generated by CoffeeScript 1.4.0

(function() {
  var PNG;

  PNG = (function() {
    var APNG_BLEND_OP_OVER, APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_NONE, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;

    PNG.load = function(url, canvas, callback) {
      var xhr,
        _this = this;
      if (typeof canvas === 'function') {
        callback = canvas;
      }
      xhr = new XMLHttpRequest;
      xhr.open("GET", url, true);
      xhr.responseType = "arraybuffer";
      xhr.onload = function() {
        var data, png;
        data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
        png = new PNG(data);
        if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
          png.render(canvas);
        }
        return typeof callback === "function" ? callback(png) : void 0;
      };
      return xhr.send(null);
    };

    APNG_DISPOSE_OP_NONE = 0;

    APNG_DISPOSE_OP_BACKGROUND = 1;

    APNG_DISPOSE_OP_PREVIOUS = 2;

    APNG_BLEND_OP_SOURCE = 0;

    APNG_BLEND_OP_OVER = 1;

    function PNG(data) {
      var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, short, text, _i, _j, _ref;
      this.data = data;
      this.pos = 8;
      this.palette = [];
      this.imgData = [];
      this.transparency = {};
      this.animation = null;
      this.text = {};
      frame = null;
      while (true) {
        chunkSize = this.readUInt32();
        section = ((function() {
          var _i, _results;
          _results = [];
          for (i = _i = 0; _i < 4; i = ++_i) {
            _results.push(String.fromCharCode(this.data[this.pos++]));
          }
          return _results;
        }).call(this)).join('');
        switch (section) {
          case 'IHDR':
            this.width = this.readUInt32();
            this.height = this.readUInt32();
            this.bits = this.data[this.pos++];
            this.colorType = this.data[this.pos++];
            this.compressionMethod = this.data[this.pos++];
            this.filterMethod = this.data[this.pos++];
            this.interlaceMethod = this.data[this.pos++];
            break;
          case 'acTL':
            this.animation = {
              numFrames: this.readUInt32(),
              numPlays: this.readUInt32() || Infinity,
              frames: []
            };
            break;
          case 'PLTE':
            this.palette = this.read(chunkSize);
            break;
          case 'fcTL':
            if (frame) {
              this.animation.frames.push(frame);
            }
            this.pos += 4;
            frame = {
              width: this.readUInt32(),
              height: this.readUInt32(),
              xOffset: this.readUInt32(),
              yOffset: this.readUInt32()
            };
            delayNum = this.readUInt16();
            delayDen = this.readUInt16() || 100;
            frame.delay = 1000 * delayNum / delayDen;
            frame.disposeOp = this.data[this.pos++];
            frame.blendOp = this.data[this.pos++];
            frame.data = [];
            break;
          case 'IDAT':
          case 'fdAT':
            if (section === 'fdAT') {
              this.pos += 4;
              chunkSize -= 4;
            }
            data = (frame != null ? frame.data : void 0) || this.imgData;
            for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
              data.push(this.data[this.pos++]);
            }
            break;
          case 'tRNS':
            this.transparency = {};
            switch (this.colorType) {
              case 3:
            	palLen = this.palette.length/3;
                this.transparency.indexed = this.read(chunkSize);
                if(this.transparency.indexed.length > palLen)
                	throw new Error('More transparent colors than palette size');
                /*
                 * According to the PNG spec trns should be increased to the same size as palette if shorter
                 */
                //short = 255 - this.transparency.indexed.length;
                short = palLen - this.transparency.indexed.length;
                if (short > 0) {
                  for (i = _j = 0; 0 <= short ? _j < short : _j > short; i = 0 <= short ? ++_j : --_j) {
                    this.transparency.indexed.push(255);
                  }
                }
                break;
              case 0:
                this.transparency.grayscale = this.read(chunkSize)[0];
                break;
              case 2:
                this.transparency.rgb = this.read(chunkSize);
            }
            break;
          case 'tEXt':
            text = this.read(chunkSize);
            index = text.indexOf(0);
            key = String.fromCharCode.apply(String, text.slice(0, index));
            this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
            break;
          case 'IEND':
            if (frame) {
              this.animation.frames.push(frame);
            }
            this.colors = (function() {
              switch (this.colorType) {
                case 0:
                case 3:
                case 4:
                  return 1;
                case 2:
                case 6:
                  return 3;
              }
            }).call(this);
            this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
            colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
            this.pixelBitlength = this.bits * colors;
            this.colorSpace = (function() {
              switch (this.colors) {
                case 1:
                  return 'DeviceGray';
                case 3:
                  return 'DeviceRGB';
              }
            }).call(this);
            this.imgData = new Uint8Array(this.imgData);
            return;
          default:
            this.pos += chunkSize;
        }
        this.pos += 4;
        if (this.pos > this.data.length) {
          throw new Error("Incomplete or corrupt PNG file");
        }
      }
      return;
    }

    PNG.prototype.read = function(bytes) {
      var i, _i, _results;
      _results = [];
      for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
        _results.push(this.data[this.pos++]);
      }
      return _results;
    };

    PNG.prototype.readUInt32 = function() {
      var b1, b2, b3, b4;
      b1 = this.data[this.pos++] << 24;
      b2 = this.data[this.pos++] << 16;
      b3 = this.data[this.pos++] << 8;
      b4 = this.data[this.pos++];
      return b1 | b2 | b3 | b4;
    };

    PNG.prototype.readUInt16 = function() {
      var b1, b2;
      b1 = this.data[this.pos++] << 8;
      b2 = this.data[this.pos++];
      return b1 | b2;
    };

    PNG.prototype.decodePixels = function(data) {
      var byte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
      if (data == null) {
        data = this.imgData;
      }
      if (data.length === 0) {
        return new Uint8Array(0);
      }
      data = new FlateStream(data);
      data = data.getBytes();
      pixelBytes = this.pixelBitlength / 8;
      scanlineLength = pixelBytes * this.width;
      pixels = new Uint8Array(scanlineLength * this.height);
      length = data.length;
      row = 0;
      pos = 0;
      c = 0;
      while (pos < length) {
        switch (data[pos++]) {
          case 0:
            for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
              pixels[c++] = data[pos++];
            }
            break;
          case 1:
            for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
              byte = data[pos++];
              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
              pixels[c++] = (byte + left) % 256;
            }
            break;
          case 2:
            for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
              byte = data[pos++];
              col = (i - (i % pixelBytes)) / pixelBytes;
              upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
              pixels[c++] = (upper + byte) % 256;
            }
            break;
          case 3:
            for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
              byte = data[pos++];
              col = (i - (i % pixelBytes)) / pixelBytes;
              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
              upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
              pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256;
            }
            break;
          case 4:
            for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
              byte = data[pos++];
              col = (i - (i % pixelBytes)) / pixelBytes;
              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
              if (row === 0) {
                upper = upperLeft = 0;
              } else {
                upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
                upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
              }
              p = left + upper - upperLeft;
              pa = Math.abs(p - left);
              pb = Math.abs(p - upper);
              pc = Math.abs(p - upperLeft);
              if (pa <= pb && pa <= pc) {
                paeth = left;
              } else if (pb <= pc) {
                paeth = upper;
              } else {
                paeth = upperLeft;
              }
              pixels[c++] = (byte + paeth) % 256;
            }
            break;
          default:
            throw new Error("Invalid filter algorithm: " + data[pos - 1]);
        }
        row++;
      }
      return pixels;
    };

    PNG.prototype.decodePalette = function() {
      var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
      palette = this.palette;
      transparency = this.transparency.indexed || [];
      ret = new Uint8Array((transparency.length || 0) + palette.length);
      pos = 0;
      length = palette.length;
      c = 0;
      for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
        ret[pos++] = palette[i];
        ret[pos++] = palette[i + 1];
        ret[pos++] = palette[i + 2];
        ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
      }
      return ret;
    };

    PNG.prototype.copyToImageData = function(imageData, pixels) {
      var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
      colors = this.colors;
      palette = null;
      alpha = this.hasAlphaChannel;
      if (this.palette.length) {
        palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
        colors = 4;
        alpha = true;
      }
      data = imageData.data || imageData;
      length = data.length;
      input = palette || pixels;
      i = j = 0;
      if (colors === 1) {
        while (i < length) {
          k = palette ? pixels[i / 4] * 4 : j;
          v = input[k++];
          data[i++] = v;
          data[i++] = v;
          data[i++] = v;
          data[i++] = alpha ? input[k++] : 255;
          j = k;
        }
      } else {
        while (i < length) {
          k = palette ? pixels[i / 4] * 4 : j;
          data[i++] = input[k++];
          data[i++] = input[k++];
          data[i++] = input[k++];
          data[i++] = alpha ? input[k++] : 255;
          j = k;
        }
      }
    };

    PNG.prototype.decode = function() {
      var ret;
      ret = new Uint8Array(this.width * this.height * 4);
      this.copyToImageData(ret, this.decodePixels());
      return ret;
    };

    scratchCanvas = document.createElement('canvas');

    scratchCtx = scratchCanvas.getContext('2d');

    makeImage = function(imageData) {
      var img;
      scratchCtx.width = imageData.width;
      scratchCtx.height = imageData.height;
      scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
      scratchCtx.putImageData(imageData, 0, 0);
      img = new Image;
      img.src = scratchCanvas.toDataURL();
      return img;
    };

    PNG.prototype.decodeFrames = function(ctx) {
      var frame, i, imageData, pixels, _i, _len, _ref, _results;
      if (!this.animation) {
        return;
      }
      _ref = this.animation.frames;
      _results = [];
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        frame = _ref[i];
        imageData = ctx.createImageData(frame.width, frame.height);
        pixels = this.decodePixels(new Uint8Array(frame.data));
        this.copyToImageData(imageData, pixels);
        frame.imageData = imageData;
        _results.push(frame.image = makeImage(imageData));
      }
      return _results;
    };

    PNG.prototype.renderFrame = function(ctx, number) {
      var frame, frames, prev;
      frames = this.animation.frames;
      frame = frames[number];
      prev = frames[number - 1];
      if (number === 0) {
        ctx.clearRect(0, 0, this.width, this.height);
      }
      if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
        ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
      } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
        ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
      }
      if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
        ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
      }
      return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
    };

    PNG.prototype.animate = function(ctx) {
      var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
        _this = this;
      frameNumber = 0;
      _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
      return (doFrame = function() {
        var f, frame;
        f = frameNumber++ % numFrames;
        frame = frames[f];
        _this.renderFrame(ctx, f);
        if (numFrames > 1 && frameNumber / numFrames < numPlays) {
          return _this.animation._timeout = setTimeout(doFrame, frame.delay);
        }
      })();
    };

    PNG.prototype.stopAnimation = function() {
      var _ref;
      return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
    };

    PNG.prototype.render = function(canvas) {
      var ctx, data;
      if (canvas._png) {
        canvas._png.stopAnimation();
      }
      canvas._png = this;
      canvas.width = this.width;
      canvas.height = this.height;
      ctx = canvas.getContext("2d");
      if (this.animation) {
        this.decodeFrames(ctx);
        return this.animate(ctx);
      } else {
        data = ctx.createImageData(this.width, this.height);
        this.copyToImageData(data, this.decodePixels());
        return ctx.putImageData(data, 0, 0);
      }
    };

    return PNG;

  })();

  window.PNG = PNG;

}).call(this);

redpajama_set_name: RedPajamaGithub


text:
package gui.observers;

import java.util.Observable;

import ast.evaluate.Int;
import expr.Ident;
import gui.component.CheckBox;
import gui.component.Control;
import gui.component.TextField;
import gui.render.State;

public class ControlChangeHandler extends Observable implements EventListener {

	private Ident ident;
	private Control control;
	private State state;

	public ControlChangeHandler(Ident ident, Control control, State state) {
		this.ident = ident;
		this.control = control;
		this.state = state;
		control.addListener(this);
	}

	@Override
	public void handleEvent(EventChange e) {
		if(e.getSource().getClass()==CheckBox.class)
		{
			CheckBox cbox= (CheckBox) e.getSource();
			state.getEnvValues().put(ident.id, cbox.getValue());
		}
		else if(((TextField) e.getSource()).getValue().getClass()==Int.class){
		//Int val= (Int) control.getValue();
			state.getEnvValues().put(ident.id, control.getValue());
			setChanged();
			notifyObservers();
		}
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Geometry (aka GGL, Generic Geometry Library)</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Examples

Classes |
Functions

within: detect if a geometry is inside another geometry, a.o. point-in-polygon

Classes

class  	boost::geometry::concepts::WithinStrategyPolygonal< Strategy >

 	Checks strategy for within (point-in-polygon)  More...

struct  	boost::geometry::strategy::within::services::default_strategy< TagContained, TagContaining, CastedTagContained, CastedTagContaining, CsTagContained, CsTagContaining, GeometryContained, GeometryContaining >

 	Traits class binding a within determination strategy to a coordinate system.  More...

Functions

template<typename Geometry1 , typename Geometry2 >

bool 	boost::geometry::within (Geometry1 const &geometry1, Geometry2 const &geometry2)

 	Checks if the first geometry is completely inside the second geometry.  More...

template<typename Geometry1 , typename Geometry2 , typename Strategy >

bool 	boost::geometry::within (Geometry1 const &geometry1, Geometry2 const &geometry2, Strategy const &strategy)

 	Checks if the first geometry is completely inside the second geometry using the specified strategy.  More...

Detailed Description

Function Documentation

template<typename Geometry1 , typename Geometry2 >

          bool boost::geometry::within
          (
          Geometry1 const &
          geometry1,

          Geometry2 const &
          geometry2

          )

Checks if the first geometry is completely inside the second geometry.

The free function within checks if the first geometry is completely inside the second geometry.

Template Parameters

Geometry1	Any type fulfilling a Geometry Concept

Geometry2	Any type fulfilling a Geometry Concept

Parameters

geometry1	A model of the specified concept which might be within the second geometry

geometry2	A model of the specified concept which might contain the first geometry

Returns

true if geometry1 is completely contained within geometry2, else false

Note

The default strategy is used for within detection

Examples:

03_polygon_example.cpp, c02_custom_box_example.cpp, and x01_qt_example.cpp.

template<typename Geometry1 , typename Geometry2 , typename Strategy >

          bool boost::geometry::within
          (
          Geometry1 const &
          geometry1,

          Geometry2 const &
          geometry2,

          Strategy const &
          strategy

          )

Checks if the first geometry is completely inside the second geometry using the specified strategy.

The free function within checks if the first geometry is completely inside the second geometry, using the specified strategy. Reasons to specify a strategy include: use another coordinate system for calculations; construct the strategy beforehand (e.g. with the radius of the Earth); select a strategy when there are more than one available for a calculation.

Template Parameters

Geometry1	Any type fulfilling a Geometry Concept

Geometry2	Any type fulfilling a Geometry Concept

Parameters

geometry1	A model of the specified concept which might be within the second geometry

geometry2	A model of the specified concept which might contain the first geometry

strategy	strategy to be used

Returns

true if geometry1 is completely contained within geometry2, else false

April 2, 2011

Copyright © 2007-2011 Barend Gehrels, Amsterdam, the Netherlands

Copyright © 2008-2011 Bruno Lalande, Paris, France

Copyright © 2009-2010 Mateusz Loskot, London, UK

<address style="text-align: right;">
Documentation is generated by Doxygen
</address>


text:
package org.apache.hadoop.hbase.namespace;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.apache.hadoop.hbase.shaded.com.google.common.collect.Sets;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.CategoryBasedTimeout;
import org.apache.hadoop.hbase.Coprocessor;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Waiter;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.MasterObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.RegionObserver;
import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.RegionServerObserver;
import org.apache.hadoop.hbase.mapreduce.TableInputFormatBase;
import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
import org.apache.hadoop.hbase.master.TableNamespaceManager;
import org.apache.hadoop.hbase.quotas.MasterQuotaManager;
import org.apache.hadoop.hbase.quotas.QuotaExceededException;
import org.apache.hadoop.hbase.quotas.QuotaUtil;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.regionserver.StoreFile;
import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.zookeeper.KeeperException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestRule;

@Category(MediumTests.class)
public class TestNamespaceAuditor {
  @Rule public final TestRule timeout = CategoryBasedTimeout.builder().
      withTimeout(this.getClass()).withLookingForStuckThread(true).build();
  private static final Log LOG = LogFactory.getLog(TestNamespaceAuditor.class);
  private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
  private static Admin ADMIN;
  private String prefix = "TestNamespaceAuditor";

  @BeforeClass
  public static void before() throws Exception {
    Configuration conf = UTIL.getConfiguration();
    conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, CustomObserver.class.getName());
    conf.setStrings(
      CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY,
      MasterSyncObserver.class.getName(), CPMasterObserver.class.getName());
    conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
    conf.setBoolean(QuotaUtil.QUOTA_CONF_KEY, true);
    conf.setClass("hbase.coprocessor.regionserver.classes", CPRegionServerObserver.class,
      RegionServerObserver.class);
    UTIL.startMiniCluster(1, 1);
    waitForQuotaInitialize(UTIL);
    ADMIN = UTIL.getAdmin();
  }

  @AfterClass
  public static void tearDown() throws Exception {
    UTIL.shutdownMiniCluster();
  }

  @After
  public void cleanup() throws Exception, KeeperException {
    for (HTableDescriptor table : ADMIN.listTables()) {
      ADMIN.disableTable(table.getTableName());
      deleteTable(table.getTableName());
    }
    for (NamespaceDescriptor ns : ADMIN.listNamespaceDescriptors()) {
      if (ns.getName().startsWith(prefix)) {
        ADMIN.deleteNamespace(ns.getName());
      }
    }
    assertTrue("Quota manager not initialized", UTIL.getHBaseCluster().getMaster()
        .getMasterQuotaManager().isQuotaInitialized());
  }

  @Test
  public void testTableOperations() throws Exception {
    String nsp = prefix + "_np2";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "5")
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
    ADMIN.createNamespace(nspDesc);
    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
    assertEquals(ADMIN.listNamespaceDescriptors().length, 3);
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");

    HTableDescriptor tableDescOne =
        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"));
    tableDescOne.addFamily(fam1);
    HTableDescriptor tableDescTwo =
        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"));
    tableDescTwo.addFamily(fam1);
    HTableDescriptor tableDescThree =
        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table3"));
    tableDescThree.addFamily(fam1);
    ADMIN.createTable(tableDescOne);
    boolean constraintViolated = false;
    try {
      ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5);
    } catch (Exception exp) {
      assertTrue(exp instanceof IOException);
      constraintViolated = true;
    } finally {
      assertTrue("Constraint not violated for table " + tableDescTwo.getTableName(),
        constraintViolated);
    }
    ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
    NamespaceTableAndRegionInfo nspState = getQuotaManager().getState(nsp);
    assertNotNull(nspState);
    assertTrue(nspState.getTables().size() == 2);
    assertTrue(nspState.getRegionCount() == 5);
    constraintViolated = false;
    try {
      ADMIN.createTable(tableDescThree);
    } catch (Exception exp) {
      assertTrue(exp instanceof IOException);
      constraintViolated = true;
    } finally {
      assertTrue("Constraint not violated for table " + tableDescThree.getTableName(),
        constraintViolated);
    }
  }

  @Test
  public void testValidQuotas() throws Exception {
    boolean exceptionCaught = false;
    FileSystem fs = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getFileSystem();
    Path rootDir = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(prefix + "vq1")
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "hihdufh")
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
    try {
      ADMIN.createNamespace(nspDesc);
    } catch (Exception exp) {
      LOG.warn(exp);
      exceptionCaught = true;
    } finally {
      assertTrue(exceptionCaught);
      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
    }
    nspDesc =
        NamespaceDescriptor.create(prefix + "vq2")
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "-456")
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
    try {
      ADMIN.createNamespace(nspDesc);
    } catch (Exception exp) {
      LOG.warn(exp);
      exceptionCaught = true;
    } finally {
      assertTrue(exceptionCaught);
      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
    }
    nspDesc =
        NamespaceDescriptor.create(prefix + "vq3")
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10")
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "sciigd").build();
    try {
      ADMIN.createNamespace(nspDesc);
    } catch (Exception exp) {
      LOG.warn(exp);
      exceptionCaught = true;
    } finally {
      assertTrue(exceptionCaught);
      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
    }
    nspDesc =
        NamespaceDescriptor.create(prefix + "vq4")
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10")
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "-1500").build();
    try {
      ADMIN.createNamespace(nspDesc);
    } catch (Exception exp) {
      LOG.warn(exp);
      exceptionCaught = true;
    } finally {
      assertTrue(exceptionCaught);
      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
    }
  }

  @Test
  public void testDeleteTable() throws Exception {
    String namespace = prefix + "_dummy";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(namespace)
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "100")
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "3").build();
    ADMIN.createNamespace(nspDesc);
    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(namespace));
    NamespaceTableAndRegionInfo stateInfo = getNamespaceState(nspDesc.getName());
    assertNotNull("Namespace state found null for " + namespace, stateInfo);
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    HTableDescriptor tableDescOne =
        new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table1"));
    tableDescOne.addFamily(fam1);
    HTableDescriptor tableDescTwo =
        new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table2"));
    tableDescTwo.addFamily(fam1);
    ADMIN.createTable(tableDescOne);
    ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5);
    stateInfo = getNamespaceState(nspDesc.getName());
    assertNotNull("Namespace state found to be null.", stateInfo);
    assertEquals(2, stateInfo.getTables().size());
    assertEquals(5, stateInfo.getRegionCountOfTable(tableDescTwo.getTableName()));
    assertEquals(6, stateInfo.getRegionCount());
    ADMIN.disableTable(tableDescOne.getTableName());
    deleteTable(tableDescOne.getTableName());
    stateInfo = getNamespaceState(nspDesc.getName());
    assertNotNull("Namespace state found to be null.", stateInfo);
    assertEquals(5, stateInfo.getRegionCount());
    assertEquals(1, stateInfo.getTables().size());
    ADMIN.disableTable(tableDescTwo.getTableName());
    deleteTable(tableDescTwo.getTableName());
    ADMIN.deleteNamespace(namespace);
    stateInfo = getNamespaceState(namespace);
    assertNull("Namespace state not found to be null.", stateInfo);
  }

  public static class CPRegionServerObserver implements RegionServerObserver {
    private volatile boolean shouldFailMerge = false;

    public void failMerge(boolean fail) {
      shouldFailMerge = fail;
    }

    private boolean triggered = false;

    public synchronized void waitUtilTriggered() throws InterruptedException {
      while (!triggered) {
        wait();
      }
    }

    @Override
    public synchronized void preMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
        Region regionA, Region regionB) throws IOException {
      triggered = true;
      notifyAll();
      if (shouldFailMerge) {
        throw new IOException("fail merge");
      }
    }
  }

  public static class CPMasterObserver implements MasterObserver {
    private volatile boolean shouldFailMerge = false;

    public void failMerge(boolean fail) {
      shouldFailMerge = fail;
    }

    @Override
    public synchronized void preMergeRegionsAction(
        final ObserverContext<MasterCoprocessorEnvironment> ctx,
        final HRegionInfo[] regionsToMerge) throws IOException {
      notifyAll();
      if (shouldFailMerge) {
        throw new IOException("fail merge");
      }
    }
  }

  @Test
  public void testRegionMerge() throws Exception {
    String nsp1 = prefix + "_regiontest";
    final int initialRegions = 3;
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp1)
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "" + initialRegions)
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
    ADMIN.createNamespace(nspDesc);
    final TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2");
    byte[] columnFamily = Bytes.toBytes("info");
    HTableDescriptor tableDescOne = new HTableDescriptor(tableTwo);
    tableDescOne.addFamily(new HColumnDescriptor(columnFamily));
    ADMIN.createTable(tableDescOne, Bytes.toBytes("1"), Bytes.toBytes("2000"), initialRegions);
    Connection connection = ConnectionFactory.createConnection(UTIL.getConfiguration());
    try (Table table = connection.getTable(tableTwo)) {
      UTIL.loadNumericRows(table, Bytes.toBytes("info"), 1000, 1999);
    }
    ADMIN.flush(tableTwo);
    List<HRegionInfo> hris = ADMIN.getTableRegions(tableTwo);
    assertEquals(initialRegions, hris.size());
    Collections.sort(hris);
    Future<?> f = ADMIN.mergeRegionsAsync(
      hris.get(0).getEncodedNameAsBytes(),
      hris.get(1).getEncodedNameAsBytes(),
      false);
    f.get(10, TimeUnit.SECONDS);

    hris = ADMIN.getTableRegions(tableTwo);
    assertEquals(initialRegions - 1, hris.size());
    Collections.sort(hris);
    ADMIN.split(tableTwo, Bytes.toBytes("500"));
    // Not much we can do here until we have split return a Future.
    Threads.sleep(5000);
    hris = ADMIN.getTableRegions(tableTwo);
    assertEquals(initialRegions, hris.size());
    Collections.sort(hris);

    // Fail region merge through Coprocessor hook
    MiniHBaseCluster cluster = UTIL.getHBaseCluster();
    MasterCoprocessorHost cpHost = cluster.getMaster().getMasterCoprocessorHost();
    Coprocessor coprocessor = cpHost.findCoprocessor(CPMasterObserver.class.getName());
    CPMasterObserver masterObserver = (CPMasterObserver) coprocessor;
    masterObserver.failMerge(true);

    f = ADMIN.mergeRegionsAsync(
      hris.get(1).getEncodedNameAsBytes(),
      hris.get(2).getEncodedNameAsBytes(),
      false);
    try {
      f.get(10, TimeUnit.SECONDS);
      fail("Merge was supposed to fail!");
    } catch (ExecutionException ee) {
      // Expected.
    }
    hris = ADMIN.getTableRegions(tableTwo);
    assertEquals(initialRegions, hris.size());
    Collections.sort(hris);
    // verify that we cannot split
    HRegionInfo hriToSplit2 = hris.get(1);
    ADMIN.split(tableTwo,
      TableInputFormatBase.getSplitKey(hriToSplit2.getStartKey(), hriToSplit2.getEndKey(), true));
    Thread.sleep(2000);
    assertEquals(initialRegions, ADMIN.getTableRegions(tableTwo).size());
  }

  /*
   * Create a table and make sure that the table creation fails after adding this table entry into
   * namespace quota cache. Now correct the failure and recreate the table with same name.
   * HBASE-13394
   */
  @Test
  public void testRecreateTableWithSameNameAfterFirstTimeFailure() throws Exception {
    String nsp1 = prefix + "_testRecreateTable";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp1)
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20")
            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1").build();
    ADMIN.createNamespace(nspDesc);
    final TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1");
    byte[] columnFamily = Bytes.toBytes("info");
    HTableDescriptor tableDescOne = new HTableDescriptor(tableOne);
    tableDescOne.addFamily(new HColumnDescriptor(columnFamily));
    MasterSyncObserver.throwExceptionInPreCreateTableAction = true;
    try {
      try {
        ADMIN.createTable(tableDescOne);
        fail("Table " + tableOne.toString() + "creation should fail.");
      } catch (Exception exp) {
        LOG.error(exp);
      }
      assertFalse(ADMIN.tableExists(tableOne));

      NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp1);
      assertEquals("First table creation failed in namespace so number of tables in namespace "
          + "should be 0.", 0, nstate.getTables().size());

      MasterSyncObserver.throwExceptionInPreCreateTableAction = false;
      try {
        ADMIN.createTable(tableDescOne);
      } catch (Exception e) {
        fail("Table " + tableOne.toString() + "creation should succeed.");
        LOG.error(e);
      }
      assertTrue(ADMIN.tableExists(tableOne));
      nstate = getNamespaceState(nsp1);
      assertEquals("First table was created successfully so table size in namespace should "
          + "be one now.", 1, nstate.getTables().size());
    } finally {
      MasterSyncObserver.throwExceptionInPreCreateTableAction = false;
      if (ADMIN.tableExists(tableOne)) {
        ADMIN.disableTable(tableOne);
        deleteTable(tableOne);
      }
      ADMIN.deleteNamespace(nsp1);
    }
  }

  private NamespaceTableAndRegionInfo getNamespaceState(String namespace) throws KeeperException,
      IOException {
    return getQuotaManager().getState(namespace);
  }

  byte[] getSplitKey(byte[] startKey, byte[] endKey) {
    String skey = Bytes.toString(startKey);
    int key;
    if (StringUtils.isBlank(skey)) {
      key = Integer.parseInt(Bytes.toString(endKey))/2 ;
    } else {
      key = (int) (Integer.parseInt(skey) * 1.5);
    }
    return Bytes.toBytes("" + key);
  }

  public static class CustomObserver implements RegionObserver {
    volatile CountDownLatch postCompact;

    @Override
    public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e,
                            Store store, StoreFile resultFile) throws IOException {
      postCompact.countDown();
    }

    @Override
    public void start(CoprocessorEnvironment e) throws IOException {
      postCompact = new CountDownLatch(1);
    }
  }

  @Test
  public void testStatePreserve() throws Exception {
    final String nsp1 = prefix + "_testStatePreserve";
    NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1)
        .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20")
        .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "10").build();
    ADMIN.createNamespace(nspDesc);
    TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1");
    TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2");
    TableName tableThree = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table3");
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    HTableDescriptor tableDescOne = new HTableDescriptor(tableOne);
    tableDescOne.addFamily(fam1);
    HTableDescriptor tableDescTwo = new HTableDescriptor(tableTwo);
    tableDescTwo.addFamily(fam1);
    HTableDescriptor tableDescThree = new HTableDescriptor(tableThree);
    tableDescThree.addFamily(fam1);
    ADMIN.createTable(tableDescOne, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3);
    ADMIN.createTable(tableDescTwo, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3);
    ADMIN.createTable(tableDescThree, Bytes.toBytes("1"), Bytes.toBytes("1000"), 4);
    ADMIN.disableTable(tableThree);
    deleteTable(tableThree);
    // wait for chore to complete
    UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
      @Override
      public boolean evaluate() throws Exception {
       return (getNamespaceState(nsp1).getTables().size() == 2);
      }
    });
    NamespaceTableAndRegionInfo before = getNamespaceState(nsp1);
    restartMaster();
    NamespaceTableAndRegionInfo after = getNamespaceState(nsp1);
    assertEquals("Expected: " + before.getTables() + " Found: " + after.getTables(), before
        .getTables().size(), after.getTables().size());
  }

  public static void waitForQuotaInitialize(final HBaseTestingUtility util) throws Exception {
    util.waitFor(60000, new Waiter.Predicate<Exception>() {
      @Override
      public boolean evaluate() throws Exception {
        HMaster master = util.getHBaseCluster().getMaster();
        if (master == null) {
          return false;
        }
        MasterQuotaManager quotaManager = master.getMasterQuotaManager();
        return quotaManager != null && quotaManager.isQuotaInitialized();
      }
    });
  }

  private void restartMaster() throws Exception {
    UTIL.getHBaseCluster().getMaster(0).stop("Stopping to start again");
    UTIL.getHBaseCluster().waitOnMaster(0);
    UTIL.getHBaseCluster().startMaster();
    waitForQuotaInitialize(UTIL);
  }

  private NamespaceAuditor getQuotaManager() {
    return UTIL.getHBaseCluster().getMaster()
        .getMasterQuotaManager().getNamespaceQuotaManager();
  }

  public static class MasterSyncObserver implements MasterObserver {
    volatile CountDownLatch tableDeletionLatch;
    static boolean throwExceptionInPreCreateTableAction;

    @Override
    public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> ctx,
        TableName tableName) throws IOException {
      tableDeletionLatch = new CountDownLatch(1);
    }

    @Override
    public void postCompletedDeleteTableAction(
        final ObserverContext<MasterCoprocessorEnvironment> ctx,
        final TableName tableName) throws IOException {
      tableDeletionLatch.countDown();
    }

    @Override
    public void preCreateTableAction(ObserverContext<MasterCoprocessorEnvironment> ctx,
        HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
      if (throwExceptionInPreCreateTableAction) {
        throw new IOException("Throw exception as it is demanded.");
      }
    }
  }

  private void deleteTable(final TableName tableName) throws Exception {
    // NOTE: We need a latch because admin is not sync,
    // so the postOp coprocessor method may be called after the admin operation returned.
    MasterSyncObserver observer = (MasterSyncObserver)UTIL.getHBaseCluster().getMaster()
      .getMasterCoprocessorHost().findCoprocessor(MasterSyncObserver.class.getName());
    ADMIN.deleteTable(tableName);
    observer.tableDeletionLatch.await();
  }

  @Test(expected = QuotaExceededException.class)
  public void testExceedTableQuotaInNamespace() throws Exception {
    String nsp = prefix + "_testExceedTableQuotaInNamespace";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1")
            .build();
    ADMIN.createNamespace(nspDesc);
    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
    assertEquals(ADMIN.listNamespaceDescriptors().length, 3);
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    HTableDescriptor tableDescOne =
        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"));
    tableDescOne.addFamily(fam1);
    HTableDescriptor tableDescTwo =
        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"));
    tableDescTwo.addFamily(fam1);
    ADMIN.createTable(tableDescOne);
    ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
  }

  @Test(expected = QuotaExceededException.class)
  public void testCloneSnapshotQuotaExceed() throws Exception {
    String nsp = prefix + "_testTableQuotaExceedWithCloneSnapshot";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1")
            .build();
    ADMIN.createNamespace(nspDesc);
    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
    TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
    TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2");
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    HTableDescriptor tableDescOne = new HTableDescriptor(tableName);
    tableDescOne.addFamily(fam1);
    ADMIN.createTable(tableDescOne);
    String snapshot = "snapshot_testTableQuotaExceedWithCloneSnapshot";
    ADMIN.snapshot(snapshot, tableName);
    ADMIN.cloneSnapshot(snapshot, cloneTableName);
    ADMIN.deleteSnapshot(snapshot);
  }

  @Test
  public void testCloneSnapshot() throws Exception {
    String nsp = prefix + "_testCloneSnapshot";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2")
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20").build();
    ADMIN.createNamespace(nspDesc);
    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
    TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
    TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2");

    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    HTableDescriptor tableDescOne = new HTableDescriptor(tableName);
    tableDescOne.addFamily(fam1);

    ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
    String snapshot = "snapshot_testCloneSnapshot";
    ADMIN.snapshot(snapshot, tableName);
    ADMIN.cloneSnapshot(snapshot, cloneTableName);

    int tableLength;
    try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(tableName)) {
      tableLength = locator.getStartKeys().length;
    }
    assertEquals(tableName.getNameAsString() + " should have four regions.", 4, tableLength);

    try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(cloneTableName)) {
      tableLength = locator.getStartKeys().length;
    }
    assertEquals(cloneTableName.getNameAsString() + " should have four regions.", 4, tableLength);

    NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp);
    assertEquals("Total tables count should be 2.", 2, nstate.getTables().size());
    assertEquals("Total regions count should be.", 8, nstate.getRegionCount());

    ADMIN.deleteSnapshot(snapshot);
  }

  @Test
  public void testRestoreSnapshot() throws Exception {
    String nsp = prefix + "_testRestoreSnapshot";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp)
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build();
    ADMIN.createNamespace(nspDesc);
    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
    TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
    HTableDescriptor tableDescOne = new HTableDescriptor(tableName1);
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    tableDescOne.addFamily(fam1);
    ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);

    NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp);
    assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount());

    String snapshot = "snapshot_testRestoreSnapshot";
    ADMIN.snapshot(snapshot, tableName1);

    List<HRegionInfo> regions = ADMIN.getTableRegions(tableName1);
    Collections.sort(regions);

    ADMIN.split(tableName1, Bytes.toBytes("JJJ"));
    Thread.sleep(2000);
    assertEquals("Total regions count should be 5.", 5, nstate.getRegionCount());

    ADMIN.disableTable(tableName1);
    ADMIN.restoreSnapshot(snapshot);

    assertEquals("Total regions count should be 4 after restore.", 4, nstate.getRegionCount());

    ADMIN.enableTable(tableName1);
    ADMIN.deleteSnapshot(snapshot);
  }

  @Test
  public void testRestoreSnapshotQuotaExceed() throws Exception {
    String nsp = prefix + "_testRestoreSnapshotQuotaExceed";
    NamespaceDescriptor nspDesc =
        NamespaceDescriptor.create(nsp)
            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build();
    ADMIN.createNamespace(nspDesc);
    NamespaceDescriptor ndesc = ADMIN.getNamespaceDescriptor(nsp);
    assertNotNull("Namespace descriptor found null.", ndesc);
    TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
    HTableDescriptor tableDescOne = new HTableDescriptor(tableName1);
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    tableDescOne.addFamily(fam1);

    ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);

    NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp);
    assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount());

    String snapshot = "snapshot_testRestoreSnapshotQuotaExceed";
    // snapshot has 4 regions
    ADMIN.snapshot(snapshot, tableName1);
    // recreate table with 1 region and set max regions to 3 for namespace
    ADMIN.disableTable(tableName1);
    ADMIN.deleteTable(tableName1);
    ADMIN.createTable(tableDescOne);
    ndesc.setConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "3");
    ADMIN.modifyNamespace(ndesc);

    ADMIN.disableTable(tableName1);
    try {
      ADMIN.restoreSnapshot(snapshot);
      fail("Region quota is exceeded so QuotaExceededException should be thrown but HBaseAdmin"
          + " wraps IOException into RestoreSnapshotException");
    } catch (RestoreSnapshotException ignore) {
      assertTrue(ignore.getCause() instanceof QuotaExceededException);
    }
    assertEquals(1, getNamespaceState(nsp).getRegionCount());
    ADMIN.enableTable(tableName1);
    ADMIN.deleteSnapshot(snapshot);
  }
}


text:
import os
import unittest

from peru import cache
from peru import rule

import shared

class RuleTest(unittest.TestCase):

    def setUp(self):
        self.cache_dir = shared.create_dir()
        self.cache = cache.Cache(self.cache_dir)
        self.content = {'a': 'foo', 'b/c': 'bar'}
        self.content_dir = shared.create_dir(self.content)
        self.content_tree = self.cache.import_tree(self.content_dir)
        self.entries = self.cache.ls_tree(self.content_tree, recursive=True)

    def test_copy(self):
        # A file copied into a directory should be placed into that directory.
        # A directory or file copied into a file should overwrite that file.
        copies = {'a': ['x', 'b', 'b/c'], 'b': ['a', 'y']}
        tree = rule.copy_files(self.cache, self.content_tree, copies)
        shared.assert_tree_contents(self.cache, tree, {
            'a/c': 'bar',
            'b/a': 'foo',
            'b/c': 'foo',
            'x':   'foo',
            'y/c': 'bar',
        })

    def test_move(self):
        # Same semantics as copy above. Also, make sure that move deletes move
        # sources, but does not delete sources that were overwritten by the
        # target of another move.
        moves = {'a': 'b', 'b': 'a'}
        tree = rule.move_files(self.cache, self.content_tree, moves)
        shared.assert_tree_contents(self.cache, tree, {
            'a/c': 'bar',
            'b/a': 'foo',
        })

    def test_pick(self):
        pick_dir = rule.pick_files(self.cache, self.content_tree, ['b'])
        shared.assert_tree_contents(self.cache, pick_dir, {'b/c': 'bar'})

        pick_file = rule.pick_files(self.cache, self.content_tree, ['a'])
        shared.assert_tree_contents(self.cache, pick_file, {'a': 'foo'})

        globs = rule.pick_files(self.cache, self.content_tree,
                                ['**/c', '**/a'])
        shared.assert_tree_contents(self.cache, globs,
                                    {'a': 'foo', 'b/c': 'bar'})

    def test_executable(self):
        exe = rule.make_files_executable(self.cache, self.content_tree,
                                         ['b/*'])
        new_content_dir = shared.create_dir()
        self.cache.export_tree(exe, new_content_dir)
        shared.assert_contents(new_content_dir, self.content)
        shared.assert_not_executable(os.path.join(new_content_dir, 'a'))
        shared.assert_executable(os.path.join(new_content_dir, 'b/c'))

    def test_export(self):
        b = rule.get_export_tree(self.cache, self.content_tree, 'b')
        shared.assert_tree_contents(self.cache, b, {'c': 'bar'})


text:
package org.efaps.esjp.common.jasperreport.datatype;

import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression;
import net.sf.dynamicreports.report.definition.ReportParameters;

import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.joda.time.DateTime;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 * @version $Id$
 */
@EFapsUUID("b8a6ae9a-31c1-4cbd-ada4-c74f903ea23f")
@EFapsApplication("eFaps-Kernel")
public class DateTimeExpression
    extends AbstractSimpleExpression<String>
{

    /**
     * Needed for serialization.
     */
    private static final long serialVersionUID = 1L;

    /**
     * The value of this expression.
     */
    private DateTime value;

    /**
     * Teh datatype.
     */
    private AbstractDateTime dataType;

    /**
     * @param _value value
     * @param _dataType datatype
     */
    public DateTimeExpression(final DateTime _value,
                              final DateTimeDate _dataType)
    {
        setValue(_value);
        setDataType(_dataType);
    }

    @Override
    public String evaluate(final ReportParameters _reportParameters)
    {
        String ret = null;
        if (getDataType() != null) {
            ret = getDataType().valueToString(getValue(), _reportParameters.getLocale());
        }
        return ret;
    }

    /**
     * Getter method for the instance variable {@link #value}.
     *
     * @return value of instance variable {@link #value}
     */
    public DateTime getValue()
    {
        return this.value;
    }

    /**
     * Setter method for instance variable {@link #value}.
     *
     * @param _value value for instance variable {@link #value}
     * @return this for chaining
     */
    public DateTimeExpression setValue(final DateTime _value)
    {
        this.value = _value;
        return this;
    }

    /**
     * Getter method for the instance variable {@link #dataType}.
     *
     * @return value of instance variable {@link #dataType}
     */
    public AbstractDateTime getDataType()
    {
        return this.dataType;
    }

    /**
     * Setter method for instance variable {@link #dataType}.
     *
     * @param _dataType value for instance variable {@link #dataType}
     * @return this for chaining
     */
    public DateTimeExpression setDataType(final AbstractDateTime _dataType)
    {
        this.dataType = _dataType;
        return this;
    }
}


text:
<?php

namespace Hail\Image\Commands;

abstract class AbstractCommand
{
    /**
     * Arguments of command
     *
     * @var array
     */
    public $arguments;

    /**
     * Output of command
     *
     * @var mixed
     */
    protected $output;

    /**
     * Executes current command on given image
     *
     * @param  \Hail\Image\Image $image
     * @return mixed
     */
    abstract public function execute($image);

    /**
     * Creates new command instance
     *
     * @param array $arguments
     */
    public function __construct($arguments)
    {
        $this->arguments = $arguments;
    }

    /**
     * Creates new argument instance from given argument key
     *
     * @param  int $key
     * @return Argument
     */
    public function argument($key)
    {
        return new Argument($this, $key);
    }

    /**
     * Returns output data of current command
     *
     * @return mixed
     */
    public function getOutput()
    {
        return $this->output ?: null;
    }

    /**
     * Determines if current instance has output data
     *
     * @return bool
     */
    public function hasOutput()
    {
        return $this->output !== null;
    }

    /**
     * Sets output data of current command
     *
     * @param mixed $value
     */
    public function setOutput($value)
    {
        $this->output = $value;
    }
}


text:
package main

import (
	"database/sql"
	"testing"
	"time"
)

func TestUpdateOrAdd(t *testing.T) {
	setup()
	defer teardown()

	cleanDB(t)

	d := data{
		sourceFile:      "etc/VGT2_e.json",
		observationFile: "etc/VGT2_e.csv",
	}

	if err := d.parseAndValidate(); err != nil {
		t.Fatal(err)
	}

	if err := d.saveSite(); err != nil {
		t.Fatal(err)
	}

	if countSites(t) != 1 {
		t.Error("didn't find site in the DB.")
	}

	if err := d.updateOrAdd(); err != nil {
		t.Fatal(err)
	}

	if countObs(t) != 7 {
		t.Error("didn't find 7 observations in the DB.")
	}
}

func TestDeleteThenSave(t *testing.T) {
	setup()
	defer teardown()

	cleanDB(t)

	d := data{
		sourceFile:      "etc/VGT2_e.json",
		observationFile: "etc/VGT2_e.csv",
	}

	if err := d.parseAndValidate(); err != nil {
		t.Fatal(err)
	}

	if err := d.saveSite(); err != nil {
		t.Fatal(err)
	}

	if countSites(t) != 1 {
		t.Error("didn't find site in the DB.")
	}

	// Save  observations with one additional one that is not in the file.
	o := obs{
		t: time.Now().UTC(),
		v: 12.2,
		e: 6.6,
	}

	d.obs = append(d.obs, o)

	if err := d.updateOrAdd(); err != nil {
		t.Fatal(err)
	}

	if countObs(t) != 8 {
		t.Error("didn't find 8 observations in the DB.")
	}

	// Add a duplicate obs and try to delete then save.  Transaction should roll back leaving
	// 8 obs in the DB.
	d.obs = append(d.obs, o)

	if err := d.deleteThenSave(); err == nil {
		t.Fatal("should get transaction error for observation primary key violation.")
	}

	if countObs(t) != 8 {
		t.Error("didn't find 8 observations in the DB.")
	}

	// reload the data then delete and save.  There should be exactly 7 rows in the DB -
	// the extra observation we added earlier is not in the observation file and should be gone.
	if err := d.parseAndValidate(); err != nil {
		t.Fatal(err)
	}

	if err := d.deleteThenSave(); err != nil {
		t.Fatal(err)
	}

	if countObs(t) != 7 {
		t.Error("didn't find 7 observations in the DB.")
	}
}

// clean out all sites and observations from the DB.
func cleanDB(t *testing.T) {
	if err := db.QueryRow("truncate fits.site cascade").Scan(); err != nil && err != sql.ErrNoRows {
		t.Fatal(err)
	}
}

// tables have been truncated so we can be lazy with the accuracy of the select

func countObs(t *testing.T) (c int) {
	if err := db.QueryRow(`	select count(*) from fits.observation`).Scan(&c); err != nil {
		t.Fatal(err)
	}

	return
}

func countSites(t *testing.T) (c int) {
	if err := db.QueryRow(`	select count(*) from fits.site`).Scan(&c); err != nil {
		t.Fatal(err)
	}

	return
}


text:
from ..utility import generateGridTable

class GridTableData(object):
    tableId = None #string
    tableHeader = None
    table = None
    weights = None
    hiddenFields = None
    changeCornAlt = False
    doesNotShowLegend = False
    checkForTableIsSave = False
    showRatingWhileFalseChangeRatingsWeights = False
    changeRatingsWeights = False
    usid = None #id of the grid

    def __init__(self, tableData=None):
        if tableData is not None:
            if tableData.has_key('table') and tableData.has_key('tableHeader') and tableData.has_key('weights'):
                self.table = tableData['table']
                self.tableHeader = tableData['tableHeader']
                self.weights = tableData['weights']

class WritableGridTableData(GridTableData):
    def __init__(self, grid=None):
        table_data = generateGridTable(grid)
        super(WritableGridTableData, self).__init__(tableData=table_data)

        if grid is not None:
            self.usid = grid.usid

        self.changeCornAlt = True
        self.checkForTableIsSave = True
        self.showRatingWhileFalseChangeRatingsWeights = True
        self.changeRatingsWeights = True


text:
package seedu.oneline.model.task;

import seedu.oneline.commons.exceptions.IllegalValueException;

public class TaskName implements Comparable<TaskName> {

    public static final String MESSAGE_TASK_NAME_CONSTRAINTS = "Task names should be spaces or alphanumeric characters";
    public static final String TASK_NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";

    public final String name;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException if given name string is invalid.
     */
    public TaskName(String name) throws IllegalValueException {
        assert name != null;
        name = name.trim();
        if (!isValidTaskName(name)) {
            throw new IllegalValueException(MESSAGE_TASK_NAME_CONSTRAINTS);
        }
        this.name = name;
    }

    /**
     * Returns true if a given string is a valid task name.
     */
    public static boolean isValidTaskName(String test) {
        return test.matches(TASK_NAME_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        return name;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof TaskName // instanceof handles nulls
                && this.name.equals(((TaskName) other).name)); // state check
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    /**
     * Serialize field for storage
     */
    public String serialize() {
        return name;
    }

    /**
     * Deserialize from storage
     */
    public static TaskName deserialize(String args) throws IllegalValueException {
        return new TaskName(args);
    }

    //@@author A0138848M
    @Override
    public int compareTo(TaskName o) {
        assert name != null;
        return this.name.compareTo(o.name);
    }
}


text:
namespace indiedevlog.web.EFModel.Objects.Tables
{
    public class PlanUpdates : BaseTable
    {
        public int UserID { get; set; }

        public string Subject { get; set; }

        public string Body { get; set; }

        public int ProjectID { get; set; }
    }
}


text:
"""Contains the OrgAppRecord model.
"""

from google.appengine.ext import db

from django.utils.translation import ugettext

from soc.models import licenses
from soc.models.linkable import LINK_ID_PATTERN_CORE
from soc.models.survey_record import SurveyRecord

import soc.models.user

class OrgAppRecord(SurveyRecord):
  """Record which must have a main admin, backup admin and proposed link ID.

  This record also contains the status of the application.
  """

#: Required field storing "ID" used in URL links. ASCII characters,
  #: digits and underscores only.  Valid link IDs successfully match
  #: the LINK_ID_REGEX.
  org_id = db.StringProperty(required=False,
      verbose_name=ugettext('Organization ID'))
  org_id.help_text = ugettext(
      'Organization ID is used as part of various URL links throughout '
      'the site.ASCII '
      'alphanumeric characters, digits, and underscores only. '
      'The regexp used to validate is "%s".') % LINK_ID_PATTERN_CORE

  #: field storing the name of the organization.
  name = db.StringProperty(
      verbose_name=ugettext('Organization Name'), required=True)

  #: field storing the description of the organization.
  description = db.TextProperty(
      verbose_name=ugettext('Organization Description'), required=True)

  #: Required field storing a home page URL of the organization.
  home_page = db.LinkProperty(
      required=True, verbose_name=ugettext('Organization Home Page URL'))

  #: Required field storing the main license an organization uses.
  license = db.StringProperty(
      required=True, choices=licenses.LICENSES,
      verbose_name=ugettext('Main Organization License'))

  #: field storing the user which first created the OrgApplicationRecord and
  #: is therefore the main admin if the application is accepted.
  main_admin = db.ReferenceProperty(
      reference_class=soc.models.user.User, required=True,
      verbose_name="Main Admin", collection_name='main_admin_org_app')

  #: field storing the user reference of the backup admin.
  backup_admin = db.ReferenceProperty(
      reference_class=soc.models.user.User, required=True,
      verbose_name="Backup Admin", collection_name='backup_admin_org_app')

  #: field storing whether the User has agreed to the org admin agreement
  agreed_to_admin_agreement = db.BooleanProperty(required=True, default=False,
      verbose_name=ugettext('I Agree to the Admin Agreement'))
  agreed_to_admin_agreement.help_text = ugettext(
      'Indicates whether the user agreed to the Admin Agreement.')

  # property containing the status of the application
  # completed means that the application has been processed into a real group
  # pre-accepted: used to indicate that the application has been accepted
  # but the group cannot be made yet.
  # pre-rejected: used to indicate that the application has been rejected
  # but the applicant has not been informed yet.
  status = db.StringProperty(required=True,
      choices=['accepted','rejected','ignored','needs review','completed',
               'pre-accepted', 'pre-rejected'],
      default='needs review',
      verbose_name=ugettext('Application Status'))


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.bazel.repository;

import com.google.common.base.Ascii;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.net.UrlEscapers;
import com.google.devtools.build.lib.bazel.repository.downloader.HttpDownloader;
import com.google.devtools.build.lib.bazel.repository.downloader.ProxyHelper;
import com.google.devtools.build.lib.buildeventstream.BuildEvent;
import com.google.devtools.build.lib.buildeventstream.FetchEvent;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.rules.repository.RepositoryFunction.RepositoryFunctionException;
import com.google.devtools.build.lib.rules.repository.WorkspaceAttributeMapper;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRefNameException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.NetRCCredentialsProvider;

/**
 * Clones a Git repository, checks out the provided branch, tag, or commit, and
 * clones submodules if specified.
 */
public class GitCloner {

  private static final Pattern GITHUB_URL = Pattern.compile(
      "(?:git@|https?://)github\\.com[:/](\\w+)/(\\w+)\\.git");

  private static final Pattern GITHUB_VERSION_FORMAT = Pattern.compile("v(\\d+\\.)*\\d+");

  private GitCloner() {
    // Only static methods in this class
  }

  private static boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
      return false;
    }
    Repository repository = null;
    try {
      repository = new FileRepositoryBuilder()
          .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile())
          .setMustExist(true)
          .build();
      ObjectId head = repository.resolve(Constants.HEAD);
      ObjectId checkout = repository.resolve(descriptor.checkout);
      if (head != null && checkout != null && head.equals(checkout)) {
        Status status = Git.wrap(repository).status().call();
        if (!status.hasUncommittedChanges()) {
          // new_git_repository puts (only) BUILD and WORKSPACE, and
          // git_repository doesn't add any files.
          Set<String> untracked = status.getUntracked();
          if (untracked.isEmpty()
              || (untracked.size() == 2
                  && untracked.contains("BUILD")
                  && untracked.contains("WORKSPACE"))) {
            return true;
          }
        }
      }
    } catch (GitAPIException | IOException e) {
      // Any exceptions here, we'll just blow it away and try cloning fresh.
      // The fresh clone avoids any weirdness due to what's there and has nicer
      // error reporting.
    } finally {
      if (repository != null) {
        repository.close();
      }
    }
    return false;
  }

  public static HttpDownloadValue clone(
      Rule rule,
      Path outputDirectory,
      ExtendedEventHandler eventHandler,
      Map<String, String> clientEnvironment,
      HttpDownloader downloader)
      throws RepositoryFunctionException {
    WorkspaceAttributeMapper mapper = WorkspaceAttributeMapper.of(rule);
    if (mapper.isAttributeValueExplicitlySpecified("commit")
        == mapper.isAttributeValueExplicitlySpecified("tag")) {
      throw new RepositoryFunctionException(
          new EvalException(rule.getLocation(), "One of either commit or tag must be defined"),
          Transience.PERSISTENT);
    }

    GitRepositoryDescriptor descriptor;
    try {
      if (mapper.isAttributeValueExplicitlySpecified("commit")) {
        descriptor = GitRepositoryDescriptor.createWithCommit(
            mapper.get("remote", Type.STRING),
            mapper.get("commit", Type.STRING),
            mapper.get("init_submodules", Type.BOOLEAN),
            outputDirectory);
      } else {
        descriptor = GitRepositoryDescriptor.createWithTag(
            mapper.get("remote", Type.STRING),
            mapper.get("tag", Type.STRING),
            mapper.get("init_submodules", Type.BOOLEAN),
            outputDirectory);
      }
    } catch (EvalException e) {
      throw new RepositoryFunctionException(e, Transience.PERSISTENT);
    }

    // Setup proxy if remote is http or https
    if (descriptor.remote != null && Ascii.toLowerCase(descriptor.remote).startsWith("http")) {
      try {
        new ProxyHelper(clientEnvironment).createProxyIfNeeded(new URL(descriptor.remote));
      } catch (IOException ie) {
        throw new RepositoryFunctionException(ie, Transience.TRANSIENT);
      }
    }

    BuildEvent fetchEvent = null;
    Git git = null;
    Exception suppressedException = null;
    try {
      if (descriptor.directory.exists()) {
        if (isUpToDate(descriptor)) {
          return new HttpDownloadValue(descriptor.directory);
        }
        try {
          FileSystemUtils.deleteTree(descriptor.directory);
        } catch (IOException e) {
          throw new RepositoryFunctionException(e, Transience.TRANSIENT);
        }
      }

      String uncheckedSha256 = getUncheckedSha256(mapper);
      if (repositoryLooksTgzable(descriptor.remote)) {
        Optional<Exception> maybeException = downloadRepositoryAsHttpArchive(
            descriptor, eventHandler, clientEnvironment, downloader, uncheckedSha256);
        if (maybeException.isPresent()) {
          suppressedException = maybeException.get();
        } else {
          return new HttpDownloadValue(descriptor.directory);
        }
      }
      if (!Strings.isNullOrEmpty(uncheckedSha256)) {
        // Specifying a sha256 forces this to use a tarball download.
        IOException e = new IOException(
            "Could not download tarball, but sha256 specified (" + uncheckedSha256 + ")");
        if (suppressedException != null) {
          e.addSuppressed(suppressedException);
        }
        throw new RepositoryFunctionException(e, Transience.TRANSIENT);
      }

      fetchEvent = new FetchEvent(descriptor.remote.toString(), false);
      git =
          Git.cloneRepository()
              .setURI(descriptor.remote)
              .setCredentialsProvider(new NetRCCredentialsProvider())
              .setDirectory(descriptor.directory.getPathFile())
              .setCloneSubmodules(false)
              .setNoCheckout(true)
              .setProgressMonitor(
                  new GitProgressMonitor(
                      descriptor.remote, "Cloning " + descriptor.remote, eventHandler))
              .call();
      git.checkout()
          .setCreateBranch(true)
          .setName("bazel-checkout")
          .setStartPoint(descriptor.checkout)
          .call();

      // Using CloneCommand.setCloneSubmodules() results in SubmoduleInitCommand and
      // SubmoduleUpdateCommand to be called recursively for all submodules. This is not
      // desirable for repositories, such as github.com/rust-lang/rust-installer, which
      // recursively includes itself as a submodule, which would result in an infinite
      // loop if submodules are cloned recursively. For now, limit submodules to only
      // the first level.
      if (descriptor.initSubmodules && !git.submoduleInit().call().isEmpty()) {
        git.submoduleUpdate()
            .setProgressMonitor(
                new GitProgressMonitor(
                    descriptor.remote, "Cloning submodules for " + descriptor.remote, eventHandler))
            .call();
      }
      fetchEvent = new FetchEvent(descriptor.remote.toString(), true);
    } catch (InvalidRemoteException e) {
      if (suppressedException != null) {
        e.addSuppressed(suppressedException);
      }
      throw new RepositoryFunctionException(
          new IOException("Invalid Git repository URI: " + e.getMessage()), Transience.PERSISTENT);
    } catch (RefNotFoundException | InvalidRefNameException e) {
      if (suppressedException != null) {
        e.addSuppressed(suppressedException);
      }
      throw new RepositoryFunctionException(
          new IOException("Invalid branch, tag, or commit: " + e.getMessage()),
          Transience.PERSISTENT);
    } catch (GitAPIException e) {
      if (suppressedException != null) {
        e.addSuppressed(suppressedException);
      }
      // This is a sad attempt to actually get a useful error message out of jGit, which will bury
      // the actual (useful) cause of the exception under several throws.
      StringBuilder errmsg = new StringBuilder();
      errmsg.append(e.getMessage());
      Throwable throwable = e;
      while (throwable.getCause() != null) {
        throwable = throwable.getCause();
        errmsg.append(" caused by " + throwable.getMessage());
      }
      throw new RepositoryFunctionException(
          new IOException("Error cloning repository: " + errmsg), Transience.PERSISTENT);
    } catch (JGitInternalException e) {
      if (suppressedException != null) {
        e.addSuppressed(suppressedException);
      }
      // This is a lame catch-all for jgit throwing RuntimeExceptions all over the place because,
      // as the docs put it, "a lot of exceptions are so low-level that is is unlikely that the
      // caller of the command can handle them effectively." Thanks, jgit.
      throw new RepositoryFunctionException(new IOException(e.getMessage()),
          Transience.PERSISTENT);
    } finally {
      if (git != null) {
        git.getRepository().close();
        git.close();
      }
      if (fetchEvent != null) {
        eventHandler.post(fetchEvent);
      }
    }
    return new HttpDownloadValue(descriptor.directory);
  }

  private static String getUncheckedSha256(WorkspaceAttributeMapper mapper)
      throws RepositoryFunctionException {
    if (mapper.isAttributeValueExplicitlySpecified("sha256")) {
      try {
        return mapper.get("sha256", Type.STRING);
      } catch (EvalException e) {
        throw new RepositoryFunctionException(e, Transience.PERSISTENT);
      }
    }
    return "";
  }

  private static boolean repositoryLooksTgzable(String remote) {
    // Only handles GitHub right now.
    return GITHUB_URL.matcher(remote).matches();
  }

  private static Optional<Exception> downloadRepositoryAsHttpArchive(
      GitRepositoryDescriptor descriptor, ExtendedEventHandler eventHandler,
      Map<String, String> clientEnvironment, HttpDownloader downloader, String uncheckedSha256)
      throws RepositoryFunctionException {
    Matcher matcher = GITHUB_URL.matcher(descriptor.remote);
    Preconditions.checkState(
        matcher.matches(), "Remote should be checked before calling this method");
    String user = matcher.group(1);
    String repositoryName = matcher.group(2);
    String downloadUrl =
        "https://github.com/"
            + UrlEscapers.urlFragmentEscaper()
                .escape(user + "/" + repositoryName + "/archive/" + descriptor.ref + ".tar.gz");
    try {
      FileSystemUtils.createDirectoryAndParents(descriptor.directory);
      Path tgz = downloader.download(ImmutableList.of(new URL(downloadUrl)), uncheckedSha256,
          Optional.of("tar.gz"), descriptor.directory, eventHandler, clientEnvironment);
      String githubRef = descriptor.ref;
      if (githubRef.startsWith("v") && GITHUB_VERSION_FORMAT.matcher(githubRef).matches()) {
        githubRef = githubRef.substring(1);
      }
      DecompressorValue.decompress(
          DecompressorDescriptor.builder()
              .setArchivePath(tgz)
              // GitHub puts the contents under a directory called <repo>-<commit>.
              .setPrefix(repositoryName + "-" + githubRef)
              .setRepositoryPath(descriptor.directory)
              .build());
    } catch (InterruptedException | IOException e) {
      try {
        FileSystemUtils.deleteTree(descriptor.directory);
      } catch (IOException e1) {
        throw new RepositoryFunctionException(
            new IOException("Unable to delete " + descriptor.directory + ": " + e1.getMessage()),
            Transience.TRANSIENT);
      }
      return Optional.<Exception>of(e);
    }
    return Optional.absent();
  }

  private static final class GitRepositoryDescriptor {
    private final String remote;
    private final String checkout;
    private final boolean initSubmodules;
    private final Path directory;
    private final String ref;

    private GitRepositoryDescriptor(String remote, String ref, String checkout,
        boolean initSubmodules, Path directory) {
      this.remote = remote;
      this.ref = ref;
      this.checkout = checkout;
      this.initSubmodules = initSubmodules;
      this.directory = directory;
    }

    @Override
    public String toString() {
      return remote + " -> " + directory + " (" + checkout + ") submodules: "
          + initSubmodules;
    }

    @Override
    public boolean equals(Object obj) {
      if (obj == this) {
        return true;
      }
      if (!(obj instanceof GitRepositoryDescriptor)) {
        return false;
      }
      GitRepositoryDescriptor other = (GitRepositoryDescriptor) obj;
      return Objects.equals(remote, other.remote)
          && Objects.equals(ref, other.ref)
          && Objects.equals(initSubmodules, other.initSubmodules)
          && Objects.equals(directory, other.directory);
    }

    @Override
    public int hashCode() {
      return Objects.hash(remote, ref, initSubmodules, directory);
    }

    static GitRepositoryDescriptor createWithCommit(String remote, String commit,
        Boolean initSubmodules, Path outputDirectory) {
      return new GitRepositoryDescriptor(
          remote, commit, commit, initSubmodules, outputDirectory);
    }

    static GitRepositoryDescriptor createWithTag(String remote, String tag,
        Boolean initSubmodules, Path outputDirectory) {
      return new GitRepositoryDescriptor(
          remote, tag, "tags/" + tag, initSubmodules, outputDirectory);
    }
  }
}


text:
import numpy as np
from rsfmodel import rsf, staterelations, plot

model = rsf.Model()

# Set model initial conditions
model.mu0 = 0.6 # Friction initial (at the reference velocity)
model.a = 0.005 # Empirical coefficient for the direct effect
model.k = 1e-3 # Normalized System stiffness (friction/micron)
model.v = 1. # Initial slider velocity, generally is vlp(t=0)
model.vref = 1. # Reference velocity, generally vlp(t=0)

state1 = staterelations.DieterichState()
state1.b = 0.01  # Empirical coefficient for the evolution effect
state1.Dc = 10.  # Critical slip distance

model.state_relations = [state1] # Which state relation we want to use

# We want to solve for 40 seconds at 100Hz
model.time = np.arange(0,40.01,0.01)

# We want to slide at 1 um/s for 10 s, then at 10 um/s for 31
lp_velocity = np.ones_like(model.time)
lp_velocity[10*100:] = 10. # Velocity after 10 seconds is 10 um/s

# Set the model load point velocity, must be same shape as model.model_time
model.loadpoint_velocity = lp_velocity

# Run the model!
model.solve()

# Make the phase plot
plot.phasePlot(model)

# Make a plot in displacement
plot.dispPlot(model)

# Make a plot in time
plot.timePlot(model)


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v1.1.3
 */
md-autocomplete.md-THEME_NAME-theme {
  background: '{{background-A100}}'; }
  md-autocomplete.md-THEME_NAME-theme[disabled]:not([md-floating-label]) {
    background: '{{background-100}}'; }
  md-autocomplete.md-THEME_NAME-theme button md-icon path {
    fill: '{{background-600}}'; }
  md-autocomplete.md-THEME_NAME-theme button:after {
    background: '{{background-600-0.3}}'; }

.md-autocomplete-suggestions-container.md-THEME_NAME-theme {
  background: '{{background-A100}}'; }
  .md-autocomplete-suggestions-container.md-THEME_NAME-theme li {
    color: '{{background-900}}'; }
    .md-autocomplete-suggestions-container.md-THEME_NAME-theme li .highlight {
      color: '{{background-600}}'; }
    .md-autocomplete-suggestions-container.md-THEME_NAME-theme li:hover, .md-autocomplete-suggestions-container.md-THEME_NAME-theme li.selected {
      background: '{{background-200}}'; }


text:
package com.sic.plugins.kpp;

import com.sic.plugins.kpp.provider.KPPKeychainsProvider;
import com.sic.plugins.kpp.model.KPPKeychain;
import com.sic.plugins.kpp.model.KPPProvisioningProfile;
import com.sic.plugins.kpp.provider.KPPProvisioningProfilesProvider;
import hudson.Extension;
import hudson.model.Hudson;
import hudson.model.ManagementLink;
import static hudson.model.ManagementLink.all;
import hudson.model.Saveable;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

/**
 * Manages the main plugin configuration page for uploading of provisioning profiles and keychains.
 *
 * @author Michael Bär
 */
@Extension
public class KPPManagementLink extends ManagementLink implements StaplerProxy, Saveable {

    private String errorMessage = null;

    /**
     * Gets the singletion instance.
     * @return the singletion instance.
     */
    public static KPPManagementLink getInstance() {
        return all().get(KPPManagementLink.class);
    }

    /**
     * Get error message
     * @return error message
     */
    public String getErrorMessage () {
        String message = errorMessage;
        errorMessage = null;
        return message;
    }

    /**
     * Get all keychains
     *
     * @return all keychains.
     */
    @SuppressWarnings("unused") // used by stapler
    public List<KPPKeychain> getKeychains() {
        return KPPKeychainsProvider.getInstance().getKeychains();
    }

    /**
     * Get all provisioning profiles.
     * @return  all provisioning profiles
     */
    public List<KPPProvisioningProfile> getProvisioningProfiles() {
        List<KPPProvisioningProfile> list = KPPProvisioningProfilesProvider.getInstance().getProvisioningProfiles();
        return list;
    }

    /**
     * Get the path to provisioning profiles on master or standalone jenkins instance.
     * @return path
     */
    public String getProvisioningProfilesPath() {
        return KPPProvisioningProfilesProvider.getInstance().getProvisioningProfilesPath();
    }

    /**
     * Action method if upload button is clicked.
     *
     * @param req Request
     * @param rsp Response
     * @throws ServletException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public void doUploadFile(StaplerRequest req, StaplerResponse rsp) throws
            ServletException,
            IOException,
            NoSuchAlgorithmException {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);

        FileItem file = req.getFileItem("file");
        if (file == null || file.getSize() == 0) {
            this.errorMessage = Messages.KPPManagementLink_Upload_Error_NoFile();
        } else {
            KPPKeychainsProvider kProvider = KPPKeychainsProvider.getInstance();
            KPPProvisioningProfilesProvider ppProvider = KPPProvisioningProfilesProvider.getInstance();
            if (kProvider.isKeychainFile(file)) {
                kProvider.upload(file);
                kProvider.update();
            } else if (ppProvider.isMobileProvisionProfileFile(file)) {
                ppProvider.upload(file);
                ppProvider.update();
            } else {
                this.errorMessage = String.format(Messages.KPPManagementLink_Upload_Error_WrongFileType(), file.getName());
            }
        }

        rsp.sendRedirect2("../"+getUrlName()+"/"); //we stay on page
    }

    /**
     * Action method if save button is clicked.
     *
     * @param req Request
     * @param rsp Response
     * @throws ServletException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public void doSave(StaplerRequest req, StaplerResponse rsp) throws
            ServletException,
            IOException,
            NoSuchAlgorithmException {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);

        JSONObject data = req.getSubmittedForm();
        List<KPPKeychain> keychains = req.bindJSONToList(KPPKeychain.class, data.get("keychain"));
        KPPKeychainsProvider.getInstance().updateKeychainsFromSave(keychains);
        List<KPPProvisioningProfile> pps = req.bindJSONToList(KPPProvisioningProfile.class, data.get("profile"));
        KPPProvisioningProfilesProvider.getInstance().updateProvisioningProfilesFromSave(pps);
        KPPProvisioningProfilesProvider.getInstance().setProvisioningProfilesPath(data.getString("provisioningProfilesPath"));
        save();
        rsp.sendRedirect2("../manage"); //we go back on management page
    }

    @Override
    public String getIconFileName() {
        return "/plugin/kpp-management-plugin/icon_kpp.png";
    }

    @Override
    public String getDisplayName() {
        return Messages.KPPManagementLink_DisplayName();
    }

    @Override
    public String getUrlName() {
        return "kppmanagment";
    }

    @Override
    public Object getTarget() {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
        KPPKeychainsProvider.getInstance().update();
        KPPProvisioningProfilesProvider.getInstance().update();
        return this;
    }

    @Override
    public void save() throws IOException {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
        KPPKeychainsProvider.getInstance().save();
        KPPProvisioningProfilesProvider.getInstance().save();
    }
}


text:
typedef struct
{
	unsigned long long StartTime;
	unsigned long long EndTime;
	double IntervalInSeconds;
#ifdef _WIN32
	unsigned long long Frequency;
#endif
} Stopwatch;

void Stopwatch_Init( Stopwatch* const stopwatch);
void Stopwatch_Start( Stopwatch* const stopwatch);
void Stopwatch_Stop( Stopwatch* const stopwatch);
void Stopwatch_Reset( Stopwatch* const stopwatch);
double Stopwatch_GetIntervalInSeconds( Stopwatch* const stopwatch);

#endif // CSR_STOPWATCH_H


text:
set -euo pipefail -o verbose
IFS=$'\n\t'

module load ncbi-blast/2.4.0+
module load samtools/1.3

#1. Create blast index of viruses Indexes
virus_dir=0_virus_fasta
mkdir -p ${virus_dir}/blastdb
cat ${virus_dir}/*.fasta > ${virus_dir}/blastdb/viruses.fasta

makeblastdb -input_type fasta -out ${virus_dir}/blastdb/viruses -title viruses -dbtype nucl -in ${virus_dir}/blastdb/viruses.fasta

blastdb=${virus_dir}/blastdb/viruses

#Run blastn
mkdir -p 1_blastn
cd 1_blastn

in_fasta=../../0_data/orfans/ALL_CLUSTERS.fa
out_prefix=orfan_to_viruses

make -r -f ../blastn.mak in_fasta=../${in_fasta} blastdb=../${blastdb} out_prefix=${out_prefix} tsv

#Query coverage should be at least 30%
awk '{if($5 > 30) print $0}' tsv/${out_prefix}.tsv > tsv/${out_prefix}_filt.tsv

mkdir -p plots/
python ../plot_blastn_hits.py tsv/${out_prefix}_filt.tsv tsv/blast_tsv_columns.txt plots/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using HIO.Backup.Model;

namespace HIO.Backup.Interface.Destination
{
    interface ISyncFileAsync
    {
        Task SyncFileAsync(BackupObj backup, System.IO.FileStream delta, string path, FileBackupMeta meta);
        Task SyncFileAsync(BackupObj backup, System.IO.FileStream file, System.IO.FileStream signature, string path, FileBackupMeta meta);
        Task SyncFileUseExistingAsync(BackupObj backup, BackupObj prevBackup, string path, FileBackupMeta meta);
    }
}


text:
export class NamesList {
    private names = ['Dijkstra', 'Knuth', 'Turing', 'Hopper'];

    get() {
        return this.names;
    }
    add(value: string) {
        this.names.push(value);
    }
}