text:
namespace {

const int kScreenWidth = 800;
const int kScreenHeight = 600;

const int kWindowWidth = 100;
const int kWindowHeight = 200;

// Size of the menu bar along the top of the screen.
const int kMenuBarSize = 22;
// Size of the normal (non-hidden) shelf.
const int kShelfSize = 30;

// A cursor position that is within the shelf. This must be < kShelfSize.
const int kCursorOnShelf = kShelfSize / 2;
// A cursor position that is within kWindowWidth pixels of the shelf.
const int kCursorNearShelfX = kShelfSize + kWindowWidth;
// A cursor position that is more than kWindowWidth pixels away from the shelf.
const int kCursorAwayFromShelfX = kCursorNearShelfX + 1;
// A cursor position that is within kWindowHeight pixels of the shelf.
const int kCursorNearShelfY = kShelfSize + kWindowHeight;
// A cursor position that is more than kWindowHeight pixels away from the shelf.
const int kCursorAwayFromShelfY = kCursorNearShelfY + 1;

// A position for the center of the window that causes the window to overlap the
// edge of the screen. This must be < kWindowWidth / 2 and < kWindowHeight / 2.
const int kWindowNearEdge = kWindowWidth / 4;
// A position for the center of the window that places the window away from all
// edges of the screen. This must be > kWindowWidth / 2, > kWindowHeight / 2, <
// kScreenWidth - kWindowWidth / 2 and < kScreenHeight - kWindowHeight / 2.
const int kWindowAwayFromEdge = 158;

}  // namespace

class AppListLinuxUnitTest : public testing::Test {
 public:
  virtual void SetUp() OVERRIDE {
    display_.set_bounds(gfx::Rect(0, 0, kScreenWidth, kScreenHeight));
    display_.set_work_area(
        gfx::Rect(0, kMenuBarSize, kScreenWidth, kScreenHeight - kMenuBarSize));
    cursor_ = gfx::Point();
    center_window_ = false;
  }

  // Set the display work area.
  void SetWorkArea(int x, int y, int width, int height) {
    display_.set_work_area(gfx::Rect(x, y, width, height));
  }

  // Sets up the test environment with the shelf along a given edge of the
  // work area.
  void PlaceShelf(AppListPositioner::ScreenEdge edge) {
    switch (edge) {
      case AppListPositioner::SCREEN_EDGE_LEFT:
        display_.set_work_area(gfx::Rect(kShelfSize,
                                         kMenuBarSize,
                                         kScreenWidth - kShelfSize,
                                         kScreenHeight - kMenuBarSize));
        break;
      case AppListPositioner::SCREEN_EDGE_RIGHT:
        display_.set_work_area(gfx::Rect(0,
                                         kMenuBarSize,
                                         kScreenWidth - kShelfSize,
                                         kScreenHeight - kMenuBarSize));
        break;
      case AppListPositioner::SCREEN_EDGE_TOP:
        display_.set_work_area(
            gfx::Rect(0,
                      kMenuBarSize + kShelfSize,
                      kScreenWidth,
                      kScreenHeight - kMenuBarSize - kShelfSize));
        break;
      case AppListPositioner::SCREEN_EDGE_BOTTOM:
        display_.set_work_area(
            gfx::Rect(0,
                      kMenuBarSize,
                      kScreenWidth,
                      kScreenHeight - kMenuBarSize - kShelfSize));
        break;
      case AppListPositioner::SCREEN_EDGE_UNKNOWN:
        NOTREACHED();
        break;
    }
  }

  // Set up the test mouse cursor in a given location.
  void PlaceCursor(int x, int y) {
    cursor_ = gfx::Point(x, y);
  }

  void EnableWindowCentering() {
    center_window_ = true;
  }

  AppListPositioner::ScreenEdge ShelfEdge() const {
    return AppListLinux::ShelfLocationInDisplay(display_);
  }

  gfx::Point DoFindAnchorPoint() const {
    return AppListLinux::FindAnchorPoint(gfx::Size(kWindowWidth, kWindowHeight),
                                         display_,
                                         cursor_,
                                         ShelfEdge(),
                                         center_window_);
  }

 private:
  gfx::Display display_;
  gfx::Point cursor_;
  bool center_window_;
};

TEST_F(AppListLinuxUnitTest, ShelfLocationInDisplay) {
  SetWorkArea(0, 0, kScreenWidth, kScreenHeight);
  EXPECT_EQ(AppListPositioner::SCREEN_EDGE_UNKNOWN, ShelfEdge());

  // The BOTTOM, LEFT and RIGHT tests test the case where there are two bars:
  // one at the top and one at the bottom/left/right. The bigger one should be
  // chosen, so TOP should not win in these cases.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
  EXPECT_EQ(AppListPositioner::SCREEN_EDGE_BOTTOM, ShelfEdge());

  PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
  EXPECT_EQ(AppListPositioner::SCREEN_EDGE_TOP, ShelfEdge());

  PlaceShelf(AppListPositioner::SCREEN_EDGE_LEFT);
  EXPECT_EQ(AppListPositioner::SCREEN_EDGE_LEFT, ShelfEdge());

  PlaceShelf(AppListPositioner::SCREEN_EDGE_RIGHT);
  EXPECT_EQ(AppListPositioner::SCREEN_EDGE_RIGHT, ShelfEdge());

  // Bar at top and bottom, same size. Top should win.
  SetWorkArea(0,
              kMenuBarSize,
              kScreenWidth,
              kScreenHeight - kMenuBarSize - kMenuBarSize);
  EXPECT_EQ(AppListPositioner::SCREEN_EDGE_TOP, ShelfEdge());
}

TEST_F(AppListLinuxUnitTest, FindAnchorPointNoShelf) {
  // Position the app list when there is no shelf on the display.
  PlaceCursor(0, 0);
  // Expect the app list to be in the top-left corner.
  EXPECT_EQ(gfx::Point(kWindowWidth / 2, kMenuBarSize + kWindowHeight / 2),
            DoFindAnchorPoint());
}

TEST_F(AppListLinuxUnitTest, FindAnchorPointMouseOffShelf) {
  // Position the app list when the mouse is away from the shelf.

  // Bottom shelf. Expect the app list to be in the bottom-left corner.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
  PlaceCursor(kWindowAwayFromEdge, kScreenHeight - kCursorAwayFromShelfY);
  EXPECT_EQ(gfx::Point(kWindowWidth / 2,
                       kScreenHeight - kShelfSize - kWindowHeight / 2),
            DoFindAnchorPoint());

  // Top shelf. Expect the app list to be in the top-left corner.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
  PlaceCursor(kWindowAwayFromEdge, kMenuBarSize + kCursorAwayFromShelfY);
  EXPECT_EQ(gfx::Point(kWindowWidth / 2,
                       kMenuBarSize + kShelfSize + kWindowHeight / 2),
            DoFindAnchorPoint());

  // Left shelf. Expect the app list to be in the top-left corner.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_LEFT);
  PlaceCursor(kCursorAwayFromShelfX, kWindowAwayFromEdge);
  EXPECT_EQ(gfx::Point(kShelfSize + kWindowWidth / 2,
                       kMenuBarSize + kWindowHeight / 2),
            DoFindAnchorPoint());

  // Right shelf. Expect the app list to be in the top-right corner.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_RIGHT);
  PlaceCursor(kScreenWidth - kCursorAwayFromShelfX, kWindowAwayFromEdge);
  EXPECT_EQ(gfx::Point(kScreenWidth - kShelfSize - kWindowWidth / 2,
                       kMenuBarSize + kWindowHeight / 2),
            DoFindAnchorPoint());
}

TEST_F(AppListLinuxUnitTest, FindAnchorPointMouseOnShelf) {
  // Position the app list when the mouse is over the shelf.

  // Bottom shelf (mouse well within shelf). Expect the app list to be at
  // the bottom centered on the mouse X coordinate.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
  PlaceCursor(kWindowAwayFromEdge, kScreenHeight - kCursorOnShelf);
  EXPECT_EQ(gfx::Point(kWindowAwayFromEdge,
                       kScreenHeight - kShelfSize - kWindowHeight / 2),
            DoFindAnchorPoint());

  // Bottom shelf (outside the shelf but still close enough).
  // Expect the app list to be at the bottom centered on the mouse X coordinate.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
  PlaceCursor(kWindowAwayFromEdge, kScreenHeight - kCursorNearShelfY);
  EXPECT_EQ(gfx::Point(kWindowAwayFromEdge,
                       kScreenHeight - kShelfSize - kWindowHeight / 2),
            DoFindAnchorPoint());

  // Top shelf. Expect the app list to be at the top centered on the
  // mouse X coordinate.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
  PlaceCursor(kWindowAwayFromEdge, kMenuBarSize + kCursorNearShelfY);
  EXPECT_EQ(gfx::Point(kWindowAwayFromEdge,
                       kMenuBarSize + kShelfSize + kWindowHeight / 2),
            DoFindAnchorPoint());

  // Left shelf. Expect the app list to be at the left centered on the
  // mouse Y coordinate.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_LEFT);
  PlaceCursor(kCursorNearShelfX, kWindowAwayFromEdge);
  EXPECT_EQ(gfx::Point(kShelfSize + kWindowWidth / 2, kWindowAwayFromEdge),
            DoFindAnchorPoint());

  // Right shelf. Expect the app list to be at the right centered on the
  // mouse Y coordinate.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_RIGHT);
  PlaceCursor(kScreenWidth - kCursorNearShelfX, kWindowAwayFromEdge);
  EXPECT_EQ(gfx::Point(kScreenWidth - kShelfSize - kWindowWidth / 2,
                       kWindowAwayFromEdge),
            DoFindAnchorPoint());

  // Bottom shelf. Mouse near left edge. App list must not go off screen.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
  PlaceCursor(kWindowNearEdge, kScreenHeight - kCursorOnShelf);
  EXPECT_EQ(gfx::Point(kWindowWidth / 2,
                       kScreenHeight - kShelfSize - kWindowHeight / 2),
            DoFindAnchorPoint());

  // Bottom shelf. Mouse near right edge. App list must not go off screen.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
  PlaceCursor(kScreenWidth - kWindowNearEdge, kScreenHeight - kCursorOnShelf);
  EXPECT_EQ(gfx::Point(kScreenWidth - kWindowWidth / 2,
                       kScreenHeight - kShelfSize - kWindowHeight / 2),
            DoFindAnchorPoint());
}

TEST_F(AppListLinuxUnitTest, FindAnchorPointCentered) {
  // Cursor on the top shelf; enable centered app list mode.
  PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
  PlaceCursor(0, 0);
  EnableWindowCentering();
  // Expect the app list to be in the center of the screen (ignore the cursor).
  EXPECT_EQ(gfx::Point(kScreenWidth / 2, kScreenHeight / 2),
            DoFindAnchorPoint());
}


text:
<?php

namespace Colibri\WebApp\Controller;

use Colibri\ServiceLocator\ContainerInterface;
use Colibri\WebApp\Controller;
use Colibri\WebApp\Exception\RuntimeException;

/**
 * Class ControllerResolver
 * @package Colibri\WebApp\Controller
 */
class ControllerResolver
{

    /**
     * @var ContainerInterface
     */
    protected $container = null;

    /**
     * @var ControllerResponse
     */
    protected $response = null;

    /**
     * @var string|null
     */
    protected $namespace;

    /**
     * @var string
     */
    protected $controllerClassName;

    /**
     * @var string
     */
    protected $actionName;

    /**
     * @var array
     */
    protected $params = [];

    /**
     * ControllerResolver constructor.
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->response = new ControllerResponse();
    }

    /**
     * @return ControllerResponse
     * @throws RuntimeException
     */
    public function execute()
    {
        $class = $this->getControllerClass();

        $reflectionClass = new \ReflectionClass($class);

        if ($reflectionClass->implementsInterface(ControllerInterface::class)) {
            /** @var Controller $controller */
            $controller = $reflectionClass->newInstance();
            $controller->setReflectionClass($reflectionClass);
            $this->getResponse()->setControllerInstance($controller);

            $controller->setContainer($this->container);

            $reflectionMethod = new \ReflectionMethod($class, $this->getActionName());
            $controller->setReflectionAction($reflectionMethod);

            $controller->setNamespace($this->getNamespace());
            $controller->setName($this->getControllerClassName());
            $controller->setAction($this->getActionName());
            $controller->setParams($this->getParams());

            $controller->beforeExecute();
            $this->response->setControllerContent($reflectionMethod->invokeArgs($controller, $this->getParams()));
            $controller->afterExecute();

        } else {
            throw new RuntimeException('Controller found but it should implemented interface [:name]', [
                'name' => ControllerInterface::class,
            ]);
        }

        return $this->response;
    }

    /**
     * @return string
     */
    public function getControllerClass()
    {
        return trim($this->getNamespace(), '\\') . '\\' . $this->getControllerClassName();
    }

    /**
     * @return null|string
     */
    public function getNamespace()
    {
        return $this->namespace;
    }

    /**
     * @param null|string $namespace
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;
    }

    /**
     * @return string
     */
    public function getControllerCamelize()
    {
        $className = $this->getControllerClassName();

        if (false !== strpos($className, 'Controller')) {
            $className = substr($className, 0, -10);
        }

        return ucfirst($className);
    }

    /**
     * @return string
     */
    public function getControllerClassName()
    {
        return $this->controllerClassName;
    }

    /**
     * @param string $controllerClassName
     */
    public function setControllerClassName($controllerClassName)
    {
        $this->controllerClassName = ucfirst($controllerClassName);
    }

    /**
     * @return ControllerResponse|null
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * @param ControllerResponse|null $response
     */
    public function setResponse($response)
    {
        $this->response = $response;
    }

    /**
     * @return string
     */
    public function getActionCamelize()
    {
        $actionName = $this->getActionName();

        if (false !== strpos($actionName, 'Action')) {
            $actionName = substr($actionName, 0, -6);
        }

        return ucfirst($actionName);
    }

    /**
     * @return string
     */
    public function getActionName()
    {
        return $this->actionName;
    }

    /**
     * @param string $actionName
     */
    public function setActionName($actionName)
    {
        $this->actionName = $actionName;
    }

    /**
     * @return array
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * @param array $params
     */
    public function setParams($params)
    {
        $this->params = $params;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*jslint nomen: true, sloppy: true */
/*global $: false, Swipe: false, Zoomer: false, L: false, console: false, clearInterval: false, clearTimeout: false, document: false, event: false, frames: false, history: false, Image: false, location: false, name: false, navigator: false, Option: false, parent: false, screen: false, setInterval: false, setTimeout: false, window: false, XMLHttpRequest: false */

// swipe.js compatibility for swiping / panning logic
// override select methods in Leaflet and Swipe.js to allow control over who gets the drag events

// unfortunately have to use class here, so...

var Zoomer = Zoomer || {};
Zoomer.guidCounter = 0; // use this to generate unique IDs for containers
var Video =
Zoomer.zoom_image_by_class = function (zoomoptions) {
    Zoomer.loadExtraTiles = window.location.href.indexOf('longSwipe') !== -1 ? 2 : 6; // load full zoom extents
    var baseContainer = zoomoptions.container;
    $('.' + zoomoptions.container).each(function() {
        var containerId = baseContainer + Zoomer.guidCounter++;
        $(this).attr('id', containerId);
        var savedHtml = $(this).innerHTML;
        zoomoptions.container = containerId;
        Zoomer.zoom_image(zoomoptions);
        if (savedHtml) {
            this.insertBefore(savedHtml, this.firstChild);
        }
    });
};

// override Draggable so we can control who gets the panning events: swipe library or leaflet
L.Draggable = L.Draggable.extend({
    _onDown: function (e) {
        // WAC_START
        this._verticalPan = undefined;
        // WAC_END
        if ((!L.Browser.touch && e.shiftKey) ||
                ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }

        // WAC_START
        var map = Zoomer.getParentMapForElement(e.target);

        Zoomer.wasAtEastEdge=undefined;
        Zoomer.wasAtWestEdge=undefined;
        // WAC_END

        if (L.Draggable._disabled) { return; }

        this._simulateClick = true;

        if (e.touches && e.touches.length > 1) {
            this._simulateClick = false;
            clearTimeout(this._longPressTimeout);
            return;
        }

        var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
            el = first.target;

        if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
            L.DomUtil.addClass(el, 'leaflet-active');
        }

        this._moved = false;
        if (this._moving) { return; }

        this._startPoint = new L.Point(first.clientX, first.clientY);
        this._startPos = this._newPos = L.DomUtil.getPosition(this._element);

        //Touch contextmenu event emulation
        if (e.touches && e.touches.length === 1 && L.Browser.touch && this._longPress) {
            this._longPressTimeout = setTimeout(L.bind(function () {
                var dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;

                if (dist < L.Draggable.TAP_TOLERANCE) {
                    this._simulateClick = false;
                    this._onUp();
                    this._simulateEvent('contextmenu', first);
                }
            }, this), 1000);
        }

        L.DomEvent.on(document, L.Draggable.MOVE[e.type], this._onMove, this);
        L.DomEvent.on(document, L.Draggable.END[e.type], this._onUp, this);
    },
    _onMove: function (e) {
        if (e.touches && e.touches.length > 1) { return; }

        var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
            newPoint = new L.Point(first.clientX, first.clientY),
            diffVec = newPoint.subtract(this._startPoint);

        if (!diffVec.x && !diffVec.y) { return; }

        // WAC_START
        var map = null;

        if (e.target) {
            if ( typeof e.target._layer !== "undefined") {
                map = e.target._layer._map;
            } else if (Zoomer.zoomers[e.target.id]) {
                map = Zoomer.zoomers[e.target.id].map;
            }
        }
        if (!L.Browser.touch || typeof Swipe !== 'function') {
            L.DomEvent.preventDefault(e);
        }
        if (map && this._verticalPan === undefined) {
            this._verticalPan = !!(this._verticalPan || ((map.isAtEastEdge() && map.isAtWestEdge()) && Math.abs(diffVec.x) < Math.abs(diffVec.y)));
        }
        if (L.Browser.touch && (!map || (diffVec.x > Zoomer.lastDiffX && map.isAtEastEdge()) || (diffVec.x < Zoomer.lastDiffX && map.isAtWestEdge()))) {
            // they are at the edge or otherwise not panning leaflet any more. Skip the pan animation
            if (Zoomer.lastDiffX) { diffVec.x=Zoomer.lastDiffX; }
        }
        if (L.Browser.touch && (!map || (diffVec.y > Zoomer.lastDiffY && map.isAtNorthEdge()) || (diffVec.y < Zoomer.lastDiffY && map.isAtSouthEdge()))) {
            if (Zoomer.lastDiffY) { diffVec.y=Zoomer.lastDiffY; }
        }
        Zoomer.lastDiffY=diffVec.y;
        Zoomer.lastDiffX=diffVec.x;
        // WAC_END

        if (!this._moved) {
            this.fire('dragstart');
            this._moved = true;

            this._startPos = L.DomUtil.getPosition(this._element).subtract(diffVec);

            if (!L.Browser.touch) {
                L.DomUtil.disableTextSelection();
                this._setMovingCursor();
            }
        }

        this._newPos = this._startPos.add(diffVec);
        this._moving = true;

        L.Util.cancelAnimFrame(this._animRequest);
        this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
    }
});

Swipe.prototype.handleEvent = function(e) {
    if (e.type.indexOf('touch')>-1 && (this.index===0 || this.index === this.slides.length-1)) {
        // this a dummy slide about to disappear: stop all events
        //console.log("dropping "+e.type);
        //e.stopPropagation();
        //return;
    }
    switch (e.type) {
      case 'touchstart': this.onTouchStart(e); break;
      case 'touchmove': this.onTouchMove(e); break;
      case 'touchend': this.onTouchEnd(e); break;
      case 'webkitTransitionEnd':
      case 'msTransitionEnd':
      case 'oTransitionEnd': // opera 11 and below
      case 'otransitionend': // opera 12 (and above?)
      case 'transitionend': this.onTransitionEnd(e); break;
      case 'resize': this.setup(); break;
    }

    //e.stopPropagation();
};

// custom current slide ID
Swipe.prototype.getCurrentSlideId = function () {
    if (!this.slides) {
        return this.element.children[0].id;
    }
    return this.slides[this.index].id;
};
Swipe.prototype.getPreviousSlideId = function () {
    return this.previousSlideId;
};

function makeDummyZoomer(dummy) {
    var zoomer = Zoomer.zoomers[dummy.id.replace('_dummy','')];
    Zoomer.zoom_image({"container":dummy.id, "tileURL":zoomer.tileURL, "imageWidth":zoomer.imageWidth, "imageHeight":zoomer.imageHeight});
    zoomer = Zoomer.zoomers[dummy.id];
    zoomer.map.options['maxZoom'] = zoomer.map._zoom;
    zoomer.map.touchZoom.removeHooks();
    zoomer.map.dragging.removeHooks()
    zoomer.map.on('click', jQuery.noop);
}

// custom START: gutter extension
Swipe.prototype.setup = function() {
    // WAC CUSTOM START
    if (this.element.children.length < 2) {
        this.container.style.visibility = 'visible';
        return;
    }
    if (!this.slides) {
        // XXX do a shallow clone, set the id and class, then make a new zoomer with shit turned off
        var dummy = this.element.children[0].cloneNode(false)
        dummy.id = dummy.id+'_dummy';
        this.element.appendChild(dummy);
        makeDummyZoomer(dummy);

        dummy = this.element.children[this.element.children.length-2].cloneNode(false),
        dummy.id = dummy.id+'_dummy';
        this.element.insertBefore(dummy, this.element.firstChild);
        makeDummyZoomer(dummy);
        this.index++;
    }
    this.gutter = 10;
    this.currentSlideId = this.element.children[0].id;
    this.previousSlideId = this.element.children[0].id;

    //this.slideDuration = window.location.href.indexOf('longSwipe') !== -1 ? 500 : 250; // 250 if small, 500 if big
    this.slideDuration = 1000; // assume big screen for this project
    // WAC CUSTOM END

    // get and measure amt of slides
    this.slides = this.element.children;
    this.length = this.slides.length;
    this.cache = new Array(this.length);

    // return immediately if their are less than two slides
    if (this.length < 2) return;

    // determine width of each slide
    this.width = this.container.getBoundingClientRect().width + (this.gutter * 2) || this.container.offsetWidth;

    // return immediately if measurement fails
    if (!this.width) return;

    // store array of slides before, current, and after
    var refArray = [[],[],[]];

    this.element.style.width = (this.slides.length * this.width) + 'px';

    // stack elements
    for (var index = this.length - 1; index > -1; index--) {

      var elem = this.slides[index];

      elem.style.width = this.width - (this.gutter * 2) + 'px';
      elem.setAttribute('data-index', index);
      elem.style.marginLeft = this.gutter +'px';
      elem.style.marginRight = this.gutter + 'px';

      if (this.browser.transitions) {
        elem.style.left = (index * -this.width) - this.gutter + 'px';
      }

      // add this index to the reference array    0:before 1:equal 2:after
      refArray[this.index > index ? 0 : (this.index < index ? 2 : 1)].push(index);

    }

    if (this.browser.transitions) {

      // stack left, current, and right slides
      this._stack(refArray[0],-1);
      this._stack(refArray[1],0);
      this._stack(refArray[2],1);

    } else {
      // move "viewport" to put current slide into view
      this.element.style.left = (this.index * -this.width)+"px";
    }

    this.container.style.visibility = 'visible';

};
Zoomer.isPinching = undefined;
Zoomer.multiTouchSwipeCount = 0;
Zoomer.deltaX = 0; // horizontal distance travelled
Zoomer.deltaD = 0; // distance between touches (pinch)

Swipe.prototype.onTouchStart = function(e) {
    Zoomer.multiTouchSwipeCount = 0;
    Zoomer.isPinching = undefined;
    if(!e.noReset) {
        Zoomer.wasAtEastEdge=undefined;
        Zoomer.wasAtWestEdge=undefined;
    }

    var _this = this;

    _this.start = {

      // get touch coordinates for delta calculations in onTouchMove
      pageX: e.touches[0].pageX,
      pageY: e.touches[0].pageY,

      // set initial timestamp of touch sequence
      time: Number( new Date() )

    };

    // used for testing first onTouchMove event
    _this.isScrolling = undefined;

    // reset deltaX
    _this.deltaX = 0;

};

Swipe.prototype.onTouchMove = function(e) {
    var _this = this;

    // WAC CUSTOM START
    // ensure not pinching (2 touch = pinch, anything else = swipe)
    if(!Zoomer.slideHasVideo && !Zoomer.abortedZoom && (e.touches.length == 2 || e.scale && e.scale !== 1)) {
        Zoomer.isPinching = true;
        Zoomer.abortedZoom = false;
        return;
    }
    if (e.touches.length > Zoomer.multiTouchSwipeCount) Zoomer.multiTouchSwipeCount = e.touches.length;
    if (e.touches.length < Zoomer.multiTouchSwipeCount) return; // stop moving, fingers coming up
    // WAC CUSTOM END
    if (Zoomer.isPinching) {
        // they WERE pinching, now not.
        _this.start.pageX = e.touches[0].pageX;
        Zoomer.isPinching = undefined;
    }
    _this.deltaX = e.touches[0].pageX - _this.start.pageX;

    // determine if scrolling test has run - one time test
    if ( typeof _this.isScrolling == 'undefined') {
      //_this.isScrolling = !!( _this.isScrolling || Math.abs(_this.deltaX) < Math.abs(e.touches[0].pageY - _this.start.pageY) );
    }

    // custom START
    if (e.target && typeof e.target._layer !== "undefined") {
        var map = e.target._layer._map;

        if (map) {
            if (Zoomer.wasAtEastEdge === undefined) { Zoomer.wasAtEastEdge = map.isAtEastEdge(); }
            if (Zoomer.wasAtWestEdge === undefined) { Zoomer.wasAtWestEdge = map.isAtWestEdge(); }
            if (!((Zoomer.wasAtEastEdge && map.isAtEastEdge()) || (Zoomer.wasAtWestEdge && map.isAtWestEdge()))) {
                // they are inside the image and the touch should go to leaflet to pan.
                e.preventDefault();
                e.noReset = true;
                return this.onTouchStart(e);
            }
        }
    }
    // custom END

    // if user is not trying to scroll vertically
    if (!_this.isScrolling) {

      // prevent native scrolling
      e.preventDefault();

      // cancel slideshow
      _this.delay = 0;
      clearTimeout(_this.interval);

      // increase resistance if first or last slide
        // if first slide and sliding left
        // or if last slide and sliding right
        // and if sliding at all
      _this.deltaX =
        _this.deltaX /
          ( (!_this.index && _this.deltaX > 0 || _this.index === _this.length - 1 && _this.deltaX < 0 ) ?
          ( Math.abs(_this.deltaX) / _this.width + 1 )  : 1 );

      // translate immediately 1:1
      _this._move([_this.index-1,_this.index,_this.index+1],_this.deltaX);

    } else if (_this.disableScroll) {

      // prevent native scrolling
      e.preventDefault();

    }
};

// use slideDuration to allow for bigger screen interaction
Swipe.prototype.onTouchEnd = function (e) {
    if (!(Zoomer.multiTouchSwipeCount > 0 && e.touches.length < Zoomer.multiTouchSwipeCount)) return; // first finger up = do it and ignore remaining end events
    Zoomer.isPinching = undefined;
    var _this = this;

    // determine if slide attempt triggers next/prev slide
    var isValidSlide =
          Number(new Date()) - _this.start.time < _this.slideDuration      // if slide duration is less than 250ms
          && Math.abs(_this.deltaX) > 20                   // and if slide amt is greater than 20px
          || Math.abs(_this.deltaX) > _this.width/2,        // or if slide amt is greater than half the width

    // determine if slide attempt is past start and end
        isPastBounds =
          !_this.index && _this.deltaX > 0                          // if first slide and slide amt is greater than 0
          || _this.index == _this.length - 1 && _this.deltaX < 0,    // or if last slide and slide amt is less than 0

        direction = _this.deltaX < 0; // true:right false:left

    // if not scrolling vertically
    if (!_this.isScrolling && _this.start) {

      var mapIdle = true,
        zoomer = Zoomer.zoomers[this.slides[this.index].id];
      if (zoomer && !zoomer.map.isIdle()) {
          mapIdle = false;
          Zoomer.abortedZoom = false;
      }

      if (isValidSlide && !isPastBounds && mapIdle) {
        Zoomer.abortedZoom = false;
        _this.start = {};
        if (direction) {
          _this._stack([_this.index-1],-1);
          _this._slide([_this.index,_this.index+1],-_this.width,_this.speed);
          _this.index += 1;
        } else {
          _this._stack([_this.index+1],1);
          _this._slide([_this.index-1,_this.index],_this.width,_this.speed);
          _this.index += -1;
        }
        _this.callback(_this.index, _this.slides[_this.index]);
      } else {
        _this._slide([_this.index-1,_this.index,_this.index+1],0,_this.speed);
      }

    }
    _this.deltaX = 0;

  },

Swipe.prototype.onTransitionEnd = function (e) {
    this.previousSlideId = this.slides[this.index].id;
    if (this._getElemIndex(e.target) == this.index) { // only call transition end on the main slide item

        if (this.index == 0) this.slide(this.slides.length-2, 0)
        if (this.index == this.slides.length-1) this.slide(1, 0)
        if (this.delay) this.begin();

        this.transitionEnd(this.index, this.slides[this.index]);
        this.currentSlideId = this.slides[this.index].id;
    }
};

Swipe.prototype.getPos = function() {
    // return current index position with awareness it may be called on "dummy slide"
    var index = this.index;
    if (this.index == 0) index = this.slides.length-2;
    if (this.index == this.slides.length-1) index = 1;
    return index-1;
};


text:
package com.abbcc.module.userNews;

import java.util.List;

import net.sf.json.JSONArray;

import com.abbcc.action.BaseAction;
import com.abbcc.common.CommonConst;
import com.abbcc.models.AbcNews;
import com.abbcc.models.AbcProduct;
import com.abbcc.service.NewsService;
import com.abbcc.service.ProductService;

public class NewsSearchAction extends BaseAction<AbcNews> {
	private String searchKey;
	private NewsService newsService;
	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}
	public String getSearchKey() {
		return searchKey;
	}
	public void setSearchKey(String searchKey) {
		this.searchKey = searchKey;
	}
	public String byName() throws Exception{
		String[] name={"name","content"};
		List<AbcNews> news = newsService.findUserByParams(name,searchKey, AbcNews.class);
		for(int i=0;i<news.size();i++){
			if(!(news.get(i).getState().equals(CommonConst.STATENORMAL))){
				news.remove(i);
			}
		}
		JSONArray jsonArray = JSONArray.fromObject(news);
		this.result = jsonArray.toString();
		return SUCCESS;

	}

}


text:
package com.wangjie.wavecompat;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ArgbEvaluator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;

/**
 * Author: wangjie
 * Email: tiantian.china.2@gmail.com
 * Date: 5/29/15.
 */
public class WaveCompat {

    private static final String TAG = WaveCompat.class.getSimpleName();

    public static class IntentKey {
        public static final String IS_WAVE_COMPAT = "WAVE_COMPAT_INTENT_KEY_IS_WAVE_COMPAT";
        public static final String BACKGROUND_COLOR = "WAVE_COMPAT_INTENT_KEY_BACKGROUND_COLOR";
    }

    /**
     * Start an activity with wave effect.
     * @param activity The FROM activity
     * @param waveDrawable
     * @param intent
     * @param backgroundColor Background of the TO activity
     */
    public static void startWaveFilter(final Activity activity, WaveDrawable waveDrawable, final Intent intent, int backgroundColor) {
        intent.putExtra(IntentKey.BACKGROUND_COLOR, backgroundColor);
        startWaveFilter(activity, waveDrawable, intent);
    }

    /**
     * Start an activity with wave effect, but without background color of the TO activity
     * @param activity
     * @param waveDrawable
     * @param intent
     */
    public static void startWaveFilter(final Activity activity, WaveDrawable waveDrawable, final Intent intent) {
        prepareWaveIntent(intent);

        View contentView = activity.findViewById(android.R.id.content);
        Bitmap bitmap = convertViewToBitmap(contentView);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        View view = new View(activity);
        view.setLayoutParams(new ViewGroup.LayoutParams(width, height));

        waveDrawable.setFrameBitmap(bitmap);
        int statusBarHeight = getStatusBarHeight(activity);

        new WaveContainer(view, waveDrawable, width, height) {
            @Override
            protected void onWaveDrawableAnimatorEndExtraAction() {
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                activity.startActivity(intent);
            }
        }
//                .showAtLocation(contentView, Gravity.NO_GRAVITY, 0, 0);
                .showAtLocation(contentView, Gravity.NO_GRAVITY, 0, statusBarHeight);
    }

    /**
     * Start an activity for result with wave effect.
     * @param activity
     * @param waveDrawable
     * @param intent
     * @param requestCode
     * @param backgroundColor
     */
    public static void startWaveFilterForResult(final Activity activity, WaveDrawable waveDrawable, final Intent intent, final int requestCode, int backgroundColor) {
        intent.putExtra(IntentKey.BACKGROUND_COLOR, backgroundColor);
        startWaveFilterForResult(activity, waveDrawable, intent, requestCode);
    }

    /**
     * Start an activity for result with wave effect, but without background color of the TO activity
     * @param activity
     * @param waveDrawable
     * @param intent
     * @param requestCode
     */
    public static void startWaveFilterForResult(final Activity activity, WaveDrawable waveDrawable, final Intent intent, final int requestCode) {
        prepareWaveIntent(intent);

        View contentView = activity.findViewById(android.R.id.content);
        Bitmap bitmap = convertViewToBitmap(contentView);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        View view = new View(activity);
        view.setLayoutParams(new ViewGroup.LayoutParams(width, height));

        waveDrawable.setFrameBitmap(bitmap);
        int statusBarHeight = getStatusBarHeight(activity);

        new WaveContainer(view, waveDrawable, width, height) {
            @Override
            protected void onWaveDrawableAnimatorEndExtraAction() {
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                activity.startActivityForResult(intent, requestCode);
            }
        }
//                .showAtLocation(contentView, Gravity.NO_GRAVITY, 0, 0);
                .showAtLocation(contentView, Gravity.NO_GRAVITY, 0, statusBarHeight);
    }

    /**
     * Do some prepare things.
     * @param intent
     */
    private static void prepareWaveIntent(Intent intent) {
        intent.putExtra(IntentKey.IS_WAVE_COMPAT, true);
    }

    /**
     * The default initial transition animation.
     * @param activity
     * @param offsetY
     * @param backgroundFromColor
     * @param backgroundToColor
     */
    public static void transitionDefaultInitial(Activity activity, int offsetY, int backgroundFromColor, int backgroundToColor) {
        final View contentView = activity.findViewById(Window.ID_ANDROID_CONTENT);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(contentView, "alpha", 0f, 1f);
        alphaAnimator.setDuration(200);
        ValueAnimator marginTopAnimator = ValueAnimator.ofInt(offsetY, 0);
        marginTopAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) contentView.getLayoutParams();
                lp.topMargin = value;
                contentView.setLayoutParams(lp);
            }
        });
        marginTopAnimator.setDuration(200);

        ValueAnimator bgColorAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), backgroundFromColor, backgroundToColor);
        bgColorAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                contentView.setBackgroundColor(value);
            }
        });
        bgColorAnimator.setDuration(300);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(marginTopAnimator).with(alphaAnimator).before(bgColorAnimator);
        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.start();
    }

    private static int getStatusBarHeight(Activity activity) {
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }

    private static Bitmap convertViewToBitmap(View view) {
//        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
//        view.buildDrawingCache();
        return view.getDrawingCache();
    }

}


text:
static NSString *const kUKRegexString = @"(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY]))))\\s?[0-9][A-Z-[CIKMOV]]{2})";
static NSString *const kCanadaRegexString = @"[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]";
static NSString *const kUSARegexString = @"(^\\d{5}$)|(^\\d{5}-\\d{4}$)";

@interface JPInputField ()

- (void)setupView;

@end

@implementation PostCodeInputField

- (void)setupView {
    [super setupView];
    self.textField.keyboardType = UIKeyboardTypeDefault;
    self.textField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
    self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
}

- (void)setBillingCountry:(BillingCountry)billingCountry {
    if (_billingCountry == billingCountry) {
        return;
    }

    _billingCountry = billingCountry;

    if (_billingCountry == BillingCountryUK || _billingCountry == BillingCountryCanada) {
        self.textField.keyboardType = UIKeyboardTypeDefault;
    } else {
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
    }

    NSString *placeholder = [self descriptionForBillingCountry:_billingCountry];
    [self.textField setPlaceholder:placeholder floatingTitle:placeholder];
}

- (NSString *)descriptionForBillingCountry:(BillingCountry)country {

    if (country == BillingCountryUSA) {
        return @"billing_zip_code".localized;
    }

    if (country == BillingCountryCanada) {
        return @"billing_postcode".localized;
    }

    return @"billing_postcode".localized;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField != self.textField) {
        return YES;
    }

    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (newString.length == 0) {
        return YES;
    }

    switch (self.billingCountry) {
        case BillingCountryUK:
            return newString.isAlphaNumeric && newString.length <= 8;
        case BillingCountryCanada:
            return newString.isAlphaNumeric && newString.length <= 6;
        case BillingCountryUSA:
            return newString.isNumeric && newString.length <= 5;
        default:
            return newString.isNumeric && newString.length <= 8;
    }
}

- (BOOL)isValid {

    NSString *newString = [self.textField.text uppercaseString];

    NSRegularExpression *ukRegex = [NSRegularExpression regularExpressionWithPattern:kUKRegexString options:NSRegularExpressionAnchorsMatchLines error:nil];
    NSRegularExpression *canadaRegex = [NSRegularExpression regularExpressionWithPattern:kCanadaRegexString options:NSRegularExpressionAnchorsMatchLines error:nil];
    NSRegularExpression *usaRegex = [NSRegularExpression regularExpressionWithPattern:kUSARegexString options:NSRegularExpressionAnchorsMatchLines error:nil];

    switch (self.billingCountry) {
        case BillingCountryUK:
            return [ukRegex numberOfMatchesInString:newString options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, newString.length)] > 0;
        case BillingCountryCanada:
            return [canadaRegex numberOfMatchesInString:newString options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, newString.length)] > 0 && newString.length == 6;
        case BillingCountryUSA:
            return [usaRegex numberOfMatchesInString:newString options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, newString.length)] > 0;
        default:
            return newString.isNumeric && newString.length <= 8;
    }

    return NO;
}

- (void)textFieldDidChangeValue:(UITextField *)textField {
    [super textFieldDidChangeValue:textField];

    [self didChangeInputText];

    [self.delegate judoPayInput:self didValidate:self.isValid];

    NSUInteger characterCount = textField.text.length;

    BOOL valid = YES;

    if (self.billingCountry == BillingCountryUK && characterCount >= 8) {
        valid = NO;
    }

    if (self.billingCountry == BillingCountryCanada && characterCount >= 6 && !self.isValid) {
        valid = NO;
    }

    if (!valid) {
        [self errorAnimation:YES];
        [self.delegate postCodeInputField:self didFailWithError:[NSError judoInputMismatchErrorWithMessage:[NSString stringWithFormat:@"Check %@", [self descriptionForBillingCountry:self.billingCountry]]]];
        return;
    }
}

- (NSString *)title {
    return [self descriptionForBillingCountry:self.billingCountry];
}

- (CGFloat)titleWidth {
    return 120.0f;
}

@end


text:
#include "SkDeviceLooper.h"

SkDeviceLooper::SkDeviceLooper(const SkBitmap& base,
                               const SkRasterClip& rc,
                               const SkIRect& bounds, bool aa)
: fBaseBitmap(base)
, fBaseRC(rc)
, fDelta(aa ? kAA_Delta : kBW_Delta)
{
    // sentinels that next() has not yet been called, and so our mapper functions
    // should not be called either.
    fCurrBitmap = NULL;
    fCurrRC = NULL;

    SkIRect bitmapBounds = SkIRect::MakeWH(base.width(), base.height());
    if (!fClippedBounds.intersect(bounds, bitmapBounds)) {
        fState = kDone_State;
    } else if (this->fitsInDelta(bounds)) {
        fState = kSimple_State;
    } else {
        // back up by 1 DX, so that next() will put us in a correct starting
        // position.
        fCurrOffset.set(fClippedBounds.left() - fDelta,
                        fClippedBounds.top());
        fState = kComplex_State;
    }
}

SkDeviceLooper::~SkDeviceLooper() {
}

void SkDeviceLooper::mapRect(SkRect* dst, const SkRect& src) const {
    SkASSERT(kDone_State != fState);
    SkASSERT(fCurrBitmap);
    SkASSERT(fCurrRC);

    *dst = src;
    dst->offset(SkIntToScalar(-fCurrOffset.fX),
                SkIntToScalar(-fCurrOffset.fY));
}

void SkDeviceLooper::mapMatrix(SkMatrix* dst, const SkMatrix& src) const {
    SkASSERT(kDone_State != fState);
    SkASSERT(fCurrBitmap);
    SkASSERT(fCurrRC);

    *dst = src;
    dst->postTranslate(SkIntToScalar(-fCurrOffset.fX),
                       SkIntToScalar(-fCurrOffset.fY));
}

bool SkDeviceLooper::computeCurrBitmapAndClip() {
    SkASSERT(kComplex_State == fState);

    SkIRect r = SkIRect::MakeXYWH(fCurrOffset.x(), fCurrOffset.y(),
                                  fDelta, fDelta);
    if (!fBaseBitmap.extractSubset(&fSubsetBitmap, r)) {
        fState = kDone_State;
        return false;
    }
    fSubsetBitmap.lockPixels();

    fBaseRC.translate(-r.left(), -r.top(), &fSubsetRC);
    (void)fSubsetRC.op(SkIRect::MakeWH(fDelta, fDelta), SkRegion::kIntersect_Op);

    fCurrBitmap = &fSubsetBitmap;
    fCurrRC = &fSubsetRC;
    return true;
}

bool SkDeviceLooper::next() {
    switch (fState) {
        case kDone_State:
            // in theory, we should not get called here, since we must have
            // previously returned false, but we check anyway.
            break;

        case kSimple_State:
            // first time for simple
            if (NULL == fCurrBitmap) {
                fCurrBitmap = &fBaseBitmap;
                fCurrRC = &fBaseRC;
                fCurrOffset.set(0, 0);
                return true;
            }
            // 2nd time for simple, we are done
            break;

        case kComplex_State:
            // need to propogate fCurrOffset through clippedbounds
            // left to right, until we wrap around and move down

            if (fCurrOffset.x() + fDelta < fClippedBounds.right()) {
                fCurrOffset.fX += fDelta;
                return this->computeCurrBitmapAndClip();
            }
            fCurrOffset.fX = fClippedBounds.left();
            if (fCurrOffset.y() + fDelta < fClippedBounds.bottom()) {
                fCurrOffset.fY += fDelta;
                return this->computeCurrBitmapAndClip();
            }
            break;
    }

    fState = kDone_State;
    return false;
}


text:
Bixby is a service-oriented framework for building cloud-native [Node.js](https://nodejs.org)
applications.

Bixby.js is a lightweight approach to developing microservices with Node.js.  It
provides a cohesive suite of components that makes it easy to write services
that work seamlessly together.

## Overview

## Tests

    $ make test

## License

[The MIT License](http://opensource.org/licenses/MIT)

Copyright (c) 2014 Jared Hanson <[http://www.jaredhanson.net/](http://www.jaredhanson.net/)>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.jboss.jive</groupId>
	<artifactId>searchisko</artifactId>
	<name>searchisko</name>
	<description>Jive and Searchisko integration</description>
	<url>https://github.com/jbossorg/jive-searchisko</url>
	<version>9.0.0</version>

	<parent>
		<groupId>com.jivesoftware.maven</groupId>
		<artifactId>jive-parent-pom</artifactId>
		<version>9.0.2.1-0</version>
	</parent>

	<inceptionYear>2014</inceptionYear>
	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<scm>
		<connection>scm:git:git://github.com/jbossorg/jive-searchisko</connection>
		<developerConnection>scm:git:ssh://github.com/jbossorg/jive-searchisko</developerConnection>
		<url>https://github.com/jbossorg/jive-searchisko</url>
	</scm>

	<issueManagement>
		<system>GitHub</system>
		<url>https://github.com/jbossorg/jive-searchisko/issues/</url>
	</issueManagement>

	<developers>
		<developer>
			<id>lkrzyzan</id>
			<name>Libor Krzyzanek</name>
			<organization>Red Hat</organization>
			<organizationUrl>http://www.redhat.com</organizationUrl>
			<timezone>+1</timezone>
			<url>https://developer.jboss.org/people/lkrzyzanek</url>
		</developer>
	</developers>

	<properties>
		<jive.min.version>${jive.version.min}</jive.min.version>
		<jive.max.version>10.10.10.10</jive.max.version>
	</properties>

	<build>
		<outputDirectory>${project.build.directory}/classes</outputDirectory>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<!--
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>aspectj-maven-plugin</artifactId>
			</plugin>
			-->
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
			</plugin>
			<!-- Unpackages this Jive plugin. Used in conjunction with the -DpluginDirs= property -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-antrun-plugin</artifactId>
			</plugin>
		</plugins>

		<!-- Has to be version 2.2-beta-5 otherwise developers[0] filtering doesn't work -->
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-assembly-plugin</artifactId>
					<version>2.2-beta-5</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>

	<dependencies>
		<dependency>
			<groupId>com.jivesoftware</groupId>
			<artifactId>jive-core</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>${servlet.api.artifactId}</artifactId>
		</dependency>

		<dependency>
			<groupId>org.skyscreamer</groupId>
			<artifactId>jsonassert</artifactId>
			<version>1.2.3</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


text:
#include "Tutorial08_Tessellation.hpp"
#include "MapHelper.hpp"
#include "GraphicsUtilities.h"
#include "TextureUtilities.h"
#include "ShaderMacroHelper.hpp"
#include "imgui.h"

namespace Diligent
{

SampleBase* CreateSample()
{
    return new Tutorial08_Tessellation();
}

namespace
{

struct GlobalConstants
{
    unsigned int NumHorzBlocks; // Number of blocks along the horizontal edge
    unsigned int NumVertBlocks; // Number of blocks along the horizontal edge
    float        fNumHorzBlocks;
    float        fNumVertBlocks;

    float fBlockSize;
    float LengthScale;
    float HeightScale;
    float LineWidth;

    float  TessDensity;
    int    AdaptiveTessellation;
    float2 Dummy2;

    float4x4 WorldView;
    float4x4 WorldViewProj;
    float4   ViewportSize;
};

} // namespace

void Tutorial08_Tessellation::CreatePipelineStates()
{
    const bool bWireframeSupported = m_pDevice->GetDeviceInfo().Features.GeometryShaders;

    ShaderMacroHelper MacroHelper;

    // Pipeline state object encompasses configuration of all GPU stages

    GraphicsPipelineStateCreateInfo PSOCreateInfo;

    // Pipeline state name is used by the engine to report issues.
    // It is always a good idea to give objects descriptive names.
    PSOCreateInfo.PSODesc.Name = "Terrain PSO";

    // This is a graphics pipeline
    PSOCreateInfo.PSODesc.PipelineType = PIPELINE_TYPE_GRAPHICS;

    // clang-format off
    // This tutorial will render to a single render target
    PSOCreateInfo.GraphicsPipeline.NumRenderTargets             = 1;
    // Set render target format which is the format of the swap chain's color buffer
    PSOCreateInfo.GraphicsPipeline.RTVFormats[0]                = m_pSwapChain->GetDesc().ColorBufferFormat;
    // Set depth buffer format which is the format of the swap chain's back buffer
    PSOCreateInfo.GraphicsPipeline.DSVFormat                    = m_pSwapChain->GetDesc().DepthBufferFormat;
    // Primitive topology type defines what kind of primitives will be rendered by this pipeline state
    PSOCreateInfo.GraphicsPipeline.PrimitiveTopology            = PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST;
    // Cull back faces. For some reason, in OpenGL the order is reversed
    PSOCreateInfo.GraphicsPipeline.RasterizerDesc.CullMode      = m_pDevice->GetDeviceInfo().IsGLDevice() ? CULL_MODE_FRONT : CULL_MODE_BACK;
    // Enable depth testing
    PSOCreateInfo.GraphicsPipeline.DepthStencilDesc.DepthEnable = True;
    // clang-format on

    // Create dynamic uniform buffer that will store shader constants
    CreateUniformBuffer(m_pDevice, sizeof(GlobalConstants), "Global shader constants CB", &m_ShaderConstants);

    ShaderCreateInfo ShaderCI;
    // Tell the system that the shader source code is in HLSL.
    // For OpenGL, the engine will convert this into GLSL under the hood.
    ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;

    // OpenGL backend requires emulated combined HLSL texture samplers (g_Texture + g_Texture_sampler combination)
    ShaderCI.Desc.UseCombinedTextureSamplers = true;

    // Create a shader source stream factory to load shaders from files.
    RefCntAutoPtr<IShaderSourceInputStreamFactory> pShaderSourceFactory;
    m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(nullptr, &pShaderSourceFactory);
    ShaderCI.pShaderSourceStreamFactory = pShaderSourceFactory;
    // Create a vertex shader
    RefCntAutoPtr<IShader> pVS;
    {
        ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX;
        ShaderCI.EntryPoint      = "TerrainVS";
        ShaderCI.Desc.Name       = "Terrain VS";
        ShaderCI.FilePath        = "terrain.vsh";

        m_pDevice->CreateShader(ShaderCI, &pVS);
    }

    // Create a geometry shader
    RefCntAutoPtr<IShader> pGS;
    if (bWireframeSupported)
    {
        ShaderCI.Desc.ShaderType = SHADER_TYPE_GEOMETRY;
        ShaderCI.EntryPoint      = "TerrainGS";
        ShaderCI.Desc.Name       = "Terrain GS";
        ShaderCI.FilePath        = "terrain.gsh";

        m_pDevice->CreateShader(ShaderCI, &pGS);
    }

    // Create a hull shader
    RefCntAutoPtr<IShader> pHS;
    {
        ShaderCI.Desc.ShaderType = SHADER_TYPE_HULL;
        ShaderCI.EntryPoint      = "TerrainHS";
        ShaderCI.Desc.Name       = "Terrain HS";
        ShaderCI.FilePath        = "terrain.hsh";
        MacroHelper.AddShaderMacro("BLOCK_SIZE", m_BlockSize);
        ShaderCI.Macros = MacroHelper;

        m_pDevice->CreateShader(ShaderCI, &pHS);
    }

    // Create a domain shader
    RefCntAutoPtr<IShader> pDS;
    {
        ShaderCI.Desc.ShaderType = SHADER_TYPE_DOMAIN;
        ShaderCI.EntryPoint      = "TerrainDS";
        ShaderCI.Desc.Name       = "Terrain DS";
        ShaderCI.FilePath        = "terrain.dsh";
        ShaderCI.Macros          = nullptr;

        m_pDevice->CreateShader(ShaderCI, &pDS);
    }

    // Create a pixel shader
    RefCntAutoPtr<IShader> pPS, pWirePS;
    {
        ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
        ShaderCI.EntryPoint      = "TerrainPS";
        ShaderCI.Desc.Name       = "Terrain PS";
        ShaderCI.FilePath        = "terrain.psh";

        m_pDevice->CreateShader(ShaderCI, &pPS);

        if (bWireframeSupported)
        {
            ShaderCI.EntryPoint = "WireTerrainPS";
            ShaderCI.Desc.Name  = "Wireframe Terrain PS";
            ShaderCI.FilePath   = "terrain_wire.psh";

            m_pDevice->CreateShader(ShaderCI, &pWirePS);
        }
    }

    PSOCreateInfo.pVS = pVS;
    PSOCreateInfo.pHS = pHS;
    PSOCreateInfo.pDS = pDS;
    PSOCreateInfo.pPS = pPS;

    // Define variable type that will be used by default
    PSOCreateInfo.PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC;

    // clang-format off
    ShaderResourceVariableDesc Vars[] =
    {
        {SHADER_TYPE_HULL | SHADER_TYPE_DOMAIN,  "g_HeightMap", SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE},
        {SHADER_TYPE_PIXEL,                      "g_Texture",   SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}
    };
    // clang-format on
    PSOCreateInfo.PSODesc.ResourceLayout.Variables    = Vars;
    PSOCreateInfo.PSODesc.ResourceLayout.NumVariables = _countof(Vars);

    // clang-format off
    // Define immutable sampler for g_HeightMap and g_Texture. Immutable samplers should be used whenever possible
    SamplerDesc SamLinearClampDesc
    {
        FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR,
        TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP
    };
    ImmutableSamplerDesc ImtblSamplers[] =
    {
        {SHADER_TYPE_HULL | SHADER_TYPE_DOMAIN, "g_HeightMap", SamLinearClampDesc},
        {SHADER_TYPE_PIXEL,                     "g_Texture",   SamLinearClampDesc}
    };
    // clang-format on
    PSOCreateInfo.PSODesc.ResourceLayout.ImmutableSamplers    = ImtblSamplers;
    PSOCreateInfo.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers);

    m_pDevice->CreateGraphicsPipelineState(PSOCreateInfo, &m_pPSO[0]);

    if (bWireframeSupported)
    {
        PSOCreateInfo.pGS = pGS;
        PSOCreateInfo.pPS = pWirePS;
        m_pDevice->CreateGraphicsPipelineState(PSOCreateInfo, &m_pPSO[1]);
    }

    for (Uint32 i = 0; i < _countof(m_pPSO); ++i)
    {
        if (m_pPSO[i])
        {
            // clang-format off
            m_pPSO[i]->GetStaticVariableByName(SHADER_TYPE_VERTEX, "VSConstants")->Set(m_ShaderConstants);
            m_pPSO[i]->GetStaticVariableByName(SHADER_TYPE_HULL,   "HSConstants")->Set(m_ShaderConstants);
            m_pPSO[i]->GetStaticVariableByName(SHADER_TYPE_DOMAIN, "DSConstants")->Set(m_ShaderConstants);
            // clang-format on
        }
    }
    if (m_pPSO[1])
    {
        // clang-format off
        m_pPSO[1]->GetStaticVariableByName(SHADER_TYPE_GEOMETRY, "GSConstants")->Set(m_ShaderConstants);
        m_pPSO[1]->GetStaticVariableByName(SHADER_TYPE_PIXEL,    "PSConstants")->Set(m_ShaderConstants);
        // clang-format on
    }
}

void Tutorial08_Tessellation::LoadTextures()
{
    {
        // Load texture
        TextureLoadInfo loadInfo;
        loadInfo.IsSRGB = false;
        loadInfo.Name   = "Terrain height map";
        RefCntAutoPtr<ITexture> HeightMap;
        CreateTextureFromFile("ps_height_1k.png", loadInfo, m_pDevice, &HeightMap);
        const auto& HMDesc = HeightMap->GetDesc();
        m_HeightMapWidth   = HMDesc.Width;
        m_HeightMapHeight  = HMDesc.Height;
        // Get shader resource view from the texture
        m_HeightMapSRV = HeightMap->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE);
    }

    {
        TextureLoadInfo loadInfo;
        loadInfo.IsSRGB = true;
        loadInfo.Name   = "Terrain color map";
        RefCntAutoPtr<ITexture> ColorMap;
        CreateTextureFromFile("ps_texture_2k.png", loadInfo, m_pDevice, &ColorMap);
        // Get shader resource view from the texture
        m_ColorMapSRV = ColorMap->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE);
    }

    // Since we are using mutable variable, we must create a shader resource binding object
    // http://diligentgraphics.com/2016/03/23/resource-binding-model-in-diligent-engine-2-0/
    for (size_t i = 0; i < _countof(m_pPSO); ++i)
    {
        if (m_pPSO[i])
        {
            m_pPSO[i]->CreateShaderResourceBinding(&m_SRB[i], true);
            // Set texture SRV in the SRB
            // clang-format off
            m_SRB[i]->GetVariableByName(SHADER_TYPE_PIXEL,  "g_Texture")->Set(m_ColorMapSRV);
            m_SRB[i]->GetVariableByName(SHADER_TYPE_DOMAIN, "g_HeightMap")->Set(m_HeightMapSRV);
            m_SRB[i]->GetVariableByName(SHADER_TYPE_HULL,   "g_HeightMap")->Set(m_HeightMapSRV);
            // clang-format on
        }
    }
}

void Tutorial08_Tessellation::UpdateUI()
{
    ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver);
    if (ImGui::Begin("Settings", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
    {
        ImGui::Checkbox("Animate", &m_Animate);
        ImGui::Checkbox("Adaptive tessellation", &m_AdaptiveTessellation);
        if (m_pPSO[1])
            ImGui::Checkbox("Wireframe", &m_Wireframe);
        ImGui::SliderFloat("Tess density", &m_TessDensity, 1.f, 32.f);
        ImGui::SliderFloat("Distance", &m_Distance, 1.f, 20.f);
    }
    ImGui::End();
}

void Tutorial08_Tessellation::ModifyEngineInitInfo(const ModifyEngineInitInfoAttribs& Attribs)
{
    SampleBase::ModifyEngineInitInfo(Attribs);

    Attribs.EngineCI.Features.Tessellation    = DEVICE_FEATURE_STATE_ENABLED;
    Attribs.EngineCI.Features.GeometryShaders = DEVICE_FEATURE_STATE_OPTIONAL;
}

void Tutorial08_Tessellation::Initialize(const SampleInitInfo& InitInfo)
{
    SampleBase::Initialize(InitInfo);

    CreatePipelineStates();
    LoadTextures();
}

// Render a frame
void Tutorial08_Tessellation::Render()
{
    auto* pRTV = m_pSwapChain->GetCurrentBackBufferRTV();
    auto* pDSV = m_pSwapChain->GetDepthBufferDSV();
    // Clear the back buffer
    const float ClearColor[] = {0.350f, 0.350f, 0.350f, 1.0f};
    m_pImmediateContext->ClearRenderTarget(pRTV, ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
    m_pImmediateContext->ClearDepthStencil(pDSV, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);

    unsigned int NumHorzBlocks = m_HeightMapWidth / m_BlockSize;
    unsigned int NumVertBlocks = m_HeightMapHeight / m_BlockSize;
    {
        // Map the buffer and write rendering data
        MapHelper<GlobalConstants> Consts(m_pImmediateContext, m_ShaderConstants, MAP_WRITE, MAP_FLAG_DISCARD);
        Consts->fBlockSize     = static_cast<float>(m_BlockSize);
        Consts->NumHorzBlocks  = NumHorzBlocks;
        Consts->NumVertBlocks  = NumVertBlocks;
        Consts->fNumHorzBlocks = static_cast<float>(NumHorzBlocks);
        Consts->fNumVertBlocks = static_cast<float>(NumVertBlocks);

        Consts->LengthScale = 10.f;
        Consts->HeightScale = Consts->LengthScale / 25.f;

        Consts->WorldView     = m_WorldViewMatrix.Transpose();
        Consts->WorldViewProj = m_WorldViewProjMatrix.Transpose();

        Consts->TessDensity          = m_TessDensity;
        Consts->AdaptiveTessellation = m_AdaptiveTessellation ? 1 : 0;

        const auto& SCDesc   = m_pSwapChain->GetDesc();
        Consts->ViewportSize = float4(static_cast<float>(SCDesc.Width), static_cast<float>(SCDesc.Height), 1.f / static_cast<float>(SCDesc.Width), 1.f / static_cast<float>(SCDesc.Height));

        Consts->LineWidth = 3.0f;
    }

    // Set the pipeline state
    m_pImmediateContext->SetPipelineState(m_pPSO[m_Wireframe ? 1 : 0]);
    // Commit shader resources. RESOURCE_STATE_TRANSITION_MODE_TRANSITION mode
    // makes sure that resources are transitioned to required states.
    m_pImmediateContext->CommitShaderResources(m_SRB[m_Wireframe ? 1 : 0], RESOURCE_STATE_TRANSITION_MODE_TRANSITION);

    DrawAttribs DrawAttrs;
    DrawAttrs.NumVertices = NumHorzBlocks * NumVertBlocks;
    DrawAttrs.Flags       = DRAW_FLAG_VERIFY_ALL;
    m_pImmediateContext->Draw(DrawAttrs);
}

void Tutorial08_Tessellation::Update(double CurrTime, double ElapsedTime)
{
    SampleBase::Update(CurrTime, ElapsedTime);
    UpdateUI();

    // Set world view matrix
    if (m_Animate)
    {
        m_RotationAngle += static_cast<float>(ElapsedTime) * 0.2f;
        if (m_RotationAngle > PI_F * 2.f)
            m_RotationAngle -= PI_F * 2.f;
    }

    float4x4 ModelMatrix = float4x4::RotationY(m_RotationAngle) * float4x4::RotationX(-PI_F * 0.1f);
    // Camera is at (0, 0, -m_Distance) looking along Z axis
    float4x4 ViewMatrix = float4x4::Translation(0.f, 0.0f, m_Distance);

    // Get pretransform matrix that rotates the scene according the surface orientation
    auto SrfPreTransform = GetSurfacePretransformMatrix(float3{0, 0, 1});

    // Get projection matrix adjusted to the current screen orientation
    auto Proj = GetAdjustedProjectionMatrix(PI_F / 4.0f, 0.1f, 1000.f);

    m_WorldViewMatrix = ModelMatrix * ViewMatrix * SrfPreTransform;

    // Compute world-view-projection matrix
    m_WorldViewProjMatrix = m_WorldViewMatrix * Proj;
}

} // namespace Diligent


text:
This project implements a genetic algorithm to discover a good (if not best) subset of variables to use.

## Dependencies

* foreach

## Suggested

* doMC -- strongly recommended, for running the algorithm on multiple cores with greater speed
* devtools -- optional, for building the package
* testthat -- optional, for running tests to verify functionality

## Usage:

```
# OPTIONAL -- for parallelism
library(doMC)
registerDoMC(cores=4) # Where 4 corresponds to the number of cores in your machine to utilize

library(bestSubsetGA)
my_subset <- bestSubset(dependent_variable, independent_variables,
                        buildModel=lm, fitnessMetric=modelSigma,
                        likelihoodFn=squared, minimize_fitness_metric=FALSE,
                        n_generations=250, n_genes=50, mutation_rate=0.0025)
independent_variables <- my_data[, my_subset] # Take only the given columns
best_model <- lm(dependent_variable ~ ., data=independent_variables)
```

The `bestSubset()` function returns a vector of the designated clusters for each row in dataset.  See `help(bestSubset)` for more information or `tests/` for more examples.

## Installation:

```
# If you do not already have the "devtools" package installed
install.packages("devtools")

devtools::install_github("rdtaylor/bestSubsetGA")
```

Alternately, use the `build.sh` script in the root of the project.


text:
#ifndef TENSORFLOW_LITE_DELEGATES_XNNPACK_PAD_TESTER_H_
#define TENSORFLOW_LITE_DELEGATES_XNNPACK_PAD_TESTER_H_

#include <cstdint>
#include <vector>

#include <gtest/gtest.h>
#include "tensorflow/lite/core/c/common.h"

namespace tflite {
namespace xnnpack {

class PadTester {
 public:
  PadTester() = default;
  PadTester(const PadTester&) = delete;
  PadTester& operator=(const PadTester&) = delete;

  inline PadTester& InputShape(std::initializer_list<int32_t> shape) {
    for (auto it = shape.begin(); it != shape.end(); ++it) {
      EXPECT_GT(*it, 0);
    }
    input_shape_ = std::vector<int32_t>(shape.begin(), shape.end());
    return *this;
  }

  inline const std::vector<int32_t>& InputShape() const { return input_shape_; }

  inline PadTester& InputPrePaddings(std::initializer_list<int32_t> paddings) {
    for (auto it = paddings.begin(); it != paddings.end(); ++it) {
      EXPECT_GE(*it, 0);
    }
    input_pre_paddings_ =
        std::vector<int32_t>(paddings.begin(), paddings.end());
    return *this;
  }

  inline const std::vector<int32_t> InputPrePaddings() const {
    return input_pre_paddings_;
  }

  inline PadTester& InputPostPaddings(std::initializer_list<int32_t> paddings) {
    for (auto it = paddings.begin(); it != paddings.end(); ++it) {
      EXPECT_GE(*it, 0);
    }
    input_post_paddings_ =
        std::vector<int32_t>(paddings.begin(), paddings.end());
    return *this;
  }

  inline const std::vector<int32_t> InputPostPaddings() const {
    return input_post_paddings_;
  }

  std::vector<int32_t> OutputShape() const;

  void Test(TfLiteDelegate* delegate) const;

 private:
  std::vector<char> CreateTfLiteModel() const;

  static int32_t ComputeSize(const std::vector<int32_t>& shape);

  std::vector<int32_t> input_shape_;
  std::vector<int32_t> input_pre_paddings_;
  std::vector<int32_t> input_post_paddings_;
};

}  // namespace xnnpack
}  // namespace tflite

#endif  // TENSORFLOW_LITE_DELEGATES_XNNPACK_PAD_TESTER_H_


text:
Animatronic-Prosthetic-Hand
===========================

A project using Arduino to control a robotic hand though a bluetooth connection with a mobile device.
=======
A project using Arduino to control a robotic hand though a bluetooth connection with a mobile device.

This Project has been suspended until further notice.
===


text:
'''@file deepclustering_flat_loss.py
contains the DeepclusteringFlatLoss'''

import tensorflow as tf
import loss_computer
from nabu.neuralnetworks.components import ops

class DeepclusteringFlatLoss(loss_computer.LossComputer):
    '''A loss computer that calculates the loss'''

    def __call__(self, targets, logits, seq_length):
        '''
        Compute the loss

        Creates the operation to compute the deep clustering loss. Same as deepclustering_loss,
        only here logits is expected in [batch_size x time x frequency x emb_dim] where for
        deepclustering_loss it is [batch_size x time x frequency*emb_dim]

        Args:
            targets: a dictionary of [batch_size x time x ...] tensor containing
                the targets
            logits: a dictionary of [batch_size x time x ...] tensors containing the logits
            seq_length: a dictionary of [batch_size] vectors containing
                the sequence lengths

        Returns:
            loss: a scalar value containing the loss
            norm: a scalar value indicating how to normalize the loss
        '''

	binary_target=targets['binary_targets']
	usedbins = targets['usedbins']
	seq_length = seq_length['bin_emb']
	logits = logits['bin_emb']

	loss, norm = ops.deepclustering_flat_loss(binary_target, logits, usedbins,
					seq_length,self.batch_size)

        return loss, norm


text:
#pragma once

#include <memory>

#include "envoy/config/core/v3/base.pb.h"
#include "envoy/config/endpoint/v3/endpoint.pb.h"
#include "envoy/config/endpoint/v3/endpoint.pb.validate.h"
#include "envoy/config/xds_resources_delegate.h"
#include "envoy/service/discovery/v3/discovery.pb.h"

#include "source/common/common/hash.h"
#include "source/common/config/api_version.h"
#include "source/common/config/grpc_mux_impl.h"
#include "source/common/config/grpc_subscription_impl.h"
#include "source/common/config/xds_mux/grpc_mux_impl.h"

#include "test/common/config/subscription_test_harness.h"
#include "test/mocks/config/custom_config_validators.h"
#include "test/mocks/config/mocks.h"
#include "test/mocks/event/mocks.h"
#include "test/mocks/grpc/mocks.h"
#include "test/mocks/local_info/mocks.h"
#include "test/mocks/upstream/cluster_manager.h"
#include "test/test_common/resources.h"
#include "test/test_common/utility.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

using testing::_;
using testing::Mock;
using testing::NiceMock;
using testing::Return;

namespace Envoy {
namespace Config {

class GrpcSubscriptionTestHarness : public SubscriptionTestHarness {
public:
  GrpcSubscriptionTestHarness(Envoy::Config::LegacyOrUnified legacy_or_unified)
      : GrpcSubscriptionTestHarness(legacy_or_unified, std::chrono::milliseconds(0)) {}

  GrpcSubscriptionTestHarness(Envoy::Config::LegacyOrUnified legacy_or_unified,
                              std::chrono::milliseconds init_fetch_timeout)
      : method_descriptor_(Protobuf::DescriptorPool::generated_pool()->FindMethodByName(
            "envoy.service.endpoint.v3.EndpointDiscoveryService.StreamEndpoints")),
        async_client_(new NiceMock<Grpc::MockAsyncClient>()),
        resource_decoder_(std::make_shared<TestUtility::TestOpaqueResourceDecoderImpl<
                              envoy::config::endpoint::v3::ClusterLoadAssignment>>("cluster_name")),
        config_validators_(std::make_unique<NiceMock<MockCustomConfigValidators>>()),
        should_use_unified_(legacy_or_unified == Envoy::Config::LegacyOrUnified::Unified) {
    node_.set_id("fo0");
    EXPECT_CALL(local_info_, node()).WillRepeatedly(testing::ReturnRef(node_));
    ttl_timer_ = new NiceMock<Event::MockTimer>(&dispatcher_);

    timer_ = new Event::MockTimer(&dispatcher_);

    if (should_use_unified_) {
      mux_ = std::make_shared<Config::XdsMux::GrpcMuxSotw>(
          std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_, *method_descriptor_,
          random_, stats_store_, rate_limit_settings_, local_info_, true,
          std::move(config_validators_));
    } else {
      mux_ = std::make_shared<Config::GrpcMuxImpl>(
          local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_,
          *method_descriptor_, random_, stats_store_, rate_limit_settings_, true,
          std::move(config_validators_), /*xds_resources_delegate=*/XdsResourcesDelegateOptRef(),
          /*target_xds_authority=*/"");
    }
    subscription_ = std::make_unique<GrpcSubscriptionImpl>(
        mux_, callbacks_, resource_decoder_, stats_, Config::TypeUrl::get().ClusterLoadAssignment,
        dispatcher_, init_fetch_timeout, false, SubscriptionOptions());
  }

  ~GrpcSubscriptionTestHarness() override {
    EXPECT_CALL(async_stream_, sendMessageRaw_(_, false));
    EXPECT_CALL(dispatcher_, clearDeferredDeleteList());
    dispatcher_.clearDeferredDeleteList();
  }

  void expectSendMessage(const std::set<std::string>& cluster_names, const std::string& version,
                         bool expect_node = false) override {
    expectSendMessage(cluster_names, version, expect_node, Grpc::Status::WellKnownGrpcStatus::Ok,
                      "");
  }

  void expectSendMessage(const std::set<std::string>& cluster_names, const std::string& version,
                         bool expect_node, const Protobuf::int32 error_code,
                         const std::string& error_message) {
    UNREFERENCED_PARAMETER(expect_node);
    API_NO_BOOST(envoy::service::discovery::v3::DiscoveryRequest) expected_request;
    if (expect_node) {
      expected_request.mutable_node()->CopyFrom(node_);
    }
    for (const auto& cluster : cluster_names) {
      expected_request.add_resource_names(cluster);
    }
    if (!version.empty()) {
      expected_request.set_version_info(version);
    }
    expected_request.set_response_nonce(last_response_nonce_);
    expected_request.set_type_url(Config::TypeUrl::get().ClusterLoadAssignment);
    if (error_code != Grpc::Status::WellKnownGrpcStatus::Ok) {
      ::google::rpc::Status* error_detail = expected_request.mutable_error_detail();
      error_detail->set_code(error_code);
      error_detail->set_message(error_message);
    }
    EXPECT_CALL(
        async_stream_,
        sendMessageRaw_(Grpc::ProtoBufferEqIgnoreRepeatedFieldOrdering(expected_request), false));
  }

  void startSubscription(const std::set<std::string>& cluster_names) override {
    EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
    last_cluster_names_ = cluster_names;
    expectSendMessage(last_cluster_names_, "", true);
    subscription_->start(flattenResources(cluster_names));
  }

  void onDiscoveryResponse(
      std::unique_ptr<envoy::service::discovery::v3::DiscoveryResponse>&& response) {
    if (should_use_unified_) {
      dynamic_cast<Config::XdsMux::GrpcMuxSotw*>(mux_.get())
          ->onDiscoveryResponse(std::move(response), control_plane_stats_);
      return;
    }
    dynamic_cast<Config::GrpcMuxImpl*>(mux_.get())
        ->onDiscoveryResponse(std::move(response), control_plane_stats_);
  }

  void onRemoteClose() {
    if (should_use_unified_) {
      dynamic_cast<Config::XdsMux::GrpcMuxSotw*>(mux_.get())
          ->grpcStreamForTest()
          .onRemoteClose(Grpc::Status::WellKnownGrpcStatus::Canceled, "");
      return;
    }
    dynamic_cast<Config::GrpcMuxImpl*>(mux_.get())
        ->grpcStreamForTest()
        .onRemoteClose(Grpc::Status::WellKnownGrpcStatus::Canceled, "");
  }

  void deliverConfigUpdate(const std::vector<std::string>& cluster_names,
                           const std::string& version, bool accept) override {
    std::unique_ptr<envoy::service::discovery::v3::DiscoveryResponse> response(
        new envoy::service::discovery::v3::DiscoveryResponse());
    response->set_version_info(version);
    last_response_nonce_ = std::to_string(HashUtil::xxHash64(version));
    response->set_nonce(last_response_nonce_);
    response->set_type_url(Config::TypeUrl::get().ClusterLoadAssignment);
    response->mutable_control_plane()->set_identifier("ground_control_foo123");
    Protobuf::RepeatedPtrField<envoy::config::endpoint::v3::ClusterLoadAssignment> typed_resources;
    for (const auto& cluster : cluster_names) {
      if (std::find(last_cluster_names_.begin(), last_cluster_names_.end(), cluster) !=
          last_cluster_names_.end()) {
        envoy::config::endpoint::v3::ClusterLoadAssignment* load_assignment = typed_resources.Add();
        load_assignment->set_cluster_name(cluster);
        response->add_resources()->PackFrom(*load_assignment);
      }
    }
    const auto decoded_resources =
        TestUtility::decodeResources<envoy::config::endpoint::v3::ClusterLoadAssignment>(
            *response, "cluster_name");

    EXPECT_CALL(callbacks_, onConfigUpdate(DecodedResourcesEq(decoded_resources.refvec_), version))
        .WillOnce(ThrowOnRejectedConfig(accept));

    if (accept) {
      expectSendMessage(last_cluster_names_, version, false);
      version_ = version;
    } else {
      EXPECT_CALL(callbacks_, onConfigUpdateFailed(
                                  Envoy::Config::ConfigUpdateFailureReason::UpdateRejected, _));
      expectSendMessage(last_cluster_names_, version_, false,
                        Grpc::Status::WellKnownGrpcStatus::Internal, "bad config");
    }

    onDiscoveryResponse(std::move(response));
    EXPECT_EQ(control_plane_stats_.identifier_.value(), "ground_control_foo123");
    Mock::VerifyAndClearExpectations(&async_stream_);
  }

  void updateResourceInterest(const std::set<std::string>& cluster_names) override {
    if (!should_use_unified_) {
      // The "watch" mechanism means that updates that lose interest in a resource
      // will first generate a request for [still watched resources, i.e. without newly unwatched
      // ones] before generating the request for all of cluster_names.
      // TODO(fredlas) this unnecessary second request will stop happening once the watch mechanism
      // is no longer internally used by GrpcSubscriptionImpl.
      std::set<std::string> both;
      for (const auto& n : cluster_names) {
        if (last_cluster_names_.find(n) != last_cluster_names_.end()) {
          both.insert(n);
        }
      }
      expectSendMessage(both, version_);
    }
    expectSendMessage(cluster_names, version_);
    subscription_->updateResourceInterest(flattenResources(cluster_names));
    last_cluster_names_ = cluster_names;
  }

  void expectConfigUpdateFailed() override {
    EXPECT_CALL(callbacks_, onConfigUpdateFailed(_, nullptr));
  }

  void expectEnableInitFetchTimeoutTimer(std::chrono::milliseconds timeout) override {
    init_timeout_timer_ = new Event::MockTimer(&dispatcher_);
    EXPECT_CALL(*init_timeout_timer_, enableTimer(timeout, _));
  }

  void expectDisableInitFetchTimeoutTimer() override {
    EXPECT_CALL(*init_timeout_timer_, disableTimer());
  }

  void callInitFetchTimeoutCb() override { init_timeout_timer_->invokeCallback(); }

  std::string version_;
  const Protobuf::MethodDescriptor* method_descriptor_;
  Grpc::MockAsyncClient* async_client_;
  NiceMock<Upstream::MockClusterManager> cm_;
  Event::MockDispatcher dispatcher_;
  Random::MockRandomGenerator random_;
  Event::MockTimer* timer_;
  Event::MockTimer* ttl_timer_;
  envoy::config::core::v3::Node node_;
  NiceMock<Config::MockSubscriptionCallbacks> callbacks_;
  OpaqueResourceDecoderSharedPtr resource_decoder_;
  NiceMock<LocalInfo::MockLocalInfo> local_info_;
  CustomConfigValidatorsPtr config_validators_;
  NiceMock<Grpc::MockAsyncStream> async_stream_;
  GrpcMuxSharedPtr mux_;
  GrpcSubscriptionImplPtr subscription_;
  std::string last_response_nonce_;
  std::set<std::string> last_cluster_names_;
  Envoy::Config::RateLimitSettings rate_limit_settings_;
  Event::MockTimer* init_timeout_timer_;
  bool should_use_unified_;
};

// TODO(danielhochman): test with RDS and ensure version_info is same as what API returned

} // namespace Config
} // namespace Envoy


text:
package com.qunadai.channel.content.base;

/**
 * Model的基类
 */

public interface BaseModel {

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class virtualpondgui.MainContentPanel</title>
<meta name="date" content="2015-10-21">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
virtualpondgui.MainContentPanel

No usage of virtualpondgui.MainContentPanel

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2007 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.util;

import java.util.*;
import org.lockss.test.*;

public class TestBoundedTreeSet extends LockssTestCase {
  public static Class testedClasses[] = {
    org.lockss.util.BoundedTreeSet.class
  };

  Set set = new BoundedTreeSet(4);

  public void testNatural() {
    Set set = new BoundedTreeSet(4);
    assertTrue(set.isEmpty());
    assertEquals(0, set.size());
    assertTrue(set.add("6"));
    assertTrue(set.add("2"));
    assertTrue(set.add("4"));
    assertTrue(set.add("9"));
    assertEquals(ListUtil.list("2", "4", "6", "9"), new ArrayList(set));
    assertTrue(set.contains("6"));
    assertTrue(set.contains("2"));
    assertTrue(set.contains("4"));
    assertTrue(set.contains("9"));

    assertTrue(set.add("8"));
    assertEquals(ListUtil.list("2", "4", "6", "8"), new ArrayList(set));
    assertTrue(set.contains("8"));
    assertFalse(set.contains("9"));
    assertTrue(set.add("1"));
    assertEquals(ListUtil.list("1", "2", "4", "6"), new ArrayList(set));
  }

  public void testComparator() {
    Set set = new BoundedTreeSet(4, new Comparator() {
	public int compare(Object a, Object b) {
	  return ((Comparable)b).compareTo(((Comparable)a));
	}});
    assertTrue(set.isEmpty());
    assertEquals(0, set.size());
    assertTrue(set.add("6"));
    assertTrue(set.add("2"));
    assertTrue(set.add("4"));
    assertTrue(set.add("9"));
    assertEquals(ListUtil.list("9", "6", "4", "2"), new ArrayList(set));
    assertTrue(set.contains("6"));
    assertTrue(set.contains("2"));
    assertTrue(set.contains("4"));
    assertTrue(set.contains("9"));

    assertTrue(set.add("8"));
    assertEquals(ListUtil.list("9", "8", "6", "4"), new ArrayList(set));
    assertTrue(set.contains("9"));
    assertFalse(set.contains("2"));
    assertTrue(set.add("1"));
    assertEquals(ListUtil.list("9", "8", "6", "4"), new ArrayList(set));
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="shortcut icon" type="image/x-icon" href="/img/favicon.png">
    <link rel="icon" type="image/png" href="/img/favicon.png" sizes="32x32">

    <title>BAPH</title>

    <link href="/vendor/bootstrap/css/bootstrap.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">

    <link rel="stylesheet" href="/vendor/font-awesome/css/font-awesome.css">
    <link rel="stylesheet" href="/vendor/simple-line-icons/css/simple-line-icons.css">
    <link rel="stylesheet" href="/vendor/device-mockups/device-mockups.css">

    <link href="/css/new-age.css" rel="stylesheet">

                <button style="margin-top: 23px; margin-bottom: 19px;" type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                       Toggle navigation Menu
                    </button>

                        Home

                        Start

                        FAQ

Build up connection

                            <form id="form">
                                Roomname: <input class="textfeld_login" type="text" id="room" name="room" value="" maxlength="35" />

                                Password:
                                <input class="textfeld_login_pw" type="password" id="password" name="password" value="" maxlength="35">

                                <input type="checkbox" class="form_checkboxes" id="nutzungBCheckbox" name="nutzungBCheckbox">
                                accept terms and conditions

                                <input type="button" id="submit" name="submit" value="Connect" class="btn btn-Formular btn-outline btn-xl page-scroll padding_button" />

                            </form>

Manual

                                Step 1:
 Connect your devices by entering a desired room name. Select a secure password to block unwanted users.

                                Step 2:
 Memorize access data and select whether you want to transfer video or audio content in the settings section. Then press "connect" and allow the use of camera and microphone.

                                Step 3:
 Now key in your previously selected access data on the second device you have decided to use, or generate an invitation link sent to you by e-mail, simply by entering your e-mail address in the field below.

                <video id="remoteVideo" autoplay></video>

                    <video id="localVideo"></video>

                <button id="hangup" name="hangup" class="btn btn-Formular btn-outline btn-xl page-scroll padding_button hangup_btn">Disconnect</button>

                            <form>

                                 Send invitation:
                                <input type="email" class="en_formtype_email" id="invite" name="invite" placeholder="example@gmail.com" maxlength="60" />

                            </form>

Settings

        <form id="form_sett">

Audio:

                                                Transfer audio:
                                                <input type="checkbox" class="form_checkboxes" id="audioSupport" name="audioSupport">

                                                    Reduce echo:
                                                    <input type="checkbox" class="form_checkboxes" id="echoCancellation" name="echoCancellation">

Video:

                                                Transfer video:
                                                <input type="checkbox" class="form_checkboxes" id="videoSupport" name="videoSupport">

                                                    Resolution:
                                                    <select class="formtype_number_res" name="resolutions" id="resolutions"></select>

                                                    Framerate:
                                                    <input type="number" class="formtype_number" id="frameRate" name="frameRate"/>

        </form>

© 2016 Start Bootstrap. All Rights Reserved.

                    FAQ

                    Imprint


text:
module Application {
    export function initialize() {
        document.addEventListener('deviceready', onDeviceReady, false);
    }

    function onDeviceReady() {

        receivedEvent('deviceready');
        (<any>navigator).splashscreen.hide();

            require(["aurelia/aurelia-bundle-latest"], function (au) {
        require(["aurelia-bundle-manifest"], function (abm) {
            require(["aurelia-bootstrapper"], function (b) {
            });
        });
    });

    }

    function receivedEvent(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
}


text:
package reads

import (
	"context"
	"fmt"

	"github.com/influxdata/flux/interval"
	"github.com/influxdata/influxdb/v2/storage/reads/datatypes"
	"github.com/influxdata/influxdb/v2/tsdb/cursors"
)

type singleValue struct {
	v interface{}
}

func (v *singleValue) Value(key string) (interface{}, bool) {
	return v.v, true
}

func newAggregateArrayCursor(ctx context.Context, agg *datatypes.Aggregate, cursor cursors.Cursor) (cursors.Cursor, error) {
	switch agg.Type {
	case datatypes.Aggregate_AggregateTypeFirst, datatypes.Aggregate_AggregateTypeLast:
		return newLimitArrayCursor(cursor), nil
	}
	return newWindowAggregateArrayCursor(ctx, agg, interval.Window{}, cursor)
}

func newWindowAggregateArrayCursor(ctx context.Context, agg *datatypes.Aggregate, window interval.Window, cursor cursors.Cursor) (cursors.Cursor, error) {
	if cursor == nil {
		return nil, nil
	}

	switch agg.Type {
	case datatypes.Aggregate_AggregateTypeCount:
		return newWindowCountArrayCursor(cursor, window), nil
	case datatypes.Aggregate_AggregateTypeSum:
		return newWindowSumArrayCursor(cursor, window)
	case datatypes.Aggregate_AggregateTypeFirst:
		return newWindowFirstArrayCursor(cursor, window), nil
	case datatypes.Aggregate_AggregateTypeLast:
		return newWindowLastArrayCursor(cursor, window), nil
	case datatypes.Aggregate_AggregateTypeMin:
		return newWindowMinArrayCursor(cursor, window), nil
	case datatypes.Aggregate_AggregateTypeMax:
		return newWindowMaxArrayCursor(cursor, window), nil
	case datatypes.Aggregate_AggregateTypeMean:
		return newWindowMeanArrayCursor(cursor, window)
	default:
		// TODO(sgc): should be validated higher up
		panic("invalid aggregate")
	}
}

type cursorContext struct {
	ctx  context.Context
	req  *cursors.CursorRequest
	itrs cursors.CursorIterators
	err  error
}

type multiShardArrayCursors struct {
	ctx context.Context
	req cursors.CursorRequest

	cursors struct {
		i integerMultiShardArrayCursor
		f floatMultiShardArrayCursor
		u unsignedMultiShardArrayCursor
		b booleanMultiShardArrayCursor
		s stringMultiShardArrayCursor
	}
}

// newMultiShardArrayCursors is a factory for creating cursors for each series key.
// The range of the cursor is [start, end). The start time is the lower absolute time
// and the end time is the higher absolute time regardless of ascending or descending order.
func newMultiShardArrayCursors(ctx context.Context, start, end int64, asc bool) *multiShardArrayCursors {
	// When we construct the CursorRequest, we translate the time range
	// from [start, stop) to [start, stop]. The cursor readers from storage are
	// inclusive on both ends and we perform that conversion here.
	m := &multiShardArrayCursors{
		ctx: ctx,
		req: cursors.CursorRequest{
			Ascending: asc,
			StartTime: start,
			EndTime:   end - 1,
		},
	}

	cc := cursorContext{
		ctx: ctx,
		req: &m.req,
	}

	m.cursors.i.cursorContext = cc
	m.cursors.f.cursorContext = cc
	m.cursors.u.cursorContext = cc
	m.cursors.b.cursorContext = cc
	m.cursors.s.cursorContext = cc

	return m
}

func (m *multiShardArrayCursors) createCursor(row SeriesRow) cursors.Cursor {
	m.req.Name = row.Name
	m.req.Tags = row.SeriesTags
	m.req.Field = row.Field

	var cond expression
	if row.ValueCond != nil {
		cond = &astExpr{row.ValueCond}
	}

	var shard cursors.CursorIterator
	var cur cursors.Cursor
	for cur == nil && len(row.Query) > 0 {
		shard, row.Query = row.Query[0], row.Query[1:]
		cur, _ = shard.Next(m.ctx, &m.req)
	}

	if cur == nil {
		return nil
	}

	switch c := cur.(type) {
	case cursors.IntegerArrayCursor:
		m.cursors.i.reset(c, row.Query, cond)
		return &m.cursors.i
	case cursors.FloatArrayCursor:
		m.cursors.f.reset(c, row.Query, cond)
		return &m.cursors.f
	case cursors.UnsignedArrayCursor:
		m.cursors.u.reset(c, row.Query, cond)
		return &m.cursors.u
	case cursors.StringArrayCursor:
		m.cursors.s.reset(c, row.Query, cond)
		return &m.cursors.s
	case cursors.BooleanArrayCursor:
		m.cursors.b.reset(c, row.Query, cond)
		return &m.cursors.b
	default:
		panic(fmt.Sprintf("unreachable: %T", cur))
	}
}


text:
'use strict';

const path = require('path');
const google = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

async function runSample(query) {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const forms = google.forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await forms.forms.create({
    requestBody: newForm,
  });
  console.log('New formId was: ' + createResponse.data.formId);

  // Request body to convert form to a quiz
  const updateRequest = {
    requests: [
      {
        updateSettings: {
          settings: {
            quizSettings: {
              isQuiz: true,
            },
          },
          updateMask: 'quizSettings.isQuiz',
        },
      },
    ],
  };
  const res = await forms.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: updateRequest,
  });
  console.log(res.data);
  return res.data;
}

if (module === require.main) {
  runSample().catch(console.error);
}
module.exports = runSample;

// [END forms_convert_form]


text:
from collections import MutableMapping
from random import randrange
class MapBase(MutableMapping):

    class _Item:
        __slots_ = '_key', '_value'

        def __init__(self,key,value):
            self._key = key
            self._value = value

        def __eq__(self, other):
            return self._key == other._key

        def _ne__(self, other):
            return not (self == other)

        def __lt__(self,other):
            return self._key < other._key

class HashMapBase(MapBase):
    ''' abstract base class for map using hash-tables with MAD compression '''

    def __init__(self,cap=11,p=109345121):
        self._table = cap * [None]
        self._n = 0
        self._prime = p
        self._scale = randrange(p-1) + 1
        self._shift = randrange(p)

    def _hash_function(self, k):
        return (hash(k)* self._scale + self._shift) % self._prime % self._table

    def __len__(self):
        return self._n

    def __getitem__(self, key):
        j = self._hash_function(key)
        return self._bucket_getitem(j,key)

    def __setitem__(self, key, value):
        j = self._hash_function(key)
        self._bucket_setitem(j,key,value)
        if self._n > len(self._table) // 2: # keep load factor <= 0.5
            self._resize(2*len(self._table)-1)

    def __delitem__(self, key):
        j = self._hash_function(key)
        self._bucket_delitem(j,key)
        self._n -= 1

    def _resize(self, c):
        old = list(self.items())
        self._table = c * [None]
        self._n = 0
        for (k, v) in old:
            self[k] = v

    ''' ABSTRACT METHODS '''

    def _bucket_getitem(self,j,k):
        ''' gets the item from the bucket at index j with key k '''
        return NotImplementedError()

    def _bucket_setitem(self,j,k,v):
        ''' sets the item in the bucket at index j with value v associated with key k.
        If Key k already exists old value will be replace with new value v
        Implementation of this method is responsible for incrementing size of the elements
        '''
        return NotImplementedError()

    def _bucket_delitem(self,j,k):
        ''' deletes the item in the bucket at index j with key k '''
        return NotImplementedError()

    def __iter__(self):
        ''' Iterator over keys '''
        return NotImplementedError()