text:
require 'evapotranspiration/validation'

module Evapotranspiration

  # Methods for estimating reference evapotransporation (ETo) for
  # a grass reference crop using the FAO-56 Penman-Monteith and Hargreaves
  # equations. The library includes numerous methods for estimating missing
  # meteorological data.
  module FAO
    include Enumerable

    # Solar constant [ MJ m-2 min-1]
    SOLAR_CONSTANT = 0.0820

    # Stefan Boltzmann constant [MJ K-4 m-2 day-1]
    STEFAN_BOLTZMANN_CONSTANT = 0.000000004903

    # Estimate atmospheric pressure from altitude.
    #
    # Calculated using a simplification of the ideal gas law, assuming 20 degrees
    # Celsius for a standard atmosphere. Based on equation 7, page 62 in Allen
    # et al (1998).
    #
    # @param altitude [Float] Elevation/altitude above sea level (m)
    # @return [Float] atmospheric pressure (kPa)
    def self.atm_pressure(altitude)
      tmp = (293.0 - (0.0065 * altitude.to_f)) / 293.0
      return (tmp.to_f ** 5.26) * 101.3
    end

    # Estimate actual vapour pressure (*ea*) from minimum temperature.
    #
    # This method is to be used where humidity data are lacking or are of
    # questionable quality. The method assumes that the dewpoint temperature
    # is approximately equal to the minimum temperature (*tmin*), i.e. the
    # air is saturated with water vapour at *tmin*.
    #
    # **Note**: This assumption may not hold in arid/semi-arid areas.
    # In these areas it may be better to subtract 2 deg C from the
    # minimum temperature (see Annex 6 in FAO paper).
    #
    # Based on equation 48 in Allen et al (1998).
    #
    # @param tmin [Float] Daily minimum temperature (deg C)
    # @return [Float] Actual vapour pressure (kPa)
    def self.avp_from_tmin(tmin)
      return 0.611 * Math.exp((17.27 * tmin.to_f) / (tmin.to_f + 237.3))
    end

    # Estimate actual vapour pressure (*ea*) from saturation vapour pressure and
    # relative humidity.
    #
    # Based on FAO equation 17 in Allen et al (1998).
    #
    # @param svp_tmin [Float] Saturation vapour pressure at daily minimum
    #   temperature (kPa). Can be estimated using svp_from_t
    # @param svp_tmax [Float] Saturation vapour pressure at daily maximum
    #   temperature (kPa). Can be estimated using svp_from_t
    # @param rh_min [Float] Minimum relative humidity (%)
    # @param rh_max [Float] Maximum relative humidity (%)
    # @return [Float] Actual vapour pressure (kPa)
    def self.avp_from_rhmin_rhmax(svp_tmin, svp_tmax, rh_min, rh_max)
      tmp1 = svp_tmin.to_f * (rh_max.to_f / 100.0)
      tmp2 = svp_tmax.to_f * (rh_min.to_f / 100.0)
      return (tmp1.to_f + tmp2.to_f) / 2.0
    end

    # Estimate actual vapour pressure (*ea*) from saturation vapour pressure at
    # daily minimum and maximum temperature, and mean relative humidity.
    #
    # Based on FAO equation 19 in Allen et al (1998).
    #
    # @param svp_tmin [Float] Saturation vapour pressure at daily minimum
    #   temperature (kPa). Can be estimated using svp_from_t
    # @param rh_max [Float] Maximum relative humidity (%)
    # @return [Float] Actual vapour pressure (kPa)
    def self.avp_from_rhmax(svp_tmin, rh_max)
      return svp_tmin.to_f * (rh_max.to_f / 100.0)
    end

    # Estimate actual vapour pressure (*e*a) from saturation vapour pressure at
    # daily minimum temperature and maximum relative humidity.
    #
    # Based on FAO equation 18 in Allen et al (1998).
    #
    # @param svp_tmin [Float] Saturation vapour pressure at daily minimum
    #   temperature (kPa). Can be estimated using svp_from_t
    # @param svp_tmax [Float] Saturation vapour pressure at daily maximum
    #   temperature (kPa). Can be estimated using svp_from_t
    # @param rh_mean [Float] Mean relative humidity (%) (average of RH min and RH max).
    # @return [Float] Actual vapour pressure (kPa)
    def self.avp_from_rhmean(svp_tmin, svp_tmax, rh_mean)
      return (rh_mean.to_f / 100.0) * ((svp_tmax.to_f + svp_tmin.to_f) / 2.0)
    end

    # Estimate actual vapour pressure (*ea*) from dewpoint temperature.
    #
    # Based on equation 14 in Allen et al (1998). As the dewpoint temperature is
    # the temperature to which air needs to be cooled to make it saturated, the
    # actual vapour pressure is the saturation vapour pressure at the dewpoint
    # temperature.
    #
    # This method is preferable to calculating vapour pressure from
    # minimum temperature.
    #
    # @param tdew [Float] Dewpoint temperature (deg C)
    # @return [Float] Actual vapour pressure (kPa)
    def self.avp_from_tdew(tdew)
      return 0.6108 * Math.exp((17.27 * tdew.to_f) / (tdew.to_f + 237.3))
    end

    # Estimate actual vapour pressure (*ea*) from wet and dry bulb temperature.
    #
    # Based on equation 15 in Allen et al (1998). As the dewpoint temperature
    # is the temperature to which air needs to be cooled to make it saturated, the
    # actual vapour pressure is the saturation vapour pressure at the dewpoint
    # temperature.
    #
    # This method is preferable to calculating vapour pressure from
    # minimum temperature.
    #
    # Values for the psychrometric constant of the psychrometer (*psy_const*)
    # can be calculated using psyc_const_of_psychrometer.
    #
    # @param twet [Float] Wet bulb temperature (deg C)
    # @param tdry [Float] Dry bulb temperature (deg C)
    # @param svp_twet [Float] Saturated vapour pressure at the wet bulb
    #   temperature (kPa). Can be estimated using svp_from_t
    # @param psy_const [Float] Psychrometric constant of the pyschrometer
    #   (kPa deg C-1). Can be estimated using psy_const or
    #   psy_const_of_psychrometer
    # @return [Float] Actual vapour pressure (kPa)
    def self.avp_from_twet_tdry(twet, tdry, svp_twet, psy_const)
      return svp_twet.to_f - (psy_const.to_f * (tdry.to_f - twet.to_f))
    end

    # Estimate clear sky radiation from altitude and extraterrestrial radiation.
    #
    # Based on equation 37 in Allen et al (1998) which is recommended when
    # calibrated Angstrom values are not available.
    #
    # @param altitude [Float] Elevation above sea level (m)
    # @param et_rad [Float] Extraterrestrial radiation (MJ m-2 day-1). Can be
    #   estimated using et_rad
    # @return [Float] Clear sky radiation (MJ m-2 day-1)
    def self.cs_rad(altitude, et_rad)
      return (0.00002 * altitude.to_f + 0.75) * et_rad.to_f
    end

    # Estimate mean daily temperature from the daily minimum and maximum
    # temperatures.
    #
    # @param tmin [Float] Minimum daily temperature (deg C)
    # @param tmax [Float] Maximum daily temperature (deg C)
    # @return [Float] Mean daily temperature (deg C)
    def self.daily_mean_t(tmin, tmax)
      return (tmax.to_f + tmin.to_f) / 2.0
    end

    # Calculate daylight hours from sunset hour angle.
    #
    # Based on FAO equation 34 in Allen et al (1998).
    #
    # @param sha [Float] Sunset hour angle (rad). Can be calculated using
    #   sunset_hour_angle
    # @return [Float] Daylight hours
    def self.daylight_hours(sha)
      Validation.check_sunset_hour_angle_rad(sha)
      return (24.0 / Math::PI) * sha.to_f
    end

    # Estimate the slope of the saturation vapour pressure curve at a given
    # temperature.
    #
    # Based on equation 13 in Allen et al (1998). If using in the Penman-Monteith
    # *t* should be the mean air temperature.
    #
    # @param t [Float] Air temperature (deg C). Use mean air temperature for
    #   use in Penman-Monteith
    # @return [Float] Saturation vapour pressure (kPa degC-1)
    def self.delta_svp(t)
      tmp = 4098 * (0.6108 * Math.exp((17.27 * t.to_f) / (t.to_f + 237.3)))
      return tmp.to_f / ((t.to_f + 237.3) ** 2)
    end

    # Convert energy (e.g. radiation energy) in MJ m-2 day-1 to the equivalent
    # evaporation, assuming a grass reference crop.
    #
    # Energy is converted to equivalent evaporation using a conversion
    # factor equal to the inverse of the latent heat of vapourisation
    # (1 / lambda = 0.408).
    #
    # Based on FAO equation 20 in Allen et al (1998).
    #
    # @param energy [Float] Energy e.g. radiation or heat flux (MJ m-2 day-1)
    # @return [Float] Equivalent evaporation (mm day-1)
    def self.energy_to_evap(energy)
      return 0.408 * energy.to_f
    end

    # Estimate daily extraterrestrial radiation (*Ra*, 'top of the atmosphere
    # radiation').
    #
    # Based on equation 21 in Allen et al (1998). If monthly mean radiation is
    # required make sure *sol_dec*. *sha* and *irl* have been calculated using
    # the day of the year that corresponds to the middle of the month.
    #
    # **Note**: From Allen et al (1998): "For the winter months in latitudes
    # greater than 55 degrees (N or S), the equations have limited validity.
    # Reference should be made to the Smithsonian Tables to assess possible
    # deviations."
    #
    # @param latitude [Float] Latitude (radians)
    # @param sol_dec [Float] Solar declination (radians). Can be calculated
    #   using sol_dec
    # @param sha [Float] Sunset hour angle (radians). Can be calculated using
    #   sunset_hour_angle
    # @param ird [Float] Inverse relative distance earth-sun (dimensionless).
    #   Can be calculated using inv_rel_dist_earth_sun
    # @return [Float] Daily extraterrestrial radiation (MJ m-2 day-1)
    def self.et_rad(latitude, sol_dec, sha, ird)
      Validation.check_latitude_rad(latitude)
      Validation.check_sol_dec_rad(sol_dec)
      Validation.check_sunset_hour_angle_rad(sha)

      tmp1 = (24.0 * 60.0) / Math::PI
      tmp2 = sha.to_f * Math.sin(latitude) * Math.sin(sol_dec.to_f)
      tmp3 = Math.cos(latitude.to_f) * Math.cos(sol_dec.to_f) * Math.sin(sha.to_f)
      return tmp1.to_f * SOLAR_CONSTANT * ird.to_f * (tmp2.to_f + tmp3.to_f)
    end

    # Estimate reference evapotranspiration (ETo) from a hypothetical
    # short grass reference surface using the FAO-56 Penman-Monteith equation.
    #
    # Based on equation 6 in Allen et al (1998).
    #
    # @param net_rad [Float] Net radiation at crop surface (MJ m-2 day-1). If
    #   necessary this can be estimated using net_rad
    # @param t [Float] Air temperature at 2 m height (deg Kelvin)
    # @param ws [Float] Wind speed at 2 m height (m s-1). If not measured at 2m,
    #   convert using wind_speed_at_2m
    # @param svp [Float] Saturation vapour pressure (kPa). Can be estimated
    #   using svp_from_t
    # @param avp [Float] Actual vapour pressure (kPa). Can be estimated using a
    #   range of methods with names beginning with avp_from
    # @param delta_svp [Float] Slope of saturation vapour pressure curve
    #   (kPa degC-1). Can be estimated using delta_svp
    # @param psy [Float] Psychrometric constant (kPa deg C). Can be estimatred
    #   using psy_const_of_psychrometer or psy_const
    # @param shf [Float] Soil heat flux (G) (MJ m-2 day-1) (default is 0.0,
    #   which is reasonable for a daily or 10-day time steps). For monthly time
    #   steps *shf* can be estimated using monthly_soil_heat_flux or
    #   monthly_soil_heat_flux2
    # @return [Float] Reference evapotranspiration (ETo) from a hypothetical
    #   grass reference surface (mm day-1)
    def self.fao56_penman_monteith(net_rad, t, ws, svp, avp, delta_svp, psy, shf=0.0)
      a1 = (0.408 * (net_rad.to_f - shf.to_f) * delta_svp.to_f / (delta_svp.to_f + (psy.to_f * (1 + 0.34 * ws.to_f))))
      a2 = (900 * ws.to_f / t.to_f * (svp.to_f - avp.to_f) * psy.to_f / (delta_svp.to_f + (psy.to_f * (1 + 0.34 * ws.to_f))))
      return a1.to_f + a2.to_f
    end

    # Estimate reference evapotranspiration over grass (ETo) using the Hargreaves
    # equation.
    #
    # Generally, when solar radiation data, relative humidity data
    # and/or wind speed data are missing, it is better to estimate them using
    # the methods available in this module, and then calculate ETo
    # the FAO Penman-Monteith equation. However, as an alternative, ETo can be
    # estimated using the Hargreaves ETo equation.
    #
    # Based on equation 52 in Allen et al (1998).
    #
    # @param tmin [Float] Minimum daily temperature (deg C)
    # @param tmax [Float] Maximum daily temperature (deg C)
    # @param tmean [Float] Mean daily temperature (deg C). If measurements not
    #   available it can be estimated as (*tmin* + *tmax*) / 2
    # @param et_rad [Float] Extraterrestrial radiation (Ra) (MJ m-2 day-1).
    #   Can be estimated using et_rad
    # @return [Float] Reference evapotranspiration over grass (ETo) (mm day-1)
    def self.hargreaves(tmin, tmax, tmean, et_rad)
      # Note, multiplied by 0.408 to convert extraterrestrial radiation could
      # be given in MJ m-2 day-1 rather than as equivalent evaporation in
      # mm day-1
      return 0.0023 * (tmean.to_f + 17.8) * (tmax.to_f - tmin.to_f) ** 0.5 * 0.408 * et_rad.to_f
    end

    # Calculate the inverse relative distance between earth and sun from
    # day of the year.
    #
    # Based on FAO equation 23 in Allen et al (1998).
    #
    # @param day_of_year [Integer] Day of the year (1 to 366)
    # @return [Float] Inverse relative distance between earth and the sun
    def self.inv_rel_dist_earth_sun(day_of_year)
      Validation.check_doy(day_of_year)
      return 1 + (0.033 * Math.cos((2.0 * Math::PI / 365.0) * day_of_year.to_f))
    end

    # Estimate mean saturation vapour pressure, *es* [kPa] from minimum and
    # maximum temperature.
    #
    # Based on equations 11 and 12 in Allen et al (1998).
    #
    # Mean saturation vapour pressure is calculated as the mean of the
    # saturation vapour pressure at tmax (maximum temperature) and tmin
    # (minimum temperature).
    #
    # @param tmin [Float] Minimum temperature (deg C)
    # @param tmax [Float] Maximum temperature (deg C)
    # @return [Float] Mean saturation vapour pressure (*es*) (kPa)
    def self.mean_svp(tmin, tmax)
      return (self.svp_from_t(tmin.to_f) + self.svp_from_t(tmax.to_f)) / 2.0
    end

    # Estimate monthly soil heat flux (Gmonth) from the mean air temperature of
    # the previous and next month, assuming a grass crop.
    #
    # Based on equation 43 in Allen et al (1998). If the air temperature of the
    # next month is not known use monthly_soil_heat_flux2 instead. The
    # resulting heat flux can be converted to equivalent evaporation [mm day-1]
    # using energy_to_evap.
    #
    # @param t_month_prev [Float] Mean air temperature of the previous month
    #   (deg Celsius)
    # @param t_month_next [Float] Mean air temperature of the next month
    #   (deg Celsius)
    # @return [Float] Monthly soil heat flux (Gmonth) (MJ m-2 day-1)
    def self.monthly_soil_heat_flux(t_month_prev, t_month_next)
      return 0.07 * (t_month_next.to_f - t_month_prev.to_f)
    end

    # Estimate monthly soil heat flux (Gmonth) from the mean air temperature of
    # the previous and next month, assuming a grass crop.
    #
    # Based on equation 44 in Allen et al (1998). If the air temperature of the
    # next month is available, use monthly_soil_heat_flux instead. The
    # resulting heat flux can be converted to equivalent evaporation [mm day-1]
    # using energy_to_evap.
    #
    # @param t_month_prev [Float] Mean air temperature of the previous month
    #   (deg Celsius)
    # @param t_month_cur [Float] Mean air temperature of the current month
    #   (deg Celsius)
    # @return [Float] Monthly soil heat flux (Gmonth) (MJ m-2 day-1)
    def self.monthly_soil_heat_flux2(t_month_prev, t_month_cur)
      return 0.14 * (t_month_cur.to_f - t_month_prev.to_f)
    end

    # Calculate net incoming solar (or shortwave) radiation from gross
    # incoming solar radiation, assuming a grass reference crop.
    #
    # Net incoming solar radiation is the net shortwave radiation resulting
    # from the balance between incoming and reflected solar radiation. The
    # output can be converted to equivalent evaporation [mm day-1] using
    # energy_to_evap.
    #
    # Based on FAO equation 38 in Allen et al (1998).
    #
    # @param sol_rad [Float] Gross incoming solar radiation (MJ m-2 day-1).
    #   If necessary this can be estimated using methods whose name begins
    #   with sol_rad_from
    # @param albedo [Float] Albedo of the crop as the proportion of gross
    #   incoming solar radiation that is reflected by the surface. Default value
    #   is 0.23, which is the value used by the FAO for a short grass reference
    #   crop. Albedo can be as high as 0.95 for freshly fallen snow and as low
    #   as 0.05 for wet bare soil. A green vegetation over has an albedo of
    #   about 0.20-0.25 (Allen et al, 1998)
    # @return [Float] Net incoming solar (or shortwave) radiation (MJ m-2 day-1)
    def self.net_in_sol_rad(sol_rad, albedo=0.23)
      return (1 - albedo.to_f) * sol_rad.to_f
    end

    # Estimate net outgoing longwave radiation.
    #
    # This is the net longwave energy (net energy flux) leaving the
    # earth's surface. It is proportional to the absolute temperature of
    # the surface raised to the fourth power according to the Stefan-Boltzmann
    # law. However, water vapour, clouds, carbon dioxide and dust are absorbers
    # and emitters of longwave radiation. This method corrects the Stefan-
    # Boltzmann law for humidity (using actual vapor pressure) and cloudiness
    # (using solar radiation and clear sky radiation). The concentrations of all
    # other absorbers are assumed to be constant.
    #
    # The output can be converted to equivalent evaporation [mm day-1] using energy_to_evap.
    #
    # Based on FAO equation 39 in Allen et al (1998).
    #
    # @param tmin [Float] Absolute daily minimum temperature (degrees Kelvin)
    # @param albedo [Float] Absolute daily maximum temperature (degrees Kelvin)
    # @param sol_rad [Float] Solar radiation (MJ m-2 day-1). If necessary this
    #   can be estimated using methods with names beginning with sol_rad
    # @param cs_rad [Float] Clear sky radiation (MJ m-2 day-1). Can be estimated
    #   using cs_rad
    # @param avp [Float] Actual vapour pressure (kPa). Can be estimated using
    #   methods with names beginning with avp_from
    # @return [Float] Net outgoing longwave radiation (MJ m-2 day-1)
    def self.net_out_lw_rad(tmin, tmax, sol_rad, cs_rad, avp)
      tmp1 = (STEFAN_BOLTZMANN_CONSTANT * (((tmax.to_f ** 4) + (tmin.to_f ** 4)) / 2))
      tmp2 = (0.34 - (0.14 * Math.sqrt(avp.to_f)))
      tmp3 = 1.35 * (sol_rad.to_f / cs_rad.to_f) - 0.35
      return tmp1.to_f * tmp2.to_f * tmp3.to_f
    end

    # Calculate daily net radiation at the crop surface, assuming a grass
    # reference crop.
    #
    # Net radiation is the difference between the incoming net shortwave (or
    # solar) radiation and the outgoing net longwave radiation. Output can be
    # converted to equivalent evaporation [mm day-1] using energy_to_evap.
    #
    # Based on equation 40 in Allen et al (1998).
    #
    # @param ni_sw_rad [Float] Net incoming shortwave radiation (MJ m-2 day-1).
    #   Can be estimated using net_in_sol_rad
    # @param no_lw_rad [Float] Net outgoing longwave radiation (MJ m-2 day-1).
    #   Can be estimated using net_out_lw_rad
    # @return [Float] Daily net radiation (MJ m-2 day-1)
    def self.net_rad(ni_sw_rad, no_lw_rad)
      return ni_sw_rad.to_f - no_lw_rad.to_f
    end

    # Calculate the psychrometric constant.
    #
    # This method assumes that the air is saturated with water vapour at the
    # minimum daily temperature. This assumption may not hold in arid areas.
    #
    # Based on equation 8, page 95 in Allen et al (1998).
    #
    # @param atmos_pres [Float] Atmospheric pressure (kPa). Can be estimated
    #   using atm_pressure
    # @return [Float] Psychrometric constant (kPa degC-1)
    def self.psy_const(atmos_pres)
      return 0.000665 * atmos_pres.to_f
    end

    # Calculate the psychrometric constant for different types of
    # psychrometer at a given atmospheric pressure.
    #
    # Based on FAO equation 16 in Allen et al (1998).
    #
    # psychrometer types:
    # 1. ventilated (Asmann or aspirated type) psychrometer with an air movement of approximately 5 m/s
    # 2. natural ventilated psychrometer with an air movement of approximately 1 m/s
    # 3. non ventilated psychrometer installed indoors
    #
    # @param psychrometer [Float] Integer between 1 and 3 which denotes type of
    #   psychrometer
    # @param atmos_pres [Float] Atmospheric pressure [kPa]. Can be estimated
    #   using atm_pressure
    # @return [Float] Psychrometric constant (kPa degC-1)
    def self.psy_const_of_psychrometer(psychrometer, atmos_pres)
      # Select coefficient based on type of ventilation of the wet bulb
      case psychrometer
      when 1
        psy_coeff = 0.000662
      when 2
        psy_coeff = 0.000800
      when 3
        psy_coeff = 0.001200
      else
        raise ArgumentError.new("psychrometer should be in range 1 to 3: #{psychrometer}")
      end

      return psy_coeff.to_f * atmos_pres.to_f
    end

    # Calculate relative humidity as the ratio of actual vapour pressure
    # to saturation vapour pressure at the same temperature.
    #
    # See Allen et al (1998), page 67 for details.
    #
    # @param avp [Float] Actual vapour pressure (units do not matter so long as
    #   they are the same as for *svp*). Can be estimated using methods whose
    #   name begins with avp_from
    # @param svp [Float] Saturated vapour pressure (units do not matter so long
    #   as they are the same as for *avp*). Can be estimated using svp_from_t
    # @return [Float] Relative humidity (%)
    def self.rh_from_avp_svp(avp, svp)
      return 100.0 * avp.to_f / svp.to_f
    end

    # Calculate solar declination from day of the year.
    #
    # Based on FAO equation 24 in Allen et al (1998).
    #
    # @param day_of_year [Integer] Day of year integer between 1 and 365 or 366
    # @return [Float] solar declination (radians)
    def self.sol_dec(day_of_year)
      Validation.check_doy(day_of_year)
      return 0.409 * Math.sin(((2.0 * Math::PI / 365.0) * day_of_year.to_f - 1.39))
    end

    # Calculate incoming solar (or shortwave) radiation, *Rs* (radiation hitting
    # a horizontal plane after scattering by the atmosphere) from relative
    # sunshine duration.
    #
    # If measured radiation data are not available this method is preferable
    # to calculating solar radiation from temperature. If a monthly mean is
    # required then divide the monthly number of sunshine hours by number of
    # days in the month and ensure that *et_rad* and *daylight_hours* was
    # calculated using the day of the year that corresponds to the middle of
    # the month.
    #
    # Based on equations 34 and 35 in Allen et al (1998).
    #
    # @param dl_hours [Integer] Number of daylight hours (hours). Can be
    #   calculated using daylight_hours()
    # @param sunshine_hours [Integer] Sunshine duration (hours). Can be
    #   calculated using sunshine_hours()
    # @param et_rad [Float] Extraterrestrial radiation (MJ m-2 day-1). Can be
    #   estimated using et_rad()
    # @return [Float] Incoming solar (or shortwave) radiation (MJ m-2 day-1)
    def self.sol_rad_from_sun_hours(daylight_hours, sunshine_hours, et_rad)
      Validation.check_day_hours(sunshine_hours, 'sun_hours')
      Validation.check_day_hours(daylight_hours, 'daylight_hours')

      # 0.5 and 0.25 are default values of regression constants (Angstrom values)
      # recommended by FAO when calibrated values are unavailable.
      return (0.5 * sunshine_hours.to_f / daylight_hours.to_f + 0.25) * et_rad.to_f
    end

    # Estimate incoming solar (or shortwave) radiation, *Rs*, (radiation hitting
    # a horizontal plane after scattering by the atmosphere) from min and max
    # temperature together with an empirical adjustment coefficient for
    # 'interior' and 'coastal' regions.
    #
    # The formula is based on equation 50 in Allen et al (1998) which is the
    # Hargreaves radiation formula (Hargreaves and Samani, 1982, 1985). This
    # method should be used only when solar radiation or sunshine hours data are
    # not available. It is only recommended for locations where it is not
    # possible to use radiation data from a regional station (either because
    # climate conditions are heterogeneous or data are lacking).
    #
    # **NOTE**: this method is not suitable for island locations due to the
    # moderating effects of the surrounding water.
    #
    # @param et_rad [Float] Extraterrestrial radiation (MJ m-2 day-1). Can be
    #   estimated using et_rad()
    # @param cs_rad [Float] Clear sky radiation (MJ m-2 day-1). Can be estimated
    #   using cs_rad()
    # @param tmin [Float] Daily minimum temperature (deg C)
    # @param tmax [Float] Daily maximum temperature (deg C)
    # @param coastal [Boolean] True if site is a coastal location, situated on
    #   or adjacent to coast of a large land mass and where air masses are
    #   influenced by a nearby water body, False if interior location where land
    #   mass dominates and air masses are not strongly influenced by a large
    #   water body.
    # @return [Float] Incoming solar (or shortwave) radiation (Rs) (MJ m-2 day-1)
    def self.sol_rad_from_t(et_rad, cs_rad, tmin, tmax, coastal)
      # Determine value of adjustment coefficient [deg C-0.5] for
      # coastal/interior locations
      adj = coastal ? 0.19 : 0.16

      sol_rad = adj.to_f * Math.sqrt(tmax.to_f - tmin.to_f) * et_rad.to_f

      # The solar radiation value is constrained by the clear sky radiation
      return [sol_rad.to_f, cs_rad.to_f].min
    end

    # Estimate incoming solar (or shortwave) radiation, *Rs* (radiation hitting
    # a horizontal plane after scattering by the atmosphere) for an island
    # location.
    #
    # An island is defined as a land mass with width perpendicular to the
    # coastline <= 20 km. Use this method only if radiation data from
    # elsewhere on the island is not available.
    #
    # **NOTE**: This method is only applicable for low altitudes (0-100 m)
    # and monthly calculations.
    #
    # Based on FAO equation 51 in Allen et al (1998).
    #
    # @param et_rad [Float] Extraterrestrial radiation (MJ m-2 day-1). Can be
    #   estimated using et_rad()
    # @return [Float] Incoming solar (or shortwave) radiation (MJ m-2 day-1)
    def self.sol_rad_island(et_rad)
      return (0.7 * et_rad.to_f) - 4.0
    end

    # Calculate sunset hour angle (*Ws*) from latitude and solar
    # declination.
    #
    # Based on FAO equation 25 in Allen et al (1998).
    #
    # @param latitude [Float] Latitude (radians). Note: *latitude* should be
    #   negative if it in the southern hemisphere, positive if in the northern
    #   hemisphere
    # @param sol_dec [Float] Solar declination (radians). Can be calculated
    #   using sol_dec()
    # @return [Float] Sunset hour angle (radians)
    def self.sunset_hour_angle(latitude, sol_dec)
      Validation.check_latitude_rad(latitude)
      Validation.check_sol_dec_rad(sol_dec)

      cos_sha = -Math.tan(latitude.to_f) * Math.tan(sol_dec.to_f)
      # If tmp is >= 1 there is no sunset, i.e. 24 hours of daylight
      # If tmp is <= 1 there is no sunrise, i.e. 24 hours of darkness
      # See http://www.itacanet.org/the-sun-as-a-source-of-energy/
      # part-3-calculating-solar-angles/
      # Domain of acos is -1 <= x <= 1 radians (this is not mentioned in FAO-56!)
      return Math.acos([[cos_sha.to_f, -1.0].max, 1.0].min)
    end

    # Estimate saturation vapour pressure (*es*) from air temperature.
    #
    # Based on equations 11 and 12 in Allen et al (1998).
    #
    # @param t [Float] Temperature (deg C)
    # @return [Float] Saturation vapour pressure (kPa)
    def self.svp_from_t(t)
      return 0.6108 * Math.exp((17.27 * t.to_f) / (t.to_f + 237.3))
    end

    # Convert wind speed measured at different heights above the soil
    # surface to wind speed at 2 m above the surface, assuming a short grass
    # surface.
    #
    # Based on FAO equation 47 in Allen et al (1998).
    #
    # @param ws [Float] Measured wind speed (m s-1)
    # @param z [Float] Height of wind measurement above ground surface (m)
    # @return [Float] Wind speed at 2 m above the surface (m s-1)
    def self.wind_speed_2m(ws, z)
      return ws.to_f * (4.87 / Math.log((67.8 * z.to_f) - 5.42))
    end

  end
end


text:
-- phpMyAdmin SQL Dump
-- version 4.6.5.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 14, 2017 at 02:27 PM
-- Server version: 10.1.21-MariaDB
-- PHP Version: 5.6.30

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
CREATE DATABASE uppharmadown;
USE uppharmadown;
--
-- Database: `uppharmadown`
--

-- --------------------------------------------------------

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `product_id` int(11) NOT NULL,
  `name` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  `dosage` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `generic_name` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `brand` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `quantity` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `name`, `price`, `dosage`, `generic_name`, `brand`, `expiry_date`, `quantity`) VALUES
(1, 'Biogesic', '5.00', '500mg', 'Paracetamol', 'Unilab', '2025-03-20', 200),
(2, 'Medicol', '7.50', '200mg', 'Ibuprofen', 'Unilab', '2025-03-20', 100),
(3, 'Tuseran Forte', '8.50', '350mg', 'Dextromethorphan', 'Unilab', '2025-03-25', 100),
(5, 'Clear', '40.00', '500ml', '', 'Unilever', '2017-06-12', 15);

-- --------------------------------------------------------

--
-- Table structure for table `product_list`
--

CREATE TABLE `product_list` (
  `list_no` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `product_qnty` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `product_list`
--

INSERT INTO `product_list` (`list_no`, `product_id`, `product_qnty`) VALUES
(1, 1, 12),
(1, 2, 10),
(1, 3, 1),
(1, 5, 2),
(2, 1, 12),
(2, 2, 10),
(2, 3, 1),
(2, 5, 2);

-- --------------------------------------------------------

--
-- Table structure for table `product_supplier`
--

CREATE TABLE `product_supplier` (
  `product_id` int(11) DEFAULT NULL,
  `supplier_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `supplier`
--

CREATE TABLE `supplier` (
  `supplier_id` int(11) NOT NULL,
  `company_name` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `address` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
  `contact_no` varchar(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `transac`
--

CREATE TABLE `transac` (
  `transaction_no` int(11) NOT NULL,
  `date_of_transaction` date DEFAULT NULL,
  `transaction_status` enum('PAID','NOTPAID') DEFAULT NULL,
  `list_no` int(11) NOT NULL,
  `consumer_id` int(11) NOT NULL,
  `discount` decimal(5,2) DEFAULT NULL,
  `grand_total` decimal(10,2) DEFAULT NULL,
  `delivery_location` varchar(100) CHARACTER SET utf8 DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `transac`
--

INSERT INTO `transac` (`transaction_no`, `date_of_transaction`, `transaction_status`, `list_no`, `consumer_id`, `discount`, `grand_total`, `delivery_location`) VALUES
(1, '2017-04-14', 'PAID', 1, 1, '0.00', '223.50', 'Puso Center Mactan, Lapu-Lapu City'),
(2, '2017-04-14', 'NOTPAID', 2, 1, '0.00', '223.50', 'Puso Center Mactan, Lapu-Lapu City');

-- --------------------------------------------------------

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `user_id` int(11) NOT NULL,
  `password` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `name` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `dob` date DEFAULT NULL,
  `email` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `address` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
  `contact_no` varchar(11) DEFAULT NULL,
  `type` enum('admin','consumer') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`user_id`, `password`, `name`, `dob`, `email`, `address`, `contact_no`, `type`) VALUES
(1, 'a8a15b230947dffe7d28e9beba511832', 'Ethan Ray Mosqueda', '1998-10-19', 'ethanray19@gmail.com', 'Puso Center Mactan, Lapu-Lapu City', '09561332497', 'consumer'),
(11, '25f9e794323b453885f5181f1b624d0b', 'Robert Michael Lim', '1998-04-04', 'robertmichaellim@yahoo.com', 'Consolacion, Cebu', '09055177511', 'consumer'),
(15, '787c74a2e618a696e34e025adda33ad3', 'Sunny Rainday', '0000-00-00', 'herecomesthesun@gmail.com', '', '09228092100', 'admin');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

--
-- Indexes for table `product_list`
--
ALTER TABLE `product_list`
  ADD KEY `fk_product_id` (`product_id`);

--
-- Indexes for table `product_supplier`
--
ALTER TABLE `product_supplier`
  ADD KEY `fk_prod_id` (`product_id`),
  ADD KEY `fk_supp_id` (`supplier_id`);

--
-- Indexes for table `supplier`
--
ALTER TABLE `supplier`
  ADD PRIMARY KEY (`supplier_id`);

--
-- Indexes for table `transac`
--
ALTER TABLE `transac`
  ADD PRIMARY KEY (`transaction_no`),
  ADD KEY `fk_dl` (`delivery_location`),
  ADD KEY `fk_ci` (`consumer_id`);

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`),
  ADD KEY `address` (`address`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `supplier`
--
ALTER TABLE `supplier`
  MODIFY `supplier_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `transac`
--
ALTER TABLE `transac`
  MODIFY `transaction_no` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
--
-- Constraints for dumped tables
--

--
-- Constraints for table `product_list`
--
ALTER TABLE `product_list`
  ADD CONSTRAINT `fk_product_id` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_id`);

--
-- Constraints for table `product_supplier`
--
ALTER TABLE `product_supplier`
  ADD CONSTRAINT `fk_prod_id` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_id`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_supp_id` FOREIGN KEY (`supplier_id`) REFERENCES `supplier` (`supplier_id`) ON DELETE CASCADE;

--
-- Constraints for table `transac`
--
ALTER TABLE `transac`
  ADD CONSTRAINT `fk_ci` FOREIGN KEY (`consumer_id`) REFERENCES `user` (`user_id`),
  ADD CONSTRAINT `fk_dl` FOREIGN KEY (`delivery_location`) REFERENCES `user` (`address`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

redpajama_set_name: RedPajamaGithub


text:
#ifndef NE_VISUALISE_H
#define NE_VISUALISE_H

#include "system.h"
#include <cinder/gl/Fbo.h>
#include <cinder/qtime/MovieWriter.h>
#include <cinder/Utilities.h>

// We use Cinder for visualisation
using namespace ci;

namespace netevo {

   /** Updates the positions of a systems nodes (the layout). */
   class Layout {
   public:
      /** Create an initial layout. */
      virtual void setInitialLayout (System &sys) { };
      /** New node has been added update initial position. */
      virtual void setInitialPosition (System &sys, Node v) { };
      /** Method called to interate the layout for a length of time. */
      virtual void iterate (System &sys, double dt) { };
   };

   /** Maps properties of a system to a visual representation. */
   class Drawer {
   public:
      virtual void draw (System &sys, gl::Fbo &framebuffer) { };
   };

   /** Visualisation of a System. User must call appropriate generate frame methods and all
    *  content is rendered to an internal OpenGL framebuffer that can then be exported to the
    *  screen or written to file. */
   class Visualisation {
   protected:
      /** Time step between frames. */
      double  mDt;
      /** Layout for the visualisation. */
		Layout  *mLayout;
      /** Drawer for the visualisation. */
		Drawer  *mDrawer;
      /** Internal framebuffer for partial updates. */
      gl::Fbo *mFramebuffer;
      /** Internal framebuffer holding current rendered display. */
		gl::Fbo *mFramebufferDone;
      /** Width in pixels of framebuffer. */
      int mWidth;
      /** Height in pixels of framebuffer. */
      int mHeight;

      /** Utility function to swap the internal buffers. */
      void swapBuffers () {
			gl::Fbo *tempFb;
			tempFb = mFramebufferDone;
			mFramebufferDone = mFramebuffer;
			mFramebuffer = tempFb;
		}

   public:
      /** Constructor for visualisation that will render directly to the screen. */
      Visualisation (System &sys, double dt, Layout *layout, Drawer *drawer, int width, int height, gl::Fbo::Format format) {
         mDt = dt;
			mLayout = layout;
			mDrawer = drawer;
         mWidth = width;
         mHeight = height;
         mState = new State(sys.totalStates(), 0.0);
         mFramebuffer = new gl::Fbo(width, height, format);
			mFramebufferDone = new gl::Fbo(width, height, format);
         // Create initial state
         mState = new State(sys.totalStates(), 0.0);
         // Generate an initial layout
         mLayout->setInitialLayout(sys);
         // Render the initial layout to the framebuffer
         generateFrame();
      }

      /** Destructor for visualisation. Free internal framebuffers. */
      ~Visualisation () {
         delete(mFramebuffer);
			delete(mFramebufferDone);
      }

      /** Width in pixels of framebuffer. */
      int width () { return mWidth; }

      /** Height in pixels of framebuffer. */
      int height () { return mHeight; }

      /** Perform single iteration of layout and draw cycle. */
		void generateFrame (System &sys) {
			mLayout->iterate(mSys,  mDt);
			mDrawer->draw(*mSys, *mFramebuffer);
			swapBuffers();
		}

      /** Grabs the current finished framebuffer. */
		gl::Fbo * getFramebuffer () { return mFramebufferDone; }
   };

   /** Renders a visualisation to a movie file. */
   class VisualisationToMovie {
   protected:
      string mFilename;
      qtime::MovieWriter::Format mFormat;
      qtime::MovieWriter *mMovie;

   public:
      /** Constructor that uses a default codec (PNG). */
      VisualisationToMovie (string filename) : mFilename(filename) {
         // Default codec and quality
         mFormat.setCodec(qtime::MovieWriter::CODEC_PNG);
         mFormat.setQuality(0.8f);
      }

      /** Constructor to use a specified codec. */
      VisualisationToMovie (string filename, qtime::MovieWriter::Format format) : mFilename(filename), mFormat(format) { }

      /** Create the movie file. */
      void start (Visualisation &vis) {
         mMovie = new qtime::MovieWriter(mFilename, vis.width(), vis.height(), mFormat);
      }

      /** Record a single frame. */
      void output (Visualisation &vis) {
         movie.addFrame(vis.getFramebuffer().getTexture());
      }

      /** Finish the movie. */
      void finish (Visualisation &vis) { mMovie->finish(); }
   };

   /** Change log for saving output to a movie file. */
   class ChangeLogToMovie : public ChangeLog {
   private:
      double mDt;
      double mSimDt;
      double mEvoDt;
      double mInitDt;
      double mCurDt;
      VisualisationToMovie *mOut;
      Visualisation        *mVis;
   public:
      ChangeLogToMovie (System &sys, string filename, Layout *layout, Drawer *drawer, double simDt, double evoDt, double initDt) {
         mDt = 1.0/30.0;
         mSimDt = simDt;
         mEvoDt = evoDt;
         mInitDt = initDt;
         mOut = new VisualisationToMovie(filename);
         mVis = new Visualisation(sys, mDt, layout, drawer, 640, 480, gl::Fbo::Format());
      }

      void start  () { mOut->start(); }
      void finish () { mOut->finish(); }

      void addNode  (System &sys, Node n) { }
      void addArc   (System &sys, Node source, Node target) { }
      void erase    (System &sys, Node n) { }
      void erase    (System &sys, Arc e) { }
      void update   (System &sys, Node n) { }
      void update   (System &sys, Arc e) { }
      void newState (System &sys, const State &newState) { }

      void endStep  (System &sys, step_type_e stepType) {
         switch (stepType) {
            case INIT_STEP:
               mCurDt = mInitDt;
               break;
            case SIM_STEP:
               mCurDt = mSimDt;
               break;
            case EVO_STEP:
               mCurDt = mEvoDt;
               break;
            default:
               // Do nothing
               break;
         }
      }

      void rollback (System &sys) { mCurDt = mDt; }

      void commit   (System &sys) {
         // Generate the number of frames required
         for (int i=0; i<(int)(mCurDt/mDt); ++i) {
            // Generate a frame and output to movie
            mVis->generateFrame(sys);
            mOut->output(*mVis);
         }
      }
   };

} // netevo namespace

#endif // NE_VISUALISE_H


text:
(function( $, undefined ) {

	// Conversion of tabs classes to Bootstrap
	$.ui.tabs.prototype.options.classes[ "ui-tabs-nav" ] = "nav nav-tabs";
	$.ui.tabs.prototype.options.classes[ "ui-tabs-panel" ] = "tab-pane";
	$.ui.tabs.prototype.options.classes[ "ui-tabs-active" ] = "active";

})(jQuery);


text:
class CCBot;

class ProductionManager
{
    CCBot &       m_bot;

    BuildingManager m_buildingManager;
    BuildOrderQueue m_queue;

    const sc2::Unit * getClosestUnitToPosition(const std::vector<const sc2::Unit *> & units, sc2::Point2D closestTo);
    bool    meetsReservedResources(const BuildType & type);
    bool    canMakeNow(const sc2::Unit * producer, const BuildType & type);
    bool    detectBuildOrderDeadlock();
    void    setBuildOrder(const BuildOrder & buildOrder);
    void    create(const sc2::Unit * producer, BuildOrderItem & item);
    void    manageBuildOrderQueue();
    int     getFreeMinerals();
    int     getFreeGas();

public:

    ProductionManager(CCBot & bot);

    void    onStart();
    void    onFrame();
    void    onUnitDestroy(const sc2::Unit * unit);
    void    drawProductionInformation();

    const sc2::Unit * getProducer(const BuildType & type, sc2::Point2D closestTo = sc2::Point2D(0, 0));
};


text:
#pragma once

#include <string>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/optional.hpp>

inline std::string
get_value_from_xml(const boost::property_tree::ptree &pt_in, std::string str, const int exit_when_error = 1)
{
    if (boost::optional<std::string> str_entry = pt_in.get_optional<std::string>(str)) {
        return str_entry.get();
    } else {
        if (exit_when_error) {
            std::cout << " Error in get_value_from_xml" << std::endl;
            std::cout << " The following entry could not be found in the XML file : "
                      << str << std::endl;
            exit(EXIT_FAILURE);
        } else {
            return "";
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2015 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
    <View android:layout_width="10dp"
          android:layout_height="10dp"
          android:background="#0F0"
          android:id="@+id/greenSquare"/>
    <View android:layout_width="10dp"
          android:layout_height="10dp"
          android:background="#F00"
          android:id="@+id/redSquare"/>
    <TextView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:transitionName="source"
              android:id="@+id/hello"
              android:text="@string/hello"/>
</LinearLayout>


text:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title>NETPIE Vote</title>

        <!-- <link href="lib/ionic/css/ionic.css" rel="stylesheet"> -->
        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above-->
        <link href="css/ionic.app.min.css" rel="stylesheet">
        <link href="css/social-icons.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">

        <!-- ionic/angularjs js -->
        <script src="lib/ionic/js/ionic.bundle.min.js"></script>

        <!-- cordova script (this will be a 404 during development) -->
        <!--<script src="cordova.js"></script>-->

        <script>
            // Facebbok OAuth init
            window.fbAsyncInit = function () {
                FB.init({
                    appId: '563906117137682', // Replace the App ID with yours
                    status: true, // check login status
                    cookie: true, // enable cookies to allow the server to access the session
                    xfbml: true  // parse XFBML
                });
            };

            // Load the SDK asynchronously
            (function (d) {
                var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) {
                    return;
                }
                js = d.createElement('script');
                js.id = id;
                js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                ref.parentNode.insertBefore(js, ref);
            }(document));
            // Facebbok OAuth init - END

        </script>
        <script src="https://netpie.io/microgear.js"></script>

<script>
    const APPID = "testvote";
    const KEY = "g1cCF9jyPjRTq7l";
    const SECRET = "tig49bxdsWYX3fbU5CjjxH7VM";

    const ALIAS = "arm";

    var status = 0;
    var onstatus=0;
    var onDashboard = false;

    var microgear = Microgear.create({
        key: KEY,
        secret: SECRET,
        alias : ALIAS
    });

    microgear.on('message',function(topic,msg) {
        console.log("in come message "+msg);
        var split_msg = msg.split("|");
        if (split_msg[0]=="login") {
            if (split_msg[1]=="facebook") {
                document.getElementById("FBbt").style.visibility = "visible";
            }
            if (split_msg[1]=="Phone number") {
                document.getElementById("Pnbt").style.visibility = "visible";
            }
        }

        if(split_msg[0] == "can vote ?"){
            if(split_msg[1] == "y"){
                // alert("You CAN vote");
                document.getElementById("voteStatus").innerHTML = "มีสิทธิโหวต";
                microgear.chat("server", "request buttons|"+getid);
            }else{
                // alert("You CANNOT vote");
                document.getElementById("loadImg").style.display = "none";
                document.getElementById("voteStatus").innerHTML = "คุณได้ทำการโหวตเรียบร้อยแล้ว";
            }
        }else  if(split_msg[split_msg.length - 1] == "teams"){
            // for(var i = 1; i < split_msg.length; i++){
            //     teams
            // }
            document.getElementById("loadImg").style.display = "none";
            if(canVote){
                angular.element(document.getElementById('buttonGroup')).scope().addTeam(split_msg);
            }
        }
    });

    microgear.on('connected', function() {
        console.log(" on connected");
        onstatus++;
        console.log(onstatus);
        microgear.subscribe("/client");
        // microgear.chat("server", "server on ?");
        document.getElementById("data").innerHTML = "เชื่อมต่อ NETPIE แล้ว";

         microgear.chat("server","Logintype?");

        if(getid){
            microgear.chat("server", "can vote ?|"+getid);
            microgear.setAlias(getid);
            microgear.subscribe("/"+getid);
        }
        if(onDashboard){
            microgear.chat("server", "verify|"+ALIAS);
        }
    });

    microgear.on('present', function(event) {
        console.log(event);
        console.log(" on present");
    });

    microgear.on('absent', function(event) {
        console.log(event);
        console.log(" on absent");
    });

    function connectMicrogear(){
     status = 1;
     onstatus = 2;
        microgear.resettoken(function(err) {
            console.log(err);
            console.log(" on resettoken");
        });
    }

</script>
    </head>
    <body ng-app="oauthApp">

        <!--
      The views will be rendered in the <ion-nav-view> directive below
      Templates are in the /templates folder (but you could also
      have templates inline in this html file if you'd like).
        -->
    <ion-nav-view animation="slide-left-right"></ion-nav-view>

    <script src="lib/angular-sanitize/angular-sanitize.min.js"></script>
    <script src="lib/angular-cookies/angular-cookies.min.js"></script>

    <!-- your app's js -->
    <script src = "js/app.js" ></script>
    <script src="js/controllers/controllers.js"></script>

</body>
</html>


text:
package org.apache.jackrabbit.spi.commons.query.qom;

import javax.jcr.query.qom.Source;

import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver;

/**
 * SourceImpl...
 */
public abstract class SourceImpl extends AbstractQOMNode implements Source {

    public SourceImpl(NamePathResolver resolver) {
        super(resolver);
    }

    /**
     * @return the selectors that are contained in this source.
     */
    public abstract SelectorImpl[] getSelectors();
}


text:
package com.wangsus.suwangapp;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class SuWangAppServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user != null) {
//			resp.setContentType("text/plain");
//			resp.getWriter().println("Hello, " + user.getNickname());
			req.setAttribute("name", user.getNickname());
			req.setAttribute("logouturl", userService.createLogoutURL("/"));
			req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req, resp);
		} else {
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
	}
}


text:
/**{
  border: 1px solid black;
}*/
body {
  background-color: silver;
}

h1 {
  font-family: Rancho;
  text-align: center;
  background-color: green;
}

img {
  margin:100px;
  width: 250px;
  height:250px;

}

img#left {
  border:2px solid blue;

}

img#center {
  border:2px solid blue;

}

img#right {
  border:2px solid blue;

}

div#intro {
  background-color: green;
}

div#intro1 {
  border:3px solid blue;
  border-bottom-left-radius: 20%;
  border-top-right-radius: 20%;
  width: 500px;
  text-align: center;
  margin:0 auto;

}
div#intro2 {
  border:3px solid blue;
  border-bottom-left-radius: 20%;
  border-top-right-radius: 20%;
  width: 600px;
  text-align: center;
  margin:0 auto;

}

.h_line {
  width:100%;
  height:1px;
  border-bottom: 1px solid #000;
}

#seeChart {
  color:silver;
  background-color: blue;
  border: 2px solid silver;
  width: 100px;
  height: 50px;
  text-align: center;

}
#container {
  display:flex;
  justify-content: space-between;
  background-color: black;
}


text:
	<ui-view></ui-view>
	<shmck-footer></shmck-footer>


text:
package examples.todolist
package http

/**
 * Finch http endpoints
 */
class Api[F[_]](
    implicit appApi: AppApi[F],
    genericApi: GenericApi[F],
    todoItemApi: TodoItemApi[F],
    todoListApi: TodoListApi[F],
    tagApi: TagApi[F]) {

  val endpoints =
    appApi.endpoints :+:
      genericApi.endpoints :+:
      todoItemApi.endpoints :+:
      todoListApi.endpoints :+:
      tagApi.endpoints

}

object Api {
  implicit def instance[F[_]](
      implicit appApi: AppApi[F],
      genericApi: GenericApi[F],
      todoItemApi: TodoItemApi[F],
      todoListApi: TodoListApi[F],
      tagApi: TagApi[F]): Api[F] = new Api[F]
}


text:
//
//  FcStatusBarHUD.m
//  FcStatusBarHUD
//
//  Created by 方存 on 16/8/15.
//  Copyright © 2016年 健康宝. All rights reserved.
//

#import "FcStatusBarHUD.h"
#define Screen_W [UIScreen mainScreen].bounds.size.width
#define Screen_H [UIScreen mainScreen].bounds.size.height
#define FcMessageFont [UIFont systemFontOfSize:13]

// 1.1.1  3.4.2 大版本号.功能更新版本号.BUG修复版本号

/** 全局窗口 */
static UIWindow *window_;
/** 定时器 */
static NSTimer *timer_;
/** 消息停留时间 */
static CGFloat const FcMessageDuration = 2.0;
/** 动画时间 */
static CGFloat const FcAnimationDuration = 0.25;

@implementation FcStatusBarHUD
/**
 *  显示窗口
 */
+ (void)showWimdow
{
    // frame数据
    CGFloat windowH = 20;
    CGRect frame = CGRectMake(0, -windowH, Screen_W, windowH);
    // 显示窗口
    window_.hidden = YES;// 防止多次创建窗口,残留窗口
    window_ = [[UIWindow alloc] init];
    window_.backgroundColor = [UIColor blackColor];
    window_.windowLevel = UIWindowLevelAlert;
    window_.frame = frame;
    window_.hidden = NO;
    // 动画
    frame.origin.y = 0;
    [UIView animateWithDuration:FcAnimationDuration animations:^{
        window_.frame = frame;
    }];
}

/**
 *  显示普通信息 + 图片
 *
 *  @param msg   文字
 *  @param image 图片
 */
+ (void)showMessage:(NSString *)msg image:(UIImage *)image
{
    // 停止计时
    [timer_ invalidate];
    // 显示窗口
    [self showWimdow];
    // 添加按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:msg forState:UIControlStateNormal];
    button.titleLabel.font = FcMessageFont;
    if (image) {
        [button setImage:image forState:UIControlStateNormal];
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    }
    button.frame = window_.bounds;
    [window_ addSubview:button];
    // 定时消失
    timer_ = [NSTimer scheduledTimerWithTimeInterval:FcMessageDuration target:self selector:@selector(hide) userInfo:nil repeats:NO];
}

/**
 *  显示文本信息
 *
 *  @param msg   文字
 */
+ (void)showMessage:(NSString *)msg
{
    [self showMessage:msg image:nil];
}

/**
 *  显示成功信息
 *
 *  @param msg   文字
 */
+ (void)showSuccess:(NSString *)msg
{
    [self showMessage:msg image:[UIImage imageNamed:@"FcStatusBarHUD.bundle/check"]];
}

/**
 *  显示失败信息
 *
 *  @param msg   文字
 */
+ (void)showError:(NSString *)msg
{
    [self showMessage:msg image:[UIImage imageNamed:@"FcStatusBarHUD.bundle/error"]];
}

/**
 *  显示正在处理信息
 *
 *  @param msg   文字
 */
+ (void)showLoading:(NSString *)msg
{
    // 停止定时器
    [timer_ invalidate];
    timer_ = nil;

    [self showWimdow];

    UILabel *label = [[UILabel alloc] init];
    label.font = FcMessageFont;
    label.frame = window_.bounds;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.text = msg;
    [window_ addSubview:label];

    // 添加菊花
    UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [loadingView startAnimating];
    // 计算文字宽度
    CGFloat msgW = [msg sizeWithAttributes:@{NSFontAttributeName : FcMessageFont}].width;
    CGFloat centerX = (window_.frame.size.width - msgW) * 0.5 - 20;
    CGFloat centerY = window_.frame.size.height * 0.5;
    loadingView.center = CGPointMake(centerX, centerY);
    [window_ addSubview:loadingView];

}

/**
 *  隐藏指示器
 */
+ (void)hide
{
    [UIView animateWithDuration:FcAnimationDuration animations:^{
        CGRect frame = window_.frame;
        frame.origin.y = - frame.size.height;
        window_.frame = frame;
    } completion:^(BOOL finished) {
        window_ = nil;
        timer_ = nil;
    }];
}

@end


text:
angular.module('ordercloud-impersonation', [])

    .factory('ImpersonationService', ImpersonationService)
    .controller('BuyerUserSelectModalCtrl', ModalController)

;
//TODO: Consider removing
function ImpersonationService(ApiClients, $q, $rootScope, $uibModal, $state, Users, Auth, toastr) {
    return {
        DecryptToken: DecryptToken,
        Impersonation: Impersonation,
        StopImpersonating: StopImpersonating
    };

    function DecryptToken() {
        Auth.SetImpersonating(false);
        var token = Auth.GetToken().split('.');
        return JSON.parse(atob(token[1]));
    }

    function Impersonation(FunctionCall) {
        var dfd = $q.defer(),
            jwt = DecryptToken();
        if (jwt.type === 'Buyer') {
            dfd.resolve(FunctionCall());
        }
        else {
            if (jwt.role === 'FullAccess') {
                if (!Auth.GetImpersonating()) {
                    var modalInstance = $uibModal.open({
                        animation: true,
                        templateUrl: 'common/impersonation/templates/buyer-user-modal.tpl.html',
                        controller: 'BuyerUserSelectModalCtrl',
                        controllerAs: 'modalSelect',
                        size: 'lg',
                        resolve: {
                            UserList: function( Users) {
                                return Users.List();
                            }
                        }
                    });
                    modalInstance.result
                        .then(function(selectedUser) {
                            ApiClients.List()
                                .then(function(apiList) {
                                    Users.GetAccessToken(selectedUser.ID, {ClientID: apiList.Items[0].ID, Claims: ['FullAccess']})
                                        .then(function(token) {
                                            Auth.SetImpersonationToken(selectedUser.ID, token["access_token"]);
                                            Auth.SetImpersonating(true);
                                            $rootScope.$broadcast('ImpersonationStarted');
                                            dfd.resolve(FunctionCall());
                                        })
                                        .catch(function() {
                                            toastr.error('Could not set an impersonation token for the selected user.', 'Error:');
                                        });
                                })
                                .catch(function() {
                                    toastr.error("No buyer client ids found.", 'Error:');
                                });
                        })
                        .catch(function() {
                            $state.go('home');
                        });
                }
                else {
                    Auth.SetImpersonating(true);
                    dfd.resolve(FunctionCall());
                }
            }
            else {
                toastr.error("You do not have permission to impersonate a buyer user.", 'Error:');
            }
        }
        return dfd.promise;
    }

    function StopImpersonating() {
        Auth.ClearImpersonationToken();
        Auth.SetImpersonating(false);
        $rootScope.$broadcast('ImpersonationStopped');
        $state.go('home');
    }
}

function ModalController($uibModalInstance, $state, UserList) {
    var vm = this;
    vm.list = UserList;
    vm.selected = vm.list[0];

    vm.selectUser = function(index) {
        $uibModalInstance.close(vm.list.Items[index]);
    };

    vm.cancel = function() {
        $uibModalInstance.dismiss('cancel');
        $state.go('home');
    };
}


text:
package com.gdn.venice.client.app.logistic.widgets;

import com.gdn.venice.client.app.DataConstantNameTokens;
import com.gdn.venice.client.app.DataNameTokens;
import com.gdn.venice.client.app.logistic.data.LogisticsData;
import com.gdn.venice.client.presenter.MainPagePresenter;
import com.gdn.venice.client.util.DateToXsdDatetimeFormatterClient;
import com.gdn.venice.client.util.Util;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.types.SortDirection;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.TextAreaItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

public class ActivityReportReconciliationProblem extends VLayout {
	Window manualAdjWindow;

	String airwayBillId;
	final ToolStripButton veniceDataButton;
	final ToolStripButton providerDataButton;
	final ToolStripButton manualAdjustButton;
	final ToolStripButton ignoreButton;

	Window commentHistoryWindow;

	public ActivityReportReconciliationProblem(final String airwayBillId, DataSource dataSource, final String airwayBillApprovalStatus) {
		this.airwayBillId = airwayBillId;

		setPadding(5);
		setHeight(150);

		ToolStrip reconciliationToolStrip = new ToolStrip();
		reconciliationToolStrip.setWidth100();

		veniceDataButton = new ToolStripButton();
		veniceDataButton.setIcon("[SKIN]/icons/accept_mta.png");
		veniceDataButton.setTooltip("Apply MTA");

		providerDataButton = new ToolStripButton();
		providerDataButton.setIcon("[SKIN]/icons/accept_logistic.png");
		providerDataButton.setTooltip("Apply Logistic");

		manualAdjustButton = new ToolStripButton();
		manualAdjustButton.setIcon("[SKIN]/icons/edit.png");
		manualAdjustButton.setTooltip("Manual Adjust");

		ignoreButton = new ToolStripButton();
		ignoreButton.setIcon("[SKIN]/icons/ignore.png");
		ignoreButton.setTooltip("Ignore Airwaybill");

		veniceDataButton.setDisabled(true);
		providerDataButton.setDisabled(true);
		manualAdjustButton.setDisabled(true);
		ignoreButton.setDisabled(true);

		reconciliationToolStrip.addButton(veniceDataButton);
		reconciliationToolStrip.addButton(providerDataButton);
		reconciliationToolStrip.addButton(manualAdjustButton);
		reconciliationToolStrip.addButton(ignoreButton);

		final ListGrid activityReconciliationProblemListGrid = new ListGrid();

		activityReconciliationProblemListGrid.setSelectionType(SelectionStyle.SIMPLE);
		activityReconciliationProblemListGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);

		activityReconciliationProblemListGrid.setDataSource(dataSource);

		activityReconciliationProblemListGrid.setAutoFetchData(true);

		ListGridField[] fields = Util.getListGridFieldsFromDataSource(dataSource);

		activityReconciliationProblemListGrid.setFields(fields);

		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_ACTIVITYRECONRECORDID).setWidth("5%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_ACTIVITYRECONRECORDID).setHidden(true);
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID).setWidth("5%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID).setHidden(true);
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTDESC).setWidth("10%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_VENICEDATA).setWidth("15%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_PROVIDERDATA).setWidth("15%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_MANUALLYENTEREDDATA).setWidth("15%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_LOGACTIONAPPLIED_ACTIONAPPLIEDID).setWidth("5%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_LOGACTIONAPPLIED_ACTIONAPPLIEDID).setHidden(true);
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_LOGACTIONAPPLIED_ACTIONAPPLIEDDESC).setWidth("10%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_COMMENT).setWidth("35%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_COMMENT).setCanEdit(true);
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_USERLOGONNAME).setWidth("10%");
		activityReconciliationProblemListGrid.getField(DataNameTokens.LOGACTIVITYRECONRECORD_COMMENTHISTORY).setWidth(20);

		setMembers(reconciliationToolStrip, activityReconciliationProblemListGrid);

		activityReconciliationProblemListGrid.addCellClickHandler(new CellClickHandler() {

			@Override
			public void onCellClick(CellClickEvent event) {
				if (activityReconciliationProblemListGrid.getField(event.getColNum()).getName().equals(DataNameTokens.LOGACTIVITYRECONRECORD_COMMENTHISTORY)) {
					buildCommentHistoryWindow(event.getRecord().getAttributeAsString(DataNameTokens.LOGACTIVITYRECONRECORD_ACTIVITYRECONRECORDID)).show();
				}

			}
		});

		activityReconciliationProblemListGrid.setCellFormatter(new CellFormatter() {

			@Override
			public String format(Object value, ListGridRecord record, int rowNum,
					int colNum) {

				if (value == null) {
					return null;
				}

				if (activityReconciliationProblemListGrid.getField(colNum).getName().equalsIgnoreCase(DataNameTokens.LOGACTIVITYRECONRECORD_MANUALLYENTEREDDATA)) {
					if (record.getAttributeAsString(DataNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID)!=null &&
							record.getAttributeAsString(DataNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID).
							equals(DataConstantNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID_PICKUPDATELATE)) {
						DateToXsdDatetimeFormatterClient formatter = new DateToXsdDatetimeFormatterClient();
						return formatter.formatToDDMMYYYY(formatter.parse((String) value));
					}

				}

				return (String) value;
			}
		});

		activityReconciliationProblemListGrid.addSelectionChangedHandler(new SelectionChangedHandler() {

			@Override
			public void onSelectionChanged(SelectionEvent event) {
				//enabled if there is more than 1 record selected,
				//approval status is new or rejected (disabled during submitted or already approved)
				boolean enabled = activityReconciliationProblemListGrid.getSelection().length > 0 &&
					(airwayBillApprovalStatus.equals(DataConstantNameTokens.LOGAPPROVALSTATUS_APPROVALSTATUSDESC_NEW.toString()) ||
							airwayBillApprovalStatus.equals(DataConstantNameTokens.LOGAPPROVALSTATUS_APPROVALSTATUSDESC_REJECTED.toString()));

				veniceDataButton.setDisabled(!enabled);
				providerDataButton.setDisabled(!enabled);
				ignoreButton.setDisabled(!enabled);

				//enabled if there is exactly 1 record selected,
				//approval status is new or rejected (disabled during submitted or already approved)
				boolean manualDataEnabled = activityReconciliationProblemListGrid.getSelection().length == 1 &&
				(airwayBillApprovalStatus.equals(DataConstantNameTokens.LOGAPPROVALSTATUS_APPROVALSTATUSDESC_NEW.toString()) ||
						airwayBillApprovalStatus.equals(DataConstantNameTokens.LOGAPPROVALSTATUS_APPROVALSTATUSDESC_REJECTED.toString()));

				manualAdjustButton.setDisabled(!manualDataEnabled);

			}
		});

		veniceDataButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord[] selectedRecords = activityReconciliationProblemListGrid.getSelection();

				for (int i=0;i<selectedRecords.length;i++) {
					selectedRecords[i].setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_LOGACTIONAPPLIED_ACTIONAPPLIEDID, DataConstantNameTokens.LOGACTIONAPPLIED_ACTIONAPPLIEDID_VENICEDATAPPLIED);
					selectedRecords[i].setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_COMMENT, DataConstantNameTokens.LOGACTIONAPPLIED_ACTIONAPPLIEDID_VENICEDATAPPLIED_DESC);
					activityReconciliationProblemListGrid.updateData(selectedRecords[i]);
					veniceDataButton.setDisabled(true);
					providerDataButton.setDisabled(true);
					ignoreButton.setDisabled(true);
					manualAdjustButton.setDisabled(true);
				}

			}
		});

		providerDataButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord[] selectedRecords = activityReconciliationProblemListGrid.getSelection();

				for (int i=0;i<selectedRecords.length;i++) {
					selectedRecords[i].setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_LOGACTIONAPPLIED_ACTIONAPPLIEDID, DataConstantNameTokens.LOGACTIONAPPLIED_ACTIONAPPLIEDID_PROVIDERDATAPPLIED);
					selectedRecords[i].setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_COMMENT, DataConstantNameTokens.LOGACTIONAPPLIED_ACTIONAPPLIEDID_PROVIDERDATAPPLIED_DESC);
					activityReconciliationProblemListGrid.updateData(selectedRecords[i]);
					veniceDataButton.setDisabled(true);
					providerDataButton.setDisabled(true);
					ignoreButton.setDisabled(true);
					manualAdjustButton.setDisabled(true);
				}
			}
		});

		manualAdjustButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				buildManualAdjustmentWindow(airwayBillId, activityReconciliationProblemListGrid).show();
			}
		});

		ignoreButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord[] selectedRecords = activityReconciliationProblemListGrid.getSelection();

				for (int i=0;i<selectedRecords.length;i++) {
					selectedRecords[i].setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_LOGACTIONAPPLIED_ACTIONAPPLIEDID, DataConstantNameTokens.LOGACTIONAPPLIED_ACTIONAPPLIEDID_IGNORED);
					activityReconciliationProblemListGrid.updateData(selectedRecords[i]);
					veniceDataButton.setDisabled(true);
					providerDataButton.setDisabled(true);
					ignoreButton.setDisabled(true);
					manualAdjustButton.setDisabled(true);
				}
			}
		});
	}

	private Window buildManualAdjustmentWindow(String airwayBillId, final ListGrid airwayBillReconciliationProblemListGrid) {
		manualAdjWindow = new Window();
		manualAdjWindow.setWidth(280);
		manualAdjWindow.setHeight(230);
		manualAdjWindow.setTitle("Manual Adjustment");
		manualAdjWindow.setShowMinimizeButton(false);
		manualAdjWindow.setIsModal(true);
		manualAdjWindow.setShowModalMask(true);
		manualAdjWindow.centerInPage();
		manualAdjWindow.addCloseClickHandler(new CloseClickHandler() {
			public void onCloseClick(CloseClientEvent event) {
				manualAdjWindow.destroy();
			}
		});

		VLayout manualAdjLayout = new VLayout();
		manualAdjLayout.setHeight100();
		manualAdjLayout.setWidth100();

		DynamicForm manualAdjForm = new DynamicForm();
		manualAdjForm.setPadding(5);

		ListGridRecord selectedRecord = airwayBillReconciliationProblemListGrid.getSelectedRecord();

		final TextItem dataTextItem = new TextItem();
		dataTextItem.setTitle("Manual Data");

		final DateItem dataDateItem = new DateItem();
		dataDateItem.setTitle("Manual Data");

		final TextAreaItem commentItem = new TextAreaItem();
		commentItem.setTitle("Comment");

		StaticTextItem userItem = new StaticTextItem();
		userItem.setTitle("By");
		userItem.setValue(MainPagePresenter.signedInUser);

//		StaticTextItem dateTimeItem = new StaticTextItem();
//		dateTimeItem.setTitle("TimeStamp");
//		dateTimeItem.setValue("01/01/2011 17:00");
//
//		manualAdjForm.setItems(dataItem, commentItem, userItem, dateTimeItem);

		if (selectedRecord.getAttributeAsString(DataNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID).
				equals(DataConstantNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID_PICKUPDATELATE)) {
			manualAdjForm.setItems(dataDateItem, commentItem, userItem);
		} else {
			manualAdjForm.setItems(dataTextItem, commentItem, userItem);
		}

		HLayout okCancelButtons = new HLayout(5);

		IButton buttonOK = new IButton("OK");
		IButton buttonCancel = new IButton("Cancel");

		buttonOK.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord selectedRecord = airwayBillReconciliationProblemListGrid.getSelectedRecord();
				selectedRecord.setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_LOGACTIONAPPLIED_ACTIONAPPLIEDID, DataConstantNameTokens.LOGACTIONAPPLIED_ACTIONAPPLIEDID_MANUALDATAPPLIED);
				if (selectedRecord.getAttributeAsString(DataNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID).
						equals(DataConstantNameTokens.LOGACTIVITYRECONRECORD_LOGRECONACTIVITYRECORDRESULT_RECONRECORDRESULTID_PICKUPDATELATE)) {
					DateToXsdDatetimeFormatterClient formatter = new DateToXsdDatetimeFormatterClient();
					selectedRecord.setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_MANUALLYENTEREDDATA, formatter.format(((DateItem) dataDateItem).getValueAsDate()));
				} else {
					selectedRecord.setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_MANUALLYENTEREDDATA, ((TextItem) dataTextItem).getValueAsString());
				}

				selectedRecord.setAttribute(DataNameTokens.LOGACTIVITYRECONRECORD_COMMENT, commentItem.getValueAsString());
				airwayBillReconciliationProblemListGrid.updateData(selectedRecord);
				veniceDataButton.setDisabled(true);
				providerDataButton.setDisabled(true);
				ignoreButton.setDisabled(true);
				manualAdjustButton.setDisabled(true);
				manualAdjWindow.destroy();
			}
		});
		buttonCancel.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				manualAdjWindow.destroy();
			}
		});
		okCancelButtons.setAlign(Alignment.CENTER);
		okCancelButtons.setMembers(buttonOK, buttonCancel);

		manualAdjLayout.setMembers(manualAdjForm, okCancelButtons);
		manualAdjWindow.addItem(manualAdjLayout);
		return manualAdjWindow;
	}

	private Window buildCommentHistoryWindow(String activityReconRecordId) {
		commentHistoryWindow = new Window();
		commentHistoryWindow.setWidth(400);
		commentHistoryWindow.setHeight(400);
		commentHistoryWindow.setTitle("Comment History");
		commentHistoryWindow.setShowMinimizeButton(false);
		commentHistoryWindow.setIsModal(true);
		commentHistoryWindow.setShowModalMask(true);
		commentHistoryWindow.centerInPage();
		commentHistoryWindow.addCloseClickHandler(new CloseClickHandler() {
			public void onCloseClick(CloseClientEvent event) {
				commentHistoryWindow.destroy();
			}
		});

		VLayout commentHistoryLayout = new VLayout(5);
		commentHistoryLayout.setHeight100();
		commentHistoryLayout.setWidth100();

		ListGrid commentHistoryListGrid = new ListGrid();
		commentHistoryListGrid.setHeight100();
		commentHistoryListGrid.setWidth100();

		DataSource dataSource = LogisticsData.getActivityReportCommentHistoryData(activityReconRecordId);

		commentHistoryListGrid.setDataSource(dataSource);

		commentHistoryListGrid.setAutoFetchData(true);

		commentHistoryListGrid.setFields(Util.getListGridFieldsFromDataSource(dataSource));
		commentHistoryListGrid.setSortField(0);
		commentHistoryListGrid.setSortDirection(SortDirection.DESCENDING);

		HLayout closeButtonLayout = new HLayout(0);
		closeButtonLayout.setHeight(30);

		IButton buttonClose = new IButton("Close");

		buttonClose.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				commentHistoryWindow.destroy();
			}
		});
		closeButtonLayout.setAlign(Alignment.CENTER);
		closeButtonLayout.setMembers(buttonClose);

		commentHistoryLayout.setMembers(commentHistoryListGrid, closeButtonLayout);
		commentHistoryWindow.addItem(commentHistoryLayout);
		return commentHistoryWindow;
	}
}


text:
![alt tag](http://38.media.tumblr.com/avatar_ca7275c00e2c_128.png)

A simple Chrome extension providing motivation on Tuesdays.
Enjoy the simple pleasure of seeing the Tuesday Again No Problem Dog on Tuesdays.
On other days? There isn't much.

I may choose to add "spin offs" for the other days.  For example, something like "Thursday Again? No trouble!" or whatever I can find that someone else has already come up with.

# to install, download the .crx file and click-and-drag this file into your chrome://extensions


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fieldiana, Bot. 21: 117 (1989)

#### Original name
Galerina oligocalyptrata Singer

### Remarks
null


text:
export PATH="./bin:/usr/local/git/bin:/usr/local/bin:/usr/local/sbin:/opt/local/bin:/opt/local/sbin:$ZSH/bin:$PATH"
export MANPATH="/usr/local/man:/usr/local/mysql/man:/usr/local/git/man:$MANPATH"


text:
<?php

namespace Bolt\Storage\ContentRequest;

use Bolt\Config;
use Bolt\Exception\AccessControlException;
use Bolt\Helpers\Input;
use Bolt\Logger\FlashLoggerInterface;
use Bolt\Storage\Entity;
use Bolt\Storage\EntityManager;
use Bolt\Translation\Translator as Trans;
use Bolt\Users;
use Carbon\Carbon;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
 * Helper class for ContentType record editor saves.
 *
 * Prior to v2.3 this functionality existed in \Bolt\Controllers\Backend::editcontent().
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Save
{
    /** @var EntityManager */
    protected $em;
    /** @var Config */
    protected $config;
    /** @var Users */
    protected $users;
    /** @var LoggerInterface */
    protected $loggerChange;
    /** @var LoggerInterface */
    protected $loggerSystem;
    /** @var FlashLoggerInterface */
    protected $loggerFlash;
    /** @var UrlGeneratorInterface */
    protected $urlGenerator;

    /**
     * Constructor function.
     *
     * @param EntityManager         $em
     * @param Config                $config
     * @param Users                 $users
     * @param LoggerInterface       $loggerChange
     * @param LoggerInterface       $loggerSystem
     * @param FlashLoggerInterface  $loggerFlash
     * @param UrlGeneratorInterface $urlGenerator
     */
    public function __construct(
        EntityManager $em,
        Config $config,
        Users $users,
        LoggerInterface $loggerChange,
        LoggerInterface $loggerSystem,
        FlashLoggerInterface $loggerFlash,
        UrlGeneratorInterface $urlGenerator
    ) {
        $this->em = $em;
        $this->config = $config;
        $this->users = $users;
        $this->loggerChange = $loggerChange;
        $this->loggerSystem = $loggerSystem;
        $this->loggerFlash = $loggerFlash;
        $this->urlGenerator = $urlGenerator;
    }

    /**
     * Do the save for a POSTed record.
     *
     * @param array   $formValues
     * @param array   $contenttype  The contenttype data
     * @param integer $id           The record ID
     * @param boolean $new          If TRUE this is a new record
     * @param string  $returnTo
     * @param string  $editReferrer
     *
     * @return Response
     */
    public function action(array $formValues, array $contenttype, $id, $new, $returnTo, $editReferrer)
    {
        $contentTypeSlug = $contenttype['slug'];
        $repo = $this->em->getRepository($contentTypeSlug);

        // If we have an ID now, this is an existing record
        if ($id) {
            $content = $repo->find($id);
            $oldContent = clone $content;
            $oldStatus = $content['status'];
        } else {
            $content = $repo->create(['contenttype' => $contentTypeSlug, 'status' => $contenttype['default_status']]);
            $oldContent = null;
            $oldStatus = 'draft';
        }

        // Don't allow spoofing the ID.
        if ($content->getId() !== null && (integer) $id !== $content->getId()) {
            if ($returnTo === 'ajax') {
                throw new AccessControlException("Don't try to spoof the id!");
            }
            $this->loggerFlash->error("Don't try to spoof the id!");

            return new RedirectResponse($this->generateUrl('dashboard'));
        }

        $this->setPostedValues($content, $formValues, $contenttype);
        $this->setTransitionStatus($content, $contentTypeSlug, $id, $oldStatus);

        // Get the associated record change comment
        $comment = isset($formValues['changelog-comment']) ? $formValues['changelog-comment'] : '';

        // Save the record
        return $this->saveContentRecord($content, $oldContent, $contenttype, $new, $comment, $returnTo, $editReferrer);
    }

    /**
     * Check whether the status is allowed.
     *
     * We act as if a status *transition* were requested and fallback to the old
     * status otherwise.
     *
     * @param Entity\Entity $content
     * @param string        $contentTypeSlug
     * @param integer       $id
     * @param string        $oldStatus
     */
    private function setTransitionStatus(Entity\Entity $content, $contentTypeSlug, $id, $oldStatus)
    {
        $canTransition = $this->users->isContentStatusTransitionAllowed($oldStatus, $content->getStatus(), $contentTypeSlug, $id);
        if (!$canTransition) {
            $content->setStatus($oldStatus);
        }
    }

    /**
     * Set a Contenttype record values from a HTTP POST.
     *
     * @param Entity\Content $content
     * @param array          $formValues
     * @param array          $contentType
     *
     * @throws AccessControlException
     */
    private function setPostedValues(Entity\Content $content, $formValues, $contentType)
    {
        // Ensure all fields have valid values
        $formValues = $this->setSuccessfulControlValues($formValues, $contentType['fields']);
        $formValues = Input::cleanPostedData($formValues);
        unset($formValues['contenttype']);

        $user = $this->users->getCurrentUser();
        if ($id = $content->getId()) {
            // Owner is set explicitly, is current user is allowed to do this?
            if (isset($formValues['ownerid']) && (integer) $formValues['ownerid'] !== $content->getOwnerid()) {
                if (!$this->users->isAllowed("contenttype:{$contentType['slug']}:change-ownership:$id")) {
                    throw new AccessControlException('Changing ownership is not allowed.');
                }
                $content->setOwnerid($formValues['ownerid']);
            }
        } else {
            $content->setOwnerid($user['id']);
        }

        // Make sure we have a proper status.
        if (!in_array($formValues['status'], ['published', 'timed', 'held', 'draft'])) {
            if ($status = $content->getStatus()) {
                $formValues['status'] = $status;
            } else {
                $formValues['status'] = 'draft';
            }
        }

        // Set the object values appropriately
        foreach ($formValues as $name => $value) {
            if ($name === 'relation') {
                $this->setPostedRelations($content, $formValues);
            } elseif ($name === 'taxonomy') {
                $this->setPostedTaxonomies($content, $formValues);
            } else {
                $content->set($name, empty($value) ? null : $value);
            }
        }
    }

    /**
     * Convert POST relationship values to an array of Entity objects keyed by
     * ContentType.
     *
     * @param Entity\Content $content
     * @param array|null     $formValues
     */
    private function setPostedRelations(Entity\Content $content, $formValues)
    {
        if (!isset($formValues['relation'])) {
            return;
        }

        $related = $this->em->createCollection('Bolt\Storage\Entity\Relations');
        $related->setFromPost($formValues, $content);
        $content->setRelation($related);
    }

    /**
     * Set valid POST taxonomies.
     *
     * @param Entity\Content $content
     * @param array|null     $formValues
     */
    private function setPostedTaxonomies(Entity\Content $content, $formValues)
    {
        if (!isset($formValues['taxonomy'])) {
            return;
        }

        $taxonomies = $this->em->createCollection('Bolt\Storage\Entity\Taxonomy');
        $taxonomies->setFromPost($formValues, $content);
        $content->setTaxonomy($taxonomies);
    }

    /**
     * Commit the record to the database.
     *
     * @param Entity\Content      $content
     * @param Entity\Content|null $oldContent
     * @param array               $contentType
     * @param boolean             $new
     * @param string              $comment
     * @param string              $returnTo
     * @param string              $editReferrer
     *
     * @return Response
     */
    private function saveContentRecord(Entity\Content $content, $oldContent, array $contentType, $new, $comment, $returnTo, $editReferrer)
    {
        // Save the record
        $repo = $this->em->getRepository($contentType['slug']);
        $repo->save($content);
        $id = $content->getId();

        // Create the change log entry if configured
        $this->logChange($contentType, $content->getId(), $content, $oldContent, $comment);

        // Log the change
        if ($new) {
            $this->loggerFlash->success(Trans::__('contenttypes.generic.saved-new', ['%contenttype%' => $contentType['slug']]));
            $this->loggerSystem->info('Created: ' . $content->getTitle(), ['event' => 'content']);
        } else {
            $this->loggerFlash->success(Trans::__('contenttypes.generic.saved-changes', ['%contenttype%' => $contentType['slug']]));
            $this->loggerSystem->info('Saved: ' . $content->getTitle(), ['event' => 'content']);
        }

        /*
         * We now only get a returnto parameter if we are saving a new
         * record and staying on the same page, i.e. "Save {contenttype}"
         */
        if ($returnTo) {
            if ($returnTo === 'new') {
                return new RedirectResponse(
                    $this->generateUrl(
                        'editcontent',
                        [
                            'contenttypeslug' => $contentType['slug'],
                            'id'              => $id,
                            '#'               => $returnTo,
                        ]
                    )
                );
            } elseif ($returnTo === 'saveandnew') {
                return new RedirectResponse(
                    $this->generateUrl(
                        'editcontent',
                        [
                            'contenttypeslug' => $contentType['slug'],
                            '#'               => $returnTo,
                        ]
                    )
                );
            } elseif ($returnTo === 'ajax') {
                return $this->createJsonUpdate($content, true);
            } elseif ($returnTo === 'test') {
                return $this->createJsonUpdate($content, false);
            }
        }

        // No returnto, so we go back to the 'overview' for this contenttype.
        // check if a pager was set in the referrer - if yes go back there
        if ($editReferrer) {
            return new RedirectResponse($editReferrer);
        } else {
            return new RedirectResponse($this->generateUrl('overview', ['contenttypeslug' => $contentType['slug']]));
        }
    }

    /**
     * Add successful control values to request values, and do needed corrections.
     *
     * @see http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
     *
     * @param array $formValues
     * @param array $fields
     *
     * @return array
     */
    private function setSuccessfulControlValues(array $formValues, $fields)
    {
        foreach ($fields as $key => $values) {
            if (isset($formValues[$key])) {
                if ($values['type'] === 'float') {
                    // We allow ',' and '.' as decimal point and need '.' internally
                    $formValues[$key] = str_replace(',', '.', $formValues[$key]);
                }
            } else {
                if ($values['type'] === 'select' && isset($values['multiple']) && $values['multiple'] === true) {
                    $formValues[$key] = [];
                } elseif ($values['type'] === 'checkbox') {
                    $formValues[$key] = 0;
                }
            }
        }

        return $formValues;
    }

    /**
     * Build a valid AJAX response for in-place saves that account for pre/post
     * save events.
     *
     * @param Entity\Content $content
     * @param boolean        $flush
     *
     * @return JsonResponse
     */
    private function createJsonUpdate(Entity\Content $content, $flush)
    {
        /*
         * Flush any buffers from saveConent() dispatcher hooks
         * and make sure our JSON output is clean.
         *
         * Currently occurs due to exceptions being generated in the dispatchers
         * in \Bolt\Storage::saveContent()
         *     StorageEvents::PRE_SAVE
         *     StorageEvents::POST_SAVE
         */
        if ($flush) {
            Response::closeOutputBuffers(0, false);
        }

        $val = $content->toArray();

        if (isset($val['datechanged'])) {
            $val['datechanged'] = (new Carbon($val['datechanged']))->toIso8601String();
        }

        // Adjust decimal point as some locales use a comma and… JavaScript
        $lc = localeconv();
        $fields = $this->config->get('contenttypes/' . $content->getContenttype() . '/fields');
        foreach ($fields as $key => $values) {
            if ($values['type'] === 'float' && $lc['decimal_point'] === ',') {
                $val[$key] = str_replace('.', ',', $val[$key]);
            }
        }

        // Unset flashbag for ajax
        $this->loggerFlash->clear();

        return new JsonResponse($val);
    }

    /**
     * Add a change log entry to track the change.
     *
     * @param string              $contentType
     * @param integer             $contentId
     * @param Entity\Content      $newContent
     * @param Entity\Content|null $oldContent
     * @param string|null         $comment
     */
    private function logChange($contentType, $contentId, $newContent = null, $oldContent = null, $comment = null)
    {
        $type = $oldContent ? 'Update' : 'Insert';

        $this->loggerChange->info(
            $type . ' record',
            [
                'action'      => strtoupper($type),
                'contenttype' => $contentType,
                'id'          => $contentId,
                'new'         => $newContent ? $newContent->toArray() : null,
                'old'         => $oldContent ? $oldContent->toArray() : null,
                'comment'     => $comment,
            ]
        );
    }

    /**
     * Shortcut for {@see UrlGeneratorInterface::generate}
     *
     * @param string $name          The name of the route
     * @param array  $params        An array of parameters
     * @param bool   $referenceType The type of reference to be generated (one of the constants)
     *
     * @return string
     */
    private function generateUrl($name, $params = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
    {
        /** @var UrlGeneratorInterface $generator */
        $generator = $this->urlGenerator;

        return $generator->generate($name, $params, $referenceType);
    }
}


text:
package sculture.models.requests;

/**
 * Created by bulent on 27.11.2015.
 */
public class CommentGetRequestBody {
    private long commentId;

    public long getCommentId() {
        return commentId;
    }

    public void setCommentId(long commentId) {
        this.commentId = commentId;
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2beta1/dlp.proto

namespace Google\Cloud\Dlp\V2beta1;

/**
 * These are commonly used subsets of the alphabet that the FFX mode
 * natively supports. In the algorithm, the alphabet is selected using
 * the "radix". Therefore each corresponds to particular radix.
 *
 * Protobuf enum Google\Privacy\Dlp\V2beta1\CryptoReplaceFfxFpeConfig\FfxCommonNativeAlphabet
 */
class CryptoReplaceFfxFpeConfig_FfxCommonNativeAlphabet
{
    /**
     * Generated from protobuf enum FFX_COMMON_NATIVE_ALPHABET_UNSPECIFIED = 0;
     */
    const FFX_COMMON_NATIVE_ALPHABET_UNSPECIFIED = 0;
    /**
     * [0-9] (radix of 10)
     *
     * Generated from protobuf enum NUMERIC = 1;
     */
    const NUMERIC = 1;
    /**
     * [0-9A-F] (radix of 16)
     *
     * Generated from protobuf enum HEXADECIMAL = 2;
     */
    const HEXADECIMAL = 2;
    /**
     * [0-9A-Z] (radix of 36)
     *
     * Generated from protobuf enum UPPER_CASE_ALPHA_NUMERIC = 3;
     */
    const UPPER_CASE_ALPHA_NUMERIC = 3;
    /**
     * [0-9A-Za-z] (radix of 62)
     *
     * Generated from protobuf enum ALPHA_NUMERIC = 4;
     */
    const ALPHA_NUMERIC = 4;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="hello">Hello World, turntest!</string>
	<string name="app_name">turntest</string>
</resources>


text:
<!DOCTYPE html>

        <title>Pothole service requests</title>

Open pot hole service requests

            Service Request Number:

            Status:


text:
<?xml version='1.0'?>
<test  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation="negativeInteger_pattern001.xsd" >
<!-- facet=pattern and value=-\p{Nd}{1,3} and document value=-5 -->
  <foo>-5</foo>
</test>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2012 Thierry-Dimitri Roy <thierryd@gmail.com>

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<selector
	xmlns:android="http://schemas.android.com/apk/res/android">

	<item>
		<shape>
			<gradient
				android:endColor="@color/gradient_dark_blue"
				android:startColor="@color/gradient_dark_blue"
				android:angle="270" />

		</shape>
	</item>
</selector>