text:
<?php

namespace app\models;

use app\libraries\Core;
use app\libraries\database\DatabaseQueries;
use app\libraries\DateUtils;

/**
 * Class RainbowCustomization
 * @package app\models
 *
 * This class is a RainbowGrades Customization.  It may contain the data found in customization.json but it also
 * contains additional data that is used by the web user interface to aid in generation/customization.
 */
class RainbowCustomization extends AbstractModel {
    /**/
    protected $core;
    private $bucket_counts = [];               // Keep track of how many items are in each bucket
    private $customization_data = [];
    private $has_error;
    private $error_messages;
    private $used_buckets = [];
    private $available_buckets;
    private $RCJSON;                           // This is the customization.json php object, or null if it wasn't found
    private $sections;                         // Contains section ids mapped to labels

    /*XXX: This is duplicated from AdminGradeableController.php, we really shouldn't have multiple copies lying around.
     * On top of that, Rainbow Grades has its own enum internally. Since that's a separate repo it's probably
     * unavoidable, but the fewer places we can duplicate this, the better.
     */
    /*XXX: It's also going to be annoying to have "none (for practice only)" since in customization it's "none"
     * which is a lot nicer to type.
     */
    //XXX: 'none (for practice only)' we want to truncate to just 'none'.
    const syllabus_buckets = [
        'homework', 'assignment', 'problem-set',
        'quiz', 'test', 'exam',
        'exercise', 'lecture-exercise', 'reading', 'lab', 'recitation', 'worksheet',
        'project',
        'participation', 'note',
        'none'];

    public function __construct(Core $main_core) {
        parent::__construct($main_core);
        $this->has_error = "false";
        $this->error_messages = [];

        $this->sections = (object) [];

        // Attempt to load json from customization file
        // If it fails then set to null, will be used to load defaults later
        $this->RCJSON = new RainbowCustomizationJSON($this->core);

        try {
            $this->RCJSON->loadFromJsonFile();
        }
        catch (\Exception $e) {
            $this->RCJSON = null;
        }
    }

    public function buildCustomization() {

        //This function should examine the DB(?) / a file(?) and if customization settings already exist, use them. Otherwise, populate with defaults.
        foreach (self::syllabus_buckets as $bucket) {
            $this->customization_data[$bucket] = [];
            $this->bucket_counts[$bucket] = 0;
        }

        $gradeables = $this->core->getQueries()->getGradeableConfigs(null);
        foreach ($gradeables as $gradeable) {
            //XXX: 'none (for practice only)' we want to truncate to just 'none', otherwise use full bucket name
            $bucket = $gradeable->getSyllabusBucket() == "none (for practice only)" ? "none" : $gradeable->getSyllabusBucket();
            /*if(!isset($this->customization_data[$bucket])){
                $this->customization_data[$bucket] = [];
            }*/
            /*XXX: Right now we aren't yet worried about pulling in from existing customization.json but if we do, then what happens in the event of a conflict?
             * I'm tempted to say for version 1.0, too bad, we override with the version from the DB (since that's more up to date), if the gradeable exists
             * In a later version we may want to highlight it in red or something, and ask the user which number to use? I'm not sure if there's a use case for using
             * the version in the customization.json, but the warning might be nice. Might even be an error state where action is required, just so the user isn't
             * confused when the grade distribution shifts around.
             */

            // Update bucket count
            $this->bucket_counts[$bucket]++;
            $max_score = $gradeable->getManualGradingPoints();
            //If the gradeable has autograding points, load the config and add the non-extra-credit autograder total
            if ($gradeable->hasAutogradingConfig()) {
                $last_index = count($this->customization_data[$bucket]) - 1;
                $max_score += $gradeable->getAutogradingConfig()->getTotalNonExtraCredit();
            }
            $this->customization_data[$bucket][] = [
                "id" => $gradeable->getId(),
                "title" => $gradeable->getTitle(),
                "max_score" => $max_score,
                "grade_release_date" => $gradeable->hasReleaseDate() ? DateUtils::dateTimeToString($gradeable->getGradeReleasedDate()) : DateUtils::dateTimeToString($gradeable->getSubmissionOpenDate()),
                "override" => false,
                "override_max" => $max_score
            ];
        }

        // Determine which 'buckets' exist in the customization.json
        if (!is_null($this->RCJSON)) {
            $json_buckets = $this->RCJSON->getGradeables();
            foreach ($json_buckets as $json_bucket) {
                // Place those buckets in $this->used_buckets
                $this->used_buckets[] = $json_bucket->type;

                // When preparing the count of how many items are in the bucket, if the instructor has previously
                // entered a value which was greater than the number of gradeables in the database, we should use the
                // instructor entered value instead
                $bucket = $json_bucket->type;

                if ($json_bucket->count > $this->bucket_counts[$bucket]) {
                    $this->bucket_counts[$bucket] = $json_bucket->count;
                }
            }
        }

        // Reorder buckets
        $this->reorderBuckets();

        //Now that the buckets are ordered and the customization has been initialized, we can
        //loop through to find differences between the max_values from the database vs the customization JSON
        if (!is_null($this->RCJSON) && count($this->RCJSON->getGradeables())) {
            $json_buckets = $this->RCJSON->getGradeables();
            //we have to keep track of the customization bucket and the JSON bucket separately, since the customization
            //has all buckets (even empty ones) while the JSON only has buckets with content in it.
            $c_bucket = "";
            foreach ($json_buckets as $json_bucket) {
                if (property_exists($json_bucket, 'type')) {
                    $c_bucket = $json_bucket->type;
                }
                else {
                    continue;
                }

                //loop through all gradeables in bucket and compare them
                $j_index = 0;
                foreach ($this->customization_data[$c_bucket] as &$c_gradeable) {
                    if ($c_gradeable['max_score'] !== (float) $json_bucket->ids[$j_index]->max) {
                        $c_gradeable['override'] = true;
                        $c_gradeable['override_max'] = $json_bucket->ids[$j_index]->max;
                    }
                    $j_index++;
                }
            }
        }
        //XXX: Assuming that the contents of these buckets will be lowercase
        $this->available_buckets = array_diff(self::syllabus_buckets, $this->used_buckets);
    }

    /**
     * Reorder each gradeable bucket in $this->customization_data to match JSON (or grade release date as a fallback) ordering
     */
    private function reorderBuckets(): void {
        $json_buckets_gradeables = [];

        // First, fetch JSON and associate ids with buckets
        if (!is_null($this->RCJSON)) {
            $json_buckets = $this->RCJSON->getGradeables();
            foreach ($json_buckets as $json_bucket) {
                if (property_exists($json_bucket, 'type') && property_exists($json_bucket, 'ids')) {
                    $json_buckets_gradeables[$json_bucket->type] = $json_bucket->ids;
                }
            }
        }

        // Reorder individual buckets
        $temp_customization_data = [];
        foreach ($this->customization_data as $bucket => $gradeables) {
            $json_bucket_ids = array_key_exists($bucket, $json_buckets_gradeables) ? $json_buckets_gradeables[$bucket] : [];
            $temp_customization_data[$bucket] = $this->reorderBucket($gradeables, $json_bucket_ids);
        }
        $this->customization_data = $temp_customization_data;
    }

    /**
     * Returns $bucket_gradeables reordered to match order in $json_bucket_ids.
     * If a gradeable is not present in $json_bucket_ids, it will be added to the end of the array in order of grade release date.
     * @param array $bucket_gradeables A gradeable bucket from $this->customization_data
     * @param array $json_bucket_ids An "ids" array from a $this->RCSJSON bucket
     * @return array
     */
    private function reorderBucket(array $bucket_gradeables, array $json_bucket_ids): array {
        $new_gradeables = [];

        // First, associate gradeables with their IDs
        $gradeables_by_id = array_reduce($bucket_gradeables, function ($accumulator, $gradeable) {
            $accumulator[$gradeable['id']] = $gradeable;
            return $accumulator;
        }, []);

        // Then, add gradeables to $new_gradeables based on JSON ordering
        if (!is_null($json_bucket_ids)) {
            foreach ($json_bucket_ids as $json_gradeable) {
                if (property_exists($json_gradeable, 'id')) {
                    $id = $json_gradeable->id;
                    if (array_key_exists($id, $gradeables_by_id)) {
                        $new_gradeables[] = $gradeables_by_id[$id];
                        unset($gradeables_by_id[$id]);
                    }
                }
            }
        }

        // Finally, add any remaining gradeables to $new_gradeables based on date ordering.
        $num_unordered_gradeables = count($gradeables_by_id);
        $gradeables_by_date = [];
        foreach ($gradeables_by_id as $gradeable) {
            $num_gradeables_counted = count($gradeables_by_date);

            // Ensure strings are sorted properly
            $gradeable_count_string = str_repeat(
                '0',
                strlen(strval($num_unordered_gradeables)) - strlen(strval($num_gradeables_counted))
            ) . $num_gradeables_counted;

            if (array_key_exists('grade_release_date', $gradeable)) {
                $gradeables_by_date[$gradeable['grade_release_date'] . '_' . $gradeable_count_string] = $gradeable;
            }
            else {
                $gradeables_by_date['END_OF_TIME_' . $gradeable_count_string] = $gradeable;
            }
        }
        ksort($gradeables_by_date);
        foreach ($gradeables_by_date as $gradeable) {
            $new_gradeables[] = $gradeable;
        }

        return $new_gradeables;
    }

    /**
     * Gets curve data for each gradeable
     *
     * In the case no rainbow grades customization.json was found the return value will be an empty array.
     * In the case a customization.json was found the return array will have the form
     * $retArray[bucket_id][gradeable_id] = curve_values
     *
     * If no curve values were found for gradeable_id then gradeable_id will not be present in the return array
     *
     * @return array
     */
    public function getPerGradeableCurves() {
        $retArray = [];

        if (!is_null($this->RCJSON)) {
            $json_buckets = $this->RCJSON->getGradeables();

            foreach ($json_buckets as $json_bucket) {
                $retArray[$json_bucket->type] = [];

                foreach ($json_bucket->ids as $json_gradeable) {
                    if (property_exists($json_gradeable, 'curve')) {
                        $curve_data = $json_gradeable->curve;
                        $curve_data_pos = 0;
                        $selected_benchmarks = $this->RCJSON->getDisplayBenchmarks();
                        $benchmarks_with_input_fields = array_slice($this->RCJSON::allowed_display_benchmarks, 3);

                        $retArray[$json_bucket->type][$json_gradeable->id] = [];

                        foreach ($benchmarks_with_input_fields as $benchmark) {
                            if (in_array($benchmark, $selected_benchmarks)) {
                                $val = $curve_data[$curve_data_pos];
                                $curve_data_pos++;
                            }
                            else {
                                $val = '';
                            }

                            array_push($retArray[$json_bucket->type][$json_gradeable->id], $val);
                        }
                    }
                }
            }
        }

        return $retArray;
    }

    /**
     * Get an array containing what percentage of the grade the bucket counts toward.  The key is the name of the
     * bucket and the value is the percentage which has been cast back to a whole number integer.  This differs
     * from the customization.json in that in the json file the percentage is represented as a decimal between 0 and 1.
     * This value is represented as an integer between 0 and 100.
     *
     * ex.  key => value
     *     'test' => 50
     *     'lab' => 25
     *     'homework' => 25
     *
     * @return array
     */
    public function getBucketPercentages() {
        $retArray = [];

        if (!is_null($this->RCJSON)) {
            $json_buckets = $this->RCJSON->getGradeables();

            $sum = 0;

            foreach ($json_buckets as $json_bucket) {
                // Get percentage, cast back to whole number integer
                $retArray[$json_bucket->type] = (int) ($json_bucket->percent * 100);

                // Keep track of the sum
                $sum += $retArray[$json_bucket->type];
            }

            // Save the sum of used percentages to special key in array
            $retArray['used_percentage'] = $sum;
        }

        return $retArray;
    }

    public function getBucketCounts() {
        return $this->bucket_counts;
    }

    public function getCustomizationData() {
        return $this->customization_data;
    }

    public function getAvailableBuckets() {
        return $this->available_buckets;
    }

    public function getUsedBuckets() {
        return $this->used_buckets;
    }

    public function getMessages() {
        return !is_null($this->RCJSON) ? $this->RCJSON->getMessages() : [];
    }

    /**
     * Get display benchmarks
     *
     * Get a multidimensional array that contains not only a list of usable display benchmarks but also which ones
     * are in use (in the customization.json)
     *
     * @return array multidimensional array of display benchmark data
     */
    public function getDisplayBenchmarks() {
        // Get allowed benchmarks
        $displayBenchmarks = RainbowCustomizationJSON::allowed_display_benchmarks;
        $retArray = [];

        // If json file available then collect used benchmarks from that, else get empty array
        !is_null($this->RCJSON) ?
            $usedDisplayBenchmarks = $this->RCJSON->getDisplayBenchmarks() :
            $usedDisplayBenchmarks = [];

        // Add data into retArray
        foreach ($displayBenchmarks as $displayBenchmark) {
            in_array($displayBenchmark, $usedDisplayBenchmarks) ? $isUsed = true : $isUsed = false;

            // Add benchmark to return array
            $retArray[] = ['id' => $displayBenchmark, 'isUsed' => $isUsed];
        }

        return $retArray;
    }

    /**
     * Get benchmark percentages
     *
     * @return object An object which maps benchmarks to the percentage (as a decimal) that is needed to obtain that
     *                letter grade
     */
    public function getBenchmarkPercent() {
        if (!is_null($this->RCJSON)) {
            $percent_obj = $this->RCJSON->getBenchmarkPercent();

            // If the RCJSON was found and it contains the benchmark percent fields then return it
            if ($percent_obj != (object) []) {
                return $percent_obj;
            }
        }

        // Otherwise return a default benchmark percent object
        return (object) [
                'lowest_a-' => 0.9,
                'lowest_b-' => 0.8,
                'lowest_c-' => 0.7,
                'lowest_d' => 0.6,
            ];
    }

    /**
     * Get section ids and labels
     *
     * If no customization.json file exists then this function will generate defaults
     * by examining what sections are registered in the database.  If a file does exist then sections and labels will
     * be read out of that.  If it turns out that new sections have been registered in the database that
     * dont yet exist in the file, those new sections will be added with default values.
     *
     * @return object The object mapping section ids to labels
     */
    public function getSectionsAndLabels() {
        // Get sections from db
        $db = new DatabaseQueries($this->core);
        $db_sections = $db->getRegistrationSections();

        $sections = [];

        // Configure sections
        foreach ($db_sections as $section) {
            $key = $section['sections_registration_id'];

            $sections[$key] = $key;
        }

        // If RCJSON is not null then load it
        if (!is_null($this->RCJSON)) {
            // Get sections from the file
            $sectionsFromFile = (array) $this->RCJSON->getSection();

            // If sections from database is larger than sections from file then there must be a new section in
            // in the database, add new fields into sections from file with defaults
            $sectionsFromFileCount = count($sectionsFromFile);
            $sectionsCount = count($sections);

            if ($sectionsFromFileCount != $sectionsCount) {
                for ($i = $sectionsFromFileCount + 1; $i <= $sectionsCount; $i++) {
                    $sectionsFromFile[$i] = (string) $i;
                }
            }

            return (object) $sectionsFromFile;
        }
        else {
            // RCJSON was null so return database sections as default
            // Collect sections out of the database
            return (object) $sections;
        }
    }

    // This function handles processing the incoming post data
    public function processForm() {

        // Get a new customization file
        $this->RCJSON = new RainbowCustomizationJSON($this->core);

        $form_json = $_POST['json_string'];
        $form_json = json_decode($form_json);

        if (isset($form_json->display_benchmark)) {
            foreach ($form_json->display_benchmark as $benchmark) {
                $this->RCJSON->addDisplayBenchmarks($benchmark);
            }
        }

        if (isset($form_json->benchmark_percent)) {
            foreach ($form_json->benchmark_percent as $key => $value) {
                $this->RCJSON->addBenchmarkPercent((string) $key, $value);
            }
        }

        if (isset($form_json->section)) {
            foreach ($form_json->section as $key => $value) {
                $this->RCJSON->addSection((string) $key, $value);
            }
        }

        if (isset($form_json->gradeables)) {
            foreach ($form_json->gradeables as $gradeable) {
                $this->RCJSON->addGradeable($gradeable);
            }
        }

        if (isset($form_json->messages)) {
            foreach ($form_json->messages as $message) {
                $this->RCJSON->addMessage($message);
            }
        }

        // Write to customization file
        $this->RCJSON->saveToJsonFile();

        // Configure json to go into jobs queue
        $job_json = (object) [];
        $job_json->job = 'RunAutoRainbowGrades';
        $job_json->semester = $this->core->getConfig()->getSemester();
        $job_json->course = $this->core->getConfig()->getCourse();

        // Encode
        $job_json = json_encode($job_json, JSON_PRETTY_PRINT);

        // Create path to new jobs queue json
        $path = '/var/local/submitty/daemon_job_queue/auto_rainbow_' .
            $this->core->getConfig()->getSemester() .
            '_' .
            $this->core->getConfig()->getCourse() .
            '.json';

        // Place in queue
        file_put_contents($path, $job_json);

//        $this->has_error = "true";
//        foreach($_POST as $field => $value){
//            $this->error_messages[] = "$field: $value";
//        }
//        throw new ValidationException('Debug Rainbow Grades error', $this->error_messages);
    }

    public function error() {
        return $this->has_error;
    }

    public function getErrorMessages() {
        return $this->error_messages;
    }
}


text:
#region Copyright © 2011 Oliver Waits
//______________________________________________________________________________________________________________
// Service Location Protocol
// Copyright © 2011 Oliver Waits
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//______________________________________________________________________________________________________________
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Acn.Slp
{
    public enum SlpErrorCode
    {
        None = 0,
        LanguageNotSupported = 1,
        ParseError = 2,
        InvalidRegistration = 3,
        ScopeNotFound = 4,
        AuthenticationUnknown = 5,
        AuthenticationAbsent = 6,
        AuthenticationFailed = 7,
        VerNotSupported = 9,
        InternalError = 10,
        DaBusyNow = 11,
        OptionNotUnderstood = 12,
        InvalidUpdate = 13,
        MsgNotSupported = 14,
        RefreshRejected = 15
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace principia {
namespace physics {

FORWARD_DECLARE_FROM(discrete_trajectory_segment,
                     TEMPLATE(typename Frame) class,
                     DiscreteTrajectorySegment);

namespace internal_discrete_trajectory {

using base::not_null;
using base::uninitialized_t;
using geometry::Instant;
using geometry::Position;
using geometry::Velocity;
using physics::DegreesOfFreedom;

template<typename Frame>
class DiscreteTrajectory : public Trajectory<Frame> {
 public:
  using key_type =
      typename internal_discrete_trajectory_types::Timeline<Frame>::key_type;
  using value_type =
      typename internal_discrete_trajectory_types::Timeline<Frame>::value_type;

  using iterator = DiscreteTrajectoryIterator<Frame>;
  using reference = value_type const&;
  using reverse_iterator = std::reverse_iterator<iterator>;
  using SegmentIterator = DiscreteTrajectorySegmentIterator<Frame>;
  using ReverseSegmentIterator = std::reverse_iterator<SegmentIterator>;
  using SegmentRange = DiscreteTrajectorySegmentRange<SegmentIterator>;
  using ReverseSegmentRange =
      DiscreteTrajectorySegmentRange<ReverseSegmentIterator>;

  DiscreteTrajectory();

  // Moveable.
  DiscreteTrajectory(DiscreteTrajectory&&) = default;
  DiscreteTrajectory& operator=(DiscreteTrajectory&&) = default;
  DiscreteTrajectory(const DiscreteTrajectory&) = delete;
  DiscreteTrajectory& operator=(const DiscreteTrajectory&) = delete;

  reference front() const;
  reference back() const;

  iterator begin() const;
  iterator end() const;

  reverse_iterator rbegin() const;
  reverse_iterator rend() const;

  bool empty() const;
  std::int64_t size() const;

  // Doesn't invalidate iterators to the first segment.
  void clear();

  iterator find(Instant const& t) const;

  iterator lower_bound(Instant const& t) const;
  iterator upper_bound(Instant const& t) const;

  SegmentRange segments() const;
  // TODO(phl): In C++20 this should be a reverse_view on segments.
  ReverseSegmentRange rsegments() const;

  SegmentIterator NewSegment();

  DiscreteTrajectory DetachSegments(SegmentIterator begin);
  SegmentIterator AttachSegments(DiscreteTrajectory trajectory);
  void DeleteSegments(SegmentIterator& begin);

  // Deletes the trajectory points with a time in [t, end[.  Drops the segments
  // that are empty as a result.
  void ForgetAfter(Instant const& t);
  void ForgetAfter(iterator it);

  // Deletes the trajectory points with a time in [begin, t[.  Preserves empty
  // segments and doesn't invalidate any segment iterator.
  void ForgetBefore(Instant const& t);
  void ForgetBefore(iterator it);

  // Return an error if downsampling was aborted.
  absl::Status Append(Instant const& t,
                      DegreesOfFreedom<Frame> const& degrees_of_freedom);

  // Merges |trajectory| (the source) into this object (the target).  The
  // operation processes pairs of segments taken from each trajectory and
  // proceeds as follows:
  // 1. If the source segment is empty (or missing), leave the target segment
  //    unchanged.
  // 2. If the target segment is empty (or missing), move the source segment
  //    into the target.  This includes its downsampling state.
  // 3. If both segments are nonempty, they must be nonoverlapping.  The points
  //    from the source segment are inserted in the target segment (possibly
  //    before the beginning of that segment).  The downsampling state of the
  //    result is that of the latest segment (the one with the largest times).
  void Merge(DiscreteTrajectory<Frame> trajectory);

  Instant t_min() const override;
  Instant t_max() const override;

  Position<Frame> EvaluatePosition(Instant const& t) const override;
  Velocity<Frame> EvaluateVelocity(Instant const& t) const override;
  DegreesOfFreedom<Frame> EvaluateDegreesOfFreedom(
      Instant const& t) const override;

  // The segments in |tracked| are restored at deserialization.  The points
  // denoted by |exact| are written and re-read exactly and are not affected by
  // any errors introduced by zfp compression.  The endpoints of each segment
  // are always exact.
  void WriteToMessage(
      not_null<serialization::DiscreteTrajectory*> message,
      std::vector<SegmentIterator> const& tracked,
      std::vector<iterator> const& exact) const;
  // Same as above, but only the points defined by [begin, end[ are written.
  void WriteToMessage(
      not_null<serialization::DiscreteTrajectory*> message,
      iterator begin,
      iterator end,
      std::vector<SegmentIterator> const& tracked,
      std::vector<iterator> const& exact) const;

  // |tracked| must have a size appropriate for the |message| being deserialized
  // and the orders of the |tracked| iterators must be consistent during
  // serialization and deserialization.  Upon return, the iterators in |tracked|
  // are past-the-end iff they were past-the-end at serialization time.
  template<typename F = Frame,
           typename = std::enable_if_t<base::is_serializable_v<F>>>
  static DiscreteTrajectory ReadFromMessage(
      serialization::DiscreteTrajectory const& message,
      std::vector<SegmentIterator*> const& tracked);

 private:
  using DownsamplingParameters =
      internal_discrete_trajectory_types::DownsamplingParameters;
  using Segments = internal_discrete_trajectory_types::Segments<Frame>;
  using SegmentByLeftEndpoint =
      absl::btree_map<Instant, typename Segments::iterator>;

  // This constructor leaves the list of segments empty (but allocated) as well
  // as the time-to-segment mapping.
  explicit DiscreteTrajectory(uninitialized_t);

  // Returns an iterator to a segment with extremities t1 and t2 such that
  // t ∈ [t1, t2[.  For the last segment, t2 is assumed to be +∞.  A 1-point
  // segment is never returned, unless it is the last one (because its upper
  // bound is assumed to be +∞).  Returns segment_by_left_endpoint_->end() iff
  // t is before the first time of the trajectory or if the trajectory is
  // empty().
  typename SegmentByLeftEndpoint::iterator FindSegment(Instant const& t);
  typename SegmentByLeftEndpoint::const_iterator
  FindSegment(Instant const& t) const;

  // Determines if this objects is in a consistent state, and returns an error
  // status with a relevant message if it isn't.
  absl::Status ConsistencyStatus() const;

  // Updates the segments self-pointers and the time-to-segment mapping after
  // segments have been spliced from |from| to |to|.  The iterator indicates the
  // segments to fix-up.
  static void AdjustAfterSplicing(
      DiscreteTrajectory& from,
      DiscreteTrajectory& to,
      typename Segments::iterator to_segments_begin);

  // Reads a pre-Hamilton downsampling message and return the downsampling
  // parameters and the start of the dense timeline.  The latter will have to be
  // converted to a number of points based on the deserialized timeline.
  static void ReadFromPreHamiltonMessage(
      serialization::DiscreteTrajectory::Downsampling const& message,
      DownsamplingParameters& downsampling_parameters,
      Instant& start_of_dense_timeline);

  // Reads a set of pre-Hamilton children.  Checks that there is only one child,
  // and that it is at the end of the preceding segment.  Append a segment to
  // the trajectory and returns an iterator to that segment.
  static SegmentIterator ReadFromPreHamiltonMessage(
      serialization::DiscreteTrajectory::Brood const& message,
      std::vector<SegmentIterator*> const& tracked,
      value_type const& fork_point,
      DiscreteTrajectory& trajectory);

  // Reads a pre-Hamilton trajectory, updating the tracked segments as needed.
  // If this is not the root of the trajectory, fork_point is set.
  static void ReadFromPreHamiltonMessage(
      serialization::DiscreteTrajectory const& message,
      std::vector<SegmentIterator*> const& tracked,
      std::optional<value_type> const& fork_point,
      DiscreteTrajectory& trajectory);

  // We need a level of indirection here to make sure that the pointer to
  // Segments in the DiscreteTrajectorySegmentIterator remain valid when the
  // DiscreteTrajectory moves.  This field is never null and never empty.
  not_null<std::unique_ptr<Segments>> segments_;

  // Maps time |t| to the last segment that start at time |t|.  Does not contain
  // entries for empty segments (at the beginning of the trajectory) or for
  // 1-point segments that are not the last at their time.  Empty iff the entire
  // trajectory is empty.  Always updated using |insert_or_assign| to override
  // any preexisting segment with the same endpoint.
  SegmentByLeftEndpoint segment_by_left_endpoint_;
};

}  // namespace internal_discrete_trajectory

using internal_discrete_trajectory::DiscreteTrajectory;

}  // namespace physics
}  // namespace principia

#include "physics/discrete_trajectory_body.hpp"


text:
template<typename T>
using term = boost::yap::terminal<boost::yap::expression, T>;

template<typename T>
using term_ref = boost::yap::expression_ref<boost::yap::expression, term<T> &>;

template<typename T>
using term_cref =
    boost::yap::expression_ref<boost::yap::expression, term<T> const &>;

namespace yap = boost::yap;
namespace bh = boost::hana;

struct void_callable
{
    void operator()() { *called_ = (*call_count_)++; }
    int * call_count_;
    int * called_;
};

struct int_callable
{
    int operator()()
    {
        *called_ = (*call_count_)++;
        return 42;
    }
    int * call_count_;
    int * called_;
};

struct double_callable
{
    double operator()()
    {
        *called_ = (*call_count_)++;
        return 13.0;
    }
    int * call_count_;
    int * called_;
};

int test_main(int, char * [])
{
{
    {
        int call_count = 0;
        int int_called = -1;
        int double_called = -1;

        auto int_double_expr =
            (term<int_callable>{{&call_count, &int_called}}(),
             term<double_callable>{{&call_count, &double_called}}());

        BOOST_CHECK(evaluate(int_double_expr) == 13.0);
        BOOST_CHECK(int_called == 0);
        BOOST_CHECK(double_called == 1);
    }

    {
        int call_count = 0;
        int int_called = -1;
        int double_called = -1;

        auto double_int_expr =
            (term<double_callable>{{&call_count, &double_called}}(),
             term<int_callable>{{&call_count, &int_called}}());

        BOOST_CHECK(evaluate(double_int_expr) == 42);
        BOOST_CHECK(int_called == 1);
        BOOST_CHECK(double_called == 0);
    }
}

{
    {
        int call_count = 0;
        int void_called = -1;
        int int_called = -1;

        auto void_int_expr =
            (term<void_callable>{{&call_count, &void_called}}(),
             term<int_callable>{{&call_count, &int_called}}());

        BOOST_CHECK(evaluate(void_int_expr) == 42);
        BOOST_CHECK(void_called == 0);
        BOOST_CHECK(int_called == 1);
    }

    {
        int call_count = 0;
        int void_called = -1;
        int int_called = -1;

        auto int_void_expr =
            (term<int_callable>{{&call_count, &int_called}}(),
             term<void_callable>{{&call_count, &void_called}}());

        using eval_type = decltype(evaluate(int_void_expr));
        BOOST_MPL_ASSERT(
            (std::is_same<void, eval_type>));

        evaluate(int_void_expr);
        BOOST_CHECK(void_called == 1);
        BOOST_CHECK(int_called == 0);
    }
}

return 0;
}


text:
div#calpopup {
  display: block;
  border: thin solid gray;
  /* This is css3 stuff that will not work in IE<=8.
   * What is here is a curved border for firefox and webkit
   * and a drop shadow that will only appear in webkit.
  **/
  -moz-border-radius: 1em;
  -webkit-border-radius: 1em;
  -webkit-box-shadow: 10px 10px 5px #888;
  /* End CSS3 stuff */
  background-color: white;
  width: 25%;
  position: absolute;
  top: 20em;
  left: 20em;

  /* CSS to make sure that the popup is on top */
  z-index: 800;
}

div#calpopup-body div.node {
  margin: 0;
  border: 0;
}

div#calpopup-body {
  margin: 1em;
  max-height: 20em;
  overflow-y: auto;
  /* IE7 Hack
   * This keeps the date from sticking in one place while scrolling.
   */
  position: relative;
}

#popup-close {
  text-align: right;
  padding: 1em 1em 0 1em;
}

div#nodelink {
  margin: 1em;
}

img#popthrobber {
  text-align: center;
  margin: 3em;
}


text:
package Help.Json;

/**
 * Created by tinysou on 14-10-13.
 */
public class Info {
    public String query = null;
    public String page = null;
    public String total_pages = null;
    public String per_page = null;
    public String total = null;
    public String max_score = null;
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Arch. Jard. Bot. Rio de Janeiro 4:311. 1925

#### Original name
null

### Remarks
null


text:
package alma.acs.logging.formatters;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Map;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

import org.omg.CORBA.Any;

import alma.ACSLoggingLog.LogBinaryRecord;
import alma.ACSLoggingLog.LogBinaryRecordHelper;
import alma.ACSLoggingLog.NameValue;
import alma.acs.logging.AcsLogLevel;
import alma.acs.logging.AcsLogRecord;
import alma.acs.logging.LogParameterUtil;
import alma.acs.logging.level.AcsLogLevelDefinition;
import alma.acs.util.IsoDateFormat;

/**
 * @author cparedes
 *
 * Class that is responsible for formatting the log records/elements of different levels
 * as well as assigning the right values to their attributes.
 */
public class AcsBinLogFormatter extends AcsLogFormatter
{
    /**
     * This is the method used by ACS, for all AcsLogFormatters.
     */
    public Any formatAny( Any anyLogRecord, LogRecord logRecord){
        LogBinaryRecord binLogRecord = formatBinary(logRecord);
        LogBinaryRecordHelper.insert(anyLogRecord,binLogRecord);
        return anyLogRecord;
    }

    LogBinaryRecord formatBinary(LogRecord logRecord){
        LogBinaryRecord rLog = new LogBinaryRecord();

		// log level
		AcsLogLevel acsLevel = AcsLogLevel.getNativeLevel(logRecord.getLevel());
		if (acsLevel == null) {
			return null;
		}
		final AcsLogLevelDefinition acsCoreLevel = acsLevel.getAcsLevel();

		// get date
		Date date = new Date(logRecord.getMillis());
		String TimeStamp = IsoDateFormat.formatDate(date);

		LogParameterUtil logParamUtil = new LogParameterUtil(logRecord);

		rLog.type = (short) acsCoreLevel.value;
        rLog.TimeStamp = TimeStamp;

		String file = logRecord.getSourceClassName();
		if (file == null)
		{
			if (acsCoreLevel == AcsLogLevelDefinition.DEBUG)
				rLog.File = "unknown";
		}
		else
			rLog.File = file;

		long line = logParamUtil.extractLongProperty(LogParameterUtil.PARAM_LINE, -1);
		if (line < 0)
		{
			if (acsCoreLevel == AcsLogLevelDefinition.TRACE || acsCoreLevel == AcsLogLevelDefinition.DEBUG)
		        rLog.Line = 0;
		}
		else
		    rLog.Line = (int)line;

		String Routine = logRecord.getSourceMethodName();
		if (Routine == null) {
			if (acsCoreLevel == AcsLogLevelDefinition.TRACE) {
	            rLog.Routine = "unknown";
			}
		}
		else {
	        rLog.Routine = Routine;
		}

        // host name: may be different from local host if ErrorTrace gets logged
        String hostName = logParamUtil.extractStringProperty(LogParameterUtil.PARAM_HOSTNAME, null);
        if (hostName == null || hostName.length() == 0) {
            hostName = getLocalHostName();
        }
		rLog.Host = hostName;

//		String process = logParamUtil.extractStringProperty(LogParameterUtil.PARAM_PROCESSNAME, null);
//		if (process != null)
//            rLog.Process = process;
//        else{
            String process = logRecord.getLoggerName();
            if(process != null)  rLog.Process = "LoggerName: " + process;
            else rLog.Process = "";
  //      }
		// source object: the container name or component name
		String sourceObject = logRecord.getLoggerName();
		if (sourceObject != null) {
			rLog.SourceObject = sourceObject;
        }else rLog.SourceObject = "";

		// add thread ID, or name if given
		String threadName = logParamUtil.extractStringProperty(LogParameterUtil.PARAM_THREAD_NAME, null);
		if (threadName != null && threadName.length() > 0)
			rLog.Thread = threadName;
		else if (logRecord.getThreadID() >= 0)
			rLog.Thread = ""+logRecord.getThreadID();
        else rLog.Thread = "";
		// add context
		String context = logParamUtil.extractStringProperty("Context", null);
		if (context != null)
			rLog.LogContext = context;
        else rLog.LogContext = "";

		// add stack info
        rLog.StackId="";
        rLog.StackLevel = 0;
		if (acsCoreLevel.compareTo(AcsLogLevelDefinition.WARNING) >= 0) {
			// add stack id
			String stackId = logParamUtil.extractStringProperty(LogParameterUtil.PARAM_STACK_ID, null);
			if (stackId == null)
				rLog.StackId="unknown";
			else
				rLog.StackId=stackId;

			// add stack idlevel
			long stackLevel = logParamUtil.extractLongProperty(LogParameterUtil.PARAM_STACK_LEVEL, -1);
			if (stackLevel > 0)
		        rLog.StackLevel = (int)stackLevel;
		}

		// add log id
		long logId = logRecord.getSequenceNumber();
		if (logId >= 0)
            rLog.LogId = "" +logId;
        else rLog.LogId = "";
		// add URI
		String uri = logParamUtil.extractStringProperty(LogParameterUtil.PARAM_URI, null);
		if (uri != null)
            rLog.Uri = uri;
        else rLog.Uri = "";
		// add priority
		// to be written only different as entry priority
		long priority = logParamUtil.extractLongProperty(LogParameterUtil.PARAM_PRIORITY, acsCoreLevel.value);
		if (priority != acsCoreLevel.value)
            rLog.Priority = (int)priority;
        else rLog.Priority = -1;

		// the log message becomes the text in our XML record
		if (logRecord.getMessage() != null)
		{
            rLog.MsgData = logRecord.getMessage();
		}else rLog.MsgData = "";

        //add Audience, Array and Antenna, if applicable
        if (logRecord instanceof AcsLogRecord) {
            rLog.Audience = ((AcsLogRecord) logRecord).getAudience();
            rLog.Array = ((AcsLogRecord) logRecord).getArray();
            rLog.Antenna = ((AcsLogRecord) logRecord).getAntenna();
        }
		// <Data> elements: logged exception or error trace, and log parameters

        //NameValue a;
		//rLog.log_data = new NameValue[propertiesMap.size() + 1];
		//TODO: see why there are not attributes here
        rLog.attributes = new NameValue[0];
		NameValue [] log_data = new NameValue[257];
		//rLog.log_data = new NameValue[257];
        int i = 0;
        try {
			// logged exception
			Throwable loggedThrowable = logRecord.getThrown();
			if (loggedThrowable != null) {
			    StringWriter exWriter = new StringWriter();
			    loggedThrowable.printStackTrace(new PrintWriter(exWriter));
                log_data[i++] = new NameValue("LoggedException", exWriter.toString());
            }
			// log parameters (except for the special properties which were used already to set specific fields)
			for (Object param : logParamUtil.getNonSpecialPropertiesMapParameters()) {
                if(i>=255) break;
				if (param instanceof Map) {
					// any map that is not the special properties map we interpret as name-value pairs.
					Map propertiesMap = (Map) param;
					for (Object keyName : propertiesMap.keySet()) {
						String value = propertiesMap.get(keyName).toString();
                        log_data[i++] = new NameValue(keyName.toString(), value);
					}
				}
				else {
					// a single parameter was logged, but we have to fit it into our name-value scheme using a fake name
					String value = param.toString();
                    log_data[i++] = new NameValue("LoggedParameter", value);
				}
			}
		}
		catch (Exception e) {
			// expected not to happen often at all, thus no try blocks inside every loop, so we may lose some <Data>
            String value = e.toString();
            log_data[i++] = new NameValue("DataConstructionError", value);
		}

        rLog.log_data = new NameValue[i];
        for(int j=0; j<i;j++) {
        	rLog.log_data[j] = log_data[j];
        }

		// end tag of BIN record

		return rLog;

    }

	/**
	 * This method should never be called. We only add it to support the inheritance of
	 * {@link AcsLogFormatter} from {@link Formatter} which is useful for text-based subclasses.
	 */
	public String format(LogRecord record) {
		return "Error: only binary format available!";
	}

}


text:
<?php

namespace common\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\TextBlock;

/**
 * TextBlockSearch represents the model behind the search form about `common\models\TextBlock`.
 */
class TextBlockSearch extends TextBlock
{
	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['id', 'status', 'creator_id', 'editor_id'], 'integer'],
			[['alias', 'created_at', 'updated_at', 'creator.username', 'editor.username', 'title'], 'safe'],
		];
	}

	/**
	 * @return array
	 */
	public function attributes()
	{
		// add related fields to searchable attributes
		return array_merge(parent::attributes(), [
			'creator.username',
			'editor.username',
		]);
	}

	/**
	 * @inheritdoc
	 */
	public function scenarios()
	{
		// bypass scenarios() implementation in the parent class
		return Model::scenarios();
	}

	/**
	 * Creates data provider instance with search query applied
	 *
	 * @param array $params
	 *
	 * @return ActiveDataProvider
	 */
	public function search($params)
	{
		$query = TextBlock::find();

		// add conditions that should always apply here

		$dataProvider = new ActiveDataProvider([
			'query' => $query,
		]);

		$query->joinWith(['creator', 'editor']);

		$dataProvider->sort->attributes['creator.username'] = [
			'asc'  => ['creator.username' => SORT_ASC],
			'desc' => ['creator.username' => SORT_DESC],
		];

		$dataProvider->sort->attributes['editor.username'] = [
			'asc'  => ['editor.username' => SORT_ASC],
			'desc' => ['editor.username' => SORT_DESC],
		];

		$this->load($params);

		if (!$this->validate()) {
			// uncomment the following line if you do not want to return any records when validation fails
			// $query->where('0=1');
			return $dataProvider;
		}

		// grid filtering conditions
		$query->andFilterWhere([
			'id'         => $this->id,
			'status'     => $this->status,
			'creator_id' => $this->creator_id,
			'editor_id'  => $this->editor_id,
			'created_at' => $this->created_at,
			'updated_at' => $this->updated_at,
		]);

		$query->andFilterWhere(['like', 'alias', $this->alias])
			->andFilterWhere(['like', 'title', $this->title])
			->andFilterWhere(['like', 'creator.username', $this->getAttribute('creator.username')])
			->andFilterWhere(['like', 'editor.username', $this->getAttribute('editor.username')]);

		return $dataProvider;
	}
}


text:
/* ------------------------------------------------------------------------ */

/*
 * nodelock.h:  licensing stuff
 */

#ifndef _NODELOCK_H
#define _NODELOCK_H

/*
 * Do the initial IP address check and expiration date check.  Reads a file
 * from admin/config, as #define'd.
 *
 * Returns 1 on error, 0 on AOK.
 */

int node_init(void);

/*
 * Check the expiration date against The Now.
 *
 * Returns 1 on error, 0 on AOK.
 */

int node_check(void);

/*
 * So how we doin, license
 *
 * Returns 1 on error, 0 on AOK
 */
int node_status(void);

#endif


text:
package com.daimajia.androidanimations.library.fading_exits;

import android.animation.ObjectAnimator;
import android.view.View;

import com.daimajia.androidanimations.library.BaseViewAnimator;

public class FadeOutRightAnimator extends BaseViewAnimator {
    @Override
    public void prepare(View target) {
        getAnimatorAgent().playTogether(
                ObjectAnimator.ofFloat(target, "alpha", 1, 0),
                ObjectAnimator.ofFloat(target, "translationX", 0, target.getWidth() / 4)
        );
    }
}


text:
class cWitch :
	public cAggressiveMonster
{
	typedef cAggressiveMonster super;

public:
	cWitch();

	CLASS_PROTODEF(cWitch);

	virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override;

	bool IsAngry(void) const {return ((m_EMState == ATTACKING) || (m_EMState == CHASING)); }
} ;


text:
<?php

use Treffynnon\Navigator\Distance\Converter as C;

class MetreToMileTest extends PHPUnit_Framework_TestCase {

    /**
     * @dataProvider distanceDataProvider
     */
    public function testConvert($distance) {
        $Mile = new C\MetreToMile;
        $this->assertRegExp('/[\d.]+/', (string) $Mile->convert($distance));
    }

    /**
     * @expectedException PHPUnit_Framework_Error
     */
    public function testFailedConvert() {
        $Mile = new C\MetreToMile;
        $Mile->convert();
    }

    /**
     * @dataProvider distanceDataProvider
     */
    public function testConvertAccuracy($distance) {
        $Mile = new C\MetreToMile;
        $actual = $Mile->convert($distance);
        $expected = $distance * $Mile->factor;
        $this->assertEquals($expected, $actual, '', 0.2);
    }

    /**
     * @dataProvider distanceDataProvider
     */
    public function testReverse($distance) {
        $Mile = new C\MetreToMile;
        $this->assertRegExp('/[\d.]+/', (string) $Mile->reverse($distance));
    }

    /**
     * @expectedException PHPUnit_Framework_Error
     */
    public function testFailedReverse() {
        $Mile = new C\MetreToMile;
        $Mile->reverse();
    }

    /**
     * @dataProvider distanceDataProvider
     */
    public function testReverseAccuracy($distance) {
        $Mile = new C\MetreToMile;
        $actual = $Mile->reverse($distance);
        $expected = $distance / $Mile->factor;
        $this->assertEquals($expected, $actual, '', 0.2);
    }

    public function distanceDataProvider() {
        return \NavigatorTestData::distanceData();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp">

    <com.github.vipulasri.timelineview.TimelineView
        android:id="@+id/time_marker"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:marker="@drawable/ic_marker"
        app:markerSize="20dp"
        app:lineSize="3dp"
        app:linePadding="5dp"
        app:line="?attr/colorPrimary"/>

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="15dp"
        android:layout_marginStart="10dp"
        android:layout_gravity="center_vertical"
        app:cardElevation="1dp"
        app:contentPadding="15dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/event_date"
                android:textSize="12sp"
                android:textAppearance="?attr/textAppearanceBody2"
                tools:text="24 JAN"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:id="@+id/event_title"
                android:textAppearance="?attr/textAppearanceCaption"
                tools:text="Title"/>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>


text:
<?php
  class Reprovador implements EstadoDeUmOrcamento {
    public function aplicaDescontoExtra(Orcamento $orcamento) {
      throw new Exception("Um orçamento reprovado não pode receber descontos");
    }

    public function aprova(Orcamento $orcamento) {
      throw new Exception ("Apenas orçamentos em aprovação podem ser aprovados");
    }

    public function reprova(Orcamento $orcamento) {
      throw new Exception("Este orçamos já se encontra reprovado");
    }

    public function finaliza(Orcamento $orcamento)  {
      throw new Exception ("Apenas orçamos aprovados podem ser finalizados");
    }
  }
?>


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Poll',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=128)),
                ('question', models.CharField(max_length=1028)),
                ('single_selection', models.BooleanField(default=True)),
                ('user_closed', models.BooleanField(default=False)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('last_edited', models.DateTimeField(auto_now=True)),
                ('end_time', models.DateTimeField()),
                ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pollapp', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='PollAnswer',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ],
        ),
        migrations.CreateModel(
            name='PollOption',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('text', models.CharField(max_length=512)),
                ('poll', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='poll_options', to='pollapp.Poll')),
            ],
        ),
        migrations.AddField(
            model_name='pollanswer',
            name='answer',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='answers', to='pollapp.PollOption'),
        ),
        migrations.AddField(
            model_name='pollanswer',
            name='owner',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='poll_answers', to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
<?php

/**
 * @file
 * Contains \Drupal\Tests\migrate\Unit\process\GetTest.
 */

namespace Drupal\Tests\migrate\Unit\process;

use Drupal\migrate\Plugin\migrate\process\TestGet;

/**
 * Tests the get process plugin.
 *
 * @group migrate
 */
class GetTest extends MigrateProcessTestCase {

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    $this->plugin = new TestGet();
    parent::setUp();
  }

  /**
   * Tests the Get plugin when source is a string.
   */
  public function testTransformSourceString() {
    $this->row->expects($this->once())
      ->method('getSourceProperty')
      ->with('test')
      ->will($this->returnValue('source_value'));
    $this->plugin->setSource('test');
    $value = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame($value, 'source_value');
  }

  /**
   * Tests the Get plugin when source is an array.
   */
  public function testTransformSourceArray() {
    $map = [
      'test1' => 'source_value1',
      'test2' => 'source_value2',
    ];
    $this->plugin->setSource(['test1', 'test2']);
    $this->row->expects($this->exactly(2))
      ->method('getSourceProperty')
      ->will($this->returnCallback(function ($argument)  use ($map) {
        return $map[$argument];
      }));
    $value = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame($value, ['source_value1', 'source_value2']);
  }

  /**
   * Tests the Get plugin when source is a string pointing to destination.
   */
  public function testTransformSourceStringAt() {
    $this->row->expects($this->once())
      ->method('getSourceProperty')
      ->with('@test')
      ->will($this->returnValue('source_value'));
    $this->plugin->setSource('@@test');
    $value = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame($value, 'source_value');
  }

  /**
   * Tests the Get plugin when source is an array pointing to destination.
   */
  public function testTransformSourceArrayAt() {
    $map = [
      'test1' => 'source_value1',
      '@test2' => 'source_value2',
      '@test3' => 'source_value3',
      'test4' => 'source_value4',
    ];
    $this->plugin->setSource(['test1', '@@test2', '@@test3', 'test4']);
    $this->row->expects($this->exactly(4))
      ->method('getSourceProperty')
      ->will($this->returnCallback(function ($argument)  use ($map) {
        return $map[$argument];
      }));
    $value = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame($value, ['source_value1', 'source_value2', 'source_value3', 'source_value4']);
  }

  /**
   * Tests the Get plugin when source has integer values.
   */
  public function testIntegerValues() {
    $this->row->expects($this->exactly(2))
      ->method('getSourceProperty')
      ->willReturnOnConsecutiveCalls('val1', 'val2');

    $this->plugin->setSource([0 => 0, 1 => 'test']);
    $return = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame([0 => 'val1', 1 => 'val2'], $return);

    $this->plugin->setSource([FALSE]);
    $return = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame([NULL], $return);

    $this->plugin->setSource([NULL]);
    $return = $this->plugin->transform(NULL, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame([NULL], $return);
  }

}

namespace Drupal\migrate\Plugin\migrate\process;

class TestGet extends Get {
  public function __construct() {
  }
  public function setSource($source) {
    $this->configuration['source'] = $source;
  }

}


text:
class RoomsController < ApplicationController
	def index
		if not signed_in?
			redirect_to root_path
		else
			room = current_user.room
			# if room
			# 	redirect_to :controller=>'game', :action => 'main', :id => room.id
			# else
				@rooms = Room.all
			# end
		end
	end

	def new
		@room = Room.new
	end

	def create
		puts "\n\n\nROOM_TEST\n\n\n#{params}\n\n\n"
		@room = Room.new(room_params)
		# @room.users.create(user_id: current_user.id)
		if @room.save
			flash[:success] = "Welcome to #{@room.name}, please select color"
			redirect_to @room
		else
			render 'new'
		end
	end

	def show
		@room = Room.find(params[:id])
		@player_white = User.find(@room.player_white_id) if (@room.player_white_id && @room.player_white_id.to_i != 0 )
		@player_black = User.find(@room.player_black_id) if (@room.player_black_id && @room.player_black_id.to_i != 0 )
		@player_red = User.find(@room.player_red_id) if (@room.player_red_id && @room.player_red_id.to_i != 0 )
	end

	def take_place
		room = Room.find(params[:room])
		user = User.find(params[:user])

		if user.room
			flash[:error] = "You are taking part in another room '#{user.room.name}'"
		else
			case params[:color]
			when "white"
				if not room.player_white_id
					room.player_white_id = user.id
					user.update_attribute(:room_id, room.id)
				else
					flash[:error] = "You can't take white color"
				end

			when "black"
				if not room.player_black_id
					room.player_black_id = user.id
					user.update_attribute(:room_id, room.id)
				else
					flash[:error] = "You can't take black color"
				end

			when "red"
				if not room.player_red_id
					room.player_red_id = user.id
					user.update_attribute(:room_id, room.id)
				else
					flash[:error] = "You can't take red color"
				end
			else
				flash[:error] = "Hmm, are you hacker ?"
			end

			room.save
		end

		if room_filled?(room)
			redirect_to :controller=>'game', :action => 'main', :id => room.id
		else
			redirect_to room
		end
	end

	def leave
		puts "<><>#{params}"
		user = current_user
		room = Room.find(params[:id])
		if not room
			flash[:error] = "Something went wrong."
		elsif user.room
			puts "user have room #{user.room.id} #{user.room.name}"
			if room.player_white_id.to_i == user.id.to_i
				room.update_attribute(:player_white_id, nil)
			elsif room.player_black_id.to_i == user.id.to_i
				room.update_attribute(:player_black_id, nil)
			elsif room.player_red_id.to_i == user.id.to_i
				room.update_attribute(:player_red_id, nil)
			end

			user.update_attribute(:room, nil)
		end

		redirect_to rooms_path
	end

	private

		def room_params
			params.require(:room).permit(:name)
		end

		def room_filled?(room)
			filled = room.player_white_id && room.player_black_id && room.player_red_id
			return filled
		end

end


text: from fpl_reader.playlist_reader import read_playlist


text:
package com.graphhopper.routing.lm;

import com.graphhopper.routing.RoutingAlgorithmTest;
import com.graphhopper.routing.util.CarFlagEncoder;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.util.spatialrules.AbstractSpatialRule;
import com.graphhopper.routing.util.spatialrules.SpatialRule;
import com.graphhopper.routing.util.spatialrules.SpatialRuleLookup;
import com.graphhopper.routing.util.spatialrules.SpatialRuleSet;
import com.graphhopper.routing.weighting.FastestWeighting;
import com.graphhopper.storage.DataAccess;
import com.graphhopper.storage.Directory;
import com.graphhopper.storage.GraphHopperStorage;
import com.graphhopper.storage.RAMDirectory;
import com.graphhopper.util.EdgeIteratorState;
import com.graphhopper.util.GHUtility;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Polygon;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.*;

/**
 * @author Peter Karich
 */
public class LandmarkStorageTest {
    private GraphHopperStorage graph;
    private FlagEncoder encoder;
    private EncodingManager encodingManager;

    @Before
    public void setUp() {
        encoder = new CarFlagEncoder();
        encodingManager = EncodingManager.create(encoder);
        graph = new GraphHopperStorage(new RAMDirectory(),
                encodingManager, false);
        graph.create(1000);
    }

    @After
    public void tearDown() {
        if (graph != null)
            graph.close();
    }

    @Test
    public void testInfiniteWeight() {
        Directory dir = new RAMDirectory();
        EdgeIteratorState edge = graph.edge(0, 1);
        int res = new LandmarkStorage(graph, dir, new LMConfig("c1", new FastestWeighting(encoder) {
            @Override
            public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
                return Integer.MAX_VALUE * 2L;
            }
        }), 8).setMaximumWeight(LandmarkStorage.PRECISION).calcWeight(edge, false);
        assertEquals(Integer.MAX_VALUE, res);

        dir = new RAMDirectory();
        res = new LandmarkStorage(graph, dir, new LMConfig("c2", new FastestWeighting(encoder) {
            @Override
            public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
                return Double.POSITIVE_INFINITY;
            }
        }), 8).setMaximumWeight(LandmarkStorage.PRECISION).calcWeight(edge, false);
        assertEquals(Integer.MAX_VALUE, res);
    }

    @Test
    public void testSetGetWeight() {
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(0, 1).setDistance(40.1));
        Directory dir = new RAMDirectory();
        DataAccess da = dir.find("landmarks_c1");
        da.create(2000);

        LandmarkStorage lms = new LandmarkStorage(graph, dir, new LMConfig("c1", new FastestWeighting(encoder)), 4).
                setMaximumWeight(LandmarkStorage.PRECISION);
        // 2^16=65536, use -1 for infinity and -2 for maximum
        lms.setWeight(0, 65536);
        // reached maximum value but do not reset to 0 instead use 2^16-2
        assertEquals(65536 - 2, lms.getFromWeight(0, 0));
        lms.setWeight(0, 65535);
        assertEquals(65534, lms.getFromWeight(0, 0));
        lms.setWeight(0, 79999);
        assertEquals(65534, lms.getFromWeight(0, 0));

        da.setInt(0, Integer.MAX_VALUE);
        assertTrue(lms.isInfinity(0));
        // for infinity return much bigger value
        // assertEquals(Integer.MAX_VALUE, lms.getFromWeight(0, 0));

        lms.setWeight(0, 79999);
        assertFalse(lms.isInfinity(0));
    }

    @Test
    public void testWithSubnetworks() {
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(0, 1).setDistance(10.1));
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(1, 2).setDistance(10.2));

        graph.edge(2, 4).set(encoder.getAccessEnc(), false, false);
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(4, 5).setDistance(10.5));
        GHUtility.setSpeed(60, true, false, encoder, graph.edge(5, 6).setDistance(10.6));

        LandmarkStorage storage = new LandmarkStorage(graph, new RAMDirectory(), new LMConfig("c1", new FastestWeighting(encoder)), 2);
        storage.setMinimumNodes(2);
        storage.createLandmarks();
        assertEquals(3, storage.getSubnetworksWithLandmarks());
        assertEquals("[2, 0]", Arrays.toString(storage.getLandmarks(1)));
        assertEquals("[6, 4]", Arrays.toString(storage.getLandmarks(2)));
    }

    @Test
    public void testWithSubnetworks2() {
        // should not happen with subnetwork preparation
        // 0 - 1 - 2 = 3 - 4
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(0, 1).setDistance(10.1));
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(1, 2).setDistance(10.2));
        GHUtility.setSpeed(60, true, false, encoder, graph.edge(2, 3).setDistance(10.3));
        GHUtility.setSpeed(60, true, false, encoder, graph.edge(3, 2).setDistance(10.2));
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(3, 4).setDistance(10.4));

        LandmarkStorage storage = new LandmarkStorage(graph, new RAMDirectory(), new LMConfig("c", new FastestWeighting(encoder)), 2);
        storage.setMinimumNodes(3);
        storage.createLandmarks();
        assertEquals(2, storage.getSubnetworksWithLandmarks());
        assertEquals("[4, 0]", Arrays.toString(storage.getLandmarks(1)));
    }

    @Test
    public void testWithOnewaySubnetworks() {
        // should not happen with subnetwork preparation
        // create an indifferent problem: node 2 and 3 are part of two 'disconnected' subnetworks
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(0, 1).setDistance(10.1));
        GHUtility.setSpeed(60, true, false, encoder, graph.edge(1, 2).setDistance(10.2));
        GHUtility.setSpeed(60, true, false, encoder, graph.edge(2, 3).setDistance(10.3));

        GHUtility.setSpeed(60, true, true, encoder, graph.edge(4, 5).setDistance(10.5));
        GHUtility.setSpeed(60, true, false, encoder, graph.edge(5, 2).setDistance(10.2));

        LandmarkStorage storage = new LandmarkStorage(graph, new RAMDirectory(), new LMConfig("c", new FastestWeighting(encoder)), 2);
        storage.setMinimumNodes(2);
        storage.createLandmarks();

        assertEquals(2, storage.getSubnetworksWithLandmarks());
        assertEquals("[4, 0]", Arrays.toString(storage.getLandmarks(1)));
    }

    @Test
    public void testWeightingConsistence() {
        // create an indifferent problem: shortest weighting can pass the speed==0 edge but fastest cannot (?)
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(0, 1).setDistance(10.1));
        GHUtility.setSpeed(0.9, true, true, encoder, graph.edge(1, 2).setDistance(10));
        GHUtility.setSpeed(60, true, true, encoder, graph.edge(2, 3).setDistance(10.3));

        LandmarkStorage storage = new LandmarkStorage(graph, new RAMDirectory(), new LMConfig("c", new FastestWeighting(encoder)), 2);
        storage.setMinimumNodes(2);
        storage.createLandmarks();

        assertEquals(2, storage.getSubnetworksWithLandmarks());
        assertEquals("[1, 0]", Arrays.toString(storage.getLandmarks(1)));
    }

    @Test
    public void testWithBorderBlocking() {
        RoutingAlgorithmTest.initBiGraph(graph, encoder);

        LandmarkStorage storage = new LandmarkStorage(graph, new RAMDirectory(), new LMConfig("c", new FastestWeighting(encoder)), 2);
        final SpatialRule ruleRight = new AbstractSpatialRule(Collections.<Polygon>emptyList()) {
            @Override
            public String getId() {
                return "right";
            }
        };
        final SpatialRule ruleLeft = new AbstractSpatialRule(Collections.<Polygon>emptyList()) {
            @Override
            public String getId() {
                return "left";
            }
        };
        final SpatialRuleLookup lookup = new SpatialRuleLookup() {

            private final List<SpatialRule> rules = Arrays.asList(ruleLeft, ruleRight);

            @Override
            public SpatialRuleSet lookupRules(double lat, double lon) {
                SpatialRule rule;
                if (lon > 0.00105) {
                    rule = ruleRight;
                } else {
                    rule = ruleLeft;
                }

                return new SpatialRuleSet(Collections.singletonList(rule), rules.indexOf(rule) + 1);
            }

            @Override
            public List<SpatialRule> getRules() {
                return rules;
            }

            @Override
            public Envelope getBounds() {
                return new Envelope(-180d, 180d, -90d, 90d);
            }
        };

        storage.setSpatialRuleLookup(lookup);
        storage.setMinimumNodes(2);
        storage.createLandmarks();
        assertEquals(3, storage.getSubnetworksWithLandmarks());
    }
}


text:
package com.simicaleksandar.radar.inner;

import android.app.Activity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

final class LayoutInflaterManager {

  private static transient LayoutInflaterManager instance;
  private final transient LayoutInflater inflater;

  static LayoutInflaterManager getInstance(Activity activity) {
    if (instance == null) {
      instance = new LayoutInflaterManager(activity);
    }

    return instance;
  }

  private LayoutInflaterManager(Activity activity) {
    inflater = activity.getLayoutInflater();
  }

  View inflate(@LayoutRes int layoutId, @Nullable ViewGroup root, boolean attachToRoot) {
    assert inflater != null;

    return inflater.inflate(layoutId, root, attachToRoot);
  }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
module Client.Key where

import Control.Lens ((.=), (%=), use, ix, (+=), (^.), (-=), preuse, zoom)
import Control.Monad.State (liftM, unless, when, void)
import Data.Char (ord, toUpper, chr)
import Data.Maybe (isJust, fromJust, isNothing)
import System.IO (Handle)
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC

import Client.ClientStateT
import Client.ClientStaticT
import Client.ConsoleT
import Game.PlayerStateT
import Client.FrameT
import Types
import QuakeState
import Client.KeyConstants
import QCommon.XCommandT
import qualified Constants
import {-# SOURCE #-} qualified Client.Menu as Menu
import {-# SOURCE #-} qualified Client.Console as Console
import qualified Game.Cmd as Cmd
import qualified QCommon.CBuf as CBuf
import {-# SOURCE #-} qualified QCommon.Com as Com

initialize :: Quake ()
initialize = do
    let kl = V.replicate 32 $ B.pack [93, 0] -- 93 is ']'
    globals.gKeyLines .= kl
    globals.gKeyLinePos .= 1

    keyGlobals.kgConsoleKeys %= (UV.// (([32..127] `zip` repeat True) ++
            ([kEnter, kKpEnter, kTab, kLeftArrow, kKpLeftArrow,
             kRightArrow, kKpRightArrow, kUpArrow, kKpUpArrow,
             kDownArrow, kKpDownArrow, kBackspace, kHome, kKpHome,
             kEnd, kKpEnd, kPgUp, kKpPgUp, kPgDn, kKpPgDn, kShift,
             kIns, kKpIns, kKpDel, kKpSlash, kKpPlus, kKpMinus,
             kKp5] `zip` repeat True) ++ [(96, False), (126, False)])) -- 96 is '`', 126 is '~'

    keyGlobals.kgMenuBound %= (UV.// ([kF1, kF2, kF3, kF4, kF5,
                             kF6, kF7, kF8, kF9, kF10,
                             kF11, kF12, kEscape] `zip` repeat True))

    Cmd.addCommand "bind" (Just bindF)
    Cmd.addCommand "unbind" (Just unbindF)
    Cmd.addCommand "unbindall" (Just unbindAllF)
    Cmd.addCommand "bindlist" (Just bindListF)

bindF :: XCommandT
bindF =
  XCommandT "Key.bindF" (do
    c <- Cmd.argc

    if c < 2
      then Com.printf "bind <key> [command] : attach a command to a key\n"
      else do
        v <- Cmd.argv 1
        b <- stringToKeynum v

        if | b == -1 -> Com.printf $ "\"" `B.append` v `B.append` "\" isn't a valid key\n"
           | c == 2 -> do
               keybindings <- use $ globals.gKeyBindings
               case keybindings V.! b of
                 Just binding -> Com.printf $ "\"" `B.append` v `B.append` "\" = \"" `B.append` binding `B.append` "\"\n"
                 Nothing -> Com.printf $ "\"" `B.append` v `B.append` "\" is not bound\n"
           | otherwise -> do
               cmd <- liftM (B.intercalate " ") $ mapM Cmd.argv [2..c-1]
               setBinding b (Just cmd)
  )

unbindF :: XCommandT
unbindF =
  XCommandT "Key.unbindF" (do
    c <- Cmd.argc

    if c /= 2
      then Com.printf "unbind <key> : remove commands from a key\n"
      else do
        v <- Cmd.argv 1
        b <- stringToKeynum v

        if b == -1
          then Com.printf $ "\"" `B.append` v `B.append` "\" isn't a valid key\n"
          else setBinding b Nothing
  )

unbindAllF :: XCommandT
unbindAllF = XCommandT "Key.unbindAllF" (globals.gKeyBindings .= V.replicate 256 Nothing)

bindListF :: XCommandT
bindListF =
  XCommandT "Key.bindListF" (do
    bindings <- use $ globals.gKeyBindings
    void $ V.sequence $ V.imap printBinding bindings
  )

  where printBinding _ Nothing = return ()
        printBinding i (Just b) =
          when (B.length b /= 0) $ do
                                    strKeynum <- keynumToString i
                                    Com.printf $ strKeynum
                                      `B.append` " \""
                                      `B.append` b
                                      `B.append` "\"\n"

-- Returns a key number to be used to index keybindings[] by looking at
-- the given string. Single ascii characters return themselves, while
-- the K_* names are matched up.
stringToKeynum :: B.ByteString -> Quake Int
stringToKeynum str =
    if B.length str == 1
      then return $ ord $ BC.index str 0
      else do
        let upperStr = BC.map toUpper str
        keynames <- use $ keyGlobals.kgKeyNames

        case V.findIndex (== Just upperStr) keynames of
          Just i -> return i
          Nothing -> return (-1)

-- Returns a string (either a single ascii char, or a K_* name) for the
-- given keynum.
keynumToString :: Int -> Quake B.ByteString
keynumToString keynum = do
    keynames <- use $ keyGlobals.kgKeyNames

    if | keynum < 0 || keynum > 255 -> return "<KEY NOT FOUND>"
       | keynum > 32 && keynum < 127 -> return $ BC.pack [chr keynum]
       | isJust (keynames V.! keynum) -> return $ fromJust $ keynames V.! keynum
       | otherwise -> return "<UNKNOWN KEYNUM>"

setBinding :: Int -> Maybe B.ByteString -> Quake ()
setBinding keyNum binding =
    unless (keyNum == -1) $ globals.gKeyBindings %= (V.// [(keyNum, binding)])

writeBindings :: Handle -> Quake ()
writeBindings h = do
    kb <- use $ globals.gKeyBindings
    void $ V.sequence $ V.imap (writeKeyBinding h) kb

  where writeKeyBinding :: Handle -> Int -> Maybe B.ByteString -> Quake ()
        writeKeyBinding _ _ Nothing = return ()
        writeKeyBinding handle i (Just b) = do
          keyStr <- keynumToString i
          io $ B.hPut handle $ "bind " `B.append` keyStr `B.append` " \"" `B.append` b `B.append` "\"\n"

-- Called by the system between frames for both key up and key down events.
event :: Int -> Bool -> Int -> Quake ()
event key down time = do
    -- TODO: do we need this?
    -- // hack for modal presses
    -- if (key_waiting == -1) {
    --     if (down)
    --         key_waiting = key;
    --     return;
    -- }

    cls' <- use $ globals.gCls

    -- update auto-repeat status
    done <- if down
              then do
                keyGlobals.kgKeyRepeats.ix key += 1

                keyRepeats <- use $ keyGlobals.kgKeyRepeats
                keyBindings' <- use $ globals.gKeyBindings

                if | keyRepeats UV.! key > 1 && (cls'^.csKeyDest) == Constants.keyGame && not ((cls'^.csState) == Constants.caDisconnected) -> -- ignore most autorepeats
                       return True
                   | key >= 200 && isNothing (keyBindings' V.! key) -> do
                       v <- keynumToString key
                       Com.printf (v `B.append` " is unbound, hit F4 to set.\n")
                       return False
                   | otherwise ->
                       return False

              else do
                keyGlobals.kgKeyRepeats.ix key .= 0
                return False

    unless done $ do
      when (key == kShift) $
        keyGlobals.kgShiftDown .= down

      -- TODO: '~' is not working for console so far? need to set it up?
      -- console key is hardcoded, so the user can never unbind it
      done' <- if key == ord '`' || key == ord '~'
                 then do
                   if not down
                     then return True
                     else do
                       (Console.toggleConsoleF)^.xcCmd
                       return True
                 else
                   return False

      unless done' $ do
        -- any key during the attract mode will bring up the menu
        cl' <- use $ globals.gCl

        let key' = if (cl'^.csAttractLoop) && (cls'^.csKeyDest) /= Constants.keyMenu && not (key >= kF1 && key <= kF12)
                     then kEscape
                     else key

        -- menu key is hardcoded, so the user can never unbind it
        if key' == kEscape
          then do
            when down $ do
              if (cl'^.csFrame.fPlayerState.psStats) UV.! Constants.statLayouts /= 0 && (cls'^.csKeyDest) == Constants.keyGame
                then
                  CBuf.addText "cmd putaway\n"
                else
                  if | (cls'^.csKeyDest) == Constants.keyMessage ->
                         message key'

                     | (cls'^.csKeyDest) == Constants.keyMenu ->
                         Menu.keyDown key'

                     | (cls'^.csKeyDest) == Constants.keyGame || (cls'^.csKeyDest) == Constants.keyConsole ->
                         (Menu.menuMainF)^.xcCmd

                     | otherwise ->
                         Com.comError Constants.errFatal "Bad cls.key_dest"
          else do
            -- track if any key is down for BUTTON_ANY
            globals.gKeyDown.ix key' .= down

            if down
              then do
                keyRepeats <- use $ keyGlobals.kgKeyRepeats
                when (keyRepeats UV.! key' == 1) $
                  keyGlobals.kgAnyKeyDown += 1
              else do
                anyKeyDown <- use $ keyGlobals.kgAnyKeyDown
                when (anyKeyDown > 0) $
                  keyGlobals.kgAnyKeyDown -= 1

            -- key up events only generate commands if the game key binding is
            -- a button command (leading + sign).  These will occur even in console mode,
            -- to keep the character from continuing an action started before a console
            -- switch.  Button commands include the kenum as a parameter, so multiple
            -- downs can be matched with ups
            if not down
              then do
                Just kb <- preuse $ globals.gKeyBindings.ix key'
                case kb of
                  Nothing -> return ()
                  Just binding ->
                    when (B.length binding > 0 && binding `BC.index` 0 == '+') $
                      CBuf.addText ("-" `B.append` (B.drop 1 binding) `B.append` " " `B.append` BC.pack (show key') `B.append` " " `B.append` BC.pack (show time) `B.append` "\n") -- IMPROVE?
              else do
                -- if not a consolekey, send to the interpreter no matter what mode is
                Just menuBound <- preuse $ keyGlobals.kgMenuBound.ix key'
                Just consoleKey <- preuse $ keyGlobals.kgConsoleKeys.ix key'

                if ((cls'^.csKeyDest) == Constants.keyMenu && menuBound) ||
                   ((cls'^.csKeyDest) == Constants.keyConsole && not consoleKey) ||
                   ((cls'^.csKeyDest) == Constants.keyGame && ((cls'^.csState) == Constants.caActive || not consoleKey))
                   then do
                     Just kb <- preuse $ globals.gKeyBindings.ix key'
                     case kb of
                       Nothing -> return ()
                       Just binding ->
                         if B.length binding > 0 && binding `BC.index` 0 == '+'
                           then CBuf.addText (binding `B.append` " " `B.append` BC.pack (show key') `B.append` " " `B.append` BC.pack (show time) `B.append` "\n") -- IMPROVE?
                           else CBuf.addText (binding `B.append` "\n")
                   else
                     -- other systems only care about key down events
                     when down $ do
                       if | (cls'^.csKeyDest) == Constants.keyMessage ->
                              message key'

                          | (cls'^.csKeyDest) == Constants.keyMenu ->
                              Menu.keyDown key'

                          | (cls'^.csKeyDest) == Constants.keyGame || (cls'^.csKeyDest) == Constants.keyConsole ->
                              console key'

                          | otherwise ->
                              Com.comError Constants.errFatal "Bad cls.key_dest"

message :: Int -> Quake ()
message key = do
    if | key `elem` [kEnter, kKpEnter] -> do
           chatTeam' <- use $ globals.gChatTeam
           if chatTeam'
             then CBuf.addText "say_team \""
             else CBuf.addText "say \""

           chatBuffer' <- use $ globals.gChatBuffer

           CBuf.addText chatBuffer'
           CBuf.addText "\"\n"

           zoom globals $ do
             gCls.csKeyDest .= Constants.keyGame
             gChatBuffer .= ""

       | key == kEscape ->
           zoom globals $ do
             gCls.csKeyDest .= Constants.keyGame
             gChatBuffer .= ""

       | key < 32 || key > 127 ->
           return () -- non printable

       | key == kBackspace -> do
           chatBuffer' <- use $ globals.gChatBuffer

           if B.length chatBuffer' > 2
             then
               globals.gChatBuffer .= B.init chatBuffer'
             else
               globals.gChatBuffer .= ""

       | otherwise -> do
           chatBuffer' <- use $ globals.gChatBuffer

           unless (B.length chatBuffer' > Constants.maxCmdLine) $
             globals.gChatBuffer %= (\v -> v `B.append` BC.pack (show key)) -- IMPROVE?

-- Interactive line editing and console scrollback
console :: Int -> Quake ()
console k = do
    let key = if | k == kKpSlash -> '/'
                 | k == kKpMinus -> '-'
                 | k == kKpPlus -> '+'
                 | k == kKpHome -> '7'
                 | k == kKpUpArrow -> '8'
                 | k == kKpPgUp -> '9'
                 | k == kKpLeftArrow -> '4'
                 | k == kKp5 -> '5'
                 | k == kKpRightArrow -> '6'
                 | k == kKpEnd -> '1'
                 | k == kKpDownArrow -> '2'
                 | k == kKpPgDn -> '3'
                 | k == kKpIns -> '0'
                 | k == kKpDel -> '.'

    keyDown' <- use $ globals.gKeyDown

    if | key == 'l' && (keyDown' UV.! kCtrl) ->
           CBuf.addText "clear\n"

       | k `elem` [kEnter, kKpEnter] -> do
           -- backslash text are commands, else chat
           editLine' <- use $ globals.gEditLine
           Just keyLine <- preuse $ globals.gKeyLines.ix editLine'
           io (putStrLn "Key.console # enter") >> undefined -- TODO

       | k == kTab ->
           completeCommand -- command completion

       | k `elem` [kBackspace, kLeftArrow, kKpLeftArrow] || (key == 'h' && (keyDown' UV.! kCtrl)) ->
           globals.gKeyLinePos %= (\v -> if v > 1 then v - 1 else v)

       | k `elem` [kUpArrow, kKpUpArrow] || (key == 'p' && (keyDown' UV.! kCtrl)) -> do
           io (putStrLn "Key.console # up arrow") >> undefined -- TODO

       | k `elem` [kDownArrow, kKpDownArrow] || (key == 'n' && (keyDown' UV.! kCtrl)) -> do
           io (putStrLn "Key.console # down arrow") >> undefined -- TODO

       | k `elem` [kPgUp, kKpPgUp] ->
           globals.gCon.cDisplay -= 2

       | k `elem` [kPgDn, kKpPgDn] -> do
           console <- use $ globals.gCon
           globals.gCon.cDisplay %= (\v -> if (v + 2) > (console^.cCurrent) then console^.cCurrent else v + 2)

       | k `elem` [kHome, kKpHome] -> do
           console <- use $ globals.gCon
           globals.gCon.cDisplay .= (console^.cCurrent) - (console^.cTotalLines) + 10

       | k `elem` [kEnd, kKpEnd] -> do
           console <- use $ globals.gCon
           globals.gCon.cDisplay .= (console^.cCurrent)

       | k < 32 || k > 127 ->
           return () -- non printable

       | otherwise -> do
           keyLinePos' <- use $ globals.gKeyLinePos

           when (keyLinePos' > Constants.maxCmdLine - 1) $ do
             io (putStrLn "Key.console") >> undefined -- TODO

clearStates :: Quake ()
clearStates = do
    keyGlobals.kgAnyKeyDown .= 0
    keyDownEvents 0 256

  where keyDownEvents :: Int -> Int -> Quake ()
        keyDownEvents idx maxIdx
          | idx >= maxIdx = return ()
          | otherwise = do
              keyDown' <- use $ globals.gKeyDown
              keyRepeats <- use $ keyGlobals.kgKeyRepeats

              when ((keyDown' UV.! idx) || (keyRepeats UV.! idx) /= 0) $
                event idx False 0

              globals.gKeyDown.ix idx .= False
              keyGlobals.kgKeyRepeats.ix idx .= 0

              keyDownEvents (idx + 1) maxIdx

clearTyping :: Quake ()
clearTyping = do
    editLine' <- use $ globals.gEditLine
    globals.gKeyLines.ix editLine' .= B.pack [93, 0] -- clear any typing
    globals.gKeyLinePos .= 1

completeCommand :: Quake ()
completeCommand = do
    io (putStrLn "Key.completeCommand") >> undefined -- TODO