text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
"""

import logging
import re
import time
from collections import namedtuple

logger = logging.getLogger(__name__)

# create a named tuple to return both the concrete URI and SSL flag
AlertUri = namedtuple('AlertUri', 'uri is_ssl_enabled')

class BaseAlert(object):
  CONFIG_KEY_REGEXP = re.compile('{{(\S+?)}}')
  # will force a kinit even if klist says there are valid tickets (4 hour default)
  _DEFAULT_KINIT_TIMEOUT = 14400000

  RESULT_OK = "OK"
  RESULT_WARNING = "WARNING"
  RESULT_CRITICAL = "CRITICAL"
  RESULT_UNKNOWN = "UNKNOWN"
  RESULT_SKIPPED = "SKIPPED"

  HA_NAMESERVICE_PARAM = "{{ha-nameservice}}"
  HA_ALIAS_PARAM = "{{alias}}"

  def __init__(self, alert_meta, alert_source_meta, config):
    self.alert_meta = alert_meta
    self.alert_source_meta = alert_source_meta
    self.cluster_name = ''
    self.cluster_id = None
    self.host_name = ''
    self.public_host_name = ''
    self.config = config

  def interval(self):
    """ gets the defined interval this check should run """
    if not self.alert_meta.has_key('interval'):
      return 1
    else:
      interval = self.alert_meta['interval']
      return 1 if interval < 1 else interval

  def get_definition_id(self):
    """
    gets the id of definition (a number)
    """
    return self.alert_meta['definitionId']

  def is_enabled(self):
    """
    gets whether the definition is enabled
    """
    return self.alert_meta['enabled']

  def get_name(self):
    """
    gets the unique name of the alert definition
    """
    return self.alert_meta['name']

  def get_uuid(self):
    """
    gets the unique has of the alert definition
    """
    return self.alert_meta['uuid']

  def set_helpers(self, collector, cluster_configuration_cache, configuration_builder):
    """
    sets helper objects for alerts without having to use them in a constructor
    """
    self.collector = collector
    self.cluster_configuration_cache = cluster_configuration_cache
    self.configuration_builder = configuration_builder

  def set_cluster(self, cluster_name, cluster_id, host_name, public_host_name=None):
    """ sets cluster information for the alert """
    self.cluster_name = cluster_name
    self.cluster_id = str(cluster_id)
    self.host_name = host_name
    self.public_host_name = host_name
    if public_host_name:
      self.public_host_name = public_host_name

  def _get_alert_meta_value_safely(self, meta_key):
    """
    safe way to get a value when outputting result json.  will not throw an exception
    """
    if self.alert_meta.has_key(meta_key):
      return self.alert_meta[meta_key]
    else:
      return None

  def collect(self):
    """ method used for collection.  defers to _collect() """

    res = (BaseAlert.RESULT_UNKNOWN, [])
    res_base_text = None

    try:
      res = self._collect()
      result_state = res[0]
      reporting_state = result_state.lower()

      # it's possible that the alert definition doesn't have reporting; safely
      # check for it and fallback to default text if it doesn't exist
      if ('reporting' in self.alert_source_meta) and \
          (reporting_state in self.alert_source_meta['reporting']) and \
          ('text' in self.alert_source_meta['reporting'][reporting_state]):
          res_base_text = self.alert_source_meta['reporting'][reporting_state]['text']

      if res_base_text is None:
        res_base_text = self._get_reporting_text(result_state)

    except Exception as exception:
      message = "[Alert][{0}] Unable to execute alert. {1}".format(
        self.get_name(), str(exception))

      # print the exception if in DEBUG, otherwise just log the warning
      # if logger.isEnabledFor(logging.DEBUG):
      logger.exception(message)
      # else:
      #  logger.warning(message)

      res = (BaseAlert.RESULT_UNKNOWN, [str(exception)])
      res_base_text = "{0}"

    if logger.isEnabledFor(logging.DEBUG):
      logger.debug("[Alert][{0}] result = {1}".format(self.get_name(), str(res)))

    data = {}
    data['name'] = self._get_alert_meta_value_safely('name')
    data['clusterId'] = self.cluster_id
    data['timestamp'] = long(time.time() * 1000)
    data['definitionId'] = self.get_definition_id()

    try:
      data['state'] = res[0]

      # * is the splat operator, which flattens a collection into positional arguments
      # flatten the array and then try formatting it
      try:
        data['text'] = res_base_text.format(*res[1])
      except ValueError, value_error:
        logger.warn("[Alert][{0}] - {1}".format(self.get_name(), str(value_error)))

        # if there is a ValueError, it's probably because the text doesn't match the type of
        # positional arguemtns (ie {0:d} with a float)
        res_base_text = res_base_text.replace("d}", "s}")
        data_as_strings = map(str, res[1])
        data['text'] = res_base_text.format(*data_as_strings)

      if logger.isEnabledFor(logging.DEBUG):
        logger.debug("[Alert][{0}] text = {1}".format(self.get_name(), data['text']))
    except Exception, exception:
      logger.exception("[Alert][{0}] - The alert's data is not properly formatted".format(self.get_name()))

      # if there's a problem with getting the data returned from collect() then mark this
      # alert as UNKNOWN
      data['state'] = self.RESULT_UNKNOWN
      data['text'] = "There is a problem with the alert definition: {0}".format(str(exception))
    finally:
      # put the alert into the collector so it can be collected on the next run
      self.collector.put(self.cluster_name, data)

  def _get_configuration_value(self, configurations, key):
    """
    Gets the value of the specified configuration key from the cache. The key
    should be of the form {{foo-bar/baz}}. If the key given is not a lookup key
    and is instead a constant, such as "foo" or "5", then the constant is
    returned.

    If the key contains more than 1 parameter to lookup, then each match is
    looked up and replaced.

    If the value does not exist in the configs, then return None to indicate
    that this key could not be found.

    This should turn {{hdfs-site/value}}/whatever/{{hdfs-site/value2}}
    into
    value/whatever/value2

    :return:  the resolved value or None if any of the placeholder parameters
              does not exist in the configs
    """
    if key is None:
      return None

    # parse {{foo-bar/baz}}/whatever/{{foobar-site/blah}}
    # into
    # ['foo-bar/baz', 'foobar-site/blah']
    placeholder_keys = BaseAlert.CONFIG_KEY_REGEXP.findall(key)

    # if none found, then return the original
    if placeholder_keys is None or len(placeholder_keys) == 0:
      return key

    # for every match, get its configuration value and replace it in the key
    resolved_key = key
    for placeholder_key in placeholder_keys:
      value = self.get_configuration_value(configurations, placeholder_key)

      # if any of the placeholder keys is missing from the configuration, then
      # return None as per the contract of this function
      if value is None:
        return None

      # it's possible that a dictionary was request (ie {{hdfs-site}} instead
      # of {{hdfs-site/foo}} - in which case, we should just return the
      # dictionary as is
      if isinstance(value, dict):
        return value

      # {{foo-bar/baz}}/whatever -> http://server/whatever
      resolved_key = resolved_key.replace("{{%s}}" % placeholder_key, value)

    return resolved_key

  def get_configuration_value(self, configurations, key):
    """
    Gets a value from the cluster configuration map for the given cluster and
    key. The key is expected to be of the form 'foo-bar/baz' or
    'foo-bar/bar-baz/foobarbaz' where every / denotes a new mapping
    :param key:  a lookup key, like 'foo-bar/baz'
    :return: the value, or None if not found
    """
    if not key.startswith("/"):
      key = "/configurations/" + key

    try:
      curr_dict = configurations
      subdicts = filter(None, key.split('/'))

      for layer_key in subdicts:
        curr_dict = curr_dict[layer_key]

      return curr_dict
    except KeyError:
      logger.debug("Cache miss for configuration property {0}".format(key))
      return None

  def _lookup_uri_property_keys(self, uri_structure):
    """
    Loads the configuration lookup keys that the URI structure needs. This
    will return a named tuple that contains the keys needed to lookup
    parameterized URI values from the cached configuration.
    The URI structure looks something like:

    "uri":{
      "http": foo,
      "https": bar,
      ...
    }
    """

    if uri_structure is None:
      return None

    acceptable_codes_key = None
    http_key = None
    https_key = None
    https_property_key = None
    https_property_value_key = None
    default_port = None
    kerberos_keytab = None
    kerberos_principal = None
    ha_nameservice = None
    ha_alias_key = None
    ha_http_pattern = None
    ha_https_pattern = None

    if 'acceptable_codes' in uri_structure:
      acceptable_codes_key = uri_structure['acceptable_codes']

    if 'http' in uri_structure:
      http_key = uri_structure['http']

    if 'https' in uri_structure:
      https_key = uri_structure['https']

    if 'https_property' in uri_structure:
      https_property_key = uri_structure['https_property']

    if 'https_property_value' in uri_structure:
      https_property_value_key = uri_structure['https_property_value']

    if 'default_port' in uri_structure:
      default_port = uri_structure['default_port']

    if 'kerberos_keytab' in uri_structure:
      kerberos_keytab = uri_structure['kerberos_keytab']

    if 'kerberos_principal' in uri_structure:
      kerberos_principal = uri_structure['kerberos_principal']

    if 'high_availability' in uri_structure:
      ha = uri_structure['high_availability']

      if 'nameservice' in ha:
        ha_nameservice = ha['nameservice']

      if 'alias_key' in ha:
        ha_alias_key = ha['alias_key']

      if 'http_pattern' in ha:
        ha_http_pattern = ha['http_pattern']

      if 'https_pattern' in ha:
        ha_https_pattern = ha['https_pattern']

    AlertUriLookupKeys = namedtuple('AlertUriLookupKeys',
      'acceptable_codes http https https_property https_property_value default_port '
      'kerberos_keytab kerberos_principal '
      'ha_nameservice ha_alias_key ha_http_pattern ha_https_pattern')

    alert_uri_lookup_keys = AlertUriLookupKeys(
      acceptable_codes=acceptable_codes_key,
      http=http_key,
      https=https_key,
      https_property=https_property_key,
      https_property_value=https_property_value_key, default_port=default_port,
      kerberos_keytab=kerberos_keytab, kerberos_principal=kerberos_principal,
      ha_nameservice=ha_nameservice, ha_alias_key=ha_alias_key,
      ha_http_pattern=ha_http_pattern, ha_https_pattern=ha_https_pattern
    )

    return alert_uri_lookup_keys

  def _get_uri_from_structure(self, alert_uri_lookup_keys):
    """
    Gets the URI to use by examining the URI structure from the definition.
    This will return a named tuple that has the uri and the SSL flag. The
    URI structure looks something like:

    "uri":{
      "http": foo,
      "https": bar,
      ...
    }
    """

    if alert_uri_lookup_keys is None:
      return None

    http_uri = None
    https_uri = None

    configurations = self.configuration_builder.get_configuration(self.cluster_id, None, None)

    # first thing is first; if there are HA keys then try to dynamically build
    # the property which is used to get the actual value of the uri
    # (ie dfs.namenode.http-address.c1ha.nn2)
    if alert_uri_lookup_keys.ha_nameservice is not None or alert_uri_lookup_keys.ha_alias_key is not None:
      alert_uri = self._get_uri_from_ha_structure(alert_uri_lookup_keys, configurations)
      if alert_uri is not None:
        return alert_uri

    # attempt to parse and parameterize the various URIs; properties that
    # do not exist int he lookup map are returned as None
    if alert_uri_lookup_keys.http is not None:
      http_uri = self._get_configuration_value(configurations, alert_uri_lookup_keys.http)

    if alert_uri_lookup_keys.https is not None:
      https_uri = self._get_configuration_value(configurations, alert_uri_lookup_keys.https)

    # without a URI, there's no way to create the structure we need - return
    # the default port if specified, otherwise throw an exception
    if http_uri is None and https_uri is None:
      if alert_uri_lookup_keys.default_port is not None:
        alert_uri = AlertUri(uri=alert_uri_lookup_keys.default_port, is_ssl_enabled=False)
        return alert_uri
      else:
        raise Exception("Could not determine result. Either the http or https URI must be specified.")

    # start out assuming plaintext
    uri = http_uri
    is_ssl_enabled = False

    if https_uri is not None:
      # https without http implies SSL, otherwise look it up based on the properties
      if http_uri is None:
        is_ssl_enabled = True
        uri = https_uri
      elif self._check_uri_ssl_property(alert_uri_lookup_keys, configurations):
        is_ssl_enabled = True
        uri = https_uri

    alert_uri = AlertUri(uri=uri, is_ssl_enabled=is_ssl_enabled)
    return alert_uri

  def _get_uri_from_ha_structure(self, alert_uri_lookup_keys, configurations):
    """
    Attempts to parse the HA URI structure in order to build a dynamic key
    that represents the correct host URI to check.
    :param alert_uri_lookup_keys:
    :return: the AlertUri named tuple if there is a valid HA URL, otherwise None
    """
    if alert_uri_lookup_keys is None:
      return None

    logger.debug("[Alert][{0}] HA URI structure detected in definition, attempting to lookup dynamic HA properties".format(self.get_name()))

    ha_nameservice = self._get_configuration_value(configurations, alert_uri_lookup_keys.ha_nameservice)
    ha_alias_key = alert_uri_lookup_keys.ha_alias_key
    ha_http_pattern = alert_uri_lookup_keys.ha_http_pattern
    ha_https_pattern = alert_uri_lookup_keys.ha_https_pattern
    ha_nameservice_aliases = {}

    # if HA alias key is not defined then it's not HA environment
    if ha_alias_key is None:
      return None

    if alert_uri_lookup_keys.ha_nameservice is not None:
      # if there is a HA nameservice defined, but it can not be evaluated then it's not HA environment
      if ha_nameservice is None:
        return None

      # convert dfs.ha.namenodes.{{ha-nameservice}} into dfs.ha.namenodes.c1ha
      ha_nameservices = filter(None, ha_nameservice.split(','))

      for nameservice in ha_nameservices:
        ha_alias_key_nameservice = ha_alias_key.replace(self.HA_NAMESERVICE_PARAM, nameservice)
        ha_nameservice_alias = self._get_configuration_value(configurations, ha_alias_key_nameservice)

        if ha_nameservice_alias:
          ha_nameservice_aliases[nameservice] = ha_nameservice_alias

      if not ha_nameservice_aliases:
        logger.warning("[Alert][{0}] HA nameservice value is present but there are no aliases for {1}".format(
          self.get_name(), ha_alias_key))
        return None
    else:
      ha_nameservice_aliases = {None: self._get_configuration_value(configurations, ha_alias_key)}

      # if HA nameservice is not defined then the fact that the HA alias_key could not be evaluated shows that it's not HA environment
      if ha_nameservice_aliases[None] is None:
        return None

    # determine which pattern to use (http or https)
    ha_pattern = ha_http_pattern
    is_ssl_enabled = self._check_uri_ssl_property(alert_uri_lookup_keys, configurations)
    if is_ssl_enabled:
      ha_pattern = ha_https_pattern

    # no pattern found
    if ha_pattern is None:
      logger.warning("[Alert][{0}] There is no matching http(s) pattern for the HA URI".format(
        self.get_name()))

      return None

    if self.HA_NAMESERVICE_PARAM in ha_pattern and ha_nameservice is None:
      logger.warning("[Alert][{0}] An HA URI pattern of {1} was detected, but there is no nameservice key".format(
        self.get_name(), ha_pattern))

      return None

    # for each alias, grab it and check to see if this host matches
    for nameservice, aliases in ha_nameservice_aliases.iteritems():
      for alias in aliases.split(','):

        # convert dfs.namenode.http-address.{{ha-nameservice}}.{{alias}} into
        # dfs.namenode.http-address.c1ha.{{alias}}
        ha_pattern_current = ha_pattern
        if nameservice is not None:
          ha_pattern_current = ha_pattern_current.replace(self.HA_NAMESERVICE_PARAM, nameservice)
        # convert dfs.namenode.http-address.c1ha.{{alias}} into
        # dfs.namenode.http-address.c1ha.nn1
        key = ha_pattern_current.replace(self.HA_ALIAS_PARAM, alias.strip())

        # get the host for dfs.namenode.http-address.c1ha.nn1 and see if it's
        # this host
        value = self._get_configuration_value(configurations, key)

        if value is not None and (self.host_name.lower() in value.lower() or self.public_host_name.lower() in value.lower()):
          return AlertUri(uri=value, is_ssl_enabled=is_ssl_enabled)

    return None

  def _check_uri_ssl_property(self, alert_uri_lookup_keys, configurations):
    """
    Gets whether the SSL property and value on the URI indicate an SSL
    connection.
    :param alert_uri_lookup_keys:
    :return:  True if the SSL check property and value are defined and match
              otherwise False
    """
    https_property = None
    https_property_value = None

    if alert_uri_lookup_keys.https_property is not None:
      https_property = self._get_configuration_value(configurations, alert_uri_lookup_keys.https_property)

    if alert_uri_lookup_keys.https_property_value is not None:
      https_property_value = self._get_configuration_value(configurations, alert_uri_lookup_keys.https_property_value)

    if https_property is None:
      return False

    return https_property == https_property_value

  def _collect(self):
    """
    Low level function to collect alert data.  The result is a tuple as:
    res[0] = the result code
    res[1] = the list of arguments supplied to the reporting text for the result code
    """
    # TODO: After implementation uncomment /src/test/python/ambari_agent/TestMetricAlert.py:194
    # and /src/test/python/ambari_agent/TestScriptAlert.py:52
    raise NotImplementedError

  def _get_reporting_text(self, state):
    '''
    Gets the default reporting text to use when the alert definition does not
    contain any. Subclasses can override this to return specific text.
    :param state: the state of the alert in uppercase (such as OK, WARNING, etc)
    :return:  the parameterized text
    '''
    return '{0}'


text:
using MonoTouch.UIKit;
using MonoTouch.CoreMotion;
using MonoTouch.Foundation;
using MonoTouch.CoreAnimation;
using System;
using System.Drawing;
using MonoTouch.CoreGraphics;

namespace PRAMotionZoom
{
	/// <summary>
	/// PRA zoom view.
	/// </summary>
	public sealed class PRAZoomView : UIScrollView
	{
		#region private Declaration

		internal UIImageView _panningImageView;
		internal PRAZoomScrollBarView _scrollBarView;

		//Motion Manager
		CMMotionManager _motionManager;
		bool motionBasedPanEnabled=true;

		//Display link
		internal CADisplayLink _displayLink;

		//Const
		float MovementSmoothing = 0.3f;
		float AnimationDuration = 0.3f;
		float RotationMultiplier = 5.0f;

		#endregion

		/// <summary>
		/// Initializes a new instance of the <see cref="PRAMotionZoom.PRAZoomView"/> class.
		/// </summary>
		/// <param name="rect">Rect. view frame</param>
		/// <param name="imageToZoom">Image to zoom.</param>
		public PRAZoomView (RectangleF rect, UIImage imageToZoom):base(rect)
		{
			_motionManager = _motionManager ?? new CMMotionManager ();
			AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			BackgroundColor = UIColor.Black;
			Delegate = new PRAScrollViewDelegate (this);
			ScrollEnabled = false;
			AlwaysBounceVertical = false;
			MaximumZoomScale = 2.0f;
			PinchGestureRecognizer.AddTarget (this, new MonoTouch.ObjCRuntime.Selector ("pinchGestureRecognized"));

			//2
			_panningImageView =new UIImageView (rect);
			_panningImageView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			_panningImageView.BackgroundColor = UIColor.Black;
			_panningImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
			AddSubview (_panningImageView);

			//bar view
			_scrollBarView = new PRAZoomScrollBarView (rect, new UIEdgeInsets (0, 10, 50, 10));
			_scrollBarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			_scrollBarView.UserInteractionEnabled = false;
			//AddSubview (_scrollBarView);

			//3
			_displayLink = UIScreen.MainScreen.CreateDisplayLink (DisplayLinkUpdate);//new CADisplayLink ();
			_displayLink.AddToRunLoop (NSRunLoop.Main, NSRunLoopMode.Common);

			var tapGestureRecognizer = new UITapGestureRecognizer (ToggleMotionBasedPan);//this.View, new ObjCRuntime.Selector ("toggleMotionBasedPan:"));
			AddGestureRecognizer (tapGestureRecognizer);

			ConfigureWithImage (imageToZoom);
		}

		internal void ConfigureWithImage(UIImage image)
		{
			_panningImageView.Image = image;
			UpdateScrollViewZoomToMaximumForImage (image);
		}
		void calculateRotationBasedOnDeviceMotionRotationRate(CMDeviceMotion motion) {
			if (motionBasedPanEnabled) {
				float xRotationRate = (float)motion.RotationRate.x;
				float yRotationRate = (float)motion.RotationRate.y;
				float zRotationRate = (float)motion.RotationRate.z;

				if (Math.Abs (yRotationRate) > (Math.Abs (xRotationRate) + Math.Abs (zRotationRate))) {
					var invertedYRotationRate = yRotationRate * (-1.0f);

					float zoomScale = MaximumZoomScaleForImage (_panningImageView.Image);
					float interpretedXOffset = (float)(ContentOffset.X + invertedYRotationRate * zoomScale * RotationMultiplier);

					var contentOffset = clampedContentOffsetForHorizontalOffset (interpretedXOffset);

					UIView.Animate (MovementSmoothing, 0.0, UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.CurveEaseOut,
						() => SetContentOffset (contentOffset, false),
						null);
				}
			}
		}
		private void ToggleMotionBasedPan() {
			bool motionBasedPanWasEnabled = motionBasedPanEnabled;

			if (motionBasedPanWasEnabled) {
				motionBasedPanEnabled = false;
			}

			UIView.Animate (AnimationDuration, () =>
				UpdateViewsForMotionBasedPanEnabled (!motionBasedPanWasEnabled)
				, () => {
					motionBasedPanEnabled |= !motionBasedPanWasEnabled;
				});
		}

		/// <summary>
		/// Starts the zooming.
		/// </summary>
		public void StartZooming()
		{
			ContentOffset = new PointF ((ContentSize.Width / 2) - (Bounds.Width / 2), (ContentSize.Height / 2) - (Bounds.Height / 2));
			_motionManager.StartDeviceMotionUpdates (NSOperationQueue.MainQueue, (motion, error) => calculateRotationBasedOnDeviceMotionRotationRate (motion));
		}

		internal void DisplayLinkUpdate() {
			var panningImageViewPresentationLayer = _panningImageView.Layer.PresentationLayer ;
			var panningScrollViewPresentationLayer = Layer.PresentationLayer;

			var horizontalContentOffset = panningScrollViewPresentationLayer.Bounds.GetMaxX ();

			var contentWidth = panningImageViewPresentationLayer.Frame.Width;
			var visibleWidth = Bounds.Width;

			float	clampedXOffsetAsPercentage = (float)Math.Max (0, Math.Min (1, horizontalContentOffset / (contentWidth - visibleWidth)));

			float scrollBarWidthPercentage = (float)(visibleWidth / contentWidth);
			float scrollableAreaPercentage = 1 - scrollBarWidthPercentage;

			_scrollBarView.UpdateWithScrollAmount (clampedXOffsetAsPercentage, scrollableAreaPercentage, scrollableAreaPercentage);

		}

		//new
		void UpdateViewsForMotionBasedPanEnabled(bool motionBasedPanEnabled) {
			if (motionBasedPanEnabled) {
				UpdateScrollViewZoomToMaximumForImage (_panningImageView.Image);
				ScrollEnabled = false;
			} else {
				ZoomScale = 1.0f;
				ScrollEnabled = true;
			}
		}
		//New

		//new
		float MaximumZoomScaleForImage(UIImage image) {
			return (float)((Bounds.Height / Bounds.Width) * (image.Size.Width / image.Size.Height));
		}

		//New
		void UpdateScrollViewZoomToMaximumForImage(UIImage image) {
			var zoomScale = MaximumZoomScaleForImage (image);

			MaximumZoomScale = zoomScale;
			ZoomScale = zoomScale;
		}

		//new
		internal PointF clampedContentOffsetForHorizontalOffset(float horizontalOffset) {
			float maximumXOffset = (float)(ContentSize.Width - Bounds.Width);
			float minimumXOffset = 0.0f;

			float	clampedXOffset = Math.Max (minimumXOffset, Math.Min (horizontalOffset, maximumXOffset));
			float centeredY = (float)((ContentSize.Height / 2.0) - (Bounds.Height / 2.0));

			return new PointF (clampedXOffset, centeredY);
		}

		//new
		[Export("pinchGestureRecognized")]
		void pinchGestureRecognized() {
			motionBasedPanEnabled = false;
			ScrollEnabled = true;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
"""
This script provides dev-ops tools for python project development.
"""

from __future__ import print_function
from pathlib_mate import Path
from setup import package

def fixcode(**kwargs):
    """
    auto pep8 format all python file in ``source code`` and ``tests`` dir.
    """
    # repository direcotry
    repo_dir = Path(__file__).parent.absolute()

    # source code directory
    source_dir = Path(repo_dir, package.__name__)

    if source_dir.exists():
        print("Source code locate at: '%s'." % source_dir)
        print("Auto pep8 all python file ...")
        source_dir.autopep8(**kwargs)
    else:
        print("Source code directory not found!")

    # unittest code directory
    unittest_dir = Path(repo_dir, "tests")
    if unittest_dir.exists():
        print("Unittest code locate at: '%s'." % unittest_dir)
        print("Auto pep8 all python file ...")
        unittest_dir.autopep8(**kwargs)
    else:
        print("Unittest code directory not found!")

    print("Complete!")

if __name__ == "__main__":
    fixcode()


text:
namespace Diversity
{
    namespace UI
    {
        DY_META_IMPL(LayoutElement, "UI.LayoutElement", meta)
        {
            meta.addFloat("preferredWidth",
                    &LayoutElement::getPreferredWidth,
                    &LayoutElement::setPreferredHeight);
            meta.addFloat("preferredHeight",
                    &LayoutElement::getPreferredHeight,
                    &LayoutElement::setPreferredHeight);
            meta.addListener(&LayoutElement::onChildChanged);
        }

        void LayoutElement::relayoutParent()
        {
            if (!getGameObject().hasParent())
            {
                return;
            }

            auto parentGroup = getGameObject().getParent().getComponentInParents<LayoutGroup>();
            if (parentGroup)
            {
                LayoutChangedEvent e{};
                parentGroup->sendEvent(e);
            }
        }

        void LayoutElement::awake()
        {
            relayoutParent();
        }

        void LayoutElement::onChildChanged(ChildChangedEvent&)
        {
            relayoutParent();
        }

        LayoutElement::LayoutElement()
        {
            preferredHeight = 0;
            preferredWidth = 0;
        }

        void LayoutElement::setPreferredHeight(float preferredHeight)
        {
            this->preferredHeight = preferredHeight;

            relayoutParent();
        }

        float LayoutElement::getPreferredHeight() const
        {
            return preferredHeight;
        }

        void LayoutElement::setPreferredWidth(float preferredWidth)
        {
            this->preferredWidth = preferredWidth;

            relayoutParent();
        }

        float LayoutElement::getPreferredWidth() const
        {
            return preferredWidth;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="EclipseCodeFormatterProjectSettings">
    <option name="selectedGlobalProfile">
      <Settings>
        <option name="formatter" value="ECLIPSE" />
        <option name="id" value="1496183671315" />
        <option name="name" value="default" />
        <option name="pathToConfigFileJava" value="$PROJECT_DIR$/tools/rules-checkstyle.xml" />
      </Settings>
    </option>
  </component>
</project>


text:
<?php
/**
 * Addons and code snippets for Nette Framework. (unofficial)
 *
 * @author   Jan Tvrdík
 * @license  MIT
 */

namespace JanTvrdik\Templates;

use Nette;
use Nette\Latte\DefaultMacros;
use Nette\Latte\ParseException;

/**
 * Latte macros for comfortable form rendering.
 *
 * List of modifiers:
 * ------------------
 * {form ...} – class, style
 * {input ...} – value, caption, size, rows, cols, placeholder, class, style
 * {label ...} – text, class, style
 *
 *
 * {form registrationForm}
 *
{$error}

 *

 *

 *       {label name, text => "Username"}
 *       {input name}
 *

 *

 *       {label password, text => "Password"}
 *       {input password}
 *

 *     {formContainer contact}
 *

 *         {label mail, text => "E-mail"}
 *         {input mail}
 *

 *

 *         {label twitter, text => "Twitter"}
 *         {input twitter}
 *

 *     {/formContainer}
 *

 *
 *       {input register, caption => "Register"}
 *

 *

 * {/form}
 *
 *
 * @author   Jan Marek, Jan Tvrdík, Daniel Robenek
 * @version  2.2
 * @link     http://nette.merxes.cz/form-macros/
 */
class FormMacros
{
	/** @var DefaultMacros */
	protected static $latte;

	/** @var array                 # => Nette\Forms\FormContainer */
	private static $containerStack;

	/**
	 * Static class – cannot be instantiated.
	 */
	final public function __construct()
	{
		throw new \LogicException('Cannot instantiate static class ' . get_class($this));
	}

	/**
	 * Registers form macros.
	 *
	 * @return   void
	 */
	public static function register(DefaultMacros $latte)
	{
		$latte->macros['form'] = '<?php %' . __CLASS__ . '::macroBegin% ?>';
		$latte->macros['/form'] = '<?php ' . __CLASS__ . '::endForm() ?>';
		$latte->macros['formContainer'] = '<?php %' . __CLASS__ . '::macroBeginContainer% ?>';
		$latte->macros['/formContainer'] = '<?php ' . __CLASS__ . '::endContainer() ?>';
		$latte->macros['input'] = '<?php %' . __CLASS__ . '::macroInput% ?>';
		$latte->macros['label'] = '<?php %' . __CLASS__ . '::macroLabel% ?>';
		$latte->macros['inputValue'] = '<?php %' . __CLASS__ . '::macroInputValue% ?>';

		self::$latte = $latte;
	}

	/**
	 * Returns current form.
	 *
	 * @return   Nette\Forms\Form
	 */
	public static function getForm()
	{
		return self::$containerStack[0];
	}

	/**
	 * {form ...}
	 *
	 * @param    string
	 * @return   string
	 */
	public static function macroBegin($content)
	{
		list($name, $modifiers) = self::fetchNameAndModifiers($content);
		return '$formErrors = ' . __CLASS__ . "::beginForm($name, \$control, $modifiers)->getErrors()";
	}

	/**
	 * Helper for {form ...} macro.
	 *
	 * @param    Nette\Forms\Form|string form instance or form name in given control
	 * @param    Nette\Application\UI\PresenterComponent
	 * @param    array             list of modifiers (name => value)
	 * @return   Nette\Forms\Form
	 */
	public static function beginForm($form, Nette\Application\UI\PresenterComponent $control, array $modifiers = NULL)
	{
		$form = ($form instanceof Nette\Forms\Form ? $form : $control->getComponent($form));
		self::$containerStack = array($form);

		if ($modifiers) self::addAttributes($form->getElementPrototype(), $modifiers, array('class', 'style'));
		$form->render('begin');

		return $form;
	}

	/**
	 * Helper for {/form} macro.
	 *
	 * @return   void
	 * @throws   ParseException    if some containers remain unclosed
	 */
	public static function endForm()
	{
		if (count(self::$containerStack) > 1) {
			throw new ParseException('There are some unclosed containers.');
		}
		self::getForm()->render('end');
		self::$containerStack = array();
	}

	/**
	 * {formContainer ...}
	 *
	 * @param    string
	 * @return   string
	 */
	public static function macroBeginContainer($content)
	{
		$name = self::$latte->formatString(self::$latte->fetchToken($content));
		return __CLASS__ . '::beginContainer(' . $name . ')';
	}

	/**
	 * Helper for {formContainer ...} macro.
	 *
	 * @param    string            container name
	 * @return   void
	 * @throws   ParseException    if container is not Nette\Forms\FormContainer instance
	 */
	public static function beginContainer($name)
	{
		$container = end(self::$containerStack)->getComponent($name);
		if (!$container instanceof Nette\Forms\Container) {
			throw new ParseException('Form container must be instance of Nette\Forms\FormContainer.');
		}
		self::$containerStack[] = $container;
	}

	/**
	 * Helper for {/formContainer} macro.
	 *
	 * @return   void
	 * @throws   ParseException    if there is no container to close
	 */
	public static function endContainer()
	{
		if (count(self::$containerStack) < 2) {
			throw new ParseException('Trying to close container which is not open.');
		}
		array_pop(self::$containerStack);
	}

	/**
	 * {input ...}
	 *
	 * @param    string
	 * @return   string
	 */
	public static function macroInput($content)
	{
		list($name, $modifiers) = self::fetchNameAndModifiers($content);
		return __CLASS__ . "::input($name, $modifiers)";
	}

	/**
	 * Helper for {input ...} macro.
	 *
	 * @param    string            input name
	 * @param    array             list of modifiers (name => value)
	 * @return   void
	 */
	public static function input($name, array $modifiers = NULL)
	{
		$input = self::getControl($name)->getControl();
		if ($modifiers) {
			self::addAttributes($input, $modifiers, array('value', 'size', 'rows', 'cols', 'placeholder', 'class', 'style'));
			if (isset($modifiers['caption'])) $input->value = $modifiers['caption'];
		}
		echo $input;
	}

	/**
	 * {label ...}
	 *
	 * @param    string
	 * @return   string
	 */
	public static function macroLabel($content)
	{
		list($name, $modifiers) = self::fetchNameAndModifiers($content);
		return __CLASS__ . "::label($name, $modifiers)";
	}

	/**
	 * Helper for {label ...} macro.
	 *
	 * @param    string            input name
	 * @param    array             list of modifiers (name => value)
	 * @return   void
	 */
	public static function label($name, array $modifiers = NULL)
	{
		$label = self::getControl($name)->getLabel();
		if ($modifiers) {
			self::addAttributes($label, $modifiers, array('class', 'style'));
			if (isset($modifiers['text'])) $label->setText($modifiers['text']);
		}
		echo $label;
	}

	/**
	 * {inputValue ...}
	 *
	 * @param    string
	 * @return   string
	 */
	public static function macroInputValue($content)
	{
		$name = self::$latte->formatString(self::$latte->fetchToken($content));
		return __CLASS__ . "::inputValue($name)";
	}

	/**
	 * Helper for {inputValue ...} macro.
	 *
	 * @param    string            input name
	 * @return   void
	 */
	public static function inputValue($name)
	{
		echo self::getControl($name)->getValue();
	}

	/**
	 * Returns form control.
	 *
	 * @param    string            input name
	 * @return   Nette\Forms\IControl
	 */
	protected static function getControl($name)
	{
		return end(self::$containerStack)->getComponent($name);
	}

	/**
	 * Parses given string a returns formatted name and modifiers as array.
	 *
	 * @param    string
	 * @return   array             0 => name, 1 => modifiers
	 */
	protected static function fetchNameAndModifiers($code)
	{
		$name = self::$latte->formatString(self::$latte->fetchToken($code));
		$modifiers = self::$latte->formatArray($code) ?: 'array()';
		return array($name, $modifiers);
	}

	/**
	 * Adds allowed attributes to given element.
	 *
	 * @param    Nette\Utils\Html
	 * @param    array             list of attributes (name => value)
	 * @param    array             list of allowed attributes (# => name)
	 * @return   void
	 */
	protected static function addAttributes(Nette\Utils\Html $el, array $attributes, array $allowedAttributes)
	{
		foreach ($attributes as $attribute => $value) {
			if (!in_array($attribute, $allowedAttributes)) continue;
			if (is_array($el->$attribute)) {
				$el->{$attribute}[] = $value;
			} else {
				$el->$attribute = $value;
			}
		}
	}

}


text:
class MirrorServerConcrete : public MirrorServer
{
public:
	// Mutators
	bool start( const char * pConfig )
	{
		Settings settings( "MirrorServer", pConfig );

		// initialize the logging first thing before we do anything else..
		std::string logFile( settings.get( "logFile", "MirrorServer.log" ) );
		std::string logExclude( settings.get( "logExclude", "" ) );
		unsigned int nLogLevel = settings.get( "logLevel", LL_STATUS );
		new FileReactor( logFile, nLogLevel, logExclude );

		m_GameID = settings.get( "gameId", (dword)1 );
		m_MetaAddress = settings.get( "metaAddress", "meta-server.palestar.com" );
		m_MetaPort = settings.get( "metaPort", 9000 );
		m_UID = settings.get( "uid", "");
		m_PW = settings.get( "pw", "" );
		m_DownloadFlags = settings.get( "downloadFlags", (dword)0 );
		m_UploadFlags = settings.get( "uploadFlags", 0xffffffff );
		m_RegisterServer = settings.get( "registerServer", 1 ) != 0;

		m_ClientFlags.release();
		m_NextUpdate = 0;

		MirrorServer::Context context;
		context.sCatalog = settings.get( "catalog", "" );
		context.mirror = settings.get( "mirror", ".\\Mirror\\" );
		context.address = settings.get( "address", "" );
		context.port = settings.get( "port", 9001  );
		context.maxClients = settings.get( "maxClients", 1000 );
		context.bVersionControl = settings.get( "VersionControl", (dword)0 ) != 0;
		context.nMinUpdateTime = settings.get( "minUpdateTime", 120 );
		context.sUID = m_UID;
		context.sPW = m_PW;

		// set the log file now, so any errors in the configuration will be logged...
		m_Context.logFile = context.logFile;

		int nLinkCount = settings.get("LinkCount", (dword)0);
		for(int i=0;i<nLinkCount;i++)
		{
			CharString sLink;
			sLink.format( "Link%d", i );

			MirrorServer::Link link;
			link.sCatalog = settings.get( sLink + "Catalog", context.sCatalog + "." + sLink );
			link.sAddress = settings.get( sLink + "Address", "" );
			link.nPort = settings.get( sLink + "Port", (dword)0 );
			link.bUpdate = true;

			if ( link.sAddress.length() > 0 && link.nPort != 0 )
			{
				LOG_STATUS( "MirrorServer", "Link %d configured for %s:%d...", i, link.sAddress.cstr(), link.nPort );
				context.links.push( link );
			}
			else
				LOG_STATUS( "MirrorServer", CharString().format("Failed to find link %d configuration!", i) );
		}

		return MirrorServer::start( context );
	}

	// MirrorServer interface
	virtual void onUpdate()
	{
		// update meta server
		m_MetaClient.update();

		AutoLock lock( &m_Lock );
		if ( m_UID.length() > 0 && m_NextUpdate < Time::seconds() )
		{
			if (! m_MetaClient.loggedIn() )
			{
				LOG_STATUS( "MirrorServer", "Connecting to MetaServer, address = %s, port = %d", m_MetaAddress.cstr(), m_MetaPort );
				if ( m_MetaClient.open( m_MetaAddress, m_MetaPort ) > 0 && m_MetaClient.login( m_UID, m_PW ) > 0 )
				{
					LOG_STATUS( "MirrorServer", "Connected to meta server..." );
				}
				else
					LOG_STATUS( "MirrorServer", "Failed to login to meta server..." );
			}

			if ( m_RegisterServer && m_MetaClient.loggedIn() )
			{
				// select the correct game
				m_MetaClient.selectGame( m_GameID );

				// register this server
				MetaClient::Server server;
				server.gameId = m_GameID;
				server.type = MetaClient::MIRROR_SERVER;
				server.flags = 0;
				server.name = CharString().format("%s:%d", context().address.cstr(), context().port);
				server.description = CharString().format("MirrorServer2, mirror = %s, logFile = %s",
					context().mirror.cstr(), context().logFile.cstr() );
				server.address = context().address;
				server.port = context().port;
				server.maxClients = context().maxClients;
				server.clients = clientCount();

				m_MetaClient.registerServer( server );
			}
			else if ( m_MetaClient.loggedIn() )
			{
				// select the correct game
				m_MetaClient.selectGame( m_GameID );

				// keep the connection alive
				CharString address;
				m_MetaClient.getAddress( address );
			}

			// register every 5 minutes
			if ( m_MetaClient.loggedIn() )
				m_NextUpdate = Time::seconds() + (60 * 5);
			else
				m_NextUpdate = Time::seconds() + 30;
		}
	}

	bool login( dword client, const char * pUser, const char * pMD5 )
	{
		// force a reconnect to the main server next update
		if (! m_MetaClient.loggedIn() )
		{
			m_NextUpdate = 0;
			onUpdate();
		}

		MetaClient::Profile profile;
		if ( m_MetaClient.loginByProxy( pUser, pMD5, profile ) > 0 )
		{
			m_ClientFlags[ client ] = profile.flags;
			return true;
		}

		// force a reconnect to the main server now
		return false;
	}
	bool login( dword client, dword nSID )
	{
		// force a reconnect to the main server next update
		if (! m_MetaClient.loggedIn() )
		{
			m_NextUpdate = 0;
			onUpdate();
		}

		MetaClient::Profile profile;
		if ( m_MetaClient.loginByProxy( nSID, profile ) > 0 )
		{
			m_ClientFlags[ client ] = profile.flags;
			return true;
		}

		return false;
	}
	void logout( dword client )
	{
		// remove the client from the hash table
		m_ClientFlags.remove( client );
	}

	bool canDownload( dword client )
	{
		if ( m_DownloadFlags == 0 )
			return true;
		if ( m_ClientFlags.find( client ).valid() )
			return (m_ClientFlags[ client ] & m_DownloadFlags) == m_DownloadFlags;
		return false;
	}

	bool canUpload( dword client )
	{
		if ( m_UploadFlags == 0 )
			return true;
		if ( m_ClientFlags.find( client ).valid() )
			return (m_ClientFlags[ client ] & m_UploadFlags) == m_UploadFlags;
		return false;
	}
	bool canLock( dword nClientId )
	{
		return canUpload( nClientId );
	}
	bool canDelete( dword nClientId )
	{
		return canUpload( nClientId );
	}
	bool canLabel( dword nClientId )
	{
		return canUpload( nClientId );
	}
	bool canRollback( dword nClientId )
	{
		return canUpload( nClientId );
	}

private:
	// Data
	dword		m_GameID;
	CharString	m_MetaAddress;
	int			m_MetaPort;
	CharString	m_UID;
	CharString	m_PW;

	dword		m_DownloadFlags;
	dword		m_UploadFlags;
	bool		m_RegisterServer;
	MetaClient	m_MetaClient;

	Hash< dword, dword >
				m_ClientFlags;
	dword		m_NextUpdate;
};

//----------------------------------------------------------------------------

#pragma warning( disable: 4800 )

int main( int argc, char ** argv )
{
	if ( argc < 2 )
	{
		printf( "Usage: %s <iniFile>", argv[0] );
		return 1;
	}

	Event serverStop( CharString().format("StopProcess%u", Process::getCurrentProcessId()) );

	// start the server
	MirrorServerConcrete theServer;
	if (! theServer.start( argv[1] ) )
		return -1;

	// run the server forever, unless it crashes
	while( theServer.running() )
	{
		if (! serverStop.wait( 10 ) )
			break;

		theServer.update();
	}

	theServer.stop();
	return 0;
}


text:
#ifndef LIB_HW_PWM_H
#define LIB_HW_PWM_H

#ifdef __cplusplus
extern "C" {
#endif

/** Check the code and datasheet to know the i/o pins of pwm output
 *
 * Warning, if you use the same timer for multiple pwm output, your pwm output share the same frequency output !
 *
 */

typedef enum _pwm_output_
{
#if defined(MCU_IS_LPC13XX)
        PWM0 = 0x01,        /**< PWM output 0 */
        PWM1 = 0x02,        /**< PWM output 1 */
        PWM2 = 0x04         /**< PWM output 2 */
#endif

#if defined(MCU_IS_LPC17XX)
        PWM1 = 0x01,
        PWM2 = 0x02,
        PWM3 = 0x04,
        PWM4 = 0x08,
        PWM5 = 0x10,
        PWM6 = 0x20
#endif
} PWMOUTPUT;

typedef enum _timertype_
{
    TIMER32_0 = 0,
    TIMER32_1 = 1,
    TIMER16_0 = 2,
    TIMER16_1 = 3
} PWMTIMER;

typedef struct _pwm_device_
{
    LPC_TMR_TypeDef *   timer;
    PWMOUTPUT           outputs;
    bool                enable;
} Pwm;

/** @brief Init PWM driver.
 *
 * @param pwm                   Output pwm object.
 * @param timerType             Select a timer for the PWM.
 * @param pwmSelected           Select an PWM output (or multiple PWM output).
 * @param widthInUs             PWM period in us.
 * @param prescaler             Constant to divide your period (to lower PWM frequency)
 * @param percentage            Duty cycle (between 0% and 1000%).
 */
extern void initPwm(Pwm *pwm, PWMTIMER timerType, PWMOUTPUT pwmSelected, uint32_t widthInUs, uint32_t prescaler, uint32_t percentage);

/** @brief Enable or Disable PWM.
 *
 * @param pwm           Pwm object.
 */
extern void enablePwm(Pwm *pwm);
extern void disablePwm(Pwm *pwm);

/** @brief Set PWM duty cycle.
 *
 * @param pwm                   Pwm object.
 * @param percentage            Set duty cycle (between 0% and 1000%).
 */
extern void setPwmDutyCycle(Pwm *pwm, uint32_t percentage);

extern void setPwmRawDutyCycle(Pwm *pwm, uint32_t raw);

extern void setPwmWidth(Pwm *pwm, uint32_t widthInUs);

#ifdef __cplusplus
 }
#endif

#endif


text:
App.ChemotaxisQuadrants2 = DS.Model.extend( App.savingMixin, {
	quadrant_1_ChemicalConcentration: DS.attr('number'),
	quadrant_2_ChemicalConcentration: DS.attr('number'),
	quadrant_1_Chemical: DS.belongsTo('chemical', {async: true}),
	quadrant_2_Chemical: DS.belongsTo('chemical', {async: true}),

	quadrantBarrierChemicalConcentration: DS.attr('number'),
	quadrantBarrierChemical: DS.belongsTo('chemical', {async: true}),
});


text:
import json

import urllib3

from minio import Minio
from minio.credentials import WebIdentityProvider

def get_jwt(client_id, client_secret, idp_client_id, idp_endpoint):
    res = urllib3.PoolManager().request(
        "POST",
        idp_endpoint,
        fields={
            "username": client_id,
            "password": client_secret,
            "grant_type": "password",
            "client_id": idp_client_id,
        },
    )

    return json.loads(res.data.encode())

# IDP endpoint.
idp_endpoint = (
    "https://IDP-HOST:IDP-PORT/auth/realms/master"
    "/protocol/openid-connect/token"
)

# Client-ID to fetch JWT.
client_id = "USER-ID"

# Client secret to fetch JWT.
client_secret = "PASSWORD"

# Client-ID of MinIO service on IDP.
idp_client_id = "MINIO-CLIENT-ID"

# STS endpoint usually point to MinIO server.
sts_endpoint = "http://STS-HOST:STS-PORT/"

# Role ARN if available.
role_arn = "ROLE-ARN"

# Role session name if available.
role_session_name = "ROLE-SESSION-NAME"

provider = WebIdentityProvider(
    lambda: get_jwt(client_id, client_secret, idp_client_id, idp_endpoint),
    sts_endpoint,
    role_arn=role_arn,
    role_session_name=role_session_name,
)

client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider)

# Get information of an object.
stat = client.stat_object("my-bucket", "my-object")
print(stat)


text:
namespace aquarius
{
namespace op
{

template <typename T>
class FCIDUMP : public task::Task
{
    protected:
        string path;
        bool semi;
        bool full_fock;

    public:
        FCIDUMP(const string& name, input::Config& config);

    protected:
        bool run(task::TaskDAG& dag, const Arena& arena);
};

}
}

#endif


text:
module NetSuite
  module Actions
    class Login

      # <userId xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com" internalId="460362">
      #   <platformCore:name>REDACTED ORG NAME</platformCore:name>
      # </userId>
      # <platformCore:wsRoleList xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com">
      #   <platformCore:wsRole>
      #     <platformCore:role internalId="1047">
      #       <platformCore:name>REDACTED ROLE</platformCore:name>
      #     </platformCore:role>
      #     <platformCore:isDefault>false</platformCore:isDefault>
      #     <platformCore:isInactive>false</platformCore:isInactive>
      #     <platformCore:isLoggedInRole>true</platformCore:isLoggedInRole>
      #   </platformCore:wsRole>
      #   <platformCore:wsRole>
      #     <platformCore:role internalId="1047">
      #       <platformCore:name>REDACTED ROLE</platformCore:name>
      #     </platformCore:role>
      #     <platformCore:isDefault>false</platformCore:isDefault>
      #     <platformCore:isInactive>false</platformCore:isInactive>
      #     <platformCore:isLoggedInRole>true</platformCore:isLoggedInRole>
      #   </platformCore:wsRole>
      # </platformCore:wsRoleList>

      def self.call(credentials)
        passport = NetSuite::Configuration.auth_header.dup
        passport['platformMsgs:passport']['platformCore:email'] = credentials[:email] || ''
        passport['platformMsgs:passport']['platformCore:password'] = credentials[:password] || ''
        passport['platformMsgs:passport']['platformCore:role'] = credentials[:role] || ''
        passport['platformMsgs:passport']['platformCore:account'] = credentials[:account] if !credentials[:account].nil?

        begin
          response = NetSuite::Configuration.connection(soap_header: NetSuite::Configuration.soap_header).call :login, message: passport
        rescue Savon::SOAPFault => e
          error_details = e.to_hash[:fault]

          if error_details[:detail].has_key?(:invalid_credentials_fault)
            return NetSuite::Response.new(
              success: false,
              errors: [ NetSuite::Error.new(
                code: error_details[:detail][:invalid_credentials_fault][:code],
                message: error_details[:faultstring]
              )],
              body: error_details
            )
          else
            raise(e)
          end
        end

        # include more data in body; leave it up to the user to pull the data they are looking for
        NetSuite::Response.new(
          success: response.to_hash[:login_response][:session_response][:status][:@is_success] == 'true',
          body: response.to_hash[:login_response][:session_response]
        )
      end

    end
  end
end


text:
namespace Tangram {
// TileSet serial + TileID
using TileCacheKey = std::pair<int32_t, TileID>;
}

namespace std {
    template <>
    struct hash<Tangram::TileCacheKey> {
        size_t operator()(const Tangram::TileCacheKey& k) const {
            std::size_t seed = 0;
            hash_combine(seed, k.first);
            hash_combine(seed, k.second);
            return seed;
        }
    };
}

namespace Tangram {

class TileCache {
    struct CacheEntry {
        TileCacheKey key;
        std::shared_ptr<Tile> tile;
    };

    using CacheList = std::list<CacheEntry>;
    using CacheMap = std::unordered_map<TileCacheKey, typename CacheList::iterator>;

public:

    TileCache(size_t _cacheSizeMB) :
        m_cacheUsage(0),
        m_cacheMaxUsage(_cacheSizeMB) {}

    void put(int32_t _source, std::shared_ptr<Tile> _tile) {
        TileCacheKey k(_source, _tile->getID());

        m_cacheList.push_front({k, _tile});
        m_cacheMap[k] = m_cacheList.begin();
        m_cacheUsage += _tile->getMemoryUsage();

        limitCacheSize(m_cacheMaxUsage);
    }

    std::shared_ptr<Tile> get(int32_t _source, TileID _tileID) {
        std::shared_ptr<Tile> tile;
        TileCacheKey k(_source, _tileID);

        auto it = m_cacheMap.find(k);
        if (it != m_cacheMap.end()) {
            std::swap(tile, (*(it->second)).tile);
            m_cacheList.erase(it->second);
            m_cacheMap.erase(it);
            m_cacheUsage -= tile->getMemoryUsage();
        }
        return tile;
    }

    void limitCacheSize(size_t _cacheSizeBytes) {
        m_cacheMaxUsage = _cacheSizeBytes;

        while (m_cacheUsage > m_cacheMaxUsage) {
            if (m_cacheList.empty()) {
                logMsg("Error: invalid cache state!\n");
                m_cacheUsage = 0;
                break;
            }
            auto& tile = m_cacheList.back().tile;
            m_cacheUsage -= tile->getMemoryUsage();
            m_cacheMap.erase(m_cacheList.back().key);
            m_cacheList.pop_back();
        }
    }

    size_t getMemoryUsage() const {
        size_t sum = 0;
        for (auto& entry : m_cacheList) {
            sum += entry.tile->getMemoryUsage();
        }
        return sum;
    }

    void clear() {
        m_cacheMap.clear();
        m_cacheList.clear();
    }

private:
    CacheMap m_cacheMap;
    CacheList m_cacheList;

    int m_cacheUsage;
    int m_cacheMaxUsage;
};

}


text:
using System;

namespace LinqToDB.Mapping
{
	[Serializable]
	[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
	public class IdentityAttribute : Attribute
	{
		public IdentityAttribute()
		{
		}

		public IdentityAttribute(string configuration)
		{
			Configuration = configuration;
		}

		public string Configuration { get; set; }
	}
}


text:
 package sbt.boot

// This is the main class for the sbt launcher.  Its purpose is to ensure the appropriate
// versions of sbt and scala are downloaded to the projects 'project/boot' directory.
// Then, the downloaded version of sbt is started as usual using the right version of
// scala.

// Artifact names must be consistent between the main sbt build and this build.

import java.io.{File, FileFilter}
import java.net.{MalformedURLException, URL, URLClassLoader}

// contains constants and paths
import BootConfiguration._
import UpdateTarget.{UpdateScala, UpdateSbt}

// The exception to use when an error occurs at the launcher level (and not a nested exception).
// This indicates overrides toString because the exception class name is not needed to understand
// the error message.
private class BootException(override val toString: String) extends RuntimeException
// The entry point to the launcher
object Boot
{
	def main(args: Array[String])
	{
		System.setProperty("sbt.boot", true.toString)
		val found = Paths.projectSearch().getCanonicalPath
		System.setProperty("user.dir", found)
		checkProxy()
		try { boot(args) }
		catch
		{
			case b: BootException => errorAndExit(b)
			case e =>
				e.printStackTrace
				errorAndExit(e)
		}
		System.exit(0)
	}
	private def errorAndExit(e: Throwable)
	{
		System.out.println("Error during sbt execution: " + e.toString)
		System.exit(1)
	}
	def boot(args: Array[String])
	{
		 // prompt to create project if it doesn't exist.
		 // will not return if user declines
		(new Paths).checkProject()
		val loaderCache = new LoaderCache
		if(args.length == 0)
			load(args, loaderCache) // interactive mode, which can only use one version of scala for a run
		else
			runBatch(args.toList, Nil, loaderCache)  // batch mode, which can reboot with a different scala version
	}
	private def runBatch(args: List[String], accumulateReversed: List[String], loaderCache: LoaderCache)
	{
		def doLoad() = if(!accumulateReversed.isEmpty) load(accumulateReversed.reverse.toArray, loaderCache)
		args match
		{
			case Nil => doLoad()
			case RebootCommand :: tail =>
				doLoad()
				runBatch(tail, Nil, loaderCache)
			case action :: tail if action.trim.startsWith(CrossBuildPrefix) =>
				doLoad()
				load(Array(action), loaderCache) // call main with the single cross-build argument, preserving the '+' prefix, with which it knows what to do
				runBatch(tail, Nil, loaderCache)
			case notReload :: tail => runBatch(tail, notReload :: accumulateReversed, loaderCache)
		}
	}
	/** Loads the project in the current working directory using the version of scala and sbt
	* declared in the build. The class loader used prevents the Scala and Ivy classes used by
	* this loader from being seen by the loaded sbt/project.*/
	private def load(args: Array[String], loaderCache: LoaderCache)
	{
		val loader = (new Setup(loaderCache)).loader()
		val sbtMain = Class.forName(SbtMainClass, true, loader)
		val exitCode = run(sbtMain, args)
		if(exitCode == NormalExitCode)
			()
		else if(exitCode == RebootExitCode)
			load(args, loaderCache)
		else
			System.exit(exitCode)
	}
	private def run(sbtMain: Class[_], args: Array[String]): Int =
	{
		try {
			// Versions newer than 0.3.8 enter through the run method, which does not call System.exit
			val runMethod = sbtMain.getMethod(MainMethodName, classOf[Array[String]])
			runMethod.invoke(null, Array(args) : _*).asInstanceOf[Int]
		} catch {
			case e: NoSuchMethodException => runOld(sbtMain, args)
		}
	}
	/** The entry point for version 0.3.8 was the main method. */
	private def runOld(sbtMain: Class[_], args: Array[String]): Int =
	{
		val runMethod = sbtMain.getMethod(OldMainMethodName, classOf[Array[String]])
		runMethod.invoke(null, Array(args) : _*)
		NormalExitCode
	}

	private def checkProxy()
	{
		import ProxyProperties._
		val httpProxy = System.getenv(HttpProxyEnv)
		if(isDefined(httpProxy) && !isPropertyDefined(ProxyHost) && !isPropertyDefined(ProxyPort))
		{
			try
			{
				val proxy = new URL(httpProxy)
				setProperty(ProxyHost, proxy.getHost)
				val port = proxy.getPort
				if(port >= 0)
					System.setProperty(ProxyPort, port.toString)
				copyEnv(HttpProxyUser, ProxyUser)
				copyEnv(HttpProxyPassword, ProxyPassword)
			}
			catch
			{
				case e: MalformedURLException =>
					System.out.println("Warning: could not parse http_proxy setting: " + e.toString)
			}
		}
	}
	private def copyEnv(envKey: String, sysKey: String) { setProperty(sysKey, System.getenv(envKey)) }
	private def setProperty(key: String, value: String) { if(value != null) System.setProperty(key, value) }
	private def isPropertyDefined(k: String) = isDefined(System.getProperty(k))
	private def isDefined(s: String) = s != null && !s.isEmpty
}

object Paths
{
	val Only = "only"
	val RootFirst = "root-first"
	val Nearest = "nearest"
	val NoSearch = "none"
	val SearchPropertyName = "sbt.boot.search"
	def projectSearch() =
	{
		val current = (new File(".")) getCanonicalFile
		lazy val fromRoot = path(current, Nil).filter(hasProject).map(_.getCanonicalFile)
		val found: Option[File] =
			(System.getProperty(SearchPropertyName, NoSearch).trim.toLowerCase match
			{
				case RootFirst => fromRoot.headOption
				case Nearest => fromRoot.reverse.headOption
				case Only =>
					if(hasProject(current))
						Some(current)
					else
						fromRoot match
						{
							case Nil => Some(current)
							case head :: Nil => Some(head)
							case xs =>
								System.err.println("Search method is 'only' and multiple ancestor directories contain project/build.properties:\n\t" + fromRoot.mkString("\n\t"))
								System.exit(1)
						        None
						}
				case _ => Some(current)
			})
		found.getOrElse(current)
	}
	private def hasProject(f: File) = new Paths(f) hasPropertiesFile
	private def path(f: File, acc: List[File]): List[File] = if(f eq null) acc else path(f.getParentFile, f :: acc)
}
private class Paths(baseDirectory: File) extends NotNull
{
	def this() = this(new File(".") getCanonicalFile)
	protected final val ProjectDirectory = new File(baseDirectory, ProjectDirectoryName)
	protected final val BootDirectory = new File(ProjectDirectory, BootDirectoryName)
	protected final val PropertiesFile = new File(ProjectDirectory, BuildPropertiesName)

	final def hasPropertiesFile = PropertiesFile.exists
	final def checkProject()
	{
		if(!ProjectDirectory.exists)
		{
			val line = SimpleReader.readLine("Project does not exist, create new project? (y/N/s) : ")
			if(Setup.isYes(line))
				ProjectProperties(PropertiesFile, true)
			else if(Setup.isScratch(line))
				ProjectProperties.scratch(PropertiesFile)
			else
				System.exit(1)
		}
	}
}
/** A class to handle setting up the properties and classpath of the project
* before it is loaded. */
private class Setup(loaderCache: LoaderCache) extends Paths
{
	/** Checks that the requested version of sbt and scala have been downloaded.
	* It performs a simple check that the appropriate directories exist.  It uses Ivy
	* to resolve and retrieve any necessary libraries. The classpath to use is returned.*/
	final def loader(): ClassLoader = loader(Nil)
	private final def loader(forcePrompt: Seq[String]): ClassLoader =
	{
		val (normalScalaVersion, sbtVersion) = ProjectProperties.forcePrompt(PropertiesFile, forcePrompt : _*)
		val scalaVersion = crossScalaVersion(normalScalaVersion)
		loaderCache( scalaVersion, sbtVersion ) match
		{
			case Some(existingLoader) =>
			{
				setScalaVersion(scalaVersion)
				existingLoader
			}
			case None =>
			{
				getLoader(scalaVersion, sbtVersion) match
				{
					case Left(retry) => loader(retry)
					case Right(classLoader) => classLoader
				}
			}
		}
	}
	private def crossScalaVersion(simpleScalaVersion: String): String =
	{
		val crossScalaVersion = System.getProperty(SbtScalaVersionKey)
		if(crossScalaVersion == null || crossScalaVersion.isEmpty)
			simpleScalaVersion
		else
			crossScalaVersion
	}
	private def getLoader(scalaVersion: String, sbtVersion: String): Either[Seq[String], ClassLoader] =
	{
		import Setup.{failIfMissing,isYes,needsUpdate}
		import ProjectProperties.{ScalaVersionKey, SbtVersionKey}

		val baseDirectory = new File(BootDirectory, baseDirectoryName(scalaVersion))
		System.setProperty(ScalaHomeProperty, baseDirectory.getAbsolutePath)
		val scalaDirectory = new File(baseDirectory, ScalaDirectoryName)
		val sbtDirectory = new File(baseDirectory, sbtDirectoryName(sbtVersion))

		val classLoader = createLoader(scalaDirectory, sbtDirectory)
		val updateTargets = needsUpdate("", classLoader, TestLoadScalaClasses, UpdateScala) ::: needsUpdate(sbtVersion, classLoader, TestLoadSbtClasses, UpdateSbt)
		if(updateTargets.isEmpty) // avoid loading Ivy related classes if there is nothing to update
			success(classLoader, scalaVersion, sbtVersion)
		else
		{
			Update(baseDirectory, sbtVersion, scalaVersion, updateTargets: _*)

			val classLoader = createLoader(scalaDirectory, sbtDirectory)
			val sbtFailed = failIfMissing(classLoader, TestLoadSbtClasses, "sbt " + sbtVersion, SbtVersionKey)
			val scalaFailed = failIfMissing(classLoader, TestLoadScalaClasses, "Scala " + scalaVersion, ScalaVersionKey)

			(scalaFailed +++ sbtFailed) match
			{
				case Success => success(classLoader, scalaVersion, sbtVersion)
				case f: Failure =>
					val noRetrieveMessage = "Could not retrieve " + f.label + "."
					val getNewVersions = SimpleReader.readLine(noRetrieveMessage + " Select different version? (y/N) : ")
					if(isYes(getNewVersions))
						Left(f.keys)
					else
						throw new BootException(noRetrieveMessage)
			}
		}
	}
	private def success(classLoader: ClassLoader, scalaVersion: String, sbtVersion: String) =
	{
		setScalaVersion(scalaVersion)
		loaderCache( scalaVersion, sbtVersion ) = classLoader
		Right(classLoader)
	}
	private def createLoader(dirs: File*) =
	{
		val classpath = Setup.getJars(dirs : _*)
		new URLClassLoader(classpath.toArray, new BootFilteredLoader)
	}
	private def setScalaVersion(scalaVersion: String) { System.setProperty(SbtScalaVersionKey, scalaVersion) }
}
private final class LoaderCache
{
	private[this] var cachedSbtVersion: Option[String] = None
	private[this] val loaderMap = new scala.collection.mutable.HashMap[String, ClassLoader]
	def apply(scalaVersion: String, sbtVersion: String): Option[ClassLoader] =
	{
		cachedSbtVersion flatMap { currentSbtVersion =>
			if(sbtVersion == currentSbtVersion)
				loaderMap.get(scalaVersion)
			else
				None
		}
	}
	def update(scalaVersion: String, sbtVersion: String, loader: ClassLoader)
	{
		for(currentSbtVersion <- cachedSbtVersion)
		{
			if(sbtVersion != currentSbtVersion)
				loaderMap.clear()
		}
		cachedSbtVersion = Some(sbtVersion)
		loaderMap(scalaVersion) = loader
	}
}
private object Setup
{
	private def failIfMissing(loader: ClassLoader, classes: Iterable[String], label: String, key: String) = checkTarget(loader, classes, Success, new Failure(label, List(key)))
	private def needsUpdate(version: String, loader: ClassLoader, classes: Iterable[String], target: UpdateTarget.Value) =
		if(version.endsWith("-SNAPSHOT"))
			target :: Nil
		else
			checkTarget(loader, classes, Nil, target :: Nil)
	private def checkTarget[T](loader: ClassLoader, classes: Iterable[String], ifSuccess: => T, ifFailure: => T): T =
	{
		try
		{
			for(c <- classes)
				Class.forName(c, false, loader)
			ifSuccess
		}
		catch { case e: ClassNotFoundException => ifFailure }
	}
	def isYes(so: Option[String]) = isValue("y", "yes")(so)
	def isScratch(so: Option[String]) = isValue("s", "scratch")(so)
	def isValue(values: String*)(so: Option[String]) =
		so match
		{
			case Some(s) => values.contains(s.toLowerCase)
			case None => false
		}
	private def getJars(directories: File*) = directories.flatMap(file => wrapNull(file.listFiles(JarFilter))).map(_.toURI.toURL)
	private def wrapNull(a: Array[File]): Array[File] = if(a == null) Array() else a
}

private object JarFilter extends FileFilter
{
	def accept(file: File) = !file.isDirectory && file.getName.endsWith(".jar")
}

private sealed trait Checked extends NotNull { def +++(o: Checked): Checked }
private final object Success extends Checked { def +++(o: Checked) = o }
private final class Failure(val label: String, val keys: List[String]) extends Checked
{
	def +++(o: Checked) =
		o match
		{
			case Success => this
			case f: Failure => new Failure(label + " and " + f.label, keys ::: f.keys)
		}
}


text:
Elm.Native.Date = {};
Elm.Native.Date.make = function(elm) {
    elm.Native = elm.Native || {};
    elm.Native.Date = elm.Native.Date || {};
    if (elm.Native.Date.values) return elm.Native.Date.values;

    var Result = Elm.Result.make(elm);

    function dateNow() {
        return new window.Date;
    }

    function readDate(str) {
        var date = new window.Date(str);
        return isNaN(date.getTime())
            ? Result.Err("unable to parse '" + str + "' as a date")
            : Result.Ok(date);
    }

    var dayTable = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var monthTable =
        ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    return elm.Native.Date.values = {
        read    : readDate,
        year    : function(d) { return d.getFullYear(); },
        month   : function(d) { return { ctor:monthTable[d.getMonth()] }; },
        day     : function(d) { return d.getDate(); },
        hour    : function(d) { return d.getHours(); },
        minute  : function(d) { return d.getMinutes(); },
        second  : function(d) { return d.getSeconds(); },
        toTime  : function(d) { return d.getTime(); },
        fromTime: function(t) { return new window.Date(t); },
        dayOfWeek : function(d) { return { ctor:dayTable[d.getDay()] }; }
    };

};


text:
5.2 LoPy
========

Pinout
------

The pinout of the module is available as a `PDF file <../_downloads/lopy_pinout.pdf>`_.

.. image:: images/pinout_lopy_screenshot.png
    :align: center
    :scale: 50 %
    :alt: LoPy Pinout
    :target: ../_downloads/lopy_pinout.pdf

.. warning::

    DO NOT connect anything to Pins ``P5``, ``P6`` and ``P7``, as this pins are used byt the SPI bus that controls the LoRa radio.
    These pins should be treated as ``NC``. Wiring connections to these pins will cause incorrect behaviour of the LoRa radio.

Specsheets
----------

The specsheet of the LoPy developer version is available as a `PDF file <../_downloads/lopySpecsheetGraffiti.pdf>`_.
The specsheet of the **L01** which is the OEM version of the LoPy can be found in the following `link <../_downloads/l01SpecsheetGraffitiOEM.pdf>`_.

L01 drawings
------------

For the exact dimensions, pin-out and footprint details of the L01 please refer to the following `PDF file <../_downloads/LoPy-OEM-Drawings.pdf>`_.


text:
module Rmqf

  module Mock

    module Adapter

      class Subscriber < Base

        def required_keys
          ['id', 'resource', 'msisdn', 'active', 'subscriptionVia', 'weekday', 'subscribedAt', 'unsubscribedAt', 'subscription']
        end

      end

    end

  end

end


text:
package org.kylin.algorithm;

public interface RandomKill {
    void setBeDeleted(boolean deleted);
    boolean isBeDeleted();
}


text:
package org.apache.flink.connectors.hive;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.IllegalConfigurationException;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.connectors.hive.read.HiveContinuousMonitoringFunction;
import org.apache.flink.connectors.hive.read.HiveTableFileInputFormat;
import org.apache.flink.connectors.hive.read.HiveTableInputFormat;
import org.apache.flink.connectors.hive.read.TimestampedHiveInputSplit;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ContinuousFileMonitoringFunction;
import org.apache.flink.streaming.api.functions.source.ContinuousFileReaderOperatorFactory;
import org.apache.flink.streaming.api.functions.source.FileProcessingMode;
import org.apache.flink.streaming.api.functions.source.TimestampedFileInputSplit;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.config.ExecutionConfigOptions;
import org.apache.flink.table.catalog.CatalogTable;
import org.apache.flink.table.catalog.ObjectPath;
import org.apache.flink.table.catalog.hive.client.HiveMetastoreClientFactory;
import org.apache.flink.table.catalog.hive.client.HiveMetastoreClientWrapper;
import org.apache.flink.table.catalog.hive.client.HiveShim;
import org.apache.flink.table.catalog.hive.client.HiveShimLoader;
import org.apache.flink.table.catalog.hive.descriptors.HiveCatalogValidator;
import org.apache.flink.table.catalog.hive.util.HiveReflectionUtils;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.TimestampData;
import org.apache.flink.table.filesystem.FileSystemLookupFunction;
import org.apache.flink.table.filesystem.FileSystemOptions;
import org.apache.flink.table.functions.AsyncTableFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.table.functions.hive.conversion.HiveInspectors;
import org.apache.flink.table.runtime.types.TypeInfoDataTypeConverter;
import org.apache.flink.table.sources.LimitableTableSource;
import org.apache.flink.table.sources.LookupableTableSource;
import org.apache.flink.table.sources.PartitionableTableSource;
import org.apache.flink.table.sources.ProjectableTableSource;
import org.apache.flink.table.sources.StreamTableSource;
import org.apache.flink.table.sources.TableSource;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.LogicalTypeRoot;
import org.apache.flink.table.utils.TableConnectorUtils;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.TimeUtils;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.mapred.JobConf;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import static org.apache.flink.table.filesystem.DefaultPartTimeExtractor.toLocalDateTime;
import static org.apache.flink.table.filesystem.FileSystemOptions.PARTITION_TIME_EXTRACTOR_CLASS;
import static org.apache.flink.table.filesystem.FileSystemOptions.PARTITION_TIME_EXTRACTOR_KIND;
import static org.apache.flink.table.filesystem.FileSystemOptions.PARTITION_TIME_EXTRACTOR_TIMESTAMP_PATTERN;
import static org.apache.flink.table.filesystem.FileSystemOptions.STREAMING_SOURCE_CONSUME_ORDER;
import static org.apache.flink.table.filesystem.FileSystemOptions.STREAMING_SOURCE_CONSUME_START_OFFSET;
import static org.apache.flink.table.filesystem.FileSystemOptions.STREAMING_SOURCE_ENABLE;
import static org.apache.flink.table.filesystem.FileSystemOptions.STREAMING_SOURCE_MONITOR_INTERVAL;

/**
 * A TableSource implementation to read data from Hive tables.
 */
public class HiveTableSource implements
		StreamTableSource<RowData>,
		PartitionableTableSource,
		ProjectableTableSource<RowData>,
		LimitableTableSource<RowData>,
		LookupableTableSource<RowData> {

	private static final Logger LOG = LoggerFactory.getLogger(HiveTableSource.class);

	private final JobConf jobConf;
	private final ReadableConfig flinkConf;
	private final ObjectPath tablePath;
	private final CatalogTable catalogTable;
	// Remaining partition specs after partition pruning is performed. Null if pruning is not pushed down.
	@Nullable
	private List<Map<String, String>> remainingPartitions = null;
	private String hiveVersion;
	private HiveShim hiveShim;
	private boolean partitionPruned;
	private int[] projectedFields;
	private boolean isLimitPushDown = false;
	private long limit = -1L;
	private Duration hiveTableCacheTTL;

	public HiveTableSource(
			JobConf jobConf, ReadableConfig flinkConf, ObjectPath tablePath, CatalogTable catalogTable) {
		this.jobConf = Preconditions.checkNotNull(jobConf);
		this.flinkConf = Preconditions.checkNotNull(flinkConf);
		this.tablePath = Preconditions.checkNotNull(tablePath);
		this.catalogTable = Preconditions.checkNotNull(catalogTable);
		this.hiveVersion = Preconditions.checkNotNull(jobConf.get(HiveCatalogValidator.CATALOG_HIVE_VERSION),
				"Hive version is not defined");
		hiveShim = HiveShimLoader.loadHiveShim(hiveVersion);
		partitionPruned = false;
	}

	// A constructor mainly used to create copies during optimizations like partition pruning and projection push down.
	private HiveTableSource(
			JobConf jobConf,
			ReadableConfig flinkConf,
			ObjectPath tablePath,
			CatalogTable catalogTable,
			List<Map<String, String>> remainingPartitions,
			String hiveVersion,
			boolean partitionPruned,
			int[] projectedFields,
			boolean isLimitPushDown,
			long limit) {
		this.jobConf = Preconditions.checkNotNull(jobConf);
		this.flinkConf = Preconditions.checkNotNull(flinkConf);
		this.tablePath = Preconditions.checkNotNull(tablePath);
		this.catalogTable = Preconditions.checkNotNull(catalogTable);
		this.remainingPartitions = remainingPartitions;
		this.hiveVersion = hiveVersion;
		hiveShim = HiveShimLoader.loadHiveShim(hiveVersion);
		this.partitionPruned = partitionPruned;
		this.projectedFields = projectedFields;
		this.isLimitPushDown = isLimitPushDown;
		this.limit = limit;
	}

	@Override
	public boolean isBounded() {
		return !isStreamingSource();
	}

	@Override
	public DataStream<RowData> getDataStream(StreamExecutionEnvironment execEnv) {
		List<HiveTablePartition> allHivePartitions = initAllPartitions();

		@SuppressWarnings("unchecked")
		TypeInformation<RowData> typeInfo =
				(TypeInformation<RowData>) TypeInfoDataTypeConverter.fromDataTypeToTypeInfo(getProducedDataType());

		HiveTableInputFormat inputFormat = getInputFormat(
				allHivePartitions,
				flinkConf.get(HiveOptions.TABLE_EXEC_HIVE_FALLBACK_MAPRED_READER));

		if (isStreamingSource()) {
			if (catalogTable.getPartitionKeys().isEmpty()) {
				return createStreamSourceForNonPartitionTable(execEnv, typeInfo, inputFormat, allHivePartitions.get(0));
			} else {
				return createStreamSourceForPartitionTable(execEnv, typeInfo, inputFormat);
			}
		} else {
			return createBatchSource(execEnv, typeInfo, inputFormat);
		}
	}

	private boolean isStreamingSource() {
		return Boolean.parseBoolean(catalogTable.getOptions().getOrDefault(
				STREAMING_SOURCE_ENABLE.key(),
				STREAMING_SOURCE_ENABLE.defaultValue().toString()));
	}

	private DataStream<RowData> createBatchSource(StreamExecutionEnvironment execEnv,
			TypeInformation<RowData> typeInfo, HiveTableInputFormat inputFormat) {
		DataStreamSource<RowData> source = execEnv.createInput(inputFormat, typeInfo);

		int parallelism = flinkConf.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_DEFAULT_PARALLELISM);
		if (flinkConf.get(HiveOptions.TABLE_EXEC_HIVE_INFER_SOURCE_PARALLELISM)) {
			int max = flinkConf.get(HiveOptions.TABLE_EXEC_HIVE_INFER_SOURCE_PARALLELISM_MAX);
			if (max < 1) {
				throw new IllegalConfigurationException(
						HiveOptions.TABLE_EXEC_HIVE_INFER_SOURCE_PARALLELISM_MAX.key() +
								" cannot be less than 1");
			}

			int splitNum;
			try {
				long nano1 = System.nanoTime();
				splitNum = inputFormat.createInputSplits(0).length;
				long nano2 = System.nanoTime();
				LOG.info(
						"Hive source({}}) createInputSplits use time: {} ms",
						tablePath,
						(nano2 - nano1) / 1_000_000);
			} catch (IOException e) {
				throw new FlinkHiveException(e);
			}
			parallelism = Math.min(splitNum, max);
		}
		parallelism = limit > 0 ? Math.min(parallelism, (int) limit / 1000) : parallelism;
		parallelism = Math.max(1, parallelism);
		source.setParallelism(parallelism);
		return source.name(explainSource());
	}

	private DataStream<RowData> createStreamSourceForPartitionTable(
			StreamExecutionEnvironment execEnv,
			TypeInformation<RowData> typeInfo,
			HiveTableInputFormat inputFormat) {
		Configuration configuration = new Configuration();
		catalogTable.getOptions().forEach(configuration::setString);

		String consumeOrderStr = configuration.get(STREAMING_SOURCE_CONSUME_ORDER);
		ConsumeOrder consumeOrder = ConsumeOrder.getConsumeOrder(consumeOrderStr);
		String consumeOffset = configuration.get(STREAMING_SOURCE_CONSUME_START_OFFSET);
		String extractorKind = configuration.get(PARTITION_TIME_EXTRACTOR_KIND);
		String extractorClass = configuration.get(PARTITION_TIME_EXTRACTOR_CLASS);
		String extractorPattern = configuration.get(PARTITION_TIME_EXTRACTOR_TIMESTAMP_PATTERN);
		Duration monitorInterval = configuration.get(STREAMING_SOURCE_MONITOR_INTERVAL);

		HiveContinuousMonitoringFunction monitoringFunction = new HiveContinuousMonitoringFunction(
				hiveShim,
				jobConf,
				tablePath,
				catalogTable,
				execEnv.getParallelism(),
				consumeOrder,
				consumeOffset,
				extractorKind,
				extractorClass,
				extractorPattern,
				monitorInterval.toMillis());

		ContinuousFileReaderOperatorFactory<RowData, TimestampedHiveInputSplit> factory =
				new ContinuousFileReaderOperatorFactory<>(inputFormat);

		String sourceName = "HiveMonitoringFunction";
		SingleOutputStreamOperator<RowData> source = execEnv
				.addSource(monitoringFunction, sourceName)
				.transform("Split Reader: " + sourceName, typeInfo, factory);

		return new DataStreamSource<>(source);
	}

	private DataStream<RowData> createStreamSourceForNonPartitionTable(
			StreamExecutionEnvironment execEnv,
			TypeInformation<RowData> typeInfo,
			HiveTableInputFormat inputFormat,
			HiveTablePartition hiveTable) {
		HiveTableFileInputFormat fileInputFormat = new HiveTableFileInputFormat(inputFormat, hiveTable);

		Configuration configuration = new Configuration();
		catalogTable.getOptions().forEach(configuration::setString);
		String consumeOrderStr = configuration.get(STREAMING_SOURCE_CONSUME_ORDER);
		ConsumeOrder consumeOrder = ConsumeOrder.getConsumeOrder(consumeOrderStr);
		if (consumeOrder != ConsumeOrder.CREATE_TIME_ORDER) {
			throw new UnsupportedOperationException(
					"Only " + ConsumeOrder.CREATE_TIME_ORDER + " is supported for non partition table.");
		}

		String consumeOffset = configuration.get(STREAMING_SOURCE_CONSUME_START_OFFSET);
		// to Local zone mills instead of UTC mills
		long currentReadTime = TimestampData.fromLocalDateTime(toLocalDateTime(consumeOffset))
				.toTimestamp().getTime();

		Duration monitorInterval = configuration.get(STREAMING_SOURCE_MONITOR_INTERVAL);

		ContinuousFileMonitoringFunction<RowData> monitoringFunction =
				new ContinuousFileMonitoringFunction<>(
						fileInputFormat,
						FileProcessingMode.PROCESS_CONTINUOUSLY,
						execEnv.getParallelism(),
						monitorInterval.toMillis(),
						currentReadTime);

		ContinuousFileReaderOperatorFactory<RowData, TimestampedFileInputSplit> factory =
				new ContinuousFileReaderOperatorFactory<>(fileInputFormat);

		String sourceName = "HiveFileMonitoringFunction";
		SingleOutputStreamOperator<RowData> source = execEnv.addSource(monitoringFunction, sourceName)
				.transform("Split Reader: " + sourceName, typeInfo, factory);

		return new DataStreamSource<>(source);
	}

	@VisibleForTesting
	HiveTableInputFormat getInputFormat(List<HiveTablePartition> allHivePartitions, boolean useMapRedReader) {
		return new HiveTableInputFormat(
				jobConf,
				catalogTable,
				allHivePartitions,
				projectedFields,
				limit,
				hiveVersion,
				useMapRedReader);
	}

	@Override
	public TableSchema getTableSchema() {
		return catalogTable.getSchema();
	}

	@Override
	public DataType getProducedDataType() {
		return getProducedTableSchema().toRowDataType().bridgedTo(RowData.class);
	}

	private TableSchema getProducedTableSchema() {
		TableSchema fullSchema = getTableSchema();
		if (projectedFields == null) {
			return fullSchema;
		} else {
			String[] fullNames = fullSchema.getFieldNames();
			DataType[] fullTypes = fullSchema.getFieldDataTypes();
			return TableSchema.builder().fields(
					Arrays.stream(projectedFields).mapToObj(i -> fullNames[i]).toArray(String[]::new),
					Arrays.stream(projectedFields).mapToObj(i -> fullTypes[i]).toArray(DataType[]::new)).build();
		}
	}

	@Override
	public boolean isLimitPushedDown() {
		return isLimitPushDown;
	}

	@Override
	public TableSource<RowData> applyLimit(long limit) {
		return new HiveTableSource(
				jobConf,
				flinkConf,
				tablePath,
				catalogTable,
				remainingPartitions,
				hiveVersion,
				partitionPruned,
				projectedFields,
				true,
				limit);
	}

	@Override
	public List<Map<String, String>> getPartitions() {
		throw new UnsupportedOperationException(
				"Please use Catalog API to retrieve all partitions of a table");
	}

	@Override
	public TableSource<RowData> applyPartitionPruning(List<Map<String, String>> remainingPartitions) {
		if (catalogTable.getPartitionKeys() == null || catalogTable.getPartitionKeys().size() == 0) {
			return this;
		} else {
			return new HiveTableSource(
					jobConf,
					flinkConf,
					tablePath,
					catalogTable,
					remainingPartitions,
					hiveVersion,
					true,
					projectedFields,
					isLimitPushDown,
					limit);
		}
	}

	@Override
	public TableSource<RowData> projectFields(int[] fields) {
		return new HiveTableSource(
				jobConf,
				flinkConf,
				tablePath,
				catalogTable,
				remainingPartitions,
				hiveVersion,
				partitionPruned,
				fields,
				isLimitPushDown,
				limit);
	}

	private List<HiveTablePartition> initAllPartitions() {
		List<HiveTablePartition> allHivePartitions = new ArrayList<>();
		// Please note that the following directly accesses Hive metastore, which is only a temporary workaround.
		// Ideally, we need to go thru Catalog API to get all info we need here, which requires some major
		// refactoring. We will postpone this until we merge Blink to Flink.
		try (HiveMetastoreClientWrapper client = HiveMetastoreClientFactory.create(new HiveConf(jobConf, HiveConf.class), hiveVersion)) {
			String dbName = tablePath.getDatabaseName();
			String tableName = tablePath.getObjectName();
			List<String> partitionColNames = catalogTable.getPartitionKeys();
			Table hiveTable = client.getTable(dbName, tableName);
			Properties tableProps = HiveReflectionUtils.getTableMetadata(hiveShim, hiveTable);
			String ttlStr = tableProps.getProperty(FileSystemOptions.LOOKUP_JOIN_CACHE_TTL.key());
			hiveTableCacheTTL = ttlStr != null ?
					TimeUtils.parseDuration(ttlStr) :
					FileSystemOptions.LOOKUP_JOIN_CACHE_TTL.defaultValue();
			if (partitionColNames != null && partitionColNames.size() > 0) {
				final String defaultPartitionName = jobConf.get(HiveConf.ConfVars.DEFAULTPARTITIONNAME.varname,
						HiveConf.ConfVars.DEFAULTPARTITIONNAME.defaultStrVal);
				List<Partition> partitions = new ArrayList<>();
				if (remainingPartitions != null) {
					for (Map<String, String> spec : remainingPartitions) {
						partitions.add(client.getPartition(dbName, tableName, partitionSpecToValues(spec, partitionColNames)));
					}
				} else {
					partitions.addAll(client.listPartitions(dbName, tableName, (short) -1));
				}
				for (Partition partition : partitions) {
					HiveTablePartition hiveTablePartition = toHiveTablePartition(
							catalogTable.getPartitionKeys(),
							catalogTable.getSchema().getFieldNames(),
							catalogTable.getSchema().getFieldDataTypes(),
							hiveShim,
							tableProps,
							defaultPartitionName,
							partition);
					allHivePartitions.add(hiveTablePartition);
				}
			} else {
				allHivePartitions.add(new HiveTablePartition(hiveTable.getSd(), tableProps));
			}
		} catch (TException e) {
			throw new FlinkHiveException("Failed to collect all partitions from hive metaStore", e);
		}
		return allHivePartitions;
	}

	public static HiveTablePartition toHiveTablePartition(
			List<String> partitionKeys,
			String[] fieldNames,
			DataType[] fieldTypes,
			HiveShim shim,
			Properties tableProps,
			String defaultPartitionName,
			Partition partition) {
		StorageDescriptor sd = partition.getSd();
		Map<String, Object> partitionColValues = new HashMap<>();
		List<String> nameList = Arrays.asList(fieldNames);
		for (int i = 0; i < partitionKeys.size(); i++) {
			String partitionColName = partitionKeys.get(i);
			String partitionValue = partition.getValues().get(i);
			DataType type = fieldTypes[nameList.indexOf(partitionColName)];
			Object partitionObject;
			if (defaultPartitionName.equals(partitionValue)) {
				LogicalTypeRoot typeRoot = type.getLogicalType().getTypeRoot();
				// while this is inline with Hive, seems it should be null for string columns as well
				partitionObject = typeRoot == LogicalTypeRoot.CHAR || typeRoot == LogicalTypeRoot.VARCHAR ? defaultPartitionName : null;
			} else {
				partitionObject = restorePartitionValueFromFromType(shim, partitionValue, type);
			}
			partitionColValues.put(partitionColName, partitionObject);
		}
		return new HiveTablePartition(sd, partitionColValues, tableProps);
	}

	private static List<String> partitionSpecToValues(Map<String, String> spec, List<String> partitionColNames) {
		Preconditions.checkArgument(spec.size() == partitionColNames.size() && spec.keySet().containsAll(partitionColNames),
				"Partition spec (%s) and partition column names (%s) doesn't match", spec, partitionColNames);
		return partitionColNames.stream().map(spec::get).collect(Collectors.toList());
	}

	private static Object restorePartitionValueFromFromType(HiveShim shim, String valStr, DataType type) {
		LogicalTypeRoot typeRoot = type.getLogicalType().getTypeRoot();
		//note: it's not a complete list ofr partition key types that Hive support, we may need add more later.
		switch (typeRoot) {
			case CHAR:
			case VARCHAR:
				return valStr;
			case BOOLEAN:
				return Boolean.parseBoolean(valStr);
			case TINYINT:
				return Integer.valueOf(valStr).byteValue();
			case SMALLINT:
				return Short.valueOf(valStr);
			case INTEGER:
				return Integer.valueOf(valStr);
			case BIGINT:
				return Long.valueOf(valStr);
			case FLOAT:
				return Float.valueOf(valStr);
			case DOUBLE:
				return Double.valueOf(valStr);
			case DATE:
				return HiveInspectors.toFlinkObject(
						HiveInspectors.getObjectInspector(type),
						shim.toHiveDate(Date.valueOf(valStr)),
						shim);
			case TIMESTAMP_WITHOUT_TIME_ZONE:
				return HiveInspectors.toFlinkObject(
						HiveInspectors.getObjectInspector(type),
						shim.toHiveTimestamp(Timestamp.valueOf(valStr)),
						shim);
			default:
				break;
		}
		throw new FlinkHiveException(
				new IllegalArgumentException(String.format("Can not convert %s to type %s for partition value", valStr, type)));
	}

	@Override
	public String explainSource() {
		String explain = String.format(" TablePath: %s, PartitionPruned: %s, PartitionNums: %d",
				tablePath.getFullName(), partitionPruned, null == remainingPartitions ? null : remainingPartitions.size());
		if (projectedFields != null) {
			explain += ", ProjectedFields: " + Arrays.toString(projectedFields);
		}
		if (isLimitPushDown) {
			explain += String.format(", LimitPushDown %s, Limit %d", isLimitPushDown, limit);
		}
		return TableConnectorUtils.generateRuntimeName(getClass(), getTableSchema().getFieldNames()) + explain;
	}

	@Override
	public TableFunction<RowData> getLookupFunction(String[] lookupKeys) {
		List<HiveTablePartition> allPartitions = initAllPartitions();
		TableSchema producedSchema = getProducedTableSchema();
		return new FileSystemLookupFunction<>(
				getInputFormat(allPartitions, flinkConf.get(HiveOptions.TABLE_EXEC_HIVE_FALLBACK_MAPRED_READER)),
				lookupKeys,
				producedSchema.getFieldNames(),
				producedSchema.getFieldDataTypes(),
				hiveTableCacheTTL
		);
	}

	@Override
	public AsyncTableFunction<RowData> getAsyncLookupFunction(String[] lookupKeys) {
		throw new UnsupportedOperationException("Hive table doesn't support async lookup");
	}

	@Override
	public boolean isAsyncEnabled() {
		return false;
	}
}


text:
package org.apache.geode.internal.admin.remote;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.geode.DataSerializer;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.PooledDistributionMessage;
import org.apache.geode.internal.admin.StatAlertDefinition;
import org.apache.geode.internal.admin.StatAlertsManager;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;

/**
 * distribution message to register alert's definition {@link StatAlertDefinition} to member's alert
 * manager {@link StatAlertsManager}
 *
 */
public class UpdateAlertDefinitionMessage extends PooledDistributionMessage {

  public static final int ADD_ALERT_DEFINITION = 1;

  public static final int UPDATE_ALERT_DEFINITION = 2;

  public static final int REMOVE_ALERT_DEFINITION = 3;

  private StatAlertDefinition[] _alertDefinitions;

  private int _actionCode;

  /**
   * Returns a FetchHostRequest to be sent to the specified recipient.
   *
   * @param alertDefs an array of stat alert definitions to set
   * @param actionCode either of ADD_ALERT_DEFINITION, UPDATE_ALERT_DEFINITION,
   *        REMOVE_ALERT_DEFINITION
   */

  public static UpdateAlertDefinitionMessage create(StatAlertDefinition[] alertDefs,
      int actionCode) {

    UpdateAlertDefinitionMessage m = new UpdateAlertDefinitionMessage();
    m._alertDefinitions = alertDefs;
    m._actionCode = actionCode;

    return m;

  }

  public UpdateAlertDefinitionMessage() {

  }

  @Override
  public void toData(DataOutput out,
      SerializationContext context) throws IOException {
    super.toData(out, context);
    out.writeByte(_actionCode);
    DataSerializer.writeObjectArray(this._alertDefinitions, out);
  }

  @Override
  public void fromData(DataInput in,
      DeserializationContext context) throws IOException, ClassNotFoundException {
    super.fromData(in, context);
    this._actionCode = in.readByte();
    this._alertDefinitions = (StatAlertDefinition[]) DataSerializer.readObjectArray(in);
  }

  /**
   * Returns the DataSerializer fixed id for the class that implements this method.
   */
  @Override
  public int getDSFID() {
    return UPDATE_ALERTS_DEFN_MESSAGE;
  }

  @Override
  protected void process(ClusterDistributionManager dm) {
    StatAlertsManager.getInstance(dm).updateAlertDefinition(_alertDefinitions, _actionCode);
  }

  /**
   * @return list of stat alert definitions
   */
  public StatAlertDefinition[] getAlertDefinitions() {
    return _alertDefinitions;
  }

  /**
   *
   * @return action(ADD_ALERT_DEFINITION, UPDATE_ALERT_DEFINITION, REMOVE_ALERT_DEFINITION) to be
   *         taken on alert definitions
   *
   */
  public int getActionCode() {
    return _actionCode;
  }

  /**
   *
   * @param alertDefinitions List of stat alert definitions
   * @param actionCode Action(ADD_ALERT_DEFINITION, UPDATE_ALERT_DEFINITION,
   *        REMOVE_ALERT_DEFINITION) to be taken on alert definitions
   */
  public void updateAlertDefinition(StatAlertDefinition[] alertDefinitions, int actionCode) {
    _alertDefinitions = alertDefinitions;
    _actionCode = actionCode;
  }

  /**
   * Returns String representation of this message object.
   *

   * 1. if the internalDS instance is not null & is connected, the returned string contains the
   * string as "... to [intended DistributedMember] from [sender DistributedMember]".
   *

   * 2. if the internalDS instance is null or is dis-connected, the returned string is -
   * "InternalDistributedSystem instance not found, no connection with DistributedSystem."
   *
   * @return String representation of this message object.
   */
  @Override
  public String toString() {
    // instance specific for VM that executes this
    InternalDistributedSystem internalDS = InternalDistributedSystem.getAnyInstance();

    String stringInfo = "";

    if (internalDS != null && internalDS.isConnected()) {
      stringInfo = "Add/update the alert definitions" + " to " + internalDS.getDistributedMember()
          + " from " + this.getSender();
    } else { // when no DS instance found in current VM
      stringInfo = "InternalDistributedSystem instance not found, "
          + "no connection with DistributedSystem.";
    }
    return stringInfo;
  }
}


text:
package model.facebook

import spray.json._

case class FacebookOauth2Response(id: String, email: String, name: String)

object FacebookOauth2Response extends DefaultJsonProtocol {

  implicit object FacebookOauth2ResponseFormat extends RootJsonFormat[FacebookOauth2Response] {
    def write(response: FacebookOauth2Response) =
      JsArray(JsString(response.id), JsString(response.email), JsString(response.name))

    def read(value: JsValue): FacebookOauth2Response = value.asJsObject.getFields("id", "email", "name") match {
      case Seq(JsString(id), JsString(email), JsString(name)) => FacebookOauth2Response(id, email, name)
      case _ => throw DeserializationException("FacebookOauth2Response expected")
    }
  }

}


text:
function MessageInfoCtrl($scope, $routeParams, $sce, Message, Inbox) {
    $scope.inbox = Inbox.get({inboxId: $routeParams.inboxId});
    $scope.message = Message.get({messageId: $routeParams.messageId}, function (message) {
        message.body_html = $sce.trustAsHtml(message.body_html);
    });
}


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Elix CalendarMonth (English/Great Britain)</title>

    <link rel="stylesheet" href="demos.css" />
    <script type="module" src="../define/CalendarMonth.js"></script>
  </head>

  <body role="main">
    <div class="demo padded">
      <elix-calendar-month locale="en-GB"></elix-calendar-month>
    </div>
  </body>
</html>


text:
var offset = 0;
var sliders = [];

function setup() {
  noCanvas();
  // Make a whole bunch of sliders and fill an array
  for (var i = 0; i < 200; i++) {
    var slider = createSlider(0, 100, 50);
    sliders.push(slider);
  }
}

function draw() {
  // Set the position of each slider dynamically using map()
  for (var i = 0; i < sliders.length; i++) {
    // Arbitrary angle
    var angle = offset + i / 46;
    // Map sine function to range from 0 to 100 for slider
    var n = map(sin(angle), -1, 1, 0, 100);
    // Control the slider
    sliders[i].value(n);
  }
  offset += 0.1;
}


text:
import defined from "../Core/defined.js";
import SphereGeometry from "../Core/SphereGeometry.js";

function createSphereGeometry(sphereGeometry, offset) {
  if (defined(offset)) {
    sphereGeometry = SphereGeometry.unpack(sphereGeometry, offset);
  }
  return SphereGeometry.createGeometry(sphereGeometry);
}
export default createSphereGeometry;


text:
define(
  'tinymce.plugins.table.queries.TableTargets',

  [
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Option',
    'ephox.katamari.api.Struct',
    'tinymce.plugins.table.queries.CellOperations'
  ],

  function (Fun, Option, Struct, CellOperations) {
    var noMenu = function (cell) {
      return {
        element: Fun.constant(cell),
        mergable: Option.none,
        unmergable: Option.none,
        selection: Fun.constant([cell])
      };
    };

    var forMenu = function (selections, table, cell) {
      return {
        element: Fun.constant(cell),
        mergable: Fun.constant(CellOperations.mergable(table, selections)),
        unmergable: Fun.constant(CellOperations.unmergable(cell, selections)),
        selection: Fun.constant(CellOperations.selection(cell, selections))
      };
    };

    var notCell = function (element) {
      return noMenu(element);
    };

    var paste = Struct.immutable('element', 'clipboard', 'generators');

    var pasteRows = function (selections, table, cell, clipboard, generators) {
      return {
        element: Fun.constant(cell),
        mergable: Option.none,
        unmergable: Option.none,
        selection: Fun.constant(CellOperations.selection(cell, selections)),
        clipboard: Fun.constant(clipboard),
        generators: Fun.constant(generators)
      };
    };

    return {
      noMenu: noMenu,
      forMenu: forMenu,
      notCell: notCell,
      paste: paste,
      pasteRows: pasteRows
    };
  }
);


text:
using System.ComponentModel;

namespace NMockaroo.Attributes
{
    /// <summary>
    ///     Represents the Mockaroo Url type
    /// </summary>
    public class MockArooUrlAttribute : MockarooInfoAttribute
    {
        /// <summary>
        ///     True to include a protocol in the url.
        /// </summary>
        [DefaultValue(true)]
        public bool IncludeProtocol { get; set; }

        /// <summary>
        ///     True to include a protocol in the url
        /// </summary>
        [DefaultValue(true)]
        public bool IncludeHost { get; set; }

        /// <summary>
        ///     True to include a path in the url
        /// </summary>
        [DefaultValue(true)]
        public bool IncludePath { get; set; }

        /// <summary>
        ///     True to include a query string in the url
        /// </summary>
        [DefaultValue(true)]
        public bool IncludeQueryString { get; set; }
    }
}


text:
package hqt.designpatterns.patterns.observer.javaexample;

public interface DisplayElement {
	public void display();
}


text:
export interface PredictedEnvVariableInterface {
    name: string;
    value?: string;
    pattern?: string;
}