text:
package org.perfcake.reporting.destinations;

import org.perfcake.PerfCakeException;
import org.perfcake.common.PeriodType;
import org.perfcake.reporting.Measurement;
import org.perfcake.reporting.ReportingException;
import org.perfcake.reporting.destinations.chart.ChartDestinationHelper;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.perfcake.util.properties.MandatoryProperty;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Creates nice charts from the results. The charts are generated to the outputPath path. The charts in the same group can be later
 * combined together based on the names of the columns. All previously generated charts in the outputPath path are placed in the final
 * report. Use with caution as the big number of results can take too long to load in the browser. Each chart has a quick view file
 * where the results can be seen while the test is still running.
 *
 * @author Martin Večeřa
 */
public class ChartDestination implements Destination {

   /**
    * A logger for this class.
    */
   private static final Logger log = LogManager.getLogger(ChartDestination.class);

   /**
    * Attributes that should be stored in the chart.
    */
   @MandatoryProperty
   private List<String> attributes;

   /**
    * Where to store the charts.
    */
   private Path outputPath = Paths.get("perfcake-chart");

   /**
    * Name of the chart for this measurement.
    */
   private String name = "PerfCake Results";

   /**
    * Group of this chart. Charts in the same group can be later matched for the column names.
    */
   private String group = "default";

   /**
    * Y axis legend.
    */
   private String yAxis = "Value";

   /**
    * X axis legend.
    */
   private String xAxis = "Time";

   /**
    * The type of the X axis. It can display the overall progress of the test in Percents, Time, or Iteration numbers.
    */
   private PeriodType xAxisType = PeriodType.TIME;

   /**
    * Helper to control the chart generation.
    */
   private ChartDestinationHelper helper;

   @Override
   public void open() {
      helper = new ChartDestinationHelper(this);
   }

   @Override
   public void close() {
      if (!helper.isSuccessInit()) {
         log.error("Chart destination was not properly initialized, skipping result creation.");
      } else {
         try {
            helper.close();
            helper.compileResults();
         } catch (final PerfCakeException e) {
            log.error("Unable to compile all collected results in a final report: ", e);
         }
      }
   }

   @Override
   public void report(final Measurement measurement) throws ReportingException {
      if (!helper.isSuccessInit()) {
         throw new ReportingException("Chart destination was not properly initialized.");
      }

      helper.appendResult(measurement);
   }

   /**
    * Gets the output directory for charts.
    *
    * @return The output directory location.
    */
   public String getOutputDir() {
      return outputPath.toString();
   }

   /**
    * Sets the output directory for charts.
    *
    * @param outputDir
    *       The output directory location.
    */
   public void setOutputDir(final String outputDir) {
      this.outputPath = Paths.get(outputDir);
   }

   /**
    * Gets the output directory for charts as the Path data type.
    *
    * @return The output directory location.
    */
   public Path getOutputDirAsPath() {
      return outputPath;
   }

   /**
    * Gets the name of the chart.
    *
    * @return The name of the chart.
    */
   public String getName() {
      return name;
   }

   /**
    * Sets the name of the chart.
    *
    * @param name
    *       The name of the chart.
    */
   public void setName(final String name) {
      this.name = name;
   }

   /**
    * Gets the group of the resulting chart.
    *
    * @return The group of the chart.
    */
   public String getGroup() {
      return group;
   }

   /**
    * Sets the group of the resulting chart.
    *
    * @param group
    *       The group of the chart.
    */
   public void setGroup(final String group) {
      if ("".equals(group)) {
         this.group = "default";
         log.warn("Empty group name, renaming to: default");
      } else if (!group.matches("[a-zA-Z][a-zA-Z0-9_]*")) {
         final String postGroup = group.replaceAll("[^a-zA-Z0-9_]", "_");

         final Matcher firstNumericCharMatcher = Pattern.compile("[0-9]").matcher(postGroup);
         final int firstNumericCharIndex;
         if (firstNumericCharMatcher.find()) {
            firstNumericCharIndex = firstNumericCharMatcher.start();
         } else {
            firstNumericCharIndex = -1;
         }

         if (firstNumericCharIndex == 0) {
            this.group = "_" + postGroup;
         } else {
            this.group = postGroup;
         }
         log.warn("Illegal characters found in the group name. Only allowed characters are letters, numbers and underscore. The group must not start with a number. Renaming to: " + this.group);
      } else {
         this.group = group;
      }
   }

   /**
    * Gets the legend of the Y axis of the chart.
    *
    * @return The legend of the Y axis of the chart.
    */
   public String getYAxis() {
      return yAxis;
   }

   /**
    * Sets the legend of the Y axis of the chart.
    *
    * @param yAxis
    *       The legend of the Y axis of the chart.
    */
   public void setYAxis(final String yAxis) {
      this.yAxis = yAxis;
   }

   /**
    * Gets the legend of the X axis of the chart.
    *
    * @return The legend of the X axis of the chart.
    */
   public String getXAxis() {
      return xAxis;
   }

   /**
    * Sets the legend of the X axis of the chart.
    *
    * @param xAxis
    *       The legend of the X axis of the chart.
    */
   public void setXAxis(final String xAxis) {
      this.xAxis = xAxis;
   }

   /**
    * Gets the type of the X axis. It can be either Time, Percents, or Iteration number.
    *
    * @return The type of the X axis.
    */
   public PeriodType getxAxisType() {
      return xAxisType;
   }

   /**
    * Sets the type of the X axis. It can be either Time, Percents, or Iteration number.
    *
    * @param xAxisType
    *       The type of the X axis.
    */
   public void setxAxisType(final PeriodType xAxisType) {
      this.xAxisType = xAxisType;
   }

   /**
    * Gets the attributes that will be written to the chart.
    *
    * @return The attributes separated by comma.
    */
   public String getAttributes() {
      return StringUtils.join(attributes, ",");
   }

   /**
    * Sets the attributes that will be written to the chart.
    *
    * @param attributes
    *       The attributes separated by comma.
    */
   public void setAttributes(final String attributes) {
      this.attributes = Arrays.asList(attributes.split("\\s*,\\s*"));
   }

   /**
    * Gets the attributes that will be written to the chart as a List.
    *
    * @return The attributes list.
    */
   public List<String> getAttributesAsList() {
      return attributes;
   }
}


text:
require 'spec_helper'

describe EssenceVersion do
  pending "add some examples to (or delete) #{__FILE__}"
end

redpajama_set_name: RedPajamaGithub


text:
import sys, os.path
import shutil
import json
import itertools

#from django.utils.timezone import now
#from datetime.datetime import now
import datetime

datadir = '/dataset/oltpbench/first_paper_experiments/analysis/knob_identification'

dbmss = {'postgres-9.6': 1}
hardwares = {'m3.xlarge': 16}
#ts = '"2011-09-01T13:20:30+03:00"'#datetime.datetime.now()
ts = '2016-12-04 11:00'
convert = True
task_type = 2

model = 'website.PipelineResult'
validate = True
extra_exceptions = {
    'checkpoint_segments',
}

def validate_postgres(knobs, dbms):
    with open('../knob_settings/{}/{}_knobs.json'.format(dbms.replace('-', '_'), dbms.replace('.', '')), 'r') as f:
        knob_info = json.load(f)
        knob_info = {k['fields']['name']: k['fields'] for k in knob_info}
    for kname, kinfo in knob_info.iteritems():
        if not kname in knobs and kinfo['tunable'] == True:
            knobs.append(kname)
            print "WARNING: adding missing knob to end ({})".format(kname)
    knob_names = knob_info.keys()
    for kname in knobs:
        if kname not in knob_names:
            if kname not in extra_exceptions:
                raise Exception('Extra knob: {}'.format(kname))
            knobs.remove(kname)
            print "WARNING: removing extra knob ({})".format(kname)

for dbms, hw in itertools.product(dbmss.keys(), hardwares):
    datapath = os.path.join(datadir, '{}_{}'.format(dbms, hw))
    if not os.path.exists(datapath):
        raise IOError('Path does not exist: {}'.format(datapath))
    with open(os.path.join(datapath, 'featured_knobs.txt'), 'r') as f:
        knobs = [k.strip() for k in f.read().split('\n')]
    if validate and dbms.startswith('postgres'):
        validate_postgres(knobs, dbms)

    basename = '{}_{}_ranked_knobs'.format(dbms, hw).replace('.', '')
    with open(basename + '.txt', 'w') as f:
        f.write('\n'.join(knobs))

    django_entry = [{
        'model': model,
        'fields': {
            'dbms': dbmss[dbms],
            'hardware': hardwares[hw],
            'creation_timestamp': ts,
            'task_type': task_type,
            'value': json.dumps(knobs, indent=4)
        }
    }]
    savepath = basename + '.json'
    with open(savepath, 'w') as f:
        json.dump(django_entry, f, indent=4)

    shutil.copy(savepath, '../../preload/{}'.format(savepath))


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Personil_model extends CI_Model
{

	private $table = "MASTER_PERSONIL";

	public function get_all_items()
	{
        return $this->db->get($this->table);
	}

    public  function get_item_by_id($id)
    {
		$this->db->select('*');
		$this->db->from($this->table);
		$this->db->where('ID', $id);
		return $this->db->get();
    }

    public function save($array_col_val = array())
    {
    	$this->db->insert($this->table,$array_col_val);
    	return $this->db->insert_id();
    }

    public function delete_by_id($id)
    {
    	$this->db->delete($this->table, array('ID' => $id));
    }

    public function update($array_col_val = array(), $id)
    {
		$this->db->where('ID', $id);
		$this->db->update($this->table, $array_col_val);
		return $id;
    }
}


text:
<server description="ferret server">

    <featureManager>
        <feature>jsp-2.3</feature>
        <feature>appSecurity-2.0</feature>
    </featureManager>

    <httpEndpoint id="defaultHttpEndpoint"
                  host="*"
                  httpPort="9080"
                  httpsPort="9443" >
        <tcpOptions soReuseAddr="true"/>
    </httpEndpoint>

    <application name="ferret" context-root="/ferret" location="${wlp.install.dir}/../../${appLocation}" type="war">
      <application-bnd>
        <security-role name="user">
          <user name="bob"/>
        </security-role>
      </application-bnd>
    </application>

    <keyStore id="defaultKeyStore" password="Liberty"/>

    <quickStartSecurity userName="bob" userPassword="passw0rd" />

</server>


text:
<?php
/**
 * Page not found error
 */

echo elgg_echo('error:404:content');


text:
package com.leonarduk.finance.utils;

import com.google.common.collect.Maps;
import com.leonarduk.finance.stockfeed.feed.yahoofinance.YahooFeed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * Helpers for common dates
 */
public class DateUtils {
    public static final Logger logger = LoggerFactory.getLogger(DateUtils.class.getName());
    private static Map<String, Date> dates;

    public static LocalDate calendarToLocalDate(Calendar calendar) {
        return LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId()).toLocalDate();
    }

    public static Calendar dateToCalendar(final Date date) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public static Calendar dateToCalendar(final ZonedDateTime fromDate) {
        return DateUtils.dateToCalendar(convertToDateViaInstant(fromDate.toLocalDate()));
    }

    public static int getDiffInWorkDays(final LocalDate startDate, final LocalDate endDate) {
        return getDiffInWorkDays(startDate, endDate, Optional.empty());
    }
    public static int getDiffInWorkDays(final LocalDate startDate, final LocalDate endDate, final Optional<List<LocalDate>> holidays) {
        // Validate method arguments
        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("Invalid method argument(s) to countBusinessDaysBetween (" + startDate + "," + endDate + "," + holidays + ")");
        }

        // Predicate 1: Is a given date is a holiday
        Predicate<LocalDate> isHoliday = date -> holidays.isPresent()
                && holidays.get().contains(date);

        // Iterate over stream of all dates and check each day against any weekday or
        // holiday
        List<LocalDate> businessDays = startDate.datesUntil(endDate)
                .filter(isWeekend().or(isHoliday).negate())
                .collect(Collectors.toList());

        return businessDays.size();
    }

    public static Predicate<LocalDate> isWeekend() {
        Predicate<LocalDate> isWeekend = date -> date.getDayOfWeek() == DayOfWeek.SATURDAY
                || date.getDayOfWeek() == DayOfWeek.SUNDAY;
        return isWeekend;
    }

    private static String getDividendDateFormat(final String date) {
        if (date.matches("[0-9][0-9]-...-[0-9][0-9]")) {
            return "dd-MMM-yy";
        } else if (date.matches("[0-9]-...-[0-9][0-9]")) {
            return "d-MMM-yy";
        } else if (date.matches("...[ ]+[0-9]+")) {
            return "MMM d";
        } else {
            return "M/d/yy";
        }
    }

    public static Iterator<LocalDate> getLocalDateIterator(final LocalDate oldestDate, final LocalDate mostRecentDate) {
        return new Iterator<LocalDate>() {

            LocalDate nextDate = oldestDate;

            @Override
            public boolean hasNext() {
                return this.nextDate.isBefore(mostRecentDate) || this.nextDate.equals(mostRecentDate);
            }

            @Override
            public LocalDate next() {
                final LocalDate currentDate = this.nextDate;
                if (this.nextDate.getDayOfWeek() == DayOfWeek.FRIDAY) {
                    this.nextDate = this.nextDate.plusDays(2);
                }
                this.nextDate = this.nextDate.plusDays(1);
                return currentDate;
            }

        };

    }

    public static Iterator<ZonedDateTime> getLocalDateNewToOldIterator(final ZonedDateTime startDate,
                                                                       final ZonedDateTime lastDate) {
        return new Iterator<ZonedDateTime>() {

            ZonedDateTime nextDate = startDate;

            @Override
            public boolean hasNext() {
                return this.nextDate.isAfter(lastDate) || this.nextDate.equals(lastDate);
            }

            @Override
            public ZonedDateTime next() {
                if (this.nextDate.getDayOfWeek() == DayOfWeek.SUNDAY) {
                    this.nextDate = this.nextDate.minusDays(2);
                }
                if (this.nextDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
                    this.nextDate = this.nextDate.minusDays(1);
                }
                final ZonedDateTime currentDate = this.nextDate;
                this.nextDate = this.nextDate.minusDays(1);
                return currentDate;
            }

        };

    }

    public static LocalDate getPreviousDate(final LocalDate localDate) {
        final LocalDate returnDate = localDate.minusDays(1);
        return getLastWeekday(returnDate);
    }

    public static LocalDate getLastWeekday(final LocalDate returnDate) {
        if ((returnDate.getDayOfWeek() == DayOfWeek.SATURDAY) || (returnDate.getDayOfWeek() == DayOfWeek.SUNDAY)) {
            return DateUtils.getPreviousDate(returnDate);
        }
        return returnDate;
    }

    public static Date parseDate(final String fieldValue) throws ParseException {
        if (null == DateUtils.dates) {
            DateUtils.dates = Maps.newConcurrentMap();
        }
        return (DateUtils.dates.computeIfAbsent(fieldValue,
                v -> DateUtils.convertToDateViaInstant(LocalDate.parse(v, DateTimeFormatter.ISO_DATE))));
    }

    /**
     * Used to parse the last trade date / time. Returns null if the date / time
     * cannot be parsed.
     *
     * @param date     String received that represents the date
     * @param time     String received that represents the time
     * @param timeZone time zone to use for parsing the date time
     * @return Calendar object with the parsed datetime
     */
    public static Calendar parseDateTime(final String date, final String time, final TimeZone timeZone) {
        final String datetime = date + " " + time;
        final SimpleDateFormat format = new SimpleDateFormat("M/d/yyyy h:mma", Locale.US);

        format.setTimeZone(timeZone);
        try {
            if (StringUtils.isParseable(date) && StringUtils.isParseable(time)) {
                final Calendar c = Calendar.getInstance();
                c.setTime(format.parse(datetime));
                return c;
            }
        } catch (final ParseException ex) {
            DateUtils.logger.warn("Failed to parse datetime: " + datetime);
            DateUtils.logger.trace("Failed to parse datetime: " + datetime, ex);
        }
        return null;
    }

    /**
     * Used to parse the dividend dates. Returns null if the date cannot be parsed.
     *
     * @param date String received that represents the date
     * @return Calendar object representing the parsed date
     */
    public static Calendar parseDividendDate(final String date) {
        if (!StringUtils.isParseable(date)) {
            return null;
        }
        final SimpleDateFormat format = new SimpleDateFormat(DateUtils.getDividendDateFormat(date.trim()), Locale.US);
        format.setTimeZone(TimeZone.getTimeZone(YahooFeed.TIMEZONE));
        try {
            final Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFeed.TIMEZONE));
            final Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFeed.TIMEZONE));
            parsedDate.setTime(format.parse(date.trim()));

            if (parsedDate.get(Calendar.YEAR) == 1970) {
                // Not really clear which year the dividend date is... making a
                // reasonable guess.
                final int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH);
                int year = today.get(Calendar.YEAR);
                if (monthDiff > 6) {
                    year -= 1;
                } else if (monthDiff < -6) {
                    year += 1;
                }
                parsedDate.set(Calendar.YEAR, year);
            }

            return parsedDate;
        } catch (final ParseException ex) {
            DateUtils.logger.warn("Failed to parse dividend date: " + date);
            DateUtils.logger.trace("Failed to parse dividend date: " + date, ex);
            return null;
        }
    }

    public static Date convertToDateViaInstant(LocalDate fromDate) {
        return java.util.Date.from(fromDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    public static ZonedDateTime calendarToZonedDateTime(Calendar lastTradeTime) {
        return lastTradeTime.toInstant().atZone(ZoneId.systemDefault());
    }

//	public ZonedDateTime convertToLocalDateViaMilisecond(Date dateToConvert) {
//		return Instant.ofEpochMilli(dateToConvert.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
//	}

    public LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
        return dateToConvert.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

}


text:
<?php

namespace Webforge\Code\Generator;

use ArrayIterator;
use Countable;
use Doctrine\Common\Util\Debug;
use InvalidArgumentException;
use IteratorAggregate;
use LogicException;
use RuntimeException;
use Webforge\Common\ClassInterface;

class Imports implements IteratorAggregate, Countable
{
    /**
     * @var array
     */
    protected $classes = array();

    /**
     * @var array the keys from $classes but lowercased
     */
    protected $aliases = array();

    /**
     * you can use numeric keys for imports without an specific alias (sets the alias to the className of the class)
     * @param array $alias => GClass $importClass
     */
    public function __construct(array $importClasses = array())
    {
        foreach ($importClasses as $alias => $gClass) {
            if (is_numeric($alias)) {
                $alias = null;
            }

            $this->add($gClass, $alias);
        }
    }

    public function php($contextNamespace, $eol = "\n")
    {
        $use = null;
        foreach ($this->classes as $alias => $import) {
            // is it needed to import the class?
            if ($import->getNamespace() === null || $import->getNamespace() !== $contextNamespace) {
                $use .= 'use ';
                if ($alias === $import->getName()) {
                    $use .= $import->getFQN();
                } else {
                    $use .= $import->getFQN() . ' AS ' . $alias;
                }

                $use .= ';' . $eol;
            }
        }
        return $use;
    }

    /**
     * Adds an Import
     *
     * its not allowed to set an already used alias.
     * You have to remove the alias first
     * @param string $alias sets an explicit alias. (the implicit is always the classname)
     */
    public function add(ClassInterface $import, $alias = null)
    {
        if (empty($alias)) {
            $alias = $import->getName();
        }

        if (empty($alias)) {
            throw new InvalidArgumentException('GClass: ' . $import . ' must have a valid FQN: ' . $import->getFQN());
        }

        if (array_key_exists($lowerAlias = mb_strtolower($alias), $this->aliases)) {
            $usedBy = $this->classes[$this->aliases[$lowerAlias]];

            if (!$import->equals($usedBy)) {
                throw new LogicException('Alias: ' . $alias . ' is already used by Class ' . $usedBy);
            }
        }

        $this->classes[$alias] = $import;
        $this->aliases[$lowerAlias] = $alias;
        return $this;
    }

    /**
     * Removes an Import
     *
     * @param string|GClass $aliasOrGClass
     * @chainable
     */
    public function remove($aliasOrGClass)
    {
        if ($aliasOrGClass instanceof ClassInterface) {
            $gClass = $aliasOrGClass;
            $alias = $aliasOrGClass->getName();
        } else {
            $gClass = null;
            $alias = $aliasOrGClass;
        }

        if (array_key_exists($loweralias = mb_strtolower($alias), $this->aliases)) {
            unset($this->classes[$this->aliases[$loweralias]]);
            unset($this->aliases[$loweralias]);
        } elseif (isset($gClass)) {
            foreach ($this->classes as $alias => $otherGClass) {
                if ($otherGClass->equals($gClass)) {
                    unset($this->aliases[mb_strtolower($alias)]);
                    unset($this->classes[$alias]);
                    break;
                }
            }
        }

        return $this;
    }

    /**
     * @return bool
     */
    public function have($aliasOrGClass)
    {
        $alias = $aliasOrGClass instanceof ClassInterface ? $aliasOrGClass->getName() : $aliasOrGClass;
        return array_key_exists(mb_strtolower($alias), $this->aliases);
    }

    /**
     * @return string|NULL
     */
    public function getAlias(ClassInterface $gClass)
    {
        foreach ($this->classes as $alias => $aliasedGClass) {
            if ($aliasedGClass->equals($gClass)) {
                return $alias;
            }
        }
        return null;
    }

    /**
     * @return GClass
     * @throws RuntimeException if alias is not in imports
     */
    public function get($alias)
    {
        if (array_key_exists($lowerAlias = mb_strtolower($alias), $this->aliases)) {
            return $this->classes[$this->aliases[$lowerAlias]];
        }

        throw new RuntimeException(sprintf("The import with alias '%s' cannot be found", $alias));
    }

    /**
     * Merges all Imports from a GClass to this imports
     *
     * @chainable
     */
    public function mergeFromClass(GClass $gClass)
    {
        try {
            foreach ($gClass->getImports()->toArray() as $alias => $import) {
                $this->add($import, $alias);
            }
        } catch (InvalidArgumentException $e) {
            Debug::dump($gClass->getImports()->toArray());
            throw new InvalidArgumentException(
                'Cannot add all imports from ' . $gClass->getFQN() . ' into imports.',
                0,
                $e
            );
        }

        return $this;
    }

    /**
     * Gets an iterator for iterating over the elements in the collection.
     *
     * @return ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->classes);
    }

    /**
     * Convert to array
     *
     * the keys of the array are the aliases (case sensitive, as given in add)
     * the values are the gclasses
     * @return array string $alias => GClass $gClass
     */
    public function toArray()
    {
        return $this->classes;
    }

    /**
     * @return int
     */
    public function count()
    {
        return count($this->classes);
    }
}


text:
<?php

class GlossaryPage extends Page {

    public function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->removeFieldFromTab('Root.Content.Main', 'Content');
        $fields->addFieldToTab('Root.Content.Main', new TextareaField('Content', 'Intro (line breaks and HTML will be ignored)', 4));

        return $fields;
    }

    /**
     * Strips HTML and line breaks from the Intro (Content) paragraph
     */
    public function onBeforeWrite() {
        parent::onBeforeWrite();
        if ( isset($this->record['Content']) ) {
            $this->record['Content'] = strip_tags($this->record['Content']);
            $this->record['Content'] = str_replace("\n", ' ', $this->record['Content']);
        }
    }

}

class GlossaryPage_Controller extends Page_Controller {

    /* Stores the term object for this particular instance. */
    private $term;

    public function init() {
        $this->isAjax = false;
        if ( array_key_exists('ajaxget', $_REQUEST) ) {
            $this->isAjax = true;
        }
        parent::init();
    }

    public function index($r) {
        if ( $this->isAjax ) {
            return $this->renderWith('GlossaryAjax');
        }
        return $this->renderWith(array('GlossaryPage','Page'));
    }

    //////////     Glossary HTML functions

    public function GlossaryTerms() {
        return DataObject::get('GlossaryTerm', null, 'Term');
    }

    public function Term() {
        $term = $this->get_term();
        if ( ! is_object($term) ) return false;
        return $term->Term;
    }

    public function Definition() {
        $term = $this->get_term();
        if ( ! is_object($term) ) return false;
        return $term->Definition;
    }

    private function get_term() {
        if ( ! is_object($this->term) ) {
            $this->term = DataObject::get_one(
                'Glossary',
                "`Term` = '".mysql_real_escape_string($this->urlParams['ID'])."'"
            );
        }

        return $this->term;
    }

    //////////     AJAX functions

    /**
     * Overload $this->Children() to grab the bits we've specified on the URL.
     * URL is of format /glossary/ajax/?ajaxget=Title
     * @return  GlossaryTerm    The GlossaryTerm's Definition field.  If not found, returns blank.
     */
    public function AjaxOutput() {
        $item = $_REQUEST['ajaxget'];
        return DataObject::get_one(
            'GlossaryTerm',
            sprintf(
                "Term = '%s'",
                mysql_real_escape_string($item)
            )
        );
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2010-2013 Ning, Inc.
  ~
  ~ Ning licenses this file to you under the Apache License, version 2.0
  ~ (the "License"); you may not use this file except in compliance with the
  ~ License.  You may obtain a copy of the License at:
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  ~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
  ~ License for the specific language governing permissions and limitations
  ~ under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>killbill</artifactId>
        <groupId>org.kill-bill.billing</groupId>
        <version>0.15.11-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>killbill-entitlement</artifactId>
    <packaging>jar</packaging>
    <name>killbill-entitlement</name>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.awaitility</groupId>
            <artifactId>awaitility</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>stringtemplate</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.jdbi</groupId>
            <artifactId>jdbi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-account</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-catalog</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-catalog</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-internal-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-base</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-lifecycle</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-osgi-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-subscription</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-util</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing.plugin</groupId>
            <artifactId>killbill-plugin-api-entitlement</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-clock</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-clock</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-embeddeddb-h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-embeddeddb-mysql</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-queue</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-queue</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.skife.config</groupId>
            <artifactId>config-magic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
global $redux_builder_amp;
if ( ( (is_single() && 1 == ampforwp_get_setting('ampforwp-bread-crumb')) || (is_page() && ampforwp_get_setting('ampforwp_pages_breadcrumbs')) ) && !checkAMPforPageBuilderStatus(get_the_ID()) ) {
    $home_non_amp = $archive_non_amp = '';
    if ( false == $redux_builder_amp['ampforwp-homepage-on-off-support'] ) {
        $home_non_amp = 'nonamp';
    }
    if ( false == $redux_builder_amp['ampforwp-archive-support'] ) {
        $archive_non_amp = 'nonamp';
    } ?>

 <?php
    // Settings
    $breadcrums_id      = 'breadcrumbs';
    $breadcrums_class   = 'breadcrumbs';
    $home_title         = ampforwp_translation($redux_builder_amp['amp-translator-breadcrumbs-homepage-text'] , 'Homepage' );
    if (function_exists('pll__')) {
        $home_title = pll__(esc_html__( ampforwp_get_setting('amp-translator-breadcrumbs-homepage-text'), 'accelerated-mobile-pages'));
    }
    // If you have any custom post types with custom taxonomies, put the taxonomy name below (e.g. product_cat)
    $custom_taxonomy    = 'product_cat';

    // Get the query & post information
    global $post,$wp_query;

    // Do not display on the homepage
    if ( !is_front_page() && !ampforwp_polylang_front_page() ) {

        // Build the breadcrums
        echo '
';

        // Home page
        echo '
' . esc_html($home_title) . '
';

        if ( is_archive() && !is_tax() && !is_category() && !is_tag() && !is_author() ) {

            echo '
' . post_type_archive_title($prefix, false) . '
';
        } else if  ( is_author() ) {
                global $author;

                $userdata = get_userdata( $author );
                $author_url= get_author_posts_url($userdata->ID);
                $author_url = trailingslashit($author_url);
                // Display author name
                echo '
user_nicename) . '">user_nicename) . '" title="' . esc_attr($userdata->display_name) . '" href="'. ampforwp_url_controller( $author_url, $archive_non_amp ). '">' . 'Author: ' . esc_html($userdata->display_name) . '
';

        } else if ( is_archive() && is_tax() && !is_category() && !is_tag() ) {

            // If post is a custom post type
            $post_type = get_post_type();

            // If it is a custom post type display name and link
            if($post_type != 'post') {

                $post_type_object = get_post_type_object($post_type);
                $post_type_archive = get_post_type_archive_link($post_type);
                if ( false != $post_type_archive){
                    echo '
labels->name) . '">' . esc_html($post_type_object->labels->name) . '
';
                }
                else {
                    echo '
' . esc_html($post_type_object->labels->name) . '
';
                }
            }

            $custom_tax_name = get_queried_object()->name;
            echo '
' . esc_html($custom_tax_name) . '
';
        } else if ( is_single() ) {

            // If post is a custom post type
            $post_type = get_post_type();

            // If it is a custom post type display name and link
            if($post_type != 'post') {

                $post_type_object = get_post_type_object($post_type);
                $post_type_archive = get_post_type_archive_link($post_type);
                if ( false != $post_type_archive){
                    echo '
labels->name) . '">' . esc_html($post_type_object->labels->name) . '
';
                }
                else {
                    echo '
' . esc_html($post_type_object->labels->name) . '
';
                }
            }
            /*Breadcrumb with tags Start*/
            $tags_breadcrumbs = '';
            if(ampforwp_get_setting('ampforwp-bread-crumb-type') == 'tags'){
                $post_tags = wp_get_post_tags($post->ID);
                if(!empty($post_tags)){
                    foreach( $post_tags as $post_obj){
                        $tag_name = $post_obj->name;
                        $tag_id = $post_obj->term_id;
                        $tag_name = $post_obj->name;
                        $tag_link = get_tag_link($tag_id);
                        if(ampforwp_get_setting('ampforwp-archive-support-tag') == true && ampforwp_get_setting('ampforwp-archive-support') == true){
                            $tag_link = ampforwp_url_controller( $tag_link );
                        }
                        $tags_breadcrumbs .= '
'.esc_html($tag_name).'
';
                    }
                    if(ampforwp_get_setting('ampforwp-bread-crumb-post')){
                        if (class_exists('WPSEO_Premium') && !empty(WPSEO_Meta::get_value( 'bctitle', ampforwp_get_the_ID()))) {
                            $bc_title = WPSEO_Meta::get_value( 'bctitle', ampforwp_get_the_ID() );
                        }else{
                            $bc_title = get_the_title(ampforwp_get_the_ID());
                        }
                            $tags_breadcrumbs .='
'.wp_kses_data( $bc_title ). '
';
                    }
                    echo $tags_breadcrumbs; // escaped above
                }
            }
            if(ampforwp_get_setting('ampforwp-bread-crumb-type') == 'category'){
             // Get post category info
                $category = get_the_category();
                if(!empty($category)) {

                    // Get last category post is in
                    $last_category = array_values($category);
                    $last_category = end($last_category);
                      $category_name = get_category($last_category);
                    // Get parent any categories and create array
                    $get_cat_parents = rtrim(get_category_parents($last_category->term_id, false, '>'),'>');
                    if(class_exists( 'WPSEO_Options' )){
                        $primary_cateogory = get_post_meta(ampforwp_get_the_ID(), '_yoast_wpseo_primary_category', true);
                    if(isset($primary_cateogory) && $primary_cateogory!=""){
                        $pcname = get_the_category_by_ID($primary_cateogory);
                        $category_name = $pcname;
                        $get_cat_parents = rtrim(get_category_parents($primary_cateogory, false, '>'),'>');
                       }
                   }
                        // Get parent any categories and create array
                        $cat_parents = explode('>',$get_cat_parents);
                    // Loop through parent categories and store in variable $cat_display
                    $cat_display = '';
                    foreach($cat_parents as $parents) {
                        $categories = get_the_category();
                        $cat_id = $categories[0]->cat_ID;
                        $cat_link = get_category_link($cat_id);
                         if(ampforwp_get_setting('ampforwp-archive-support-cat') == true && ampforwp_get_setting('ampforwp-archive-support') == true){
                            $cat_link = ampforwp_url_controller( $cat_link );
                        }
                        $cat_display .= '
'.esc_html($parents).'
';
                    }
                        if(ampforwp_get_setting('ampforwp-bread-crumb-post')){
                            if (class_exists('WPSEO_Premium') && !empty(WPSEO_Meta::get_value( 'bctitle', ampforwp_get_the_ID()))) {
                               $bc_title = WPSEO_Meta::get_value( 'bctitle', ampforwp_get_the_ID() );
                            }else{
                                $bc_title = get_the_title(ampforwp_get_the_ID());
                            }
                            $cat_display .='
'.wp_kses_data( $bc_title ). '
';
                        }
                }
            }
            /*Breadcrumb with tags End*/

            // If it's a custom post type within a custom taxonomy
            $taxonomy_exists = taxonomy_exists($custom_taxonomy);
            if(empty($last_category) && !empty($custom_taxonomy) && $taxonomy_exists) {

                $taxonomy_terms = get_the_terms( $post->ID, $custom_taxonomy );
                if ( $taxonomy_terms ) {
                    $cat_id         = $taxonomy_terms[0]->term_id;
                    $cat_nicename   = $taxonomy_terms[0]->slug;
                    $cat_link       = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy);
                    $cat_link       = trailingslashit($cat_link);
                    $cat_name       = $taxonomy_terms[0]->name;
                }
            }

            // Check if the post is in a category
            if(!empty($last_category)) {
                echo $cat_display; // escaped above

            // Else if post is in a custom taxonomy
            } else if(!empty($cat_id)) {

                echo '
' . esc_attr($cat_name) . '
';
            }

        } else if ( is_category() ) {

            // Category page
            echo '
' . single_cat_title('', false) . '
';
        } else if ( is_page() ) {

            // Standard page
            if( $post->post_parent ){

                // If child page, get parents
                $anc = get_post_ancestors( $post->ID );

                // Get parents in the right order
                $anc = array_reverse($anc);

                // Parent page loop
                if ( !isset( $parents ) ) $parents = null;
                foreach ( $anc as $ancestor ) {
                    $parents .= '
' . esc_html(get_the_title($ancestor)) . '
';
                }

                // Display parent pages
                echo $parents; // escaped above

                // Current page

            }

        } else if ( is_tag() ) {

            // Tag page

            // Get tag information
            $term_id        = get_query_var('tag_id');
            $taxonomy       = 'post_tag';
            $args           = 'include=' . intval($term_id);
            $terms          = get_terms( $taxonomy, $args );
            $get_term_id    = $terms[0]->term_id;
            $get_term_slug  = $terms[0]->slug;
            $get_term_name  = $terms[0]->name;

            // Display the tag name
            echo '
' . esc_html($get_term_name) . '
';
        } elseif ( is_day() ) {

            // Day archive

            // Year link
            echo '
' . esc_attr(get_the_time('Y')) . esc_html(ampforwp_translation($redux_builder_amp['amp-translator-archives-text'], 'Archives')) . '
';

            // Month link
            echo '
' . esc_attr(get_the_time('M')) . esc_html(ampforwp_translation($redux_builder_amp['amp-translator-archives-text'], 'Archives')) . '
';

            // Day display
            echo '
 ' . esc_attr(get_the_time('jS')) . ' ' . esc_attr(get_the_time('M')) . esc_html(ampforwp_translation($redux_builder_amp['amp-translator-archives-text'], 'Archives')) . '
';

        } else if ( is_month() ) {

            // Month Archive

            // Year link
            echo '
' . esc_attr(get_the_time('Y')) . esc_html(ampforwp_translation($redux_builder_amp['amp-translator-archives-text'], 'Archives')) . '
';

            // Month display
            echo '
' . esc_attr(get_the_time('M')) . esc_html(ampforwp_translation($redux_builder_amp['amp-translator-archives-text'], 'Archives')) . '
';

        } else if ( is_year() ) {

            // Display year archive
            echo '
' . esc_attr(get_the_time('Y')) . esc_html(ampforwp_translation($redux_builder_amp['amp-translator-archives-text'], 'Archives')). '
';

        }   else if ( get_query_var('paged') ) {

            // Paginated archives
            echo '
'. esc_html(ampforwp_translation($redux_builder_amp['amp-translator-page-text'], 'Page')) . ' ' . esc_attr(get_query_var('paged')) . '
';

        } else if ( is_search() ) {

            // Search results page
            echo '

            ' . esc_html(ampforwp_translation($redux_builder_amp['amp-translator-breadcrumbs-search-text'], 'Search results for')) . ': ' . esc_attr(get_search_query()) . '
';

        }
        echo '
';

    }?>

<?php }


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

package kafka.api

import java.io.File
import java.{lang, util}
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger}
import java.util.{Collections, Properties}

import kafka.api.GroupedUserPrincipalBuilder._
import kafka.api.GroupedUserQuotaCallback._
import kafka.server._
import kafka.utils.JaasTestUtils.ScramLoginModule
import kafka.utils.{JaasTestUtils, Logging, TestUtils}
import kafka.zk.ConfigEntityChangeNotificationZNode
import org.apache.kafka.clients.admin.{AdminClient, AdminClientConfig}
import org.apache.kafka.clients.consumer.{ConsumerConfig, KafkaConsumer}
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.{Cluster, Reconfigurable}
import org.apache.kafka.common.config.SaslConfigs
import org.apache.kafka.common.network.ListenerName
import org.apache.kafka.common.security.auth._
import org.apache.kafka.common.security.scram.ScramCredential
import org.apache.kafka.server.quota._
import org.junit.Assert._
import org.junit.{After, Before, Test}

import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConverters._

class CustomQuotaCallbackTest extends IntegrationTestHarness with SaslSetup {

  override protected def securityProtocol = SecurityProtocol.SASL_SSL
  override protected def listenerName = new ListenerName("CLIENT")
  override protected def interBrokerListenerName: ListenerName = new ListenerName("BROKER")

  override protected lazy val trustStoreFile = Some(File.createTempFile("truststore", ".jks"))
  override val serverCount: Int = 2

  private val kafkaServerSaslMechanisms = Seq("SCRAM-SHA-256")
  private val kafkaClientSaslMechanism = "SCRAM-SHA-256"
  override protected val serverSaslProperties = Some(kafkaServerSaslProperties(kafkaServerSaslMechanisms, kafkaClientSaslMechanism))
  override protected val clientSaslProperties = Some(kafkaClientSaslProperties(kafkaClientSaslMechanism))
  private val adminClients = new ArrayBuffer[AdminClient]()
  private var producerWithoutQuota: KafkaProducer[Array[Byte], Array[Byte]] = _

  val defaultRequestQuota = 1000
  val defaultProduceQuota = 2000 * 1000 * 1000
  val defaultConsumeQuota = 1000 * 1000 * 1000

  @Before
  override def setUp() {
    startSasl(jaasSections(kafkaServerSaslMechanisms, Some("SCRAM-SHA-256"), KafkaSasl, JaasTestUtils.KafkaServerContextName))
    this.serverConfig.setProperty(KafkaConfig.ProducerQuotaBytesPerSecondDefaultProp, Long.MaxValue.toString)
    this.serverConfig.setProperty(KafkaConfig.ConsumerQuotaBytesPerSecondDefaultProp, Long.MaxValue.toString)
    this.serverConfig.setProperty(KafkaConfig.ClientQuotaCallbackClassProp, classOf[GroupedUserQuotaCallback].getName)
    this.serverConfig.setProperty(s"${listenerName.configPrefix}${KafkaConfig.PrincipalBuilderClassProp}",
      classOf[GroupedUserPrincipalBuilder].getName)
    this.serverConfig.setProperty(KafkaConfig.DeleteTopicEnableProp, "true")
    super.setUp()
    brokerList = TestUtils.bootstrapServers(servers, listenerName)

    producerConfig.put(SaslConfigs.SASL_JAAS_CONFIG,
      ScramLoginModule(JaasTestUtils.KafkaScramAdmin, JaasTestUtils.KafkaScramAdminPassword).toString)
    producerWithoutQuota = createProducer()
  }

  @After
  override def tearDown(): Unit = {
    adminClients.foreach(_.close())
    super.tearDown()
  }

  override def configureSecurityBeforeServersStart() {
    super.configureSecurityBeforeServersStart()
    zkClient.makeSurePersistentPathExists(ConfigEntityChangeNotificationZNode.path)
    createScramCredentials(zkConnect, JaasTestUtils.KafkaScramAdmin, JaasTestUtils.KafkaScramAdminPassword)
  }

  @Test
  def testCustomQuotaCallback() {
    // Large quota override, should not throttle
    var brokerId = 0
    var user = createGroupWithOneUser("group0_user1", brokerId)
    user.configureAndWaitForQuota(1000000, 2000000)
    quotaLimitCalls.values.foreach(_.set(0))
    user.produceConsume(expectProduceThrottle = false, expectConsumeThrottle = false)

    // ClientQuotaCallback#quotaLimit is invoked by each quota manager once for each new client
    assertEquals(1, quotaLimitCalls(ClientQuotaType.PRODUCE).get)
    assertEquals(1, quotaLimitCalls(ClientQuotaType.FETCH).get)
    assertTrue(s"Too many quotaLimit calls $quotaLimitCalls", quotaLimitCalls(ClientQuotaType.REQUEST).get <= serverCount)
    // Large quota updated to small quota, should throttle
    user.configureAndWaitForQuota(9000, 3000)
    user.produceConsume(expectProduceThrottle = true, expectConsumeThrottle = true)

    // Quota override deletion - verify default quota applied (large quota, no throttling)
    user = addUser("group0_user2", brokerId)
    user.removeQuotaOverrides()
    user.waitForQuotaUpdate(defaultProduceQuota, defaultConsumeQuota, defaultRequestQuota)
    user.removeThrottleMetrics() // since group was throttled before
    user.produceConsume(expectProduceThrottle = false, expectConsumeThrottle = false)

    // Make default quota smaller, should throttle
    user.configureAndWaitForQuota(8000, 2500, divisor = 1, group = None)
    user.produceConsume(expectProduceThrottle = true, expectConsumeThrottle = true)

    // Configure large quota override, should not throttle
    user = addUser("group0_user3", brokerId)
    user.configureAndWaitForQuota(2000000, 2000000)
    user.removeThrottleMetrics() // since group was throttled before
    user.produceConsume(expectProduceThrottle = false, expectConsumeThrottle = false)

    // Quota large enough for one partition, should not throttle
    brokerId = 1
    user = createGroupWithOneUser("group1_user1", brokerId)
    user.configureAndWaitForQuota(8000 * 100, 2500 * 100)
    user.produceConsume(expectProduceThrottle = false, expectConsumeThrottle = false)

    // Create large number of partitions on another broker, should result in throttling on first partition
    val largeTopic = "group1_largeTopic"
    createTopic(largeTopic, numPartitions = 99, leader = 0)
    user.waitForQuotaUpdate(8000, 2500, defaultRequestQuota)
    user.produceConsume(expectProduceThrottle = true, expectConsumeThrottle = true)

    // Remove quota override and test default quota applied with scaling based on partitions
    user = addUser("group1_user2", brokerId)
    user.waitForQuotaUpdate(defaultProduceQuota / 100, defaultConsumeQuota / 100, defaultRequestQuota)
    user.removeThrottleMetrics() // since group was throttled before
    user.produceConsume(expectProduceThrottle = false, expectConsumeThrottle = false)
    user.configureAndWaitForQuota(8000 * 100, 2500 * 100, divisor=100, group = None)
    user.produceConsume(expectProduceThrottle = true, expectConsumeThrottle = true)

    // Remove the second topic with large number of partitions, verify no longer throttled
    adminZkClient.deleteTopic(largeTopic)
    user = addUser("group1_user3", brokerId)
    user.waitForQuotaUpdate(8000 * 100, 2500 * 100, defaultRequestQuota)
    user.removeThrottleMetrics() // since group was throttled before
    user.produceConsume(expectProduceThrottle = false, expectConsumeThrottle = false)

    // Alter configs of custom callback dynamically
    val adminClient = createAdminClient()
    val newProps = new Properties
    newProps.put(GroupedUserQuotaCallback.DefaultProduceQuotaProp, "8000")
    newProps.put(GroupedUserQuotaCallback.DefaultFetchQuotaProp, "2500")
    TestUtils.alterConfigs(servers, adminClient, newProps, perBrokerConfig = false)
    user.waitForQuotaUpdate(8000, 2500, defaultRequestQuota)
    user.produceConsume(expectProduceThrottle = true, expectConsumeThrottle = true)

    assertEquals(serverCount, callbackInstances.get)
  }

  /**
   * Creates a group with one user and one topic with one partition.
   * @param firstUser First user to create in the group
   * @param brokerId The broker id to use as leader of the partition
   */
  private def createGroupWithOneUser(firstUser: String, brokerId: Int): GroupedUser = {
    val user = addUser(firstUser, brokerId)
    createTopic(user.topic, numPartitions = 1, brokerId)
    user.configureAndWaitForQuota(defaultProduceQuota, defaultConsumeQuota, divisor = 1, group = None)
    user
  }

  private def createTopic(topic: String, numPartitions: Int, leader: Int): Unit = {
    val assignment = (0 until numPartitions).map { i => i -> Seq(leader) }.toMap
    TestUtils.createTopic(zkClient, topic, assignment, servers)
  }

  private def createAdminClient(): AdminClient = {
    val config = new util.HashMap[String, Object]
    config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
      TestUtils.bootstrapServers(servers, new ListenerName("BROKER")))
    clientSecurityProps("admin-client").asInstanceOf[util.Map[Object, Object]].asScala.foreach { case (key, value) =>
      config.put(key.toString, value)
    }
    config.put(SaslConfigs.SASL_JAAS_CONFIG,
      ScramLoginModule(JaasTestUtils.KafkaScramAdmin, JaasTestUtils.KafkaScramAdminPassword).toString)
    val adminClient = AdminClient.create(config)
    adminClients += adminClient
    adminClient
  }

  private def produceWithoutThrottle(topic: String, numRecords: Int): Unit = {
    (0 until numRecords).foreach { i =>
      val payload = i.toString.getBytes
      producerWithoutQuota.send(new ProducerRecord[Array[Byte], Array[Byte]](topic, null, null, payload))
    }
  }

  private def addUser(user: String, leader: Int): GroupedUser = {
    val password = s"$user:secret"
    createScramCredentials(zkConnect, user, password)
    servers.foreach { server =>
      val cache = server.credentialProvider.credentialCache.cache(kafkaClientSaslMechanism, classOf[ScramCredential])
      TestUtils.waitUntilTrue(() => cache.get(user) != null, "SCRAM credentials not created")
    }

    val userGroup = group(user)
    val topic = s"${userGroup}_topic"
    val producerClientId = s"$user:producer-client-id"
    val consumerClientId = s"$user:consumer-client-id"

    producerConfig.put(ProducerConfig.CLIENT_ID_CONFIG, producerClientId)
    producerConfig.put(SaslConfigs.SASL_JAAS_CONFIG, ScramLoginModule(user, password).toString)
    val producer = createProducer()

    consumerConfig.put(ConsumerConfig.CLIENT_ID_CONFIG, consumerClientId)
    consumerConfig.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 4096.toString)
    consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, s"$user-group")
    consumerConfig.put(SaslConfigs.SASL_JAAS_CONFIG, ScramLoginModule(user, password).toString)
    val consumer = createConsumer()

    GroupedUser(user, userGroup, topic, servers(leader), producerClientId, consumerClientId, producer, consumer)
  }

  case class GroupedUser(user: String, userGroup: String, topic: String, leaderNode: KafkaServer,
                         producerClientId: String, consumerClientId: String,
                         override val producer: KafkaProducer[Array[Byte], Array[Byte]],
                         override val consumer: KafkaConsumer[Array[Byte], Array[Byte]]) extends
    QuotaTestClients(topic, leaderNode, producerClientId, consumerClientId, producer, consumer) {

    override def userPrincipal: KafkaPrincipal = GroupedUserPrincipal(user, userGroup)

    override def quotaMetricTags(clientId: String): Map[String, String] = {
      Map(GroupedUserQuotaCallback.QuotaGroupTag -> userGroup)
    }

    override def overrideQuotas(producerQuota: Long, consumerQuota: Long, requestQuota: Double): Unit = {
      configureQuota(userGroup, producerQuota, consumerQuota, requestQuota)
    }

    override def removeQuotaOverrides(): Unit = {
      adminZkClient.changeUserOrUserClientIdConfig(quotaEntityName(userGroup), new Properties)
    }

    def configureQuota(userGroup: String, producerQuota: Long, consumerQuota: Long, requestQuota: Double): Unit = {
      val quotaProps = quotaProperties(producerQuota, consumerQuota, requestQuota)
      adminZkClient.changeUserOrUserClientIdConfig(quotaEntityName(userGroup), quotaProps)
    }

    def configureAndWaitForQuota(produceQuota: Long, fetchQuota: Long, divisor: Int = 1,
                                 group: Option[String] = Some(userGroup)): Unit = {
      configureQuota(group.getOrElse(""), produceQuota, fetchQuota, defaultRequestQuota)
      waitForQuotaUpdate(produceQuota / divisor, fetchQuota / divisor, defaultRequestQuota)
    }

    def produceConsume(expectProduceThrottle: Boolean, expectConsumeThrottle: Boolean): Unit = {
      val numRecords = 1000
      val produced = produceUntilThrottled(numRecords, waitForRequestCompletion = false)
      verifyProduceThrottle(expectProduceThrottle, verifyClientMetric = false)
      // make sure there are enough records on the topic to test consumer throttling
      produceWithoutThrottle(topic, numRecords - produced)
      consumeUntilThrottled(numRecords, waitForRequestCompletion = false)
      verifyConsumeThrottle(expectConsumeThrottle, verifyClientMetric = false)
    }

    def removeThrottleMetrics(): Unit = {
      def removeSensors(quotaType: QuotaType, clientId: String): Unit = {
        val sensorSuffix = quotaMetricTags(clientId).values.mkString(":")
        leaderNode.metrics.removeSensor(s"${quotaType}ThrottleTime-$sensorSuffix")
        leaderNode.metrics.removeSensor(s"$quotaType-$sensorSuffix")
      }
      removeSensors(QuotaType.Produce, producerClientId)
      removeSensors(QuotaType.Fetch, consumerClientId)
      removeSensors(QuotaType.Request, producerClientId)
      removeSensors(QuotaType.Request, consumerClientId)
    }

    private def quotaEntityName(userGroup: String): String = s"${userGroup}_"
  }
}

object GroupedUserPrincipalBuilder {
  def group(str: String): String = {
    if (str.indexOf("_") <= 0)
      ""
    else
      str.substring(0, str.indexOf("_"))
  }
}

class GroupedUserPrincipalBuilder extends KafkaPrincipalBuilder {
  override def build(context: AuthenticationContext): KafkaPrincipal = {
    val securityProtocol = context.securityProtocol
    if (securityProtocol == SecurityProtocol.SASL_PLAINTEXT || securityProtocol == SecurityProtocol.SASL_SSL) {
      val user = context.asInstanceOf[SaslAuthenticationContext].server().getAuthorizationID
      val userGroup = group(user)
      if (userGroup.isEmpty)
        new KafkaPrincipal(KafkaPrincipal.USER_TYPE, user)
      else
        GroupedUserPrincipal(user, userGroup)
    } else
      throw new IllegalStateException(s"Unexpected security protocol $securityProtocol")
  }
}

case class GroupedUserPrincipal(user: String, userGroup: String) extends KafkaPrincipal(KafkaPrincipal.USER_TYPE, user)

object GroupedUserQuotaCallback {
  val QuotaGroupTag = "group"
  val DefaultProduceQuotaProp = "default.produce.quota"
  val DefaultFetchQuotaProp = "default.fetch.quota"
  val UnlimitedQuotaMetricTags = Collections.emptyMap[String, String]
  val quotaLimitCalls = Map(
    ClientQuotaType.PRODUCE -> new AtomicInteger,
    ClientQuotaType.FETCH -> new AtomicInteger,
    ClientQuotaType.REQUEST -> new AtomicInteger
  )
  val callbackInstances = new AtomicInteger
}

/**
 * Quota callback for a grouped user. Both user principals and topics of each group
 * are prefixed with the group name followed by '_'. This callback defines quotas of different
 * types at the group level. Group quotas are configured in ZooKeeper as user quotas with
 * the entity name "${group}_". Default group quotas are configured in ZooKeeper as user quotas
 * with the entity name "_".
 *
 * Default group quotas may also be configured using the configuration options
 * "default.produce.quota" and "default.fetch.quota" which can be reconfigured dynamically
 * without restarting the broker. This tests custom reconfigurable options for quota callbacks,
 */
class GroupedUserQuotaCallback extends ClientQuotaCallback with Reconfigurable with Logging {

  var brokerId: Int = -1
  val customQuotasUpdated = ClientQuotaType.values.toList
    .map(quotaType =>(quotaType -> new AtomicBoolean)).toMap
  val quotas = ClientQuotaType.values.toList
    .map(quotaType => (quotaType -> new ConcurrentHashMap[String, Double])).toMap

  val partitionRatio = new ConcurrentHashMap[String, Double]()

  override def configure(configs: util.Map[String, _]): Unit = {
    brokerId = configs.get(KafkaConfig.BrokerIdProp).toString.toInt
    callbackInstances.incrementAndGet
  }

  override def reconfigurableConfigs: util.Set[String] = {
    Set(DefaultProduceQuotaProp, DefaultFetchQuotaProp).asJava
  }

  override def validateReconfiguration(configs: util.Map[String, _]): Unit = {
    reconfigurableConfigs.asScala.foreach(configValue(configs, _))
  }

  override def reconfigure(configs: util.Map[String, _]): Unit = {
    configValue(configs, DefaultProduceQuotaProp).foreach(value => quotas(ClientQuotaType.PRODUCE).put("", value))
    configValue(configs, DefaultFetchQuotaProp).foreach(value => quotas(ClientQuotaType.FETCH).put("", value))
    customQuotasUpdated.values.foreach(_.set(true))
  }

  private def configValue(configs: util.Map[String, _], key: String): Option[Long] = {
    val value = configs.get(key)
    if (value != null) Some(value.toString.toLong) else None
  }

  override def quotaMetricTags(quotaType: ClientQuotaType, principal: KafkaPrincipal, clientId: String): util.Map[String, String] = {
    principal match {
      case groupPrincipal: GroupedUserPrincipal =>
        val userGroup = groupPrincipal.userGroup
        val quotaLimit = quotaOrDefault(userGroup, quotaType)
        if (quotaLimit != null)
          Map(QuotaGroupTag -> userGroup).asJava
        else
          UnlimitedQuotaMetricTags
      case _ =>
        UnlimitedQuotaMetricTags
    }
  }

  override def quotaLimit(quotaType: ClientQuotaType, metricTags: util.Map[String, String]): lang.Double = {
    quotaLimitCalls(quotaType).incrementAndGet
    val group = metricTags.get(QuotaGroupTag)
    if (group != null) quotaOrDefault(group, quotaType) else null
  }

  override def updateClusterMetadata(cluster: Cluster): Boolean = {
    val topicsByGroup = cluster.topics.asScala.groupBy(group)

    !topicsByGroup.forall { case (group, groupTopics) =>
      val groupPartitions = groupTopics.flatMap(topic => cluster.partitionsForTopic(topic).asScala)
      val totalPartitions = groupPartitions.size
      val partitionsOnThisBroker = groupPartitions.count { p => p.leader != null && p.leader.id == brokerId }
      val multiplier = if (totalPartitions == 0)
        1
      else if (partitionsOnThisBroker == 0)
        1.0 / totalPartitions
      else
        partitionsOnThisBroker.toDouble / totalPartitions
      partitionRatio.put(group, multiplier) != multiplier
    }
  }

  override def updateQuota(quotaType: ClientQuotaType, quotaEntity: ClientQuotaEntity, newValue: Double): Unit = {
    quotas(quotaType).put(userGroup(quotaEntity), newValue)
  }

  override def removeQuota(quotaType: ClientQuotaType, quotaEntity: ClientQuotaEntity): Unit = {
    quotas(quotaType).remove(userGroup(quotaEntity))
  }

  override def quotaResetRequired(quotaType: ClientQuotaType): Boolean = customQuotasUpdated(quotaType).getAndSet(false)

  def close(): Unit = {}

  private def userGroup(quotaEntity: ClientQuotaEntity): String = {
    val configEntity = quotaEntity.configEntities.get(0)
    if (configEntity.entityType == ClientQuotaEntity.ConfigEntityType.USER)
      group(configEntity.name)
    else
      throw new IllegalArgumentException(s"Config entity type ${configEntity.entityType} is not supported")
  }

  private def quotaOrDefault(group: String, quotaType: ClientQuotaType): lang.Double = {
    val quotaMap = quotas(quotaType)
    var quotaLimit: Any = quotaMap.get(group)
    if (quotaLimit == null)
      quotaLimit = quotaMap.get("")
    if (quotaLimit != null) scaledQuota(quotaType, group, quotaLimit.asInstanceOf[Double]) else null
  }

  private def scaledQuota(quotaType: ClientQuotaType, group: String, configuredQuota: Double): Double = {
    if (quotaType == ClientQuotaType.REQUEST)
      configuredQuota
    else {
      val multiplier = partitionRatio.get(group)
      if (multiplier <= 0.0) configuredQuota else configuredQuota * multiplier
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="scaffolded-by" content="https://github.com/google/stagehand">
    <title>Simple Game Lib - Demo 7</title>
    <link rel="stylesheet" href="styles.css">

Demo 7 - Obstacles

 <canvas id="surface" style="border-top-width: 1px;border-top-style: ridge;border-right-width: 1px;border-right-style: ridge;border-left-width: 1px;border-left-style: ridge;border-bottom-width: 1px;border-bottom-style: ridge;background-color: white"></canvas>

Use the cursor keys to move and collect the hearts!


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* representation of length values in computed style data */

#ifndef nsStyleCoord_h___
#define nsStyleCoord_h___

#include "nsCoord.h"
#include "nsStyleConsts.h"

namespace mozilla {
class WritingMode;

// Logical axis, edge and side constants for use in various places.
enum LogicalAxis {
  eLogicalAxisBlock  = 0x0,
  eLogicalAxisInline = 0x1
};
enum LogicalEdge {
  eLogicalEdgeStart  = 0x0,
  eLogicalEdgeEnd    = 0x1
};
enum LogicalSide {
  eLogicalSideBStart = (eLogicalAxisBlock  << 1) | eLogicalEdgeStart,  // 0x0
  eLogicalSideBEnd   = (eLogicalAxisBlock  << 1) | eLogicalEdgeEnd,    // 0x1
  eLogicalSideIStart = (eLogicalAxisInline << 1) | eLogicalEdgeStart,  // 0x2
  eLogicalSideIEnd   = (eLogicalAxisInline << 1) | eLogicalEdgeEnd     // 0x3
};
};

enum nsStyleUnit : uint8_t {
  eStyleUnit_Null         = 0,      // (no value) value is not specified
  eStyleUnit_Normal       = 1,      // (no value)
  eStyleUnit_Auto         = 2,      // (no value)
  eStyleUnit_None         = 3,      // (no value)
  eStyleUnit_Percent      = 10,     // (float) 1.0 == 100%
  eStyleUnit_Factor       = 11,     // (float) a multiplier
  eStyleUnit_Degree       = 12,     // (float) angle in degrees
  eStyleUnit_Grad         = 13,     // (float) angle in grads
  eStyleUnit_Radian       = 14,     // (float) angle in radians
  eStyleUnit_Turn         = 15,     // (float) angle in turns
  eStyleUnit_FlexFraction = 16,     // (float) <flex> in fr units
  eStyleUnit_Coord        = 20,     // (nscoord) value is twips
  eStyleUnit_Integer      = 30,     // (int) value is simple integer
  eStyleUnit_Enumerated   = 32,     // (int) value has enumerated meaning

  // The following are reference counted allocated types.
  eStyleUnit_Calc         = 40,     // (Calc*) calc() toplevel; always present
                                    // to distinguish 50% from calc(50%), etc.

  eStyleUnit_MAX          = 40      // highest valid nsStyleUnit value
};

typedef union {
  int32_t     mInt;   // nscoord is a int32_t for now
  float       mFloat;
  // An mPointer is a reference counted pointer.  Currently this can only
  // ever be an nsStyleCoord::Calc*.
  void*       mPointer;
} nsStyleUnion;

/**
 * Class that hold a single size specification used by the style
 * system.  The size specification consists of two parts -- a number
 * and a unit.  The number is an integer, a floating point value, an
 * nscoord, or undefined, and the unit is an nsStyleUnit.  Checking
 * the unit is a must before asking for the value in any particular
 * form.
 */
class nsStyleCoord {
public:
  // Non-reference counted calc() value.  See nsStyleStruct.h for some uses
  // of this.
  struct CalcValue {
    // Every calc() expression evaluates to a length plus a percentage.
    nscoord mLength;
    float mPercent;
    bool mHasPercent; // whether there was any % syntax, even if 0

    bool operator==(const CalcValue& aOther) const {
      return mLength == aOther.mLength &&
             mPercent == aOther.mPercent &&
             mHasPercent == aOther.mHasPercent;
    }
    bool operator!=(const CalcValue& aOther) const {
      return !(*this == aOther);
    }
  };

  // Reference counted calc() value.  This is the type that is used to store
  // the calc() value in nsStyleCoord.
  struct Calc final : public CalcValue {
    NS_INLINE_DECL_REFCOUNTING(Calc)
    Calc() {}

  private:
    Calc(const Calc&) = delete;
    ~Calc() {}
    Calc& operator=(const Calc&) = delete;
  };

  explicit nsStyleCoord(nsStyleUnit aUnit = eStyleUnit_Null);
  enum CoordConstructorType { CoordConstructor };
  inline nsStyleCoord(nscoord aValue, CoordConstructorType);
  nsStyleCoord(int32_t aValue, nsStyleUnit aUnit);
  nsStyleCoord(float aValue, nsStyleUnit aUnit);
  inline nsStyleCoord(const nsStyleCoord& aCopy);
  inline nsStyleCoord(const nsStyleUnion& aValue, nsStyleUnit aUnit);
  ~nsStyleCoord() { Reset(); }

  nsStyleCoord&  operator=(const nsStyleCoord& aOther)
  {
    if (this != &aOther) {
      SetValue(mUnit, mValue, aOther);
    }
    return *this;
  }
  bool           operator==(const nsStyleCoord& aOther) const;
  bool           operator!=(const nsStyleCoord& aOther) const;

  nsStyleUnit GetUnit() const {
    NS_ASSERTION(mUnit != eStyleUnit_Null, "reading uninitialized value");
    return mUnit;
  }

  bool IsAngleValue() const {
    return eStyleUnit_Degree <= mUnit && mUnit <= eStyleUnit_Turn;
  }

  static bool IsCalcUnit(nsStyleUnit aUnit) {
    return aUnit == eStyleUnit_Calc;
  }

  static bool IsPointerUnit(nsStyleUnit aUnit) {
    return IsCalcUnit(aUnit);
  }

  bool IsCalcUnit() const {
    return IsCalcUnit(mUnit);
  }

  bool IsPointerValue() const {
    return IsPointerUnit(mUnit);
  }

  bool IsCoordPercentCalcUnit() const {
    return mUnit == eStyleUnit_Coord ||
           mUnit == eStyleUnit_Percent ||
           IsCalcUnit();
  }

  // Does this calc() expression have any percentages inside it?  Can be
  // called only when IsCalcUnit() is true.
  bool CalcHasPercent() const {
    return GetCalcValue()->mHasPercent;
  }

  bool HasPercent() const {
    return mUnit == eStyleUnit_Percent ||
           (IsCalcUnit() && CalcHasPercent());
  }

  bool ConvertsToLength() const {
    return mUnit == eStyleUnit_Coord ||
           (IsCalcUnit() && !CalcHasPercent());
  }

  nscoord     GetCoordValue() const;
  int32_t     GetIntValue() const;
  float       GetPercentValue() const;
  float       GetFactorValue() const;
  float       GetFactorOrPercentValue() const;
  float       GetAngleValue() const;
  double      GetAngleValueInDegrees() const;
  double      GetAngleValueInRadians() const;
  float       GetFlexFractionValue() const;
  Calc*       GetCalcValue() const;
  uint32_t    HashValue(uint32_t aHash) const;

  // Sets to null and releases any refcounted objects.  Only use this if the
  // object is initialized (i.e. don't use it in nsStyleCoord constructors).
  void Reset();

  void  SetCoordValue(nscoord aValue);
  void  SetIntValue(int32_t aValue, nsStyleUnit aUnit);
  void  SetPercentValue(float aValue);
  void  SetFactorValue(float aValue);
  void  SetAngleValue(float aValue, nsStyleUnit aUnit);
  void  SetFlexFractionValue(float aValue);
  void  SetNormalValue();
  void  SetAutoValue();
  void  SetNoneValue();
  void  SetCalcValue(Calc* aValue);

  // Resets a coord represented by a unit/value pair.
  static inline void Reset(nsStyleUnit& aUnit, nsStyleUnion& aValue);

  // Sets a coord represented by a unit/value pair from a second
  // unit/value pair.
  static inline void SetValue(nsStyleUnit& aUnit,
                              nsStyleUnion& aValue,
                              nsStyleUnit aOtherUnit,
                              const nsStyleUnion& aOtherValue);

  // Sets a coord represented by a unit/value pair from an nsStyleCoord.
  static inline void SetValue(nsStyleUnit& aUnit, nsStyleUnion& aValue,
                              const nsStyleCoord& aOther);

private:
  nsStyleUnit   mUnit;
  nsStyleUnion  mValue;
};

/**
 * Class that represents a set of top/right/bottom/left nsStyleCoords.
 * This is commonly used to hold the widths of the borders, margins,
 * or paddings of a box.
 */
class nsStyleSides {
public:
  nsStyleSides();
  nsStyleSides(const nsStyleSides&);
  ~nsStyleSides();

  nsStyleSides&  operator=(const nsStyleSides& aCopy);
  bool           operator==(const nsStyleSides& aOther) const;
  bool           operator!=(const nsStyleSides& aOther) const;

  inline nsStyleUnit GetUnit(mozilla::css::Side aSide) const;
  inline nsStyleUnit GetLeftUnit() const;
  inline nsStyleUnit GetTopUnit() const;
  inline nsStyleUnit GetRightUnit() const;
  inline nsStyleUnit GetBottomUnit() const;

  inline nsStyleCoord Get(mozilla::css::Side aSide) const;
  inline nsStyleCoord GetLeft() const;
  inline nsStyleCoord GetTop() const;
  inline nsStyleCoord GetRight() const;
  inline nsStyleCoord GetBottom() const;

  // Methods to access the units and values in terms of logical sides
  // for a given writing mode.
  // NOTE: The definitions are in WritingModes.h (after we have the full
  // declaration of WritingMode available).
  inline nsStyleUnit GetUnit(mozilla::WritingMode aWritingMode,
                             mozilla::LogicalSide aSide) const;
  inline nsStyleUnit GetIStartUnit(mozilla::WritingMode aWritingMode) const;
  inline nsStyleUnit GetBStartUnit(mozilla::WritingMode aWritingMode) const;
  inline nsStyleUnit GetIEndUnit(mozilla::WritingMode aWritingMode) const;
  inline nsStyleUnit GetBEndUnit(mozilla::WritingMode aWritingMode) const;

  inline nsStyleCoord Get(mozilla::WritingMode aWritingMode,
                          mozilla::LogicalSide aSide) const;
  inline nsStyleCoord GetIStart(mozilla::WritingMode aWritingMode) const;
  inline nsStyleCoord GetBStart(mozilla::WritingMode aWritingMode) const;
  inline nsStyleCoord GetIEnd(mozilla::WritingMode aWritingMode) const;
  inline nsStyleCoord GetBEnd(mozilla::WritingMode aWritingMode) const;

  // Sets each side to null and releases any refcounted objects.  Only use this
  // if the object is initialized (i.e. don't use it in nsStyleSides
  // constructors).
  void Reset();

  inline void Set(mozilla::css::Side aSide, const nsStyleCoord& aCoord);
  inline void SetLeft(const nsStyleCoord& aCoord);
  inline void SetTop(const nsStyleCoord& aCoord);
  inline void SetRight(const nsStyleCoord& aCoord);
  inline void SetBottom(const nsStyleCoord& aCoord);

protected:
  nsStyleUnit   mUnits[4];
  nsStyleUnion  mValues[4];
};

/**
 * Class that represents a set of top-left/top-right/bottom-left/bottom-right
 * nsStyleCoord pairs.  This is used to hold the dimensions of the
 * corners of a box (for, e.g., border-radius and outline-radius).
 */
class nsStyleCorners {
public:
  nsStyleCorners();
  nsStyleCorners(const nsStyleCorners&);
  ~nsStyleCorners();

  // use compiler's version
  nsStyleCorners& operator=(const nsStyleCorners& aCopy);
  bool           operator==(const nsStyleCorners& aOther) const;
  bool           operator!=(const nsStyleCorners& aOther) const;

  // aCorner is always one of NS_CORNER_* defined in nsStyleConsts.h
  inline nsStyleUnit GetUnit(uint8_t aHalfCorner) const;

  inline nsStyleCoord Get(uint8_t aHalfCorner) const;

  // Sets each corner to null and releases any refcounted objects.  Only use
  // this if the object is initialized (i.e. don't use it in nsStyleCorners
  // constructors).
  void Reset();

  inline void Set(uint8_t aHalfCorner, const nsStyleCoord& aCoord);

protected:
  nsStyleUnit   mUnits[8];
  nsStyleUnion  mValues[8];
};

// -------------------------
// nsStyleCoord inlines
//
inline nsStyleCoord::nsStyleCoord(nscoord aValue, CoordConstructorType)
  : mUnit(eStyleUnit_Coord)
{
  mValue.mInt = aValue;
}

inline nsStyleCoord::nsStyleCoord(const nsStyleCoord& aCopy)
  : mUnit(eStyleUnit_Null)
{
  SetValue(mUnit, mValue, aCopy);
}

inline nsStyleCoord::nsStyleCoord(const nsStyleUnion& aValue, nsStyleUnit aUnit)
  : mUnit(eStyleUnit_Null)
{
  SetValue(mUnit, mValue, aUnit, aValue);
}

inline bool nsStyleCoord::operator!=(const nsStyleCoord& aOther) const
{
  return !((*this) == aOther);
}

inline nscoord nsStyleCoord::GetCoordValue() const
{
  NS_ASSERTION((mUnit == eStyleUnit_Coord), "not a coord value");
  if (mUnit == eStyleUnit_Coord) {
    return mValue.mInt;
  }
  return 0;
}

inline int32_t nsStyleCoord::GetIntValue() const
{
  NS_ASSERTION((mUnit == eStyleUnit_Enumerated) ||
               (mUnit == eStyleUnit_Integer), "not an int value");
  if ((mUnit == eStyleUnit_Enumerated) ||
      (mUnit == eStyleUnit_Integer)) {
    return mValue.mInt;
  }
  return 0;
}

inline float nsStyleCoord::GetPercentValue() const
{
  NS_ASSERTION(mUnit == eStyleUnit_Percent, "not a percent value");
  if (mUnit == eStyleUnit_Percent) {
    return mValue.mFloat;
  }
  return 0.0f;
}

inline float nsStyleCoord::GetFactorValue() const
{
  NS_ASSERTION(mUnit == eStyleUnit_Factor, "not a factor value");
  if (mUnit == eStyleUnit_Factor) {
    return mValue.mFloat;
  }
  return 0.0f;
}

inline float nsStyleCoord::GetFactorOrPercentValue() const
{
  NS_ASSERTION(mUnit == eStyleUnit_Factor || mUnit == eStyleUnit_Percent,
               "not a percent or factor value");
  if (mUnit == eStyleUnit_Factor || mUnit == eStyleUnit_Percent) {
    return mValue.mFloat;
  }
  return 0.0f;
}

inline float nsStyleCoord::GetAngleValue() const
{
  NS_ASSERTION(mUnit >= eStyleUnit_Degree &&
               mUnit <= eStyleUnit_Turn, "not an angle value");
  if (mUnit >= eStyleUnit_Degree && mUnit <= eStyleUnit_Turn) {
    return mValue.mFloat;
  }
  return 0.0f;
}

inline float nsStyleCoord::GetFlexFractionValue() const
{
  NS_ASSERTION(mUnit == eStyleUnit_FlexFraction, "not a fr value");
  if (mUnit == eStyleUnit_FlexFraction) {
    return mValue.mFloat;
  }
  return 0.0f;
}

inline nsStyleCoord::Calc* nsStyleCoord::GetCalcValue() const
{
  NS_ASSERTION(IsCalcUnit(), "not a pointer value");
  if (IsCalcUnit()) {
    return static_cast<Calc*>(mValue.mPointer);
  }
  return nullptr;
}

/* static */ inline void
nsStyleCoord::Reset(nsStyleUnit& aUnit, nsStyleUnion& aValue)
{
  MOZ_ASSERT(aUnit <= eStyleUnit_MAX,
             "calling Reset on uninitialized nsStyleCoord?");

  switch (aUnit) {
    case eStyleUnit_Calc:
      static_cast<Calc*>(aValue.mPointer)->Release();
      break;
    default:
      MOZ_ASSERT(!IsPointerUnit(aUnit), "check pointer refcounting logic");
  }

  aUnit = eStyleUnit_Null;
  aValue.mInt = 0;
}

/* static */ inline void
nsStyleCoord::SetValue(nsStyleUnit& aUnit,
                       nsStyleUnion& aValue,
                       nsStyleUnit aOtherUnit,
                       const nsStyleUnion& aOtherValue)
{
  Reset(aUnit, aValue);

  aUnit = aOtherUnit;
  aValue = aOtherValue;

  switch (aUnit) {
    case eStyleUnit_Calc:
      static_cast<Calc*>(aValue.mPointer)->AddRef();
      break;
    default:
      MOZ_ASSERT(!IsPointerUnit(aUnit), "check pointer refcounting logic");
  }
}

/* static */ inline void
nsStyleCoord::SetValue(nsStyleUnit& aUnit, nsStyleUnion& aValue,
                       const nsStyleCoord& aOther)
{
  SetValue(aUnit, aValue, aOther.mUnit, aOther.mValue);
}

// -------------------------
// nsStyleSides inlines
//
inline bool nsStyleSides::operator!=(const nsStyleSides& aOther) const
{
  return !((*this) == aOther);
}

inline nsStyleUnit nsStyleSides::GetUnit(mozilla::css::Side aSide) const
{
  return (nsStyleUnit)mUnits[aSide];
}

inline nsStyleUnit nsStyleSides::GetLeftUnit() const
{
  return GetUnit(NS_SIDE_LEFT);
}

inline nsStyleUnit nsStyleSides::GetTopUnit() const
{
  return GetUnit(NS_SIDE_TOP);
}

inline nsStyleUnit nsStyleSides::GetRightUnit() const
{
  return GetUnit(NS_SIDE_RIGHT);
}

inline nsStyleUnit nsStyleSides::GetBottomUnit() const
{
  return GetUnit(NS_SIDE_BOTTOM);
}

inline nsStyleCoord nsStyleSides::Get(mozilla::css::Side aSide) const
{
  return nsStyleCoord(mValues[aSide], nsStyleUnit(mUnits[aSide]));
}

inline nsStyleCoord nsStyleSides::GetLeft() const
{
  return Get(NS_SIDE_LEFT);
}

inline nsStyleCoord nsStyleSides::GetTop() const
{
  return Get(NS_SIDE_TOP);
}

inline nsStyleCoord nsStyleSides::GetRight() const
{
  return Get(NS_SIDE_RIGHT);
}

inline nsStyleCoord nsStyleSides::GetBottom() const
{
  return Get(NS_SIDE_BOTTOM);
}

inline void nsStyleSides::Set(mozilla::css::Side aSide, const nsStyleCoord& aCoord)
{
  nsStyleCoord::SetValue(mUnits[aSide], mValues[aSide], aCoord);
}

inline void nsStyleSides::SetLeft(const nsStyleCoord& aCoord)
{
  Set(NS_SIDE_LEFT, aCoord);
}

inline void nsStyleSides::SetTop(const nsStyleCoord& aCoord)
{
  Set(NS_SIDE_TOP, aCoord);
}

inline void nsStyleSides::SetRight(const nsStyleCoord& aCoord)
{
  Set(NS_SIDE_RIGHT, aCoord);
}

inline void nsStyleSides::SetBottom(const nsStyleCoord& aCoord)
{
  Set(NS_SIDE_BOTTOM, aCoord);
}

// -------------------------
// nsStyleCorners inlines
//
inline bool nsStyleCorners::operator!=(const nsStyleCorners& aOther) const
{
  return !((*this) == aOther);
}

inline nsStyleUnit nsStyleCorners::GetUnit(uint8_t aCorner) const
{
  return (nsStyleUnit)mUnits[aCorner];
}

inline nsStyleCoord nsStyleCorners::Get(uint8_t aCorner) const
{
  return nsStyleCoord(mValues[aCorner], nsStyleUnit(mUnits[aCorner]));
}

inline void nsStyleCorners::Set(uint8_t aCorner, const nsStyleCoord& aCoord)
{
  nsStyleCoord::SetValue(mUnits[aCorner], mValues[aCorner], aCoord);
}

#endif /* nsStyleCoord_h___ */


text:
/*
http://www.codeeval.com/open_challenges/10/
*/

	import java.util.*;
	import java.lang.*;
	import java.math.*;
	import java.io.*;

	public class m2last {

		public static void main(String[] args) {
			/*
			Scanner sc = new Scanner(System.in);
			while (sc.hasNextLine()) {
				String line = sc.nextLine();
				String[] lineArray = line.split(" ");
				int arraySize = lineArray.length;
				int m = Integer.parseInt(lineArray[arraySize-1]);
				//System.out.println(Arrays.toString(lineArray));
				//System.out.println(m);
				if (arraySize-1 >= m){
					System.out.println(lineArray[arraySize-m-1]);
				}
			}*/
	    try {
	        File file = new File(args[0]);
	        BufferedReader in = new BufferedReader(new FileReader(file));
	        String line;
	        while ((line = in.readLine()) != null) {
						String[] lineArray = line.split(" ");
						int arraySize = lineArray.length;
						int m = Integer.parseInt(lineArray[arraySize-1]);
						if (arraySize-1 >= m){
							System.out.println(lineArray[arraySize-m-1]);
						}
	        }
	    } catch (IOException e) {
	        System.out.println("File Read Error: " + e.getMessage());
	    }
		}
	}


text:
namespace TestStack.ConventionTests.Internal
{
    using System;

    public static class PredicateHelpers
    {
        public static Func<T, bool> All<T>()
        {
            return _ => true;
        }

        public static Func<T, bool> None<T>()
        {
            return _ => false;
        }
    }
}


text:
using System;
using FluentRegistration.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

namespace FluentRegistration.Internal;

public class ComponentRegistration<TService> :
    IComponentImplementationSelector<TService>,
    IRegister
    where TService : class
{
    private readonly Type[] _serviceTypes;
    private IRegister? _register;

    public ComponentRegistration(Type[] serviceTypes)
    {
        _serviceTypes = serviceTypes;
    }

    public ILifetime ImplementedBy<TImplementation>()
        where TImplementation : TService
    {
        var implementedByRegistration = new ComponentImplementedByRegistration<TService, TImplementation>(_serviceTypes);
        _register = implementedByRegistration;
        return implementedByRegistration;
    }

    public IValidRegistration Instance(TService instance)
    {
        GuardAgainst.Null(instance);

        var instanceRegistration = new ComponentInstanceRegistration(_serviceTypes, instance);
        _register = instanceRegistration;
        return instanceRegistration;
    }

    public IValidRegistration UsingFactory<TFactory>(Func<TFactory, TService> factoryMethod)
        where TFactory : class
    {
        GuardAgainst.Null(factoryMethod);

        var factoryRegistration = new ComponentFactoryRegistration<TFactory, TService>(factoryMethod);
        _register = factoryRegistration;
        return factoryRegistration;
    }

    public IValidRegistration UsingFactoryMethod(Func<TService> factoryMethod)
    {
        GuardAgainst.Null(factoryMethod);

        return UsingFactoryMethod(serviceProvider => factoryMethod());
    }

    public IValidRegistration UsingFactoryMethod(Func<IServiceProvider, TService> factoryMethod)
    {
        GuardAgainst.Null(factoryMethod);

        var factoryMethodRegistration = new ComponentFactoryMethodRegistration<TService>(factoryMethod);
        _register = factoryMethodRegistration;
        return factoryMethodRegistration;
    }

    public void Register(IServiceCollection services)
    {
        if (_register == null)
        {
            throw new InvalidOperationException("Register called without defining what to register via the fluent Api.");
        }

        _register.Register(services);
    }
}


text:
package com.bumptech.glide.load.resource.transcode;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawableResource;

/**
 * 这是一个资源转码器:实现从Bitmap到BitmapDrawable的转换
 * An {@link ResourceTranscoder} that converts
 * {@link Bitmap}s into {@link android.graphics.drawable.BitmapDrawable}s.
 */
public class GlideBitmapDrawableTranscoder implements ResourceTranscoder<Bitmap, GlideBitmapDrawable> {
    private final Resources resources;
    private final BitmapPool bitmapPool;

    public GlideBitmapDrawableTranscoder(Context context) {
        this(context.getResources(), Glide.get(context).getBitmapPool());
    }

    public GlideBitmapDrawableTranscoder(Resources resources, BitmapPool bitmapPool) {
        this.resources = resources;
        this.bitmapPool = bitmapPool;
    }

    @Override
    public Resource<GlideBitmapDrawable> transcode(Resource<Bitmap> toTranscode) {
        GlideBitmapDrawable drawable = new GlideBitmapDrawable(resources, toTranscode.get());
        return new GlideBitmapDrawableResource(drawable, bitmapPool);
    }

    @Override
    public String getId() {
        return "GlideBitmapDrawableTranscoder.com.bumptech.glide.load.resource.transcode";
    }
}


text:
/**
ComboHandler.Cluster.Worker
**/
var cluster = require('cluster');
var util = require('util');

var ComboBase = require('./base');

exports = module.exports = ComboWorker;

/**
A factory for combohandler worker processes.

@class ComboWorker
@extends ComboBase
@constructor
@param {Object} options
**/
function ComboWorker(options) {
    // factory constructor
    if (!(this instanceof ComboWorker)) {
        return new ComboWorker(options);
    }

    ComboBase.call(this, options);

    // this doesn't work in OS X (node-v0.8.x), but whatever
    this.process.title = 'combohandler worker';

    // aid precise detaching during _destroy
    this._boundDispatch = this.dispatch.bind(this);
    this.process.on('message', this._boundDispatch);
}

util.inherits(ComboWorker, ComboBase);

ComboWorker.defaults = require('../defaults').worker;

ComboWorker.prototype.dispatch = function dispatch(msg) {
    if (!msg || !msg.hasOwnProperty('cmd')) {
        throw new Error("Message must have command");
    }
    var cmd = msg.cmd;
    if (cmd === 'listen') {
        if (msg.data) {
            this.init(msg.data);
        }
        this.listen();
    } else {
        throw new Error("Message command invalid");
    }
};

ComboWorker.prototype._destroy = function (cb) {
    this.process.removeListener('message', this._boundDispatch);

    if (this._server) {
        this._server.close(cb);
    } else {
        this._maybeCallback(cb);
    }
};

ComboWorker.prototype._listen = function () {
    var app = require(this.options.server)(this.options);
    this._server = app.listen(this.options.port);
    this._server.once('listening', this._listening.bind(this));
};

ComboWorker.prototype._listening = function () {
    this.emit('listening');
};

if (cluster.isWorker) {
    /*jshint newcap: false */
    ComboWorker();
}


text:
<?php
    interface rACLActionHandler {}

    class rACLActionHandlerActions {
        static function index(rACLActionHandler $self) {
            $ddm = DSM::Get();
            $view = array();

            // get model types
            $view['models'] = $ddm->ListTypes();

            return $view;
        }
        static function owner(rACLActionHandler $self, $record_id) {
            $ddm = DSM::Get();
            $permissions = $ddm->ACL_Get($record_id);

            return array("permissions" => $permissions, "record_id" => $record_id);
        }
        static function resource(rACLActionHandler $self, $resource_id) {
            $ddm = DSM::Get();
            $permissions = $ddm->ACL_Get(NULL, $resource_id);
            return array("permissions" => $permissions);
        }
        static function remove_permission(rACLActionHandler $self) {
            $ddm = DSM::Get();
            if ($_POST) {
                $record = $_POST['record_id'];
                $resource = $_POST['resource_id'];

                $ddm->ACL_Set($record,$resource,NULL);
                redirect("owner", NULL, array($record));
            }
            else
                redirect("index");
        }
        static function give_permission(rACLActionHandler $self) {
            $ddm = DSM::Get();
            if ($_POST) {
                $ddm->ACL_Set($_POST['record_id'], $_POST['resource_id']);
                redirect("owner", NULL, array($_POST['record_id']));
            }
            else {

            }
        }
    }
?>