text:
package io.druid.server.http.security;

import com.google.inject.Inject;
import com.sun.jersey.spi.container.ContainerRequest;
import io.druid.server.security.Access;
import io.druid.server.security.AuthorizerMapper;
import io.druid.server.security.AuthorizationUtils;
import io.druid.server.security.ForbiddenException;
import io.druid.server.security.Resource;
import io.druid.server.security.ResourceAction;
import io.druid.server.security.ResourceType;

/**
 * Use this ResourceFilter at end points where Druid Cluster State is read or written
 * Here are some example paths where this filter is used -
 * - druid/broker/v1
 * - druid/coordinator/v1
 * - druid/historical/v1
 * - druid/indexer/v1
 * - druid/coordinator/v1/rules
 * - druid/coordinator/v1/tiers
 * - druid/worker/v1
 * - druid/coordinator/v1/servers
 * - status
 * Note - Currently the resource name for all end points is set to "STATE" however if more fine grained access control
 * is required the resource name can be set to specific state properties.
 */
public class StateResourceFilter extends AbstractResourceFilter
{
  @Inject
  public StateResourceFilter(
      AuthorizerMapper authorizerMapper
  )
  {
    super(authorizerMapper);
  }

  @Override
  public ContainerRequest filter(ContainerRequest request)
  {
    final ResourceAction resourceAction = new ResourceAction(
        new Resource("STATE", ResourceType.STATE),
        getAction(request)
    );

    final Access authResult = AuthorizationUtils.authorizeResourceAction(
        getReq(),
        resourceAction,
        getAuthorizerMapper()
    );

    if (!authResult.isAllowed()) {
      throw new ForbiddenException(authResult.toString());
    }

    return request;
  }

  @Override
  public boolean isApplicable(String requestPath)
  {
    return requestPath.startsWith("druid/broker/v1") ||
           requestPath.startsWith("druid/coordinator/v1") ||
           requestPath.startsWith("druid/historical/v1") ||
           requestPath.startsWith("druid/indexer/v1") ||
           requestPath.startsWith("druid/coordinator/v1/rules") ||
           requestPath.startsWith("druid/coordinator/v1/tiers") ||
           requestPath.startsWith("druid/worker/v1") ||
           requestPath.startsWith("druid/coordinator/v1/servers") ||
           requestPath.startsWith("druid/v2") ||
           requestPath.startsWith("status");
  }
}


text:
"""Porter Duff compositing."""
from abc import ABCMeta, abstractmethod

class PorterDuff(metaclass=ABCMeta):
    """Porter Duff compositing."""

    def __init__(self, cba, csa):
        """Initialize."""

        self.cba = cba
        self.csa = csa

    @abstractmethod
    def _fa(self):  # pragma: no cover
        """Calculate `Fa`."""

        raise NotImplementedError('fa is not implemented')

    @abstractmethod
    def _fb(self):  # pragma: no cover
        """Calculate `Fb`."""

        raise NotImplementedError('fb is not implemented')

    def co(self, cb, cs):
        """Calculate premultiplied coordinate."""

        return self.csa * self._fa() * cs + self.cba * self._fb() * cb

    def ao(self):
        """Calculate output alpha."""

        return self.csa * self._fa() + self.cba * self._fb()

class Clear(PorterDuff):
    """Clear."""

    def _fa(self):
        """Calculate `Fa`."""

        return 0

    def _fb(self):
        """Calculate `Fb`."""

        return 0

class Copy(PorterDuff):
    """Copy."""

    def _fa(self):
        """Calculate `Fa`."""

        return 1

    def _fb(self):
        """Calculate `Fb`."""

        return 0

class Destination(PorterDuff):
    """Destination."""

    def _fa(self):
        """Calculate `Fa`."""

        return 0

    def _fb(self):
        """Calculate `Fb`."""

        return 1

class SourceOver(PorterDuff):
    """Source over."""

    def _fa(self):
        """Calculate `Fa`."""

        return 1

    def _fb(self):
        """Calculate `Fb`."""

        return 1 - self.csa

class DestinationOver(PorterDuff):
    """Destination over."""

    def _fa(self):
        """Calculate `Fa`."""

        return 1 - self.cba

    def _fb(self):
        """Calculate `Fb`."""

        return 1

class SourceIn(PorterDuff):
    """Source in."""

    def _fa(self):
        """Calculate `Fa`."""

        return self.cba

    def _fb(self):
        """Calculate `Fb`."""

        return 0

class DestinationeIn(PorterDuff):
    """Destination in."""

    def _fa(self):
        """Calculate `Fa`."""

        return 0

    def _fb(self):
        """Calculate `Fb`."""

        return self.csa

class SourceOut(PorterDuff):
    """Source out."""

    def _fa(self):
        """Calculate `Fa`."""

        return 1 - self.cba

    def _fb(self):
        """Calculate `Fb`."""

        return 0

class DestinationOut(PorterDuff):
    """Destination out."""

    def _fa(self):
        """Calculate `Fa`."""

        return 0

    def _fb(self):
        """Calculate `Fb`."""

        return 1 - self.csa

class SourceAtop(PorterDuff):
    """Source atop."""

    def _fa(self):
        """Calculate `Fa`."""

        return self.cba

    def _fb(self):
        """Calculate `Fb`."""

        return 1 - self.csa

class DestinationAtop(PorterDuff):
    """Destination atop."""

    def _fa(self):
        """Calculate `Fa`."""

        return 1 - self.cba

    def _fb(self):
        """Calculate `Fb`."""

        return self.csa

class XOR(PorterDuff):
    """XOR."""

    def _fa(self):
        """Calculate `Fa`."""

        return 1 - self.cba

    def _fb(self):
        """Calculate `Fb`."""

        return 1 - self.csa

class Lighter(PorterDuff):
    """Lighter."""

    def _fa(self):
        """Calculate `Fa`."""

        return 1

    def _fb(self):
        """Calculate `Fb`."""

        return 1

SUPPORTED = {
    'clear': Clear,
    'copy': Copy,
    'destination': Destination,
    'source-over': SourceOver,
    'destination-over': DestinationOver,
    'source-in': SourceIn,
    'destination-in': DestinationeIn,
    'source-out': SourceOut,
    'destination-out': DestinationOut,
    'source-atop': SourceAtop,
    'destination-atop': DestinationAtop,
    'xor': XOR,
    'lighter': Lighter
}

def compositor(name):
    """Get the requested compositor."""

    name = name.lower()
    if name not in SUPPORTED:
        raise ValueError("'{}' compositing is not supported".format(name))
    return SUPPORTED[name]

redpajama_set_name: RedPajamaGithub


text:
package multiplicity3.csys.items.item;

import java.util.List;
import java.util.UUID;

import multiplicity3.csys.behaviours.IBehaviour;
import multiplicity3.csys.items.INestable;
import multiplicity3.csys.items.events.IItemListener;
import multiplicity3.csys.items.events.MultiTouchEventDispatcher;
import multiplicity3.csys.zorder.IZOrderManager;

import com.jme3.math.Vector2f;
import com.jme3.scene.Spatial;

public interface IItem extends INestable {
	public UUID getUUID();
	public void setParentItem(IItem parent);
	public IItem getParentItem();
	public String getName();
	public MultiTouchEventDispatcher getMultiTouchDispatcher();

	public void addItemListener(IItemListener itemListener);
	public void removeItemListener(IItemListener itemListener);
	public List<IItemListener> getItemListeners();
	public void setItemListeners(List<IItemListener> itemListeners);

	/**
	 * Puts the item to a location on screen, given by screen coordinates
	 * @param loc a position, in screen coordinates
	 */
	public void setWorldLocation(Vector2f loc);
	public Vector2f getWorldLocation();

	/**
	 * Get the world location of an arbitrary point, where the
	 * arbitrary point is given in relative coordinates to this item.
	 * @param v
	 * @return
	 */
	public Vector2f getWorldLocation(Vector2f v);
	public void setRelativeLocation(Vector2f loc);
	public Vector2f getRelativeLocation();
	public Vector2f getRelativeLocationOfWorldLocation(Vector2f worldloc);
	public Vector2f convertWorldVelocityToLocalVelocity(Vector2f loc);
	public void centerItem();
	public void setRelativeRotation(float angle);
	public float getRelativeRotation();
	public float getWorldRotationDegrees();
	public void setRelativeScale(float scale);
	public float getRelativeScale();

	public IZOrderManager getZOrderManager();

	public void setInteractionEnabled(boolean b);

	// 'undocumented' API methods
	//public Spatial getTreeRootSpatial();
	//public Spatial getManipulableSpatial();

	public void behaviourAdded(IBehaviour behaviour);
	public List<IBehaviour> getBehaviours();
	public <T extends IBehaviour> List<T> getBehaviours(Class<T> clazz);

    public void setVisible(boolean isVisible);
	public boolean isVisible();
	public int getZOrder();
	void setZOrder(int zOrder);

	public Spatial getManipulableSpatial();

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Magick++ API: Working with Pixels </title>
<link rel="stylesheet" href="https://www.imagemagick.org/Magick++/magick.css" type="text/css" />

Magick::Pixels

The Pixels class provides efficient access to raw image
pixels. Image pixels (of type PixelPacket)
may be accessed directly via the Image Pixel Cache. The image
pixel cache is a rectangular window (a view) into the actual image
pixels (which may be in memory, memory-mapped from a disk file, or
entirely on disk). Obtain existing image pixels via get().
Create a new pixel region using set().

Depending on the capabilities of the operating system, and the
relationship of the window to the image, the pixel cache may be a copy
of the pixels in the selected window, or it may be the actual image
pixels. In any case calling sync() insures that the base image
is updated with the contents of the modified pixel cache. The method decode()supports
copying foreign pixel data formats into the pixel cache according to
the QuantumTypes. The method encode() supports copying
the pixels in the cache to a foreign pixel representation according to
the format specified by QuantumTypes.

Setting a view using the Pixels class does not cause the number of
references to the underlying image to be reduced to one. Therefore, in
order to ensure that only the current generation of the image is
modified, the Image's modifyImage()
method should be invoked to reduce the reference count on the underlying
image to one. If this is not done, then it is possible for a previous
generation of the image to be modified due to the use of reference
counting when copying or constructing an Image.

The PixelPacket* returned by the set and get
methods, and the IndexPacket* returned by the indexes
method point to pixel data managed by the Pixels class. The Pixels
class is responsible for releasing resources associated with the pixel
view. This means that the pointer should never be passed to delete() or
free().

The pixel view is a small image in which
the pixels may be accessed, addressed, and updated, as shown in the
following example, which produces an image similar to the one on the
right (minus lines and text):

 // Create base image
 Image image(Geometry(254,218), "white");

   // Set the image type to TrueColor DirectClass representation.
 image.type(TrueColorType);
 // Ensure that there is only one reference to underlying image
 // If this is not done, then image pixels will not be modified.
 image.modifyImage();

 // Allocate pixel view
 Pixels view(image);

 // Set all pixels in region anchored at 38x36, with size 160x230 to green.
 size_t columns = 196; size_t rows = 162;
 Color green("green");
 PixelPacket *pixels = view.get(38,36,columns,rows);
 for ( ssize_t row = 0; row < rows ; ++row )
   for ( ssize_t column = 0; column < columns ; ++column )
     *pixels++=green;

 // Save changes to image.
 view.sync();

 // Set all pixels in region anchored at 86x72, with size 108x67 to yellow.
 columns = 108; rows = 67;
 Color yellow("yellow");
 pixels = view.get(86,72,columns,rows);
 for ( ssize_t row = 0; row < rows ; ++row )
    for ( ssize_t column = 0; column < columns ; ++column )
       *pixels++=yellow;
  view.sync();

 // Set pixel at position 108,94 to red
 *(view.get(108,94,1,1)) = Color("red");

 // Save changes to image.
 view.sync();

Pixels supports the following
methods:

Pixel Cache Methods

Method

Returns

Signature

Description

get

PixelPacket*

const ssize_t x_, const ssize_t y_, const size_t
columns_, const size_t rows_

Transfers read-write pixels from the image to
the 			pixel cache as defined by the specified rectangular region.
			Modified pixels may be subsequently transferred back to the image
			via sync. The value returned is intended for pixel access
			only. It should never be deallocated.

getConst

const PixelPacket*

const ssize_t x_, const ssize_t y_, const size_t
			columns_, const size_t rows_

Transfers read-only pixels from the image to
the 			pixel cache as defined by the specified rectangular region.

set

PixelPacket*

const ssize_t x_, const ssize_t y_, const size_t
			columns_, const size_t rows_

Allocates a pixel cache region to store image
			pixels as defined by the region rectangle.  This area is
			subsequently transferred from the pixel cache to the image via 			sync.
The value returned is intended for pixel access only. 			It should
never be deallocated.

sync

void

void

Transfers the image cache pixels to the image.

indexes

IndexPacket*

void

Returns the PsuedoColor pixel indexes
			corresponding to the pixel region defined by the last get
			, getConst, or set
			call. Only valid for PseudoColor and CMYKA images. The pixel
			indexes (an array of type IndexPacket, which is typedef 			Quantum,
which is itself typedef unsigned char, or 			unsigned short,
depending on the value of the QuantumDepth 			define) provide
the colormap index 			(see colorMap) for each pixel in 			the
image. For CMYKA images, the indexes represent the black
channel. The value returned is intended for pixel access 			only. It
should never be deallocated.

x

int

void

Left ordinate of view

y

int

void

Top ordinate of view

columns

size_t

void

Width of view

rows

size_t

void

Height of view


text:
/*can@2.2.5#map/backup/backup*/
//allows you to backup and restore a map instance
steal('can/util', 'can/compute', 'can/map', 'can/util/object', function (can) {
	var flatProps = function (a, cur) {
		var obj = {};
		for (var prop in a) {
			if (typeof a[prop] !== 'object' || a[prop] === null || a[prop] instanceof Date) {
				obj[prop] = a[prop];
			} else {
				obj[prop] = cur.attr(prop);
			}
		}
		return obj;
	};

	var oldSetup = can.Map.prototype.setup;

	can.extend(can.Map.prototype, {
		setup: function() {
			this._backupStore = can.compute();
			return oldSetup.apply(this, arguments);
		},

		backup: function () {
			this._backupStore(this.attr());
			return this;
		},
		isDirty: function (checkAssociations) {
			return this._backupStore() && !can.Object.same(this.attr(), this._backupStore(), undefined, undefined, undefined, !! checkAssociations);
		},
		restore: function (restoreAssociations) {
			var props = restoreAssociations ? this._backupStore() : flatProps(this._backupStore(), this);
			if (this.isDirty(restoreAssociations)) {
				this.attr(props, true);
			}
			return this;
		}
	});
	return can.Map;
});


text:
#ifndef __BASE_DEBUG_HH__
#define __BASE_DEBUG_HH__

#include <map>
#include <string>
#include <vector>

namespace Debug {

void breakpoint();

class Flag
{
  protected:
    const char *_name;
    const char *_desc;

  public:
    Flag(const char *name, const char *desc);
    virtual ~Flag();

    std::string name() const { return _name; }
    std::string desc() const { return _desc; }
    virtual std::vector<Flag *> kids() { return std::vector<Flag*>(); }

    virtual void enable() = 0;
    virtual void disable() = 0;
    virtual void sync() {}
};

class SimpleFlag : public Flag
{
    static bool _active; // whether debug tracings are enabled
  protected:
    bool _tracing; // tracing is enabled and flag is on
    bool _status;  // flag status

  public:
    SimpleFlag(const char *name, const char *desc)
        : Flag(name, desc), _status(false)
    { }

    bool status() const { return _tracing; }
    operator bool() const { return _tracing; }
    bool operator!() const { return !_tracing; }

    void enable()  { _status = true;  sync(); }
    void disable() { _status = false; sync(); }

    void sync() { _tracing = _active && _status; }

    static void enableAll();
    static void disableAll();
};

class CompoundFlag : public Flag
{
  protected:
    std::vector<Flag *> _kids;

    void
    addFlag(Flag *f)
    {
        if (f != nullptr)
            _kids.push_back(f);
    }

  public:
    CompoundFlag(const char *name, const char *desc,
        Flag *f00 = nullptr, Flag *f01 = nullptr,
        Flag *f02 = nullptr, Flag *f03 = nullptr,
        Flag *f04 = nullptr, Flag *f05 = nullptr,
        Flag *f06 = nullptr, Flag *f07 = nullptr,
        Flag *f08 = nullptr, Flag *f09 = nullptr,
        Flag *f10 = nullptr, Flag *f11 = nullptr,
        Flag *f12 = nullptr, Flag *f13 = nullptr,
        Flag *f14 = nullptr, Flag *f15 = nullptr,
        Flag *f16 = nullptr, Flag *f17 = nullptr,
        Flag *f18 = nullptr, Flag *f19 = nullptr)
        : Flag(name, desc)
    {
        addFlag(f00); addFlag(f01); addFlag(f02); addFlag(f03); addFlag(f04);
        addFlag(f05); addFlag(f06); addFlag(f07); addFlag(f08); addFlag(f09);
        addFlag(f10); addFlag(f11); addFlag(f12); addFlag(f13); addFlag(f14);
        addFlag(f15); addFlag(f16); addFlag(f17); addFlag(f18); addFlag(f19);
    }

    std::vector<Flag *> kids() { return _kids; }

    void enable();
    void disable();
};

typedef std::map<std::string, Flag *> FlagsMap;
FlagsMap &allFlags();

Flag *findFlag(const std::string &name);

extern Flag *const All;

bool changeFlag(const char *s, bool value);

} // namespace Debug

void setDebugFlag(const char *string);

void clearDebugFlag(const char *string);

void dumpDebugFlags();

#endif // __BASE_DEBUG_HH__


text:
/*jshint indent:2, curly:true eqeqeq:true, immed:true, latedef:true,
newcap:true, noarg:true, regexp:true, undef:true, strict:true, trailing:true
white:true*/
/*global XT:true, XM:true, Backbone:true, _:true, console:true, setTimeout: true, enyo:true */

(function () {
  "use strict";

  /**
  */
  _.extend(XT.Session, {
    /** @scope XT.Session */

    privileges: {},
    relevantPrivileges: [], // those privileges that are needed for an active extension
    settings: {},
    schema: {},

    SETTINGS: 0x01,
    PRIVILEGES: 0x02,
    SCHEMA: 0x04,
    LOCALE: 0x08,
    EXTENSIONS: 0x10,
    ALL: 0x01 | 0x02 | 0x04 | 0x08 | 0x10,

    /**
      Loads session objects for settings, preferences and privileges into local
      memory. Types `XT.session.SETTINGS` or `XT.session.PRIVILEGES` can be passed
      as bitwise operators. If no arguments are passed the default is
      `XT.session.ALL` which will load all session objects.

      @param {Number} Types
      @param {Object} Options
    */
    loadSessionObjects: function (types, options) {
      var that = this,
        privilegesOptions,
        privileges,
        settingsOptions,
        settings,
        schemaOptions,
        localeOptions,
        extensionOptions,
        callback,
        schemaCount = 0,
        schemasReturned = 0,
        privilegeSetCount = 0,
        privilegeSetsReturned = 0,
        i;

      if (options && options.success && options.success instanceof Function) {
        callback = options.success;
      } else { callback = XT.K; }

      if (types === undefined) { types = this.ALL; }

      if (types & this.PRIVILEGES) {
        privilegesOptions = options ? _.clone(options) : {};

        // callback
        privilegesOptions.success = function (resp) {
          var privileges, i;

          if (that.getPrivileges().attributes) {
            // add incoming data to already loaded privilege
            privileges = that.getPrivileges();

          } else {
            // create privilege as a new model
            privileges = new Backbone.Model();
            privileges.get = function (attr) {
              // Sometimes the answer is already known...
              if (_.isBoolean(attr)) { return attr; }
              return Backbone.Model.prototype.get.call(this, attr);
            };
          }

          privilegeSetsReturned++;

          // Loop through the response and set a privilege for each found.
          for (i = 0; i < resp.length; i++) {
            privileges.set(resp[i].privilege, resp[i].isGranted);
          }

          // Attach the privileges to the session object.
          that.setPrivileges(privileges);

          if (privilegeSetsReturned === privilegeSetCount) {
            callback();
          }
        };

        if (!privilegesOptions.databaseTypes) {
          // by default we just run one query against the default database type
          privilegesOptions.databaseTypes = [undefined];
        }
        for (i = 0; i < privilegesOptions.databaseTypes.length; i++) {
          privilegesOptions.databaseType = privilegesOptions.databaseTypes[i];
          XT.dataSource.dispatch('XT.Session', 'privileges', null, privilegesOptions);
          privilegeSetCount++;
        }

      }

      if (types & this.SETTINGS) {
        settingsOptions = options ? _.clone(options) : {};

        // callback
        settingsOptions.success = function (resp) {
          settings = new Backbone.Model(resp);

          // Attach the settings to the session object
          that.setSettings(settings);

          callback();
        };

        XT.dataSource.dispatch('XT.Session', 'settings', null, settingsOptions);
      }

      if (types & this.SCHEMA) {
        schemaOptions = options ? _.clone(options) : {};

        // callback
        schemaOptions.success = function (resp) {
          var schema,
            prop,
            Klass,
            relations,
            i;

          if (that.getSchema().attributes) {
            // add incoming data to already loaded schema attributes
            schema = that.getSchema();
            schema.set(resp);

          } else {
            // create schema as a new model
            schema = new Backbone.Model(resp);
            that.setSchema(schema);
          }
          schemasReturned++;

          if (schemasReturned === schemaCount) {
            // Set relations
            for (prop in schema.attributes) {
              if (schema.attributes.hasOwnProperty(prop)) {
                Klass = XM.Model.getObjectByName('XM' + '.' + prop);
                if (Klass) {
                  relations = schema.attributes[prop].relations || [];
                  if (relations.length) {
                    Klass.prototype.relations = [];
                    for (i = 0; i < relations.length; i++) {
                      if (relations[i].type === "Backbone.HasOne") {
                        relations[i].type = Backbone.HasOne;
                      } else if (relations[i].type === "Backbone.HasMany") {
                        relations[i].type = Backbone.HasMany;
                      } else {
                        continue;
                      }
                      Klass.prototype.relations.push(relations[i]);
                    }
                  }

                  privileges = schema.attributes[prop].privileges;
                  if (privileges) {
                    Klass.prototype.privileges = privileges;
                  }
                }
              }
            }
            callback();
          }
        };

        // get schema for instance DB models
        XT.dataSource.dispatch('XT.Session', 'schema', 'xm', schemaOptions);
        schemaCount++;

        // get schema for global DB models
        schemaOptions.databaseType = 'global';
        XT.dataSource.dispatch('XT.Session', 'schema', 'xm', schemaOptions);
        schemaCount++;
      }

      if (types & this.LOCALE) {
        localeOptions = options ? _.clone(options) : {};

        // callback
        localeOptions.success = function (resp) {
          var locale = new Backbone.Model(resp);
          that.setLocale(locale);
          callback();
        };

        XT.dataSource.dispatch('XT.Session', 'locale', null, localeOptions);
      }

      if (types & this.EXTENSIONS) {
        extensionOptions = options ? _.clone(options) : {};

        // callback
        extensionOptions.error = function (resp) {
          XT.log("Error loading extensions");
        };
        extensionOptions.success = function (resp) {
          that.extensions = resp;
          callback();
        };

        XT.dataSource.getExtensionList(extensionOptions);
      }

      return true;
    },

    getLocale: function () {
      return this.locale;
    },

    getSchema: function () {
      return this.schema;
    },

    getSettings: function () {
      return this.settings;
    },

    getPrivileges: function () {
      return this.privileges;
    },

    setLocale: function (value) {
      this.locale = value;
      return this;
    },

    setSchema: function (value) {
      this.schema = value;
      return this;
    },

    setSettings: function (value) {
      this.settings = value;
      return this;
    },

    setPrivileges: function (value) {
      this.privileges = value;
      return this;
    },

    /**
      Each extension has a set of privileges that it cares about. The extension will load those
      privileges here into the session object with then name of the module that the privilege
      should be associated with. The module name will frequently be the extension name, but some
      extensions do not have their own modules.

      @param {String} module
      @param {Array} privArray
    */
    addRelevantPrivileges: function (module, privArray) {
      var privMap = _.map(privArray, function (priv) {return {module: module, privilege: priv}; });
      this.relevantPrivileges = _.union(this.relevantPrivileges, privMap);
    },

    // ..........................................................
    // CLASS CONSTANTS
    //

    DB_BOOLEAN: 'B',
    DB_STRING: 'S',
    DB_COMPOUND: 'C',
    DB_DATE: 'D',
    DB_NUMBER: 'N',
    DB_ARRAY: 'A',
    DB_BYTEA: 'U',
    DB_UNKNOWN: 'X'

  });

}());


text:
<?php
require_once('php/util/path.inc.php');
require_once('php/class/pagedata.class.php');
require_once('php/class/mixin.class.php');

require_once('php/layout/components.php');
//loading page
$request_url = get_request_url();
$parts = parse_url($request_url);
$request_uri = strtolower($parts['path']);
/* Normalize Path */
$path = remove_ext($request_uri);

if (empty($path) || $path == "/" || $path=="/index" || $path=="/start") {
    $path="/home"; //later: check short urls ;)
}
if (file_exists("pages".$path.".php"))
    loadPage("pages".$path.".php");
else {
    loadPage("pages/error.php");
    header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
}
echo HTML();
exit;
function loadPage($file)
{
    $page = PageData::GetInstance();
    include($file);
}
function HTML()
{
    $page = PageData::GetInstance();
    $html = "<!DOCTYPE html>";
    $html .= "<meta charset='UTF-8'>";
    $html .= "<meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=yes'/>";
    $html .= "<meta name='format-detection' content='telephone=no'/>";
    $html .= "<title>".$page->title."</title>";
    $html .= "<link rel='icon' href='favicon.png'>";
    $html .= "<link rel='apple-touch-icon' href='favicon.png'>";
    $html .= Styles() . Scripts();
    $html .= "";
    $html .= htmlBody();
    $html .= "";
    return $html;
}

function Styles()
{
    $html = "";
    $html .= "";
    $html .= "<link href='bundle/css/icons-fallback.css' rel='stylesheet'>";
    $html .= "";
    //$html .= "<link rel='stylesheet' type='text/css' href='bundle/css/print.css' media='print'>";
    return $html;
}

function Scripts()
{
    /*
    $html = "";
    */
    $html = "";
    return $html;
}

function htmlBody()
{
    $request_url = get_request_url();
    $parts = parse_url($request_url);
    $request_uri = strtolower($parts['path']);
    /* Normalize Path */
    $path = remove_ext($request_uri);

    $html = "";
    $html .= "";
    $html .= "
";
    $html .=    "
url: ".$request_url."
";
    $html .=    "uri: ".$request_uri."
";
    $html .=    "Path: ".$path."
";
    $html .= "
";
    $html .= "
" . SiteHeader() . "
";
    $html .= "
";
    $html .=    "
" . SiteArticle() . "
";
    $html .= "
";
    $html .= "" . SiteFooter() . "";

    $html .= "";

    return $html;
}

function SiteArticle()
{
    $page = PageData::GetInstance();
    return $page->html;
}
function tmpleval($matches) {
    $t="";
    $code = $matches[1];
    $t = eval("return (".$code.");");
    return $t;
}

function SiteHeader()
{
    $html = "";
    $html .= "";
    $html .= "";
    $html .= "
";
    $html .= "

";
    $html .= "
";
    $html .= "
";
    $html .= "
Oliver Jean Eifler
";
    $html .= "Programmierer Techniker Künstler";
    $html .= "
";
    $html .= "";
    $html .= "";
    $html .= "";
    $html .= "";
    $html .= "
";

    $html .= Components::printMainMenu();

    $html .= Components::printSocialMenu();

    $html .= "
";
    $html .= "";
    $html .= "";
    return $html;
}

function SiteFooter()
{
    $fromYear = 2015;
    $thisYear = (int)date('Y');
    $Year = $fromYear . (($fromYear != $thisYear) ? '-' . $thisYear : '');
    $html = "";
    $html .= "
";
    $html .= "
";
    $html .= "
";
    $html .= "Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License.";
    $html .= "
";
    $html .= "
 For internal use only
";
    $html .= "
" . $_SERVER['SERVER_NAME'] . " is created and maintained " . $Year . " with care* by  Oliver Jean Eifler
";
    $html .= "
*Not recommended for or tested with IE 9- or any other legacy browser
";
    $html .= "
";
    $html .= "
";

    return $html;
}

?>


text:
namespace blink {

// Ensures RefPtr values are compared by their values, not by pointers.
#define TEST_STYLE_REFCOUNTED_VALUE_NO_DIFF(type, fieldName)               \
  {                                                                        \
    scoped_refptr<SVGComputedStyle> svg1 = SVGComputedStyle::Create();     \
    scoped_refptr<SVGComputedStyle> svg2 = SVGComputedStyle::Create();     \
    scoped_refptr<type> value1 = base::MakeRefCounted<type>();             \
    scoped_refptr<type> value2 = base::MakeRefCounted<type>(value1->data); \
    svg1->Set##fieldName(value1);                                          \
    svg2->Set##fieldName(value2);                                          \
    EXPECT_FALSE(svg1->Diff(*svg2).HasDifference());                       \
  }

// This is not very useful for fields directly stored by values, because they
// can only be compared by values. This macro mainly ensures that we update the
// comparisons and tests when we change some field to RefPtr in the future.
#define TEST_STYLE_VALUE_NO_DIFF(type, fieldName)                      \
  {                                                                    \
    scoped_refptr<SVGComputedStyle> svg1 = SVGComputedStyle::Create(); \
    scoped_refptr<SVGComputedStyle> svg2 = SVGComputedStyle::Create(); \
    svg1->Set##fieldName(SVGComputedStyle::Initial##fieldName());      \
    svg2->Set##fieldName(SVGComputedStyle::Initial##fieldName());      \
    EXPECT_FALSE(svg1->Diff(*svg2).HasDifference());                   \
  }

TEST(SVGComputedStyleTest, StrokeStyleShouldCompareValue) {
  TEST_STYLE_VALUE_NO_DIFF(float, StrokeOpacity);
  TEST_STYLE_VALUE_NO_DIFF(float, StrokeMiterLimit);
  TEST_STYLE_VALUE_NO_DIFF(UnzoomedLength, StrokeWidth);
  TEST_STYLE_VALUE_NO_DIFF(Length, StrokeDashOffset);
  TEST_STYLE_REFCOUNTED_VALUE_NO_DIFF(SVGDashArray, StrokeDashArray);

  TEST_STYLE_VALUE_NO_DIFF(SVGPaint, StrokePaint);
  {
    scoped_refptr<SVGComputedStyle> svg1 = SVGComputedStyle::Create();
    scoped_refptr<SVGComputedStyle> svg2 = SVGComputedStyle::Create();
    svg1->SetInternalVisitedStrokePaint(SVGComputedStyle::InitialStrokePaint());
    svg2->SetInternalVisitedStrokePaint(SVGComputedStyle::InitialStrokePaint());
    EXPECT_FALSE(svg1->Diff(*svg2).HasDifference());
  }
}

TEST(SVGComputedStyleTest, MiscStyleShouldCompareValue) {
  TEST_STYLE_VALUE_NO_DIFF(Color, FloodColor);
  TEST_STYLE_VALUE_NO_DIFF(float, FloodOpacity);
  TEST_STYLE_VALUE_NO_DIFF(Color, LightingColor);
  TEST_STYLE_VALUE_NO_DIFF(Length, BaselineShiftValue);
}

}  // namespace blink


text:
import datetime

import bottle
import core.mtwsgi

class MTServer(bottle.ServerAdapter):

    def __init__(self,scheduler):
        app = bottle.Bottle()

        @app.route('/sigSchedule')
        def foo():
            scheduler.start_process();
            #asd.set_asd(1);
            return 'Verificação\n'
            #return str(datetime.datetime.now())

        @app.route('/sigSensor')
        def foo():
            #scheduler.start_process();
            #asd.set_asd(0);
            return 'Verificação\n'
            #return str(datetime.datetime.now())

        @app.route('/time')
        def time():
            #return 'hello, world 2!\n'
            return str(datetime.datetime.now())

        app.run(host='0.0.0.0', port=8081, thread_count=3)

    def run(self, handler):
        thread_count = self.options.pop('thread_count', None)
        server = mtwsgi.make_server(self.host, self.port, handler, thread_count, **self.options)
        server.serve_forever()


text:
package org.esmerilprogramming.overtown.http.converter;

import org.esmerilprogramming.overtown.http.OvertownRequest;
import org.junit.Before;
import org.junit.Test;

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class LongConverterTest {

  private LongConverter translator;

  @Before
  public void setUp() {
    translator = new LongConverter();
  }

  @Test
  public void givenALongParameterIdShouldTranslateTheValueToLongObject() {
    String paramName = "id";
    OvertownRequest request = mock(OvertownRequest.class);
    when(request.getParameter(paramName)).thenReturn("10");

    Long value = translator.translate(Long.class, paramName, request);

    assertSame("Translated value should be a long 10", 10l, value);
  }

  @Test
  public void givenALongParameterButWithANullValueInRequestShouldReturnNull() {
    String paramName = "id";
    OvertownRequest request = mock(OvertownRequest.class);
    when(request.getParameter(paramName)).thenReturn(null);

    Long value = translator.translate(Long.class, paramName, request);

    assertSame("Translated value should have returned null ", null, value);
  }

  @Test
  public void givenALongParameterAndARequestWithWrongParameterTypeShouldReturnNull() {
    String paramName = "id";
    OvertownRequest request = mock(OvertownRequest.class);
    when(request.getParameter(paramName)).thenReturn("NOT A NUMBER");

    Long value = translator.translate(Long.class, paramName, request);

    assertSame("Translated value should have returned null ", null, value);
  }

}


text:
<ion-side-menus enable-menu-with-back-views="false">

    <ion-side-menu-content>

        <ion-nav-bar class="bar-content">
            <ion-nav-back-button>
            </ion-nav-back-button>
            <ion-nav-buttons side="left">
                <button menu-toggle="left" class="button button-icon icon ion-navicon" aria-label="{{ 'mm.sidemenu.togglemenu' | translate }}"></button>
            </ion-nav-buttons>
        </ion-nav-bar>

        <ion-nav-view name="site">
        </ion-nav-view>

    </ion-side-menu-content>

    <ion-side-menu side="left" id="mm-side-menu-left">

{{siteinfo.fullname}}

<mm-format-text watch="true">{{siteinfo.sitename}}</mm-format-text>

        <ion-content class="has-side-menu-header mm-sidemenu-menu">

                        <ion-spinner></ion-spinner>

                             {{title | translate}}
                            {{badge}}
                            <ion-spinner ng-if="loading" class="icon"></ion-spinner>

                            {{item.label}}

                            {{item.label}}

                            Página Universidad

  Campus Virtual UCG

  Publicaciones Digitales UGC

  Correo Institucional UGC

  Intranet Docentes

                            Documentación Aplicación

                            {{ 'mm.sidemenu.appsettings' | translate}}

                            {{ logoutLabel | translate}}

        </ion-content>
    </ion-side-menu>

    <ion-side-menu side="right" id="mm-side-menu-right" is-enabled="rightSideMenu && rightSideMenu.show">
        <ng-include ng-if="rightSideMenu && rightSideMenu.show" src="rightSideMenu.template"></ng-include>
    </ion-side-menu>
</ion-side-menus>


text:
package com.tsaplin.util.jmx;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Denotes a managed property.
 */
@Target(value=ElementType.METHOD)
@Retention(value=RetentionPolicy.RUNTIME)
public @interface JMXProperty {
	String description() default "";
}


text:
/* eslint-env mocha */
import { setup, teardown } from "./helpers"

describe("Artwork page", () => {
  let metaphysics, browser

  before(async () => {
    ;({ metaphysics, browser } = await setup())
    metaphysics.post("/", (req, res) => {
      res.send(require("./fixtures/metaphysics/artwork"))
    })
  })

  after(teardown)

  it("renders an artwork title and partner name", async () => {
    const $ = await browser.page("/artwork/andy-warhol-skull")
    $.html().should.containEql("Skull")
    $.html().should.containEql("Gagosian")
  })
})


text:
package com.library.loading;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.library.R;
import com.library.utils.CommonUtils;

public class VaryViewHelperController {

    private IVaryViewHelper helper;

    public VaryViewHelperController(View view) {
        this(new VaryViewHelper(view));
    }

    public VaryViewHelperController(IVaryViewHelper helper) {
        super();
        this.helper = helper;
    }

    public void showNetworkError(View.OnClickListener onClickListener) {
        View layout = helper.inflate(R.layout.message);
        TextView textView = (TextView) layout.findViewById(R.id.message_info);
        textView.setText(helper.getContext().getResources().getString(R.string.common_no_network_msg));

        ImageView imageView = (ImageView) layout.findViewById(R.id.message_icon);
        imageView.setImageResource(R.drawable.ic_exception);

        if (null != onClickListener) {
            layout.setOnClickListener(onClickListener);
        }

        helper.showLayout(layout);
    }

    public void showError(String errorMsg, View.OnClickListener onClickListener) {
        View layout = helper.inflate(R.layout.message);
        TextView textView = (TextView) layout.findViewById(R.id.message_info);
        if (!CommonUtils.isEmpty(errorMsg)) {
            textView.setText(errorMsg);
        } else {
            textView.setText(helper.getContext().getResources().getString(R.string.common_error_msg));
        }

        ImageView imageView = (ImageView) layout.findViewById(R.id.message_icon);
        imageView.setImageResource(R.drawable.ic_error);

        if (null != onClickListener) {
            layout.setOnClickListener(onClickListener);
        }

        helper.showLayout(layout);
    }

    public void showEmpty(String emptyMsg, View.OnClickListener onClickListener) {
        View layout = helper.inflate(R.layout.message);
        TextView textView = (TextView) layout.findViewById(R.id.message_info);
        if (!CommonUtils.isEmpty(emptyMsg)) {
            textView.setText(emptyMsg);
        } else {
            textView.setText(helper.getContext().getResources().getString(R.string.common_empty_msg));
        }

        ImageView imageView = (ImageView) layout.findViewById(R.id.message_icon);
        imageView.setImageResource(R.drawable.ic_exception);

        if (null != onClickListener) {
            layout.setOnClickListener(onClickListener);
        }

        helper.showLayout(layout);
    }

    public void showLoading(String msg) {
        View layout = helper.inflate(R.layout.loading);
        if (!CommonUtils.isEmpty(msg)) {
            TextView textView = (TextView) layout.findViewById(R.id.loading_msg);
            textView.setText(msg);
        }
        helper.showLayout(layout);
    }

    public void restore() {
        helper.restoreView();
    }
}


text:
An ES6-ready boilerplate for building Backbone/Marionette apps using Gulp.

## Getting Started

#### 1. Install gulp globally:

```sh
$ npm install --global gulp
```

#### 2. Install project dependencies:

```sh
$ npm install
```

#### 3. Run gulp

Start a local dev environment:
```sh
$ gulp
```

Generate a production build:
```sh
$ gulp production
```

#### 4. Deployment

Download [settings.json](link to settings.json file goes here) and place in root directory.

The following command will deploy to [AWS S3](http://aws.amazon.com/s3/):
```sh
$ gulp deploy --[env]
```

This boilerplate assumes you've created a `settings.json` file in the project root. _This file should be (git)ignored as it contains sensitive information, i.e. AWS keys, etc._ When deployment is finished, a [Slack](http://slack.com) hook will be triggered in a channel of your choice. If you haven't heard of Slack, close Skype immediately and [read about it](http://slack.com).

##### Environment options

- `--dev` or `--development`
- `--qa`
- `--stage` or `--staging`
- `--prod` or `--production`

One of these arguments is required to successfully deploy files to S3, i.e `gulp deploy --staging`.

##### Sample `settings.json`:

```
{
    "default": {
        "aws": {
            "accessKeyId": "xxx",
            "secretAccessKey": "xxx",
            "basePath": "xxx",
            "bucket": "madeinhaus"
        },
        "slack": {
            "hook_url": "https://hooks.slack.com/services/xxx/xxx/xxx",
            "username": "Arnold Scavonegger",
            "message": "New build up on: "
        }
    }
}
```

Individual envs can have their own settings by adding a corresponding `'env': {...}` to the settings file,  only those settings which are different from default need to be set.


text:
package com.amazon.pay.request;

import com.amazon.pay.response.model.ProviderCredit;
import com.amazon.pay.types.CurrencyCode;
import java.io.Serializable;
import java.util.List;

/**
 * For more information documentation, see
 * https://pay.amazon.com/documentation/apireference/201751630#201751940
 */
public class AuthorizeOnBillingAgreementRequest extends DelegateRequest<AuthorizeOnBillingAgreementRequest> implements Serializable {

    @Override
    protected AuthorizeOnBillingAgreementRequest getThis() {
        return this;
    }

    //required parameters
    private final String amazonBillingAgreementId;
    private final String authorizationReferenceId;
    private final String authorizationAmount;
    private CurrencyCode authorizationCurrencyCode;

    //optional parameters
    private String sellerAuthorizationNote;
    private String transactionTimeout;
    private Boolean captureNow;
    private String softDescriptor;
    private String platformId;
    private String sellerNote;
    private Boolean inheritShippingAddress;
    private String sellerOrderId;
    private String storeName;
    private String supplementaryData;
    private String customInformation;
    private List<ProviderCredit> providerCredit;

    /**
     * Constructs request for AuthorizeOnBillingAgreement operation
     *
     * @param amazonBillingAgreementId
     *                       The billing agreement identifier. This value is
     *                       retrieved from the Amazon Button, AddressBook, or
     *                       Wallet widgets.
     *
     * @param authorizationReferenceId
     *                       The identifier for this authorization transaction that you specify.
     *                       This identifier must be unique for all your authorization transactions.
     * @param authorizationAmount
     *                       Represents the amount to be authorized
     *
     */
    public AuthorizeOnBillingAgreementRequest(final String amazonBillingAgreementId, final String authorizationReferenceId, final String authorizationAmount) {
        this.amazonBillingAgreementId = amazonBillingAgreementId;
        this.authorizationReferenceId = authorizationReferenceId;
        this.authorizationAmount = authorizationAmount;
    }

    /**
     * @param authorizationCurrencyCode three-digit currency code
     *
     * @return Returns a reference to this object so that methods
     *          can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setAuthorizationCurrencyCode(final CurrencyCode authorizationCurrencyCode){
        this.authorizationCurrencyCode = authorizationCurrencyCode;
        return this;

    }

    /**
     * @param sellerAuthorizationNote description for the transaction that is
     *                                displayed in emails to the buyer.
     *
     * @return Returns a reference to this object so that methods can be
     * chained together.
     */
    public AuthorizeOnBillingAgreementRequest setSellerAuthorizationNote(final String sellerAuthorizationNote){
        this.sellerAuthorizationNote = sellerAuthorizationNote;
        return this;
    }

    /**
     * @param TransactionTimeout The number of minutes after which the authorization
     *                           will automatically be closed and you will not be
     *                           able to capture funds against the authorization.
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setTransactionTimeout(final String TransactionTimeout) {
        this.transactionTimeout = TransactionTimeout;
        return this;

    }

    /**
     * @param CaptureNow Indicates whether to directly capture the amount specified by the
     *                   AuthorizationAmount request parameter against an order reference
     *                   (without needing to call Capture and without waiting until the order ships).
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setCaptureNow(final boolean CaptureNow) {
        this.captureNow = CaptureNow;
        return this;
    }

    /**
     * @param softDescriptor The description to be shown on the buyer's payment
     *                       instrument statement if CaptureNow is set to true.
     *
     * @return Returns a reference to this object so that methods can be chained
     *          together.
     */
    public AuthorizeOnBillingAgreementRequest setSoftDescriptor(final String softDescriptor) {
        this.softDescriptor = softDescriptor;
        return this;
    }

    /**
     * @param sellerNote Represents a description of the order that is displayed
     *                   in emails to the buyer.
     *
     * @return Returns a reference to this object so that methods can be chained
     *          together.
     */
    public AuthorizeOnBillingAgreementRequest setSellerNote(final String sellerNote) {
        this.sellerNote = sellerNote;
        return this;
    }

    /**
     * @param platformId Represents the SellerId of the Solution Provider that
     *                   developed the platform. This value should only be provided
     *                   by Solution Providers. It should not be provided by merchants
     *                   creating their own custom integration.
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setPlatformId(final String platformId) {
        this.platformId = platformId;
        return this;
    }

    /**
     *
     *
     * @param sellerOrderId The merchant-specified identifier of this order.
     *                      This is displayed to the buyer in their emails and
     *                      transaction history on the Amazon Pay website.
     *
     * @return Returns a reference to this object so that methods can be chained
     *          together.
     */
    public AuthorizeOnBillingAgreementRequest setSellerOrderId(final String sellerOrderId) {
        this.sellerOrderId = sellerOrderId;
        return this;
    }

    /**
     * @param storeName The identifier of the store from which the order was placed.
     * This overrides the default value in Seller Central under Settings and Account Settings.
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setStoreName(final String storeName) {
        this.storeName = storeName;
        return this;
    }

    /**
     * Set the trusted authorization supplementary data.
     * Use only as directed by Amazon Pay.
     *
     * @param supplementaryData Trusted authorization supplementary data (JSON string)
     *
     * @return Request object
     */
    public AuthorizeOnBillingAgreementRequest setSupplementaryData(final String supplementaryData) {
        this.supplementaryData = supplementaryData;
        return this;
    }

    /**
     * @param customInformation Sets any additional information that you want to include
     *                          with this order reference.
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setCustomInformation(final String customInformation) {
        this.customInformation = customInformation;
        return this;
    }

    /**
     * @param inheritShippingAddress Sets inheritShippingAddress parameter
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setInheritShippingAddress(final Boolean inheritShippingAddress) {
        this.inheritShippingAddress = inheritShippingAddress;
        return this;
    }

    /**
     * Sets inheritShippingAddress parameter
     * Deprecated since SDK 2.2.1
     *
     * @param inheritShippingAddress Sets inheritShippingAddress parameter
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    @Deprecated
    public AuthorizeOnBillingAgreementRequest setInheritShippingAddress(final String inheritShippingAddress) {
        return setInheritShippingAddress(
                Boolean.parseBoolean(inheritShippingAddress));
    }

    /**
     * The billing agreement identifier. This value is
     * retrieved from the Amazon Button, AddressBook, or
     * Wallet widgets.
     *
     * @return amazonBillingAgreementId
     */
    public String getAmazonBillingAgreementId() {
        return amazonBillingAgreementId;
    }

    /**
     *The identifier for this authorization transaction that you specify.
     *
     * @return Returns authorizationReferenceId from request
     */
    public String getAuthorizationReferenceId() {
        return authorizationReferenceId;
    }

    /**
     * Represents the amount to be authorized.
     *
     * @return Returns authorizationAmount from request
     */
    public String getAuthorizationAmount() {
        return authorizationAmount;
    }

    /**
     * Represents the three-digit currency code.
     *
     * @return Returns authorizationCurrencyCode from request
     */
    public CurrencyCode getAuthorizationCurrencyCode() {
        return authorizationCurrencyCode;
    }

    /**
     * Represents the Seller Authorization Note.
     *
     * @return Returns sellerAuthorizationNote from request
     */
    public String getSellerAuthorizationNote() {
        return sellerAuthorizationNote;
    }

    /**
     * The number of minutes after which the authorization will automatically be
     * closed and you will not be able to capture funds against the authorization.
     *
     * @return Returns transactionTimeout from request
     */
    public String getTransactionTimeout() {
        return transactionTimeout;
    }

    /**
     * Indicates whether to directly capture the amount specified by the
     * AuthorizationAmount request parameter against an order reference
     * (without needing to call Capture and without waiting until the order ships).
     *
     * @return Returns captureNow status from request
     */
    public Boolean getCaptureNow() {
        return captureNow;
    }

    /**
     * The description to be shown on the buyer's payment instrument statement
     * if CaptureNow is set to true.
     *
     * @return Returns softDescriptor status from request
     */
    public String getSoftDescriptor() {
        return softDescriptor;
    }

    /**
     * Represents the SellerId of the Solution Provider that developed the platform.
     * This value should only be provided by Solution Providers. It should
     * not be provided by merchants creating their own custom integration.
     *
     * @return Returns platformId status from request
     */
    public String getPlatformId() {
        return platformId;
    }

    /**
     * Represents a description of the order that is displayed in emails to the buyer.
     *
     * @return Returns sellerNote status from request
     */
    public String getSellerNote() {
        return sellerNote;
    }

    /**
     * Returns inheritShippingAddress parameter
     *
     * @return Returns inheritShippingAddress status from request
     */
    public Boolean getInheritShippingAddress() {
        return inheritShippingAddress;
    }

    /**
     * Returns Seller Order Id
     *
     * @return Returns sellerOrderId status from request
     */
    public String getSellerOrderId() {
        return sellerOrderId;
    }

    /**
     * The identifier of the store from which the order was placed.
     * This overrides the default value in Seller Central under Settings > Account Settings.
     *
     * @return Returns storeName status from request
     */
    public String getStoreName() {
        return storeName;
    }

    /**
     * Returns the trusted authorization supplementary data.
     *
     * @return supplementaryData as a JSON string
     */
    public String getSupplementaryData() {
        return supplementaryData;
    }

    /**
     * Sets any additional information that you want to include with this order reference.
     *
     * @return Returns customInformation status from request
     */
    public String getCustomInformation() {
        return customInformation;
    }

    /**
     * Applicable for third-party solution providers only.
     *
     * @return ProviderCredit associated with this operation
     */
    public List<ProviderCredit> getProviderCredit() {
        return providerCredit;
    }

    /**
     * Applicable for third-party solution providers only.
     *
     * @param providerCreditList associated with this operation
     *
     * @return Returns a reference to this object so that methods can be chained together.
     */
    public AuthorizeOnBillingAgreementRequest setProviderCredit(List<ProviderCredit> providerCreditList) {
        this.providerCredit = providerCreditList;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "AuthorizeOnBillingAgreementRequest{"
                + "amazonBillingAgreementId=" + amazonBillingAgreementId
                + ", authorizationReferenceId=" + authorizationReferenceId
                + ", authorizationAmount=" + authorizationAmount
                + ", authorizationCurrencyCode=" + authorizationCurrencyCode
                + ", sellerAuthorizationNote=" + sellerAuthorizationNote
                + ", transactionTimeout=" + transactionTimeout
                + ", captureNow=" + captureNow
                + ", softDescriptor=" + softDescriptor
                + ", platformId=" + platformId
                + ", sellerNote=" + sellerNote
                + ", inheritShippingAddress=" + inheritShippingAddress
                + ", sellerOrderId=" + sellerOrderId
                + ", storeName=" + storeName
                + ", supplementaryData=" + supplementaryData
                + ", customInformation=" + customInformation
                + ", providerCredit=" + providerCredit
                + ", mwsAuthToken=" + getMwsAuthToken() + '}';
    }

}


text:
Exams

				Posted on

				by

    	No Exams yet, why don't you create one?


text:
package com.trusolve.atlassian.bamboo.plugins.scriptengine;

public class ScriptEngineConstants
{
	public static final String SCRIPTENGINE_RUNONSERVER = "com_trusolve_scriptengine_runOnServer";
	public static final String SCRIPTENGINE_LOCATIONTYPES = "com_trusolve_scriptengine_locationTypes";
	public static final String SCRIPTENGINE_SCRIPTTYPES = "com_trusolve_scriptengine_scriptTypes";
	public static final String SCRIPTENGINE_SCRIPTBODY = "com_trusolve_scriptengine_scriptbody";
	public static final String SCRIPTENGINE_SCRIPTTYPE = "com_trusolve_scriptengine_scripttype";
	public static final String SCRIPTENGINE_SCRIPTLOCATION = "com_trusolve_scriptengine_scriptlocation";
	public static final String SCRIPTENGINE_SCRIPTFILE = "com_trusolve_scriptengine_scriptfile";
	public static final String PLUGIN_KEY = "com.trusolve.atlassian.bamboo.plugins.ScriptEngine:scriptEngineTask";
}


text:
<% if (testType === 'integration') { %>import { expect } from 'chai';
import { describe, it } from 'mocha';
import { setupRenderingTest } from 'ember-mocha';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

describe('<%= friendlyTestDescription %>', function() {
  setupRenderingTest();

  it('renders', async function() {
    // Set any properties with this.set('myProperty', 'value');
    // Handle any actions with this.set('myAction', function(val) { ... });

    await render(hbs`<%= selfCloseComponent(componentName) %>`);

    expect(this.element.textContent.trim()).to.equal('');

    // Template block usage:
    await render(hbs`
      <%= openComponent(componentName) %>
        template block text
      <%= closeComponent(componentName) %>
    `);

    expect(this.element.textContent.trim()).to.equal('template block text');
  });
});<% } else if (testType === 'unit') { %>import { expect } from 'chai';
import { describe, it } from 'mocha';
import { setupTest } from 'ember-mocha';

describe('<%= friendlyTestDescription %>', function() {
  setupTest();

  it('exists', function() {
    let component = this.owner.factoryFor('component:<%= componentPathName %>').create();
    expect(component).to.be.ok;
  });
});<% } %>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Evol.Common;
using Microsoft.EntityFrameworkCore;

namespace Evol.EntityFrameworkCore.MySql.Repository
{
    /// <summary>
    /// 基础仓储抽象类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TDbContext"></typeparam>
    public abstract class BaseEntityFrameworkCoreRepository<T, TDbContext> : BaseEntityFrameworkCoreRepository<T, Guid, TDbContext> where TDbContext : DbContext where T : class, IPrimaryKey, new()
    {
        protected BaseEntityFrameworkCoreRepository(IEfCoreDbContextProvider dbContextProvider) : base(dbContextProvider)
        {
        }
    }

    /// <summary>
    /// 基础仓储抽象类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TDbContext"></typeparam>
    public abstract class BaseEntityFrameworkCoreRepository<T, TKey, TDbContext> where TDbContext : DbContext where T : class, IPrimaryKey<TKey>, new()
    {
        private TDbContext _context;

        //[Dependency]
        public IEfCoreDbContextProvider DbContextProvider { get; set; }

        protected DbContext Context
        {
            get
            {
                return _context = _context ?? DbContextProvider.Get<TDbContext>();
            }
        }

        public DbSet<T> DbSet => Context.Set<T>();

        protected BaseEntityFrameworkCoreRepository(IEfCoreDbContextProvider dbContextProvider)
        {
            DbContextProvider = dbContextProvider;
        }

        public Task InsertAsync(T item)
        {
            DbSet.Add(item);
            return Task.FromResult(1);
        }

        public Task InsertRangeAsync(IEnumerable<T> items)
        {
            DbSet.AddRange(items);
            return Task.FromResult(1);
        }

        public Task DeleteAsync(T item)
        {
            if (item is ISoftDelete)
            {
                //如果软删除
                var softItem = (ISoftDelete)item;
                softItem.DeleteTime = DateTime.Now;
                softItem.IsDeleted = true;
                //由工作单元自动保存到数据库
            }
            else
                DbSet.Remove(item);
            return Task.FromResult(1);
        }

        public async Task DeleteAsync(TKey id)
        {
            //方式二: 先查找,在删除(EF官方推荐)。两次数据库操作
            var item = await DbSet.FindAsync(id);
            await DeleteAsync(item);
        }

        public void Save()
        {
            //wait for Context.SaveChange(),  item is being tracked object
        }

        public async Task<T> FindAsync(TKey id)
        {
            return await DbSet.FindAsync(id);
        }

        public async Task<T> FindAsync(Expression<Func<T, bool>> predicate)
        {
            return await DbSet.Where(predicate).FirstOrDefaultAsync();
        }

        public async Task<List<T>> SelectAsync(TKey[] ids)
        {
            return await DbSet.Where(e => ids.Contains(e.Id)).ToListAsync();
        }

        public async Task<List<T>> SelectAsync(Expression<Func<T, bool>> predicate)
        {
            return await DbSet.Where(predicate).ToListAsync();
        }

        public async Task<List<T>> SelectAsync(Func<IQueryable<T>, IQueryable<T>> condition)
        {
            var query = Query();
            query = condition.Invoke(query);
            var items = await query.ToListAsync();
            return items;
        }

        public IQueryable<T> Query()
        {
            return DbSet.AsQueryable();
        }

        public void Update(T item)
        {
            //wait for Context.SaveChange(),  item is being tracked object
        }

        public Task UpdateAsync(T item)
        {
            return Task.FromResult(1);
            //wait for Context.SaveChange(),  item is being tracked object
        }

        public async Task<bool> AnyAsync(Expression<Func<T, bool>> predicate)
        {
            return await DbSet.AnyAsync(predicate);
        }

        public async Task<IPaged<T>> PagedAsync(int pageIndex, int pageSize)
        {
            var total = await DbSet.CountAsync();
            var list = await DbSet.OrderBy(e => e.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            var paged = new PagedList<T>(list, total, pageIndex, pageSize);
            return paged;
        }

        public async Task<IPaged<T>> PagedAsync(Expression<Func<T, bool>> predicate, int pageIndex, int pageSize)
        {
            var total = await DbSet.CountAsync(predicate);
            var skip = (pageIndex - 1) * pageSize;
            var query = DbSet.Where(predicate);
            if (skip > 0)
                query = query.Skip(skip);
            var list = await query.Take(pageSize).OrderBy(e => e.Id).ToListAsync();
            var paged = new PagedList<T>(list, total, pageIndex, pageSize);
            return paged;
        }

        public async Task<IPaged<T>> PagedAsync(Func<IQueryable<T>, IQueryable<T>> condition, int pageIndex, int pageSize)
        {
            var query = Query();
            query = condition.Invoke(query);

            var total = await query.CountAsync();
            var skip = (pageIndex - 1) * pageSize;
            if (skip > 0)
                query = query.Skip(skip);
            var list = await query.Take(pageSize).OrderBy(e => e.Id).ToListAsync();
            var paged = new PagedList<T>(list, total, pageIndex, pageSize);
            return paged;
        }

    }
}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.util.bin.format.elf;

public class ElfProgramHeaderConstants {

	private ElfProgramHeaderConstants() {
	}

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

	// Segment Types

	/**Unused/Undefined segment*/
	public static final int PT_NULL = 0;
	/**Loadable segment*/
	public static final int PT_LOAD = 1;
	/**Dynamic linking information (.dynamic section)*/
	public static final int PT_DYNAMIC = 2;
	/**Interpreter path name*/
	public static final int PT_INTERP = 3;
	/**Auxiliary information location*/
	public static final int PT_NOTE = 4;
	/**Unused*/
	public static final int PT_SHLIB = 5;
	/**Program header table*/
	public static final int PT_PHDR = 6;
	/**Thread-local storage segment*/
	public static final int PT_TLS = 7;

	/**GCC .eh_frame_hdr segment*/
	public static final int PT_GNU_EH_FRAME = 0x6474e550;
	/**Indicates stack executability*/
	public static final int PT_GNU_STACK = 0x6474e551;
	/**Specifies segments which may be read-only after relocation*/
	public static final int PT_GNU_RELRO = 0x6474e552;
	/**Sun Specific segment*/
	public static final int PT_SUNWBSS = 0x6ffffffa;
	/**Stack segment*/
	public static final int PT_SUNWSTACK = 0x6ffffffb;

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

	/**Segment is executable*/
	public static final int PF_X                    =      1 << 0;
	/**Segment is writable*/
	public static final int PF_W                    =      1 << 1;
	/**Segment is readable*/
	public static final int PF_R                    =      1 << 2;
	/**OS-specific*/
	public static final int PF_MASKOS               =  0x0ff00000;
	/**Processor-specific*/
	public static final int PF_MASKPROC             =  0xf0000000;

}


text:
package org.apache.jena.sparql.util;

import org.apache.jena.graph.Node ;
import org.apache.jena.sparql.core.Var ;
import org.apache.jena.sparql.engine.ExecutionContext ;
import org.apache.jena.sparql.engine.QueryIterator ;
import org.apache.jena.sparql.engine.binding.Binding ;
import org.apache.jena.sparql.engine.iterator.QueryIterNullIterator ;
import org.apache.jena.sparql.engine.iterator.QueryIterSingleton ;

public class IterLib
{
    public static QueryIterator noResults(ExecutionContext execCxt)
    {
        return QueryIterNullIterator.create(execCxt) ;
    }

    public static QueryIterator oneResult(Binding parent, Var var, Node value, ExecutionContext execCxt)
    {
        return QueryIterSingleton.create(parent, var, value, execCxt) ;
    }

    public static QueryIterator result(Binding binding, ExecutionContext execCxt)
    {
        return QueryIterSingleton.create(binding, execCxt) ;
    }
}


text:
/**
 * apl.ElevationsChart.Pane
 *
 * Elevations Profile Chart
 *  - dijit to show profile chart of elevation values returned from Elevations SOE
 *  - works in conjunction with a map and measure dijits
 *  - works with selected features in Feature Layer or map service with popups enabled
 *  - mouseover/touchmove events to dynamically show elevation on chart and location on map
 *
 * John Grayson
 * Applications Prototype Lab, ESRI
 * Jan 2012
 *
 */
dojo.provide("apl.ElevationsChart.Pane");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojo.colors");
dojo.require("dojo.fx.easing");
dojo.require("dojox.charting.themes.ThreeD");
dojo.require("apl.ElevationsChart.ElevationsSOE");

dojo.require("dojo.i18n");
dojo.requireLocalization("apl.ElevationsChart", "template");

/**
 *  apl.ElevationsChart.Pane
 */
dojo.declare("apl.ElevationsChart.Pane", [dijit._Widget, dijit._Templated], {

  /** @static */ templateString : dojo.cache("apl.ElevationsChart", "templates/Pane.html"),
  /** @static */ widgetsInTemplate : true,
  /** @static */ baseClass : "aplElevationsChart",

  /**
   * @constructor
   *
   * CREATE AND INSTANCE OF apl.ElevationsChart.Pane
   *
   * @param {Object} options - map, measure, defaultDistanceUnits
   */
  constructor: function(options, srcNodeRef) {
    // MIXIN OPTIONS //
    dojo.mixin(this, options);

    // SOURCE NODE //
    if (srcNodeRef) {
      this.srcNodeRef = srcNodeRef;
    }

    // INSTANCE VARIABLES //
    this.profileSourceIsSelectedFeature = false;
    this.profileChart = null;
    this.elevationData = [];
    this.sampleDist = 1.0;
    this.profilePolyline = null;
    this.chartMoveGroup = null;
    this.chartLocationGraphic = null;

    // USE ELEVATIONS SOE ON SAMPLESERVER //
    this._elevationsSOE = new apl.ElevationsChart.ElevationsSOE();

    /*
     // USE YOUR OWN ELEVATIONS SOE //
     var mySOEService = {
     URL: "http://sampleserver4.arcgisonline.com/ArcGIS/rest/services/Elevation/ESRI_Elevation_World/MapServer/exts/ElevationsSOE/ElevationLayers",
     index: 1,
     version: 10.0,
     label: "Global: SRTM, GTopo30 & GEBCO @ 92m"
     };
     this._elevationsSOE = new apl.ElevationsChart.ElevationsSOE(mySOEService);
     */
  },

  /**
   * postMixInProperties
   */
  postMixInProperties: function() {
    this.inherited(arguments);

    // GET i18n MESSAGES //
    this.messages = dojo.i18n.getLocalization("apl.ElevationsChart", "template", this.lang);

    // MIXIN  i18n MESSAGES //
    dojo.mixin(this, this.messages);
  },

  /**
   * postCreate
   */
  postCreate : function() {
    this.inherited(arguments);

    // MAKE SURE SOURCE NODE WAS PASSED IN //
    if (!this.srcNodeRef) {
      throw this.messages.errors.MissingConstructorParameters;
    }

    // PROVIDE PROPER CONTEXT TO METHODS //
    this.setProfileWindowVisible = dojo.hitch(this, this.setProfileWindowVisible);
    this.setChartVisible = dojo.hitch(this, this.setChartVisible);
    this.getElevationProfile = dojo.hitch(this, this.getElevationProfile);
    this.getElevationLabel = dojo.hitch(this, this.getElevationLabel);
    this.getDistanceLabel = dojo.hitch(this, this.getDistanceLabel);
    this.getDisplayLabel = dojo.hitch(this, this.getDisplayLabel);
    this.getDisplayValue = dojo.hitch(this, this.getDisplayValue);
    this.getDisplayUnits = dojo.hitch(this, this.getDisplayUnits);
    this.getFilledArray = dojo.hitch(this, this.getFilledArray);
    this.adjustYTickStep = dojo.hitch(this, this.adjustYTickStep);
    this.makeProfileChart = dojo.hitch(this, this.makeProfileChart);
    this.onChartLocationMove = dojo.hitch(this, this.onChartLocationMove);
    this.displayChartLocation = dojo.hitch(this, this.displayChartLocation);

    // DISPLAY CAUTION MESSAGE //
    this.cautionMsgNode.innerHTML = this._elevationsSOE.getCautionMessage();
  },

  /**
   * init
   *
   * @param {Object} options
   *    @param {esri.Map} map
   *    @param {esri.dijit.Measurement} measure
   *    @param {String} defaultDistanceUnits (Miles || Meters)
   *    @param {Boolean} showElevationDifference
   */
  init: function(options) {

    // ADJUST INITIAL UI SIZE //
    this.containerNode.resize();

    // MIXIN OPTIONS //
    dojo.mixin(this, options);

    // MAP //
    if (!this.map) {
      throw this.messages.errors.MissingInitParameter;
    }

    // MEASURE //
    if (!this.measure) {
      throw this.messages.errors.MissingInitParameter;
    }

    // DEFAULT DISTANCE UNITS //
    if (!this.defaultDistanceUnits) {
      throw this.messages.errors.MissingInitParameter;
    }

    // POPUP WINDOW EVENTS //
    dojo.connect(this.map.infoWindow, 'onSelectionChange', this, this.mapFeatureSelectionChange);
    dojo.connect(this.map.infoWindow, 'onHide', this, this.mapInfoWindowHide);

    // MEASURE WIDGET EVENTS //
    dojo.connect(this.measure, 'setTool', this, this.onMeasureSetTool);
    dojo.connect(this.measure, 'onMeasureEnd', this, this.onMeasureEnd);
    dojo.connect(this.measure, '_switchUnit', this, this.onMeasureUnitChange);

    // CREATE INITIAL CHART //
    this.makeProfileChart();

    // SET INITIAL STATE OF PROFILE WINDOW //
    this.setProfileWindowVisible(false);
  },

  /**
   * setProfileWindowVisible
   *
   * SETS THE PROFILE PANE AS THE SELECTED PANE OF THE STACK CONTAINER
   *
   * @param {Boolean} visible
   */
  setProfileWindowVisible: function (visible) {
    if (visible) {
      this.setChartVisible(false, dojo.hitch(this, function() {
        this.containerNode.selectChild(this.profileParentPane);

      }));
    } else {
      this.setChartVisible(false, dojo.hitch(this, function() {
        this.containerNode.selectChild(this.profileInfo);
        this.displayChartLocation(-1);
      }));
    }
  },

  /**
   * setChartVisible
   *
   * FADE IN/OUT THE PROFILE CHART
   *
   * @param {Boolean} visible
   * @param {Function} onEnd
   */
  setChartVisible:  function(visible, onEnd) {
    var animateOptions = {
      node: this.profilePane,
      duration: 1000,
      onEnd: onEnd
    };
    if (visible) {
      dojo.fadeIn(animateOptions).play();
    } else {
      dojo.fadeOut(animateOptions).play();
    }
  },

  /**
   * mapFeatureSelectionChange
   *
   * CALLED WHEN THE SELECTED FEATURE OF THE POPUP WINDOW CHANGES
   */
  mapFeatureSelectionChange: function() {
    // REMOVE PREVIOUS MEASURE LOCATIONS RESULTS //
    dojo.query(".measureLocationResult", map.infoWindow.domNode).orphan();
    // SET ACTIVE TOOL NAME //
    var selectedFeature = this.map.infoWindow.getSelectedFeature();
    if (selectedFeature) {
      var activeToolName = 'unknown';
      switch (selectedFeature.geometry.type) {
        case 'polygon':
          activeToolName = 'area';
          break;
        case 'polyline':
          activeToolName = 'distance';
          break;
        case 'point':
          activeToolName = 'location';
          break;
      }
      // CALCULATE ELEVATIONS //
      this.calculateElevations(activeToolName, selectedFeature.geometry, true);
    }
  },

  /**
   * mapInfoWindowHide
   *
   * CALLED WHEN THE POPUP WINDOW IS CLOSED
   */
  mapInfoWindowHide: function() {
    this.setProfileWindowVisible(false);
  },

  /**
   * onMeasureSetTool
   *
   * CALLED WHEN ONE OF THE MEASURE WIDGET TOOLS IS SELECTED
   */
  onMeasureSetTool: function() {
    this.setProfileWindowVisible(false);
  },

  /**
   * onMeasureEnd
   *
   * CALLED WHEN THE MEASURE TOOLS IS FINISHED MEASURING
   *
   * @param {String} activeToolName
   * @param {esri.geometry.Geometry} geometry
   */
  onMeasureEnd: function(activeToolName, geometry) {
    // CALCULATE ELEVATIONS //
    this.calculateElevations(activeToolName, geometry, false);
  },

  /**
   * calculateElevations
   *
   * CALCULATE PROFILE ELEVATIONS FOR GEOMETRIES
   *
   * @param {String} activeToolName
   * @param {esri.geometry.Geometry} geometry
   * @param {Boolean} sourceIsSelectedFeature
   */
  calculateElevations: function(activeToolName, geometry, sourceIsSelectedFeature) {

    this.profileSourceIsSelectedFeature = sourceIsSelectedFeature;

    switch (activeToolName) {
      case 'area':
        this.setProfileWindowVisible(true);
        var distancePolyline = new esri.geometry.Polyline(geometry.spatialReference);
        distancePolyline.addPath(geometry.rings[0]);
        this.getElevationProfile(distancePolyline);
        break;

      case 'distance':
        this.setProfileWindowVisible(true);
        this.getElevationProfile(geometry);
        break;

      case 'location':
        this.setProfileWindowVisible(false);
        var geoPoint = esri.geometry.webMercatorToGeographic(geometry);
        this.map.setMapCursor('wait');
        this._elevationsSOE.GetElevationAtLonLat(geoPoint, dojo.hitch(this, function(response) {
          this.map.setMapCursor('default');
          var elevStr = dojo.number.format(response.elevation, { places: 2 });
          var parentNode = this.measure.resultValue.containerNode;
          if (sourceIsSelectedFeature) {
            parentNode = dojo.query(".actionList", map.infoWindow.domNode)[0];
          }
          dojo.create('div', {
            'class':'measureLocationResult',
            style:  sourceIsSelectedFeature ? 'float:right': '',
            innerHTML : dojo.replace(this.messages.locationResultTemplate, [elevStr])
          }, parentNode, 'last');
        }), dojo.hitch(this, function(error) {
          this.map.setMapCursor('default');
          console.warn(error.message);
        }));
        break;

      default:
        this.setProfileWindowVisible(false);
        break;
    }
  },

  /**
   * onMeasureUnitChange
   *
   * CALLED WHEN THE UNIT OF MEASURE IS CHANGED IN THE MEASURE WIDGET
   *
   */
  onMeasureUnitChange: function() {
    if (this.elevationData) {
      this.makeProfileChart();
    }
  },

  /**
   * getElevationProfile
   *
   * CALLS THE ELEVATIONS SOE WITH THE PASSED IN GEOMETRY.
   * SETS THE ELEVATION DATA, PROFILE GEOMETRY AND SAMPLE DISTANCE.
   *
   * @param {esri.geometry.Polyline} geometry
   */
  getElevationProfile: function(geometry) {

    if (!geometry) {
      return;
    }

    // CLEAR PREVIOUS RESULTS //
    this.elevationData = null;
    this.sampleDist = null;

    this.map.setMapCursor('wait');
    this._elevationsSOE.GetElevations(geometry, dojo.hitch(this, function(response) {
      this.map.setMapCursor('default');

      // ELEVATION DATA //
      if (this._elevationsSOE.getVersion() >= 10.1) {
        // STARTING WITH VERSION 10.1 THE ELEVATIONS SOE RETURNS THE   //
        // ELEVATION VALUES AS THE Z COMPONENT OF THE POINT GEOMETRIES //
        this.elevationData = [];
        dojo.forEach(response.geometries[0].paths, function(path) {
          dojo.forEach(path, function(coords) {
            this.elevationData.push(coords[2]);
          }, this);
        }, this);
      } else {
        this.elevationData = response.elevations[0];
      }

      // PROFILE GRAPHIC //
      this.profilePolyline = new esri.geometry.Polyline(this.map.spatialReference);
      // CREATE A SINGLE PATH FROM ALL PATHS                //
      // ISSUE: WHEN MULTIPLE PATHS ARE RETURNED WE HAVE    //
      //        DUPLICATE POINTS AT END AND START OF PATHS, //
      //        NOT A HUGE ISSUE AS ELEVATIONS VALUES MATCH //
      var profilePath = [];
      dojo.forEach(response.geometries[0].paths, function(path) {
        profilePath = profilePath.concat(path);
      }, this);
      this.profilePolyline.addPath(profilePath);

      // SAMPLE DISTANCE //
      var profileLengthMeters = esri.geometry.geodesicLengths([esri.geometry.webMercatorToGeographic(this.profilePolyline)], esri.Units.METERS)[0];
      this.sampleDist = (profileLengthMeters / this.elevationData.length);

      // CREATE PROFILE CHART //
      this.makeProfileChart();
      this.setChartVisible(true);

    }), dojo.hitch(this, function(error) {
      this.map.setMapCursor('default');
      console.warn(error.message);
    }));
  },

  /**
   * getElevationLabel
   *
   * Y-AXIS LABEL FUNCTION
   *
   * @param {String} label
   * @param {Number} val
   */
  getElevationLabel: function(label, val) {
    var displayUnits = this.getDisplayUnits(true);
    return this.getDisplayLabel(val, displayUnits);
  },

  /**
   * getDistanceLabel
   *
   * X-AXIS LABEL FUNCTION
   *
   * @param {String} label
   * @param {Number} val
   */
  getDistanceLabel: function(label, val) {
    var displayUnits = this.getDisplayUnits(false);
    return this.getDisplayLabel((val * this.sampleDist), displayUnits);
  },

  /**
   * getDisplayLabel
   *
   * GET DISPLAY LABEL GIVEN A VALUE IN METERS AND THE DISPLAY UNITS
   * CONVERT FROM METERS TO MILES THEN FROM MILES TO DISPLAY UNITS
   *
   * @param {Number} valueMeters
   * @param {String} displayUnits
   */
  getDisplayLabel: function(valueMeters, displayUnits) {
    var displayDistance = this.getDisplayValue(valueMeters, displayUnits);
    return dojo.number.format(displayDistance, { 'places': 1 });
  },

  /**
   * getDisplayValue
   *
   * GET DISPLAY VALUE GIVEN A VALUE IN METERS AND THE DISPLAY UNITS
   * CONVERT FROM METERS TO MILES THEN FROM MILES TO DISPLAY UNITS
   *
   * @param {Number} valueMeters
   * @param {String} displayUnits
   */
  getDisplayValue: function(valueMeters, displayUnits) {
    if (displayUnits === this.measure.units.esriMeters) {
      return valueMeters;
    } else {
      var distanceMiles = (valueMeters / this.measure.unitDictionary[this.measure.units.esriMeters]);
      return (distanceMiles * this.measure.unitDictionary[displayUnits]);
    }
  },

  /**
   * getDisplayUnits
   *
   * GET DISPLAY UNITS FOR AXIS LABELS
   * IF USING A SELECTED FEATURE WE'LL USE THE DEFAULT DISTANCE UNITS BASED ON THE MAP SCALEBAR (OR MILES IF NO SCALEBAR)
   * IF GETTING DISPLAY UNITS FOR ELEVATION WE'LL SWITCH TO FEET OR METERS
   *
   * @param {Boolean} isElevation
   */
  getDisplayUnits: function(isElevation) {
    var displayUnits = this.profileSourceIsSelectedFeature ? this.defaultDistanceUnits: this.measure.unit.label;
    if (isElevation) {
      switch (displayUnits) {
        case this.measure.units.esriMiles:
          displayUnits = this.measure.units.esriFeet;
          break;
        case this.measure.units.esriYards:
          displayUnits = this.measure.units.esriFeet;
          break;
        case this.measure.units.esriKilometers:
          displayUnits = this.measure.units.esriMeters;
          break;
      }
    }
    return displayUnits;
  },

  /**
   * getFilledArray
   *
   * GET A FILLED ARRAY OF PASSED IN SIZE WITH PASSED IN VALUES
   * ZEROS USED IF NO VALUE PASSED IN
   *
   * @param {Number} size
   * @param {Object} value
   */
  getFilledArray: function(size, value) {
    var dataArray = new Array(size);
    for (var dataIdx = 0; dataIdx < size; ++dataIdx) {
      dataArray[dataIdx] = value || 0;
    }
    return dataArray;
  },

  /**
   * adjustYTickStep
   *
   * ADJUST Y-AXIS TICK STEP
   *
   * @param {Number} yTickStep
   */
  adjustYTickStep: function(yTickStep) {
    var newYTickStep = yTickStep;
    var limits = [1000,100,10,1];
    dojo.some(limits, function(limit) {
      newYTickStep = ((yTickStep + limit) - ((yTickStep + limit) % limit));
      return (yTickStep > limit);
    });
    return newYTickStep;
  },

  /**
   * makeProfileChart
   *
   * CREATE A PROFILE CHART FROM TEH ELEVATION DATA AND SAMPLE DISTANCE
   *
   * @param {Node} profileChartNode
   */
  makeProfileChart: function(profileChartNode) {

    if (!this.elevationData) {
      return;
    }

    if (profileChartNode) {
      this.profileChart = null;
    }

    // ADJUSTED MIN/MAX ELEVATIONS //
    var yMinSource = this.getArrayMin(this.elevationData);
    var yMaxSource = this.getArrayMax(this.elevationData);
    var yRange = (yMaxSource - yMinSource);
    var yMin = yMinSource - (yRange * 0.05);
    var yMax = yMaxSource + (yRange * 0.05);
    var yTickStep = this.adjustYTickStep((yRange / 5.0));

    // FILLED ZERO ARRAY //
    var waterData = this.getFilledArray(this.elevationData.length);

    if (this.profileChart) {

      this.chartMoveGroup = null;

      // UPDATE CHART //
      this.profileChart.getAxis("y").opt.min = yMin;
      this.profileChart.getAxis("y").opt.max = yMax;
      this.profileChart.getAxis("y").opt.majorTickStep = yTickStep;
      this.profileChart.getAxis("y").opt.title = dojo.replace(this.messages.chart.elevationTitleTemplate, [this.getDisplayUnits(true)]);
      this.profileChart.getAxis("x").opt.title = dojo.replace(this.messages.chart.distanceTitleTemplate, [this.getDisplayUnits(false)]);
      this.profileChart.dirty = true;
      this.profileChart.updateSeries("Water", waterData);
      this.profileChart.updateSeries("Elevation Profile", this.elevationData);
      this.profileChart.render();

    } else {

      // CHART NODE //
      var chartNode = profileChartNode || this.profilePane;

      // ANIMATION OPTIONS //
      var chartAnimationOpts = {
        duration: 1500,
        easing: dojo.fx.easing.linear
      };

      // CREATE CHART //
      this.profileChart = new dojox.charting.Chart2D(chartNode, {
        title: this.messages.chart.title,
        titlePos: "top",
        titleGap: 5,
        titleFontColor: 'darkgreen',
        animationType: chartAnimationOpts.easing
      });

      // SET THEME //
      this.profileChart.setTheme(dojox.charting.themes.ThreeD);
      // OVERRIDE DEFAULTS //
      this.profileChart.fill = 'white';
      this.profileChart.theme.axis.stroke.width = 2;
      this.profileChart.theme.axis.majorTick = {
        color: dojo.Color.named.white.concat(0.5),
        width: 1.0
      };
      this.profileChart.theme.plotarea.fill = {
        type: "linear",
        space: "plot",
        x1: 50, y1: 100, x2: 50, y2: 0,
        colors: [
          { offset: 0.0, color: dojo.Color.named.powderblue },
          { offset: 1.0, color: dojo.Color.named.steelblue }
        ]
      };

      // Y AXIS //
      this.profileChart.addAxis("y", {
        min: yMin,
        max: yMax,
        majorTickStep: yTickStep,
        fontColor: 'black',
        font: "normal normal bold 7pt Tahoma",
        vertical: true,
        fixLower: "major",
        fixUpper: "minor",
        natural: true,
        fixed: true,
        includeZero: false,
        majorTicks: true,
        majorTick: { color: 'black', length: 4 },
        labelFunc: this.getElevationLabel,
        minorTicks: false,
        title: dojo.replace(this.messages.chart.elevationTitleTemplate, [this.getDisplayUnits(true)]),
        titleGap: 30,
        titleFont: "normal normal bold 11pt Tahoma",
        titleFontColor: 'green',
        titleOrientation: 'axis'
      });

      // X AXIS //
      this.profileChart.addAxis("x", {
        fontColor: 'black',
        font: "normal normal bold 7pt Tahoma",
        fixLower: "none",
        fixUpper: "none",
        includeZero: false,
        natural: false,
        fixed: true,
        majorTicks: true,
        majorTick: { color: 'black', length: 4 },
        labelFunc: this.getDistanceLabel,
        minorTicks: true,
        minorTick: { color: 'black', length: 4 },
        title: dojo.replace(this.messages.chart.distanceTitleTemplate, [this.getDisplayUnits(false)]),
        titleGap: 5,
        titleFont: "normal normal bold 11pt Tahoma",
        titleFontColor: 'green',
        titleOrientation: 'away'
      });

      // GRID //
      this.profileChart.addPlot("Grid", {
        type: "Grid",
        hMajorLines: true,
        hMinorLines: false,
        vMajorLines: false,
        vMinorLines: false
      });

      // PROFIlE PLOT //
      this.profileChart.addPlot("default", {
        type: "Areas",
        tension: "X",
        animate: chartAnimationOpts
      });

      // WATER PLOT //
      this.profileChart.addPlot("water", {
        type: "Areas",
        animate: chartAnimationOpts
      });

      // WATER DATA //
      this.profileChart.addSeries("Water", waterData, {
        plot:"water",
        stroke: { color: dojo.Color.named.white, width: 2.0 },
        fill: {
          type: "linear",
          space: "plot",
          x1: 50, y1: 0, x2: 50, y2: 100,
          colors: [
            { offset: 0.0, color: dojo.Color.named.lightblue.concat(0.5) },
            { offset: 1.0, color: dojo.Color.named.blue.concat(0.5) }
          ]
        }
      });

      // PROFILE DATA //
      this.profileChart.addSeries("Elevation Profile", this.elevationData, {
        stroke: { color: dojo.Color.named.tan, width: 1.5 },
        fill: {
          type: "linear",
          space: "plot",
          x1: 50, y1: 0, x2: 50, y2: 100,
          colors: [
            { offset: 0.0, color: dojo.Color.named.saddlebrown },
            { offset: 1.0, color: dojo.Color.named.peru }
          ]
        }
      });

      // DISPLAY CHART LOCATION ON MAP //
      if (!esri.isTouchEnabled) {
        // MOUSE MOVE EVENT //
        this.profileChart.surface.connect("onmousemove", this, function(evt) {
          dojo.stopEvent(evt);
          this.onChartLocationMove(evt.clientX, evt.clientY);
        });
      } else {
        // TOUCH MOVE EVENT //
        this.profileChart.surface.connect("ontouchmove", this, function(evt) {
          dojo.stopEvent(evt);
          if (evt.touches && (evt.touches.length > 0)) {
            this.onChartLocationMove(evt.touches[0].clientX, evt.touches[0].clientY);
          }
        });
        // TOUCH END EVENT //
        this.profileChart.surface.connect("ontouchend", this, function(evt) {
          dojo.stopEvent(evt);
          this.onChartLocationMove(0, 0);
        });
      }

      // RENDER CHART //
      this.profileChart.render();
    }

    // ELEVATION INFO //
    var elevDisplayUnits = this.getDisplayUnits(true);

    var elevMinStr = this.getDisplayLabel(yMinSource, elevDisplayUnits);
    var elevMaxStr = this.getDisplayLabel(yMaxSource, elevDisplayUnits);
    var elevFirst = this.elevationData[0];
    var elevLast = this.elevationData[this.elevationData.length - 1];
    var elevStartStr = this.getDisplayLabel(elevFirst, elevDisplayUnits);
    var elevEndStr = this.getDisplayLabel(elevLast, elevDisplayUnits);
    var startElev = this.getDisplayValue(elevFirst, elevDisplayUnits);
    var endElev = this.getDisplayValue(elevLast, elevDisplayUnits);
    var gainloss = (endElev - startElev);
    var gainlossStr = dojo.number.format(gainloss, {places:1});

    var elevInfo = {
      min: elevMinStr,
      max: elevMaxStr,
      start: elevStartStr,
      end: elevEndStr,
      gainloss: gainlossStr
    };

    // ELEVATION INFO TEXT //
    var elevMinMaxMsg = dojo.replace(this.messages.chart.gainLossTemplate, elevInfo);
    var chartCoords = this.profileChart.getCoords();
    this.profileChart.surface.createText({
      x: chartCoords.x,
      y: (chartCoords.h - 5.0),
      text: elevMinMaxMsg,
      align: "start"
    }).setFont({family:"Tahoma", style:"bold", size:"9pt"}).setFill('darkred');

    // ELEVATION SOURCE TEXT //
    this.profileChart.surface.createText({
      x: (chartCoords.w - 5.0),
      y: (chartCoords.h - 5.0),
      text: this._elevationsSOE.getDataSourceInfo(),
      align: "end"
    }).setFont({family:"Tahoma", style:"bold", size:"9pt"}).setFill('silver');

  },

  /**
   * onChartLocationMove
   *
   * DISPLAY INTERACTIVE VERTICAL LINE AND ELEVATION TEXT AT MOUSE/TOUCH LOCATION
   *
   * @param {Number} clientX
   * @param {Number} clientY
   */
  onChartLocationMove: function(clientX, clientY) {

    if (this.elevationData) {
      var chartCoords = dojo.coords(this.profileChart.node, true);
      var chartOffsets = this.profileChart.offsets;

      // PLOT COORDINATES //
      var plotCoords = {
        x: (clientX - chartCoords.x),
        y: (clientY - chartCoords.y),
        l: (chartCoords.x + chartOffsets.l),
        r: (chartCoords.x + chartCoords.w - chartOffsets.r),
        t: (chartCoords.y + chartOffsets.t),
        b: (chartCoords.y + chartCoords.h - chartOffsets.b)
      };

      if (!this.chartMoveGroup) {
        // CREATE GROUP OF GRAPHICS TO MOVE //
        this.chartMoveGroup = this.profileChart.surface.createGroup();
      } else {
        // REMOVE PREVIOUS //
        this.chartMoveGroup.clear()
      }

      // IS CURSOR OVER CHART PLOT AREA //
      if (((clientX > plotCoords.l) && (clientX < plotCoords.r)) &&
          ((clientY > plotCoords.t) && (clientY < plotCoords.b))) {

        // X POINT INDEX //
        var plotPercentAlongX = ((clientX - plotCoords.l) / (chartCoords.w - plotCoords.l));
        var pointIndex = parseInt((this.elevationData.length - 1) * plotPercentAlongX);
        // DISPLAY CHART LOCATION ON MAP //
        this.displayChartLocation(pointIndex);

        // Y COORDINATE //
        var elev = this.elevationData[pointIndex];
        var elevDisplayUnits = this.getDisplayUnits(true);
        var elevStr = this.getDisplayLabel(elev, elevDisplayUnits);
        var yAxisBounds = this.profileChart.getAxis('y').scaler.bounds;
        var plotPercentAlongY = ((yAxisBounds.upper - elev) / (yAxisBounds.upper - yAxisBounds.lower));
        var chartElevationLineY = (plotCoords.t + ((plotCoords.b - plotCoords.t) * plotPercentAlongY)) - chartCoords.y;
        var chartElevationMiddle = (plotCoords.t + ((plotCoords.b - plotCoords.t) * 0.5)) - chartCoords.y;

        // ELEVATION CHANGE //
        var currentElev = this.getDisplayValue(this.elevationData[pointIndex], elevDisplayUnits);
        var startElev = this.getDisplayValue(this.elevationData[0], elevDisplayUnits);
        var gainloss = (currentElev - startElev);
        var gainlossStr = dojo.number.format(gainloss, {places:1});
        var plotPercentAlongYChange = ((yAxisBounds.upper - this.elevationData[0]) / (yAxisBounds.upper - yAxisBounds.lower));
        var chartElevationLineYChange = (plotCoords.t + ((plotCoords.b - plotCoords.t) * plotPercentAlongYChange)) - chartCoords.y;

        // VERTICAL LINE //
        this.chartMoveGroup.createLine({
          x1: plotCoords.x,
          y1: plotCoords.t - chartCoords.y,
          x2: plotCoords.x,
          y2: plotCoords.b - chartCoords.y
        }).setStroke({color:"black",width:1.5});

        if (!isNaN(chartElevationLineY)) {

          // ELEVATION TEXT //
          var leftOfCenter = (plotCoords.x < (plotCoords.l + ((plotCoords.r - plotCoords.l) * 0.5)));
          var bottomOfMiddle = (chartElevationLineY > chartElevationMiddle);
          var textOffset = 10.0;
          var textX = (leftOfCenter ? (plotCoords.x + textOffset): (plotCoords.x - textOffset));
          var textY = (bottomOfMiddle ? (chartElevationLineY - textOffset): (chartElevationLineY + (textOffset * 3)));

          this.chartMoveGroup.createText({
            x: textX,
            y: textY,
            text: elevStr,
            align: leftOfCenter ? "start": "end"
          }).setFont({family:"Tahoma", weight:"bold", size:"22pt"}).setFill("black").setStroke({color:"white",width:1.5});

          // ELEVATION CHANGE //
          if (this.showElevationDifference && (gainloss != 0.0)) {
            var changeTextX = (!leftOfCenter ? (plotCoords.x + 5.0): (plotCoords.x - 5.0));
            var gainlosslabelcolor = ((gainloss > 0.0) ? "green": "red");

            this.chartMoveGroup.createLine({
              x1: plotCoords.x,
              y1: chartElevationLineYChange,
              x2: plotCoords.x,
              y2: chartElevationLineY
            }).setStroke({color:gainlosslabelcolor,width:3.0});

            var textLength = gainlossStr.length - ((gainloss > 1000) ? 2: 1);
            var textWidth = (textLength * 10.0) + 5.0;
            this.chartMoveGroup.createRect({
              x: leftOfCenter ? (changeTextX - textWidth - 5.0): changeTextX + 5.0,
              y: chartElevationLineYChange - 10.0,
              width: textWidth,
              height: 20.0,
              r: 5.0
            }).setFill(dojo.Color.named.white.concat(0.75)).setStroke({color:gainlosslabelcolor,width:1});

            this.chartMoveGroup.createText({
              x: leftOfCenter ? changeTextX - 10.0: changeTextX + 10.0,
              y: chartElevationLineYChange + 5.0,
              text: gainlossStr,
              align: leftOfCenter ? "end": "start"
            }).setFont({family:"Tahoma", weight:"normal", size:"10pt"}).setFill(gainlosslabelcolor);
          }

          // CIRCLE //
          this.chartMoveGroup.createCircle({
            cx: plotCoords.x,
            cy: chartElevationLineY,
            r: 6
          }).setStroke({color:"white",width:2.0});

        }
      } else {
        this.displayChartLocation(-1);
      }
    }
  },

  /**
   * displayChartLocation
   *
   * DISPLAY CHART LOCATION AS RED X GRAPHIC ON THE MAP
   *
   * @param {Number} pointIndex
   */
  displayChartLocation: function(pointIndex) {

    if (!this.elevationData) {
      return;
    }

    if (!this.chartLocationGraphic) {
      var red = new dojo.Color(dojo.Color.named.red);
      var outline = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, red, 3);
      var chartLocationSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_X, 13, outline, red);
      this.chartLocationGraphic = new esri.Graphic(null, chartLocationSymbol);
      this.map.graphics.add(this.chartLocationGraphic);
    }

    if ((pointIndex >= 0) && (pointIndex < this.elevationData.length)) {
      this.chartLocationGraphic.setGeometry(this.profilePolyline.getPoint(0, pointIndex))
    } else {
      this.chartLocationGraphic.setGeometry(null);
    }

  },

  /**
   * RETURN THE MAXIMUM VALUE IN THE ARRAY
   *
   * @param {Array} array
   */
  getArrayMax: function(array) {
    return Math.max.apply(Math, array);
  },

  /**
   * RETURN THE MINIMUM VALUE IN THE ARRAY
   *
   * @param {Array} array
   */
  getArrayMin: function(array) {
    return Math.min.apply(Math, array);
  }
});