text:
"""
Collection of curve tools
"""

from cmivfx import c, xsi

def addCnsCurve(parent, name, centres, closed=False, degree=1):
    """"Draws a curve through centre points. Curve cv's driven by centre points"""
    centres = list(centres)

    # cubic curves need at least 4 points
    if degree == 3:
        if len(centres) == 2:
            centres.insert(0, centres[0])
            centres.append(centres[-1])
        elif len(centres) == 3:
            centres.append(centres[-1])

    points = []
    for centre in centres:
        x = centre.Kinematics.Global.Transform.PosX
        y = centre.Kinematics.Global.Transform.PosY
        z = centre.Kinematics.Global.Transform.PosZ
        points.extend([x, y, z, 1])

    # draws a curve through given points
    curve = parent.AddNurbsCurve(points, None, closed, degree, c.siNonUniformParameterization, c.siSINurbs, name)

    # add a cluster to given cv [i] on the curve driven by the centre
    for i, centre in enumerate(centres):
        cluster = curve.ActivePrimitive.Geometry.AddCluster(c.siVertexCluster, 'centre{:02d}'.format(i), [i])
        xsi.ApplyOp('ClusterCenter', '{};{}'.format(cluster.FullName, centre.FullName))

    return curve

redpajama_set_name: RedPajamaGithub


text:
import unittest
from test import support
from test.support import import_module

# Skip test if _thread or _tkinter wasn't built or idlelib was deleted.
import_module('threading')  # imported by PyShell, imports _thread
tk = import_module('tkinter')  # imports _tkinter
idletest = import_module('idlelib.idle_test')

# Without test_main present, regrtest.runtest_inner (line1219) calls
# unittest.TestLoader().loadTestsFromModule(this_module) which calls
# load_tests() if it finds it. (Unittest.main does the same.)
load_tests = idletest.load_tests

if __name__ == '__main__':
    unittest.main(verbosity=2, exit=False)


text:
package com.github.ricardobaumann.spring_blog_frontend.pageforms;

import lombok.Data;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Created by ricardobaumann on 21/11/16.
 */
@Data
public class PersonForm {

    @NotNull
    @Size(min=2, max=30)
    private String name;

    @NotNull
    @Min(18)
    private Integer age;

}


text:
package org.eclipse.rdf4j.examples.model;

import java.time.LocalDate;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.util.ModelBuilder;

/**
 * RDF Tutorial example 03: Datatyped literals
 *
 * @author Jeen Broekstra
 */
public class Example03LiteralDatatypes {

	public static void main(String[] args) {

		// Create a new RDF model containing information about the painting "The Potato Eaters"
		ModelBuilder builder = new ModelBuilder();
		Model model = builder
				.setNamespace("ex", "http://example.org/")
				.subject("ex:PotatoEaters")
				// this painting was created on April 1, 1885
				.add("ex:creationDate", LocalDate.parse("1885-04-01"))
				// instead of a java.time value, you can directly create a date-typed literal as well
				// .add("ex:creationDate", literal("1885-04-01", XSD.DATE))

				// the painting shows 5 people
				.add("ex:peopleDepicted", 5)
				.build();

		// To see what's in our model, let's just print stuff to the screen
		for (Statement st : model) {
			// we want to see the object values of each property
			IRI property = st.getPredicate();
			Value value = st.getObject();
			if (value instanceof Literal) {
				Literal literal = (Literal) value;
				System.out.println("datatype: " + literal.getDatatype());

				// get the value of the literal directly as a Java primitive.
				if (property.getLocalName().equals("peopleDepicted")) {
					int peopleDepicted = literal.intValue();
					System.out.println(peopleDepicted + " people are depicted in this painting");
				} else if (property.getLocalName().equals("creationDate")) {
					LocalDate date = LocalDate.from(literal.temporalAccessorValue());
					System.out.println("The painting was created on " + date);
				}

				// you can also just get the lexical value (a string) without worrying about the datatype
				System.out.println("Lexical value: '" + literal.getLabel() + "'");
			}
		}
	}
}


text:
package com.google.libwebm.mkvparser;

import com.google.libwebm.Common;

public class ContentEncAesSettings extends Common {

  public ContentEncAesSettings() {
    nativePointer = newContentEncAesSettings();
  }

  public ContentEncoding.CipherMode getCipherMode() {
    int ordinal = (int) getCipherMode(nativePointer);
    return ContentEncoding.CipherMode.values()[ordinal];
  }

  public void setCipherMode(ContentEncoding.CipherMode cipherMode) {
    setCipherMode(nativePointer, cipherMode.ordinal());
  }

  protected ContentEncAesSettings(long nativePointer) {
    super(nativePointer);
  }

  @Override
  protected void deleteObject() {
    deleteContentEncAesSettings(nativePointer);
  }

  private static native void deleteContentEncAesSettings(long jContentEncAesSettings);
  private static native long getCipherMode(long jContentEncAesSettings);
  private static native long newContentEncAesSettings();
  private static native void setCipherMode(long jContentEncAesSettings, long cipherMode);
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

require_once($CFG->dirroot . '/question/type/questionbase.php');
require_once($CFG->dirroot . '/question/type/numerical/question.php');

/**
 * Represents a calculated question.
 *
 * @copyright  2011 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class qtype_calculated_question extends qtype_numerical_question
        implements qtype_calculated_question_with_expressions {

    /** @var qtype_calculated_dataset_loader helper for loading the dataset. */
    public $datasetloader;

    /** @var qtype_calculated_variable_substituter stores the dataset we are using. */
    public $vs;

    /**
     * @var bool wheter the dataset item to use should be chose based on attempt
     * start time, rather than randomly.
     */
    public $synchronised;

    public function start_attempt(question_attempt_step $step, $variant) {
        qtype_calculated_question_helper::start_attempt($this, $step, $variant);
        parent::start_attempt($step, $variant);
    }

    public function apply_attempt_state(question_attempt_step $step) {
        qtype_calculated_question_helper::apply_attempt_state($this, $step);
        parent::apply_attempt_state($step);
    }

    public function calculate_all_expressions() {
        $this->questiontext = $this->vs->replace_expressions_in_text($this->questiontext);
        $this->generalfeedback = $this->vs->replace_expressions_in_text($this->generalfeedback);

        foreach ($this->answers as $ans) {
            if ($ans->answer && $ans->answer !== '*') {
                $ans->answer = $this->vs->calculate($ans->answer,
                        $ans->correctanswerlength, $ans->correctanswerformat);
            }
            $ans->feedback = $this->vs->replace_expressions_in_text($ans->feedback,
                        $ans->correctanswerlength, $ans->correctanswerformat);
        }
    }

    public function get_num_variants() {
        return $this->datasetloader->get_number_of_items();
    }

    public function get_variants_selection_seed() {
        if (!empty($this->synchronised) &&
                $this->datasetloader->datasets_are_synchronised($this->category)) {
            return 'category' . $this->category;
        } else {
            return parent::get_variants_selection_seed();
        }
    }

    public function get_correct_response() {
        $answer = $this->get_correct_answer();
        if (!$answer) {
            return array();
        }

        $response = array('answer' => $this->vs->format_float($answer->answer,
            $answer->correctanswerlength, $answer->correctanswerformat));

        if ($this->has_separate_unit_field()) {
            $response['unit'] = $this->ap->get_default_unit();
        } else if ($this->unitdisplay == qtype_numerical::UNITINPUT) {
            $response['answer'] = $this->ap->add_unit($response['answer']);
        }

        return $response;
    }

}

/**
 * This interface defines the method that a quetsion type must implement if it
 * is to work with {@link qtype_calculated_question_helper}.
 *
 * As well as this method, the class that implements this interface must have
 * fields
 * public $datasetloader; // of type qtype_calculated_dataset_loader
 * public $vs; // of type qtype_calculated_variable_substituter
 *
 * @copyright  2011 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
interface qtype_calculated_question_with_expressions {
    /**
     * Replace all the expression in the question definition with the values
     * computed from the selected dataset by calling $this->vs->calculate() and
     * $this->vs->replace_expressions_in_text() on the parts of the question
     * that require it.
     */
    public function calculate_all_expressions();
}

/**
 * Helper class for questions that use datasets. Works with the interface
 * {@link qtype_calculated_question_with_expressions} and the class
 * {@link qtype_calculated_dataset_loader} to set up the value of each variable
 * in start_attempt, and restore that in apply_attempt_state.
 *
 * @copyright  2011 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
abstract class qtype_calculated_question_helper {
    public static function start_attempt(
            qtype_calculated_question_with_expressions $question,
            question_attempt_step $step, $variant) {

        $question->vs = new qtype_calculated_variable_substituter(
                $question->datasetloader->get_values($variant),
                get_string('decsep', 'langconfig'));
        $question->calculate_all_expressions();

        foreach ($question->vs->get_values() as $name => $value) {
            $step->set_qt_var('_var_' . $name, $value);
        }
    }

    public static function apply_attempt_state(
            qtype_calculated_question_with_expressions $question, question_attempt_step $step) {
        $values = array();
        foreach ($step->get_qt_data() as $name => $value) {
            if (substr($name, 0, 5) === '_var_') {
                $values[substr($name, 5)] = $value;
            }
        }

        $question->vs = new qtype_calculated_variable_substituter(
                $values, get_string('decsep', 'langconfig'));
        $question->calculate_all_expressions();
    }
}

/**
 * This class is responsible for loading the dataset that a question needs from
 * the database.
 *
 * @copyright  2011 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class qtype_calculated_dataset_loader {
    /** @var int the id of the question we are helping. */
    protected $questionid;

    /** @var int the id of the question we are helping. */
    protected $itemsavailable = null;

    /**
     * Constructor
     * @param int $questionid the question to load datasets for.
     */
    public function __construct($questionid) {
        $this->questionid = $questionid;
    }

    /**
     * Get the number of items (different values) in each dataset used by this
     * question. This is the minimum number of items in any dataset used by this
     * question.
     * @return int the number of items available.
     */
    public function get_number_of_items() {
        global $DB;

        if (is_null($this->itemsavailable)) {
            $this->itemsavailable = $DB->get_field_sql('
                    SELECT MIN(qdd.itemcount)
                      FROM {question_dataset_definitions} qdd
                      JOIN {question_datasets} qd ON qdd.id = qd.datasetdefinition
                     WHERE qd.question = ?
                    ', array($this->questionid), MUST_EXIST);
        }

        return $this->itemsavailable;
    }

    /**
     * Actually query the database for the values.
     * @param int $itemnumber which set of values to load.
     * @return array name => value;
     */
    protected function load_values($itemnumber) {
        global $DB;

        return $DB->get_records_sql_menu('
                SELECT qdd.name, qdi.value
                  FROM {question_dataset_items} qdi
                  JOIN {question_dataset_definitions} qdd ON qdd.id = qdi.definition
                  JOIN {question_datasets} qd ON qdd.id = qd.datasetdefinition
                 WHERE qd.question = ?
                   AND qdi.itemnumber = ?
                ', array($this->questionid, $itemnumber));
    }

    /**
     * Load a particular set of values for each dataset used by this question.
     * @param int $itemnumber which set of values to load.
     *      0 < $itemnumber <= {@link get_number_of_items()}.
     * @return array name => value.
     */
    public function get_values($itemnumber) {
        if ($itemnumber <= 0 || $itemnumber > $this->get_number_of_items()) {
            $a = new stdClass();
            $a->id = $this->questionid;
            $a->item = $itemnumber;
            throw new moodle_exception('cannotgetdsfordependent', 'question', '', $a);
        }

        return $this->load_values($itemnumber);
    }

    public function datasets_are_synchronised($category) {
        global $DB;
        // We need to ensure that there are synchronised datasets, and that they
        // all use the right category.
        $categories = $DB->get_record_sql('
                SELECT MAX(qdd.category) AS max,
                       MIN(qdd.category) AS min
                  FROM {question_dataset_definitions} qdd
                  JOIN {question_datasets} qd ON qdd.id = qd.datasetdefinition
                 WHERE qd.question = ?
                   AND qdd.category <> 0
            ', array($this->questionid));

        return $categories && $categories->max == $category && $categories->min == $category;
    }
}

/**
 * This class holds the current values of all the variables used by a calculated
 * question.
 *
 * It can compute formulae using those values, and can substitute equations
 * embedded in text.
 *
 * @copyright  2011 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class qtype_calculated_variable_substituter {

    /** @var array variable name => value */
    protected $values;

    /** @var string character to use for the decimal point in displayed numbers. */
    protected $decimalpoint;

    /** @var array variable names wrapped in {...}. Used by {@link substitute_values()}. */
    protected $search;

    /**
     * @var array variable values, with negative numbers wrapped in (...).
     * Used by {@link substitute_values()}.
     */
    protected $safevalue;

    /**
     * @var array variable values, with negative numbers wrapped in (...).
     * Used by {@link substitute_values()}.
     */
    protected $prettyvalue;

    /**
     * Constructor
     * @param array $values variable name => value.
     */
    public function __construct(array $values, $decimalpoint) {
        $this->values = $values;
        $this->decimalpoint = $decimalpoint;

        // Prepare an array for {@link substitute_values()}.
        $this->search = array();
        $this->replace = array();
        foreach ($values as $name => $value) {
            if (!is_numeric($value)) {
                $a = new stdClass();
                $a->name = '{' . $name . '}';
                $a->value = $value;
                throw new moodle_exception('notvalidnumber', 'qtype_calculated', '', $a);
            }

            $this->search[] = '{' . $name . '}';
            $this->safevalue[] = '(' . $value . ')';
            $this->prettyvalue[] = $this->format_float($value);
        }
    }

    /**
     * Display a float properly formatted with a certain number of decimal places.
     * @param number $x the number to format
     * @param int $length restrict to this many decimal places or significant
     *      figures. If null, the number is not rounded.
     * @param int format 1 => decimalformat, 2 => significantfigures.
     * @return string formtted number.
     */
    public function format_float($x, $length = null, $format = null) {
        if (!is_null($length) && !is_null($format)) {
            if ($format == '1' ) { // Answer is to have $length decimals.
                // Decimal places.
                $x = sprintf('%.' . $length . 'F', $x);

            } else if ($x) { // Significant figures does only apply if the result is non-zero.
                $answer = $x;
                // Convert to positive answer.
                if ($answer < 0) {
                    $answer = -$answer;
                    $sign = '-';
                } else {
                    $sign = '';
                }

                // Determine the format 0.[1-9][0-9]* for the answer...
                $p10 = 0;
                while ($answer < 1) {
                    --$p10;
                    $answer *= 10;
                }
                while ($answer >= 1) {
                    ++$p10;
                    $answer /= 10;
                }
                // ... and have the answer rounded of to the correct length.
                $answer = round($answer, $length);

                // If we rounded up to 1.0, place the answer back into 0.[1-9][0-9]* format.
                if ($answer >= 1) {
                    ++$p10;
                    $answer /= 10;
                }

                // Have the answer written on a suitable format.
                // Either scientific or plain numeric.
                if (-2 > $p10 || 4 < $p10) {
                    // Use scientific format.
                    $exponent = 'e'.--$p10;
                    $answer *= 10;
                    if (1 == $length) {
                        $x = $sign.$answer.$exponent;
                    } else {
                        // Attach additional zeros at the end of $answer.
                        $answer .= (1 == strlen($answer) ? '.' : '')
                            . '00000000000000000000000000000000000000000x';
                        $x = $sign
                            .substr($answer, 0, $length +1).$exponent;
                    }
                } else {
                    // Stick to plain numeric format.
                    $answer *= "1e{$p10}";
                    if (0.1 <= $answer / "1e{$length}") {
                        $x = $sign.$answer;
                    } else {
                        // Could be an idea to add some zeros here.
                        $answer .= (preg_match('~^[0-9]*$~', $answer) ? '.' : '')
                            . '00000000000000000000000000000000000000000x';
                        $oklen = $length + ($p10 < 1 ? 2-$p10 : 1);
                        $x = $sign.substr($answer, 0, $oklen);
                    }
                }

            } else {
                $x = 0.0;
            }
        }
        return str_replace('.', $this->decimalpoint, $x);
    }

    /**
     * Return an array of the variables and their values.
     * @return array name => value.
     */
    public function get_values() {
        return $this->values;
    }

    /**
     * Evaluate an expression using the variable values.
     * @param string $expression the expression. A PHP expression with placeholders
     *      like {a} for where the variables need to go.
     * @return float the computed result.
     */
    public function calculate($expression) {
        // Make sure no malicious code is present in the expression. Refer MDL-46148 for details.
        if ($error = qtype_calculated_find_formula_errors($expression)) {
            throw new moodle_exception('illegalformulasyntax', 'qtype_calculated', '', $error);
        }
        return $this->calculate_raw($this->substitute_values_for_eval($expression));
    }

    /**
     * Evaluate an expression after the variable values have been substituted.
     * @param string $expression the expression. A PHP expression with placeholders
     *      like {a} for where the variables need to go.
     * @return float the computed result.
     */
    protected function calculate_raw($expression) {
        try {
            // In older PHP versions this this is a way to validate code passed to eval.
            // The trick came from http://php.net/manual/en/function.eval.php.
            if (@eval('return true; $result = ' . $expression . ';')) {
                return eval('return ' . $expression . ';');
            }
        } catch (Throwable $e) {
            // PHP7 and later now throws ParseException and friends from eval(),
            // which is much better.
        }
        // In either case of an invalid $expression, we end here.
        throw new moodle_exception('illegalformulasyntax', 'qtype_calculated', '', $expression);
    }

    /**
     * Substitute variable placehodlers like {a} with their value wrapped in ().
     * @param string $expression the expression. A PHP expression with placeholders
     *      like {a} for where the variables need to go.
     * @return string the expression with each placeholder replaced by the
     *      corresponding value.
     */
    protected function substitute_values_for_eval($expression) {
        return str_replace($this->search, $this->safevalue, $expression);
    }

    /**
     * Substitute variable placehodlers like {a} with their value without wrapping
     * the value in anything.
     * @param string $text some content with placeholders
     *      like {a} for where the variables need to go.
     * @return string the expression with each placeholder replaced by the
     *      corresponding value.
     */
    protected function substitute_values_pretty($text) {
        return str_replace($this->search, $this->prettyvalue, $text);
    }

    /**
     * Replace any embedded variables (like {a}) or formulae (like {={a} + {b}})
     * in some text with the corresponding values.
     * @param string $text the text to process.
     * @return string the text with values substituted.
     */
    public function replace_expressions_in_text($text, $length = null, $format = null) {
        $vs = $this; // Can't use $this in a PHP closure.
        $text = preg_replace_callback(qtype_calculated::FORMULAS_IN_TEXT_REGEX,
                function ($matches) use ($vs, $format, $length) {
                    return $vs->format_float($vs->calculate($matches[1]), $length, $format);
                }, $text);
        return $this->substitute_values_pretty($text);
    }
}


text:
package net.crowmagnumb.database;

@FunctionalInterface
public interface PostTransFunc {
    public void perform() throws Exception;
}


text:
import {
  moduleFor,
  test
} from 'ember-qunit';

moduleFor('adapter:application', 'FixtureAdapter', {
  // Specify the other units that are required for this test.
  // needs: ['serializer:foo']
});

// Replace this with your real tests.
test('it exists', function() {
  var adapter = this.subject();
  ok(adapter);
});


text:
//
//  LoginViewModel.h
//  001--RAC映射
//
//  Created by linxiang on 2017/5/10.
//  Copyright © 2017年 TZ. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <ReactiveObjC.h>

@interface LoginViewModel : NSObject

/* 账号 摩玛 */
@property (nonatomic, strong) NSString * account;
@property (nonatomic, strong) NSString * pwd;

/**
 处理登录按钮能否点击的信号
 */
@property (nonatomic, strong) RACSignal * loginEnableSignal;

/**
 处理登录的命令
 */
@property (nonatomic, strong) RACCommand * loginCommand;

-(void)SetUp;

@end


text:
// Make sure the compiler doesn't complain about missing Xml comments and CLS compliance
// 0108: suppress "Foo hides inherited member Foo. Use the new keyword if hiding was intended." when a controller and its abstract parent are both processed
// 0114: suppress "Foo.BarController.Baz()' hides inherited member 'Qux.BarController.Baz()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." when an action (with an argument) overrides an action in a parent controller
#pragma warning disable 1591, 3008, 3009, 0108, 0114
#region T4MVC

using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using T4MVC;
namespace WebExtras.DemoApp.Areas.Bootstrap3.Controllers
{
    public partial class HomeController
    {
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public HomeController() { }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected HomeController(Dummy d) { }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoute(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(Task<ActionResult> taskResult)
        {
            return RedirectToAction(taskResult.Result);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(Task<ActionResult> taskResult)
        {
            return RedirectToActionPermanent(taskResult.Result);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public HomeController Actions { get { return MVC.Bootstrap3.Home; } }
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Area = "Bootstrap3";
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Name = "Home";
        [GeneratedCode("T4MVC", "2.0")]
        public const string NameConst = "Home";
        [GeneratedCode("T4MVC", "2.0")]
        static readonly ActionNamesClass s_actions = new ActionNamesClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionNamesClass ActionNames { get { return s_actions; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNamesClass
        {
            public readonly string Index = "Index";
            public readonly string Download = "Download";
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNameConstants
        {
            public const string Index = "Index";
            public const string Download = "Download";
        }

        static readonly ViewsClass s_views = new ViewsClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ViewsClass Views { get { return s_views; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ViewsClass
        {
            static readonly _ViewNamesClass s_ViewNames = new _ViewNamesClass();
            public _ViewNamesClass ViewNames { get { return s_ViewNames; } }
            public class _ViewNamesClass
            {
                public readonly string Download = "Download";
            }
            public readonly string Download = "~/Areas/Bootstrap3/Views/Home/Download.cshtml";
        }
    }

    [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
    public partial class T4MVC_HomeController : WebExtras.DemoApp.Areas.Bootstrap3.Controllers.HomeController
    {
        public T4MVC_HomeController() : base(Dummy.Instance) { }

        [NonAction]
        partial void IndexOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Index()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Index);
            IndexOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void DownloadOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Download()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Download);
            DownloadOverride(callInfo);
            return callInfo;
        }

    }
}

#endregion T4MVC
#pragma warning restore 1591, 3008, 3009, 0108, 0114


text:
import refect from 'react-refect';

interface Store {
  dispatch: (action: any) => any
  getState: () => any
  subscribe: any
}

export class BaseEffect<Actions> {
  protected getActions?: () => Actions
  protected getStore?: () => Store
  protected namespace?: string
}

interface Get<State> {
  /**
   * 获取整个组件的数据
   */
  (): State

  /**
   * 获取当前组件的数据。
   *
   * @param path 数据路径,支持数组,如:a.b、2.1、a.1
   *
   * @returns 返回对应路径的数据,不存在则返回 undefined
   */
  (path: string | number): any
}

export class BaseTasks<Actions, State, Effects> {
  protected actions: Actions
  protected effects: Effects

  /**
   * 监听一个 action
   *
   * @param pattern 可以是数组、字符串、函数、action、可以引用深层级,如 watch('counter.changeNum')
   *
   * @param callback 监听回调。参数为 rest 加上被监听 action 的参数
   *
   */
  protected watch: (pattern: any, callback: any, ...rest: any[]) => any

  /**
   * 获取当前组件的数据。当没有参数时,获取整个组件的数据。
   *
   * @param path 数据路径,支持数组,如:a.b、2.1、a.1
   *
   * @returns 返回对应路径的数据,不存在则返回 undefined
   */
  protected get: Get<State>

  /**
   * 一般用来 dispatch redux-router action
   */
  protected dispatch: (action: any) => any

  /**
   * 用来 dispatch 自己的 action,如: put('child1.fetchData')
   */
  protected put: (pattern: string, ...rest: any[]) => any

  /**
   * dispatch 一个 task action,并返回 task 执行结果
   */
  protected done: (action: any, ...rest: any[]) => any
}

export class BaseReducer<State> {
  protected state: State
}

interface Options {
  Reducer?: ({ new(): BaseReducer<any> })
  Tasks?: ({ new(): BaseTasks<any, any, any> })
  State?: ({ new(): any })
  mapStateToProps?: (storeState?: any, props?: any, storeAllState?: any) => any;
  Effects?: any[]
  defaultNamespace: string
  defaultProps?: any
  View: any
}

function getActions(inst: any, bindings: any, filters: string[] = [], bindSelf = false) {
  const babelMethods: any = Object.keys(inst).reduce((res, methodName) => {
    return {
      ...res,
      [methodName]: inst[methodName],
    };
  }, {});
  const babelMethodNames = Object.keys(babelMethods);

  const methods: any = Object.getPrototypeOf(inst);
  const methodNames = Object.getOwnPropertyNames(methods).concat(babelMethodNames);
  const finalFilters = [...filters, 'constructor'];

  const actionMap = methodNames
    .filter(str => finalFilters.indexOf(str) < 0)
    .reduce((result: any, methodName) => {
      const method = methods[methodName] || babelMethods[methodName];

      return {
        ...result,
        [methodName]: method.bind(bindings),
      };
    }, {});

  if (bindSelf) {
    Object.keys(actionMap).forEach((methodName) => {
      bindings[methodName] = actionMap[methodName];
    });
  }

  return actionMap;
}

function parseReducer(Reducer: any) {
  return Reducer ? (state: any, manager: any) => {
    return getActions(new Reducer(), { state }, ['state']);
  } : undefined;
}

function parseEffect(Effect: any) {
  return (ctx: any) => {
    return getActions(new Effect(), ctx, ['putinReducer']);
  }
}

function parseOptions(options: Options) {
  const { Reducer, Tasks, State, Effects = [], View } = options;

  const reducer = parseReducer(Reducer);

  const tasks = Tasks ? (actions: any, effects: any, coreEffects: any = {}, plugins: any = {}) => {
    const filters = Object.keys(coreEffects).concat(['plugins', 'actions']);

    return getActions(new Tasks(), { ...coreEffects, actions, effects: plugins }, filters, true);
  } : undefined;

  const effects = Effects.map((Effect: { new(): any }) => {
    const effector = new Effect();
    const PutinReducer = effector.putinReducer;

    return {
      putinReducer: parseReducer(PutinReducer),
      effector: parseEffect(Effect),
    };
  }, {});

  return {
    ...options,
    reducer,
    tasks,
    initialState: new State(),
    effects,
    view: View,
  };
}

export default function refectNext<T = {}>(options: Options) {
  const parsedOptions = parseOptions(options);

  return refect<T>(parsedOptions);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SixFourThree.BoxPacker.Helpers;

namespace SixFourThree.BoxPacker.Model
{
    public class Item : IComparable<Item>
    {
        /// <summary>
        /// Identifier for the item
        /// </summary>
        public String Id { get; set; }

        /// <summary>
        /// Reference number (i.e. SKU, description, etc.)
        /// </summary>
        public String Description { get; set; }

        /// <summary>
        /// Extra information
        /// </summary>
        public String ExtraInfo { get; set; }

        /// <summary>
        /// Total financial value of item.
        /// </summary>
        public Decimal? FinancialValue { get; set; }

        /// <summary>
        /// Width in mm
        /// </summary>
        public Int32 Width { get; set; }

        public Double WidthInInches => ConversionHelper.ConvertMillimetersToInches(Width);

        /// <summary>
        /// Length in mm
        /// </summary>
        public Int32 Length { get; set; }

        public Double LengthInInches => ConversionHelper.ConvertMillimetersToInches(Length);

        /// <summary>
        /// Depth in mm
        /// </summary>
        public Int32 Depth { get; set; }

        public Double DepthInInches => ConversionHelper.ConvertMillimetersToInches(Depth);

        /// <summary>
        /// Weight in g
        /// </summary>
        public Int32 Weight { get; set; }

        public Double WeightInPounds => ConversionHelper.ConvertGramsToPounds(Weight);

        /// <summary>
        /// Volume in mm^3
        /// </summary>
        public Int32 Volume { get { return Length * Depth * Width; } }

        public Double VolumeInInches => LengthInInches * DepthInInches * WidthInInches;

        public int CompareTo(Item other)
        {
            if (Volume > other.Volume)
                return 1;

            if (Volume < other.Volume)
                return -1;

            return 0;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text.RegularExpressions;

namespace Slavin.BLL {
	public class TranslateContext : FilterAttribute, IResultFilter {

		public virtual void OnResultExecuting(ResultExecutingContext context) {
			//base.on
			//if (context.HttpContext.Response.Filter != null)
			//   context.HttpContext.Response.Filter =
			//	new LanguageFilter(context.HttpContext.Response.Filter);
		}
		public virtual void OnResultExecuted(ResultExecutedContext context) {
			if (context.HttpContext.Response.Filter != null)
				context.HttpContext.Response.Filter =
					new LanguageFilter(context.HttpContext.Response.Filter);
		}
	}
	public class LanguageFilter : MemoryStream {

		StreamWriter sw = null;
		public LanguageFilter(Stream s) {
			sw = new StreamWriter(s);
		}

		public override void Close() {

			string s = System.Text.Encoding.UTF8.GetString(this.ToArray());
			s = Regex.Replace(
				s,
				"(<|<)trn[^(<|>)]*(>|>)(?<text>.*?)(<|<)/trn(>|>)",
				m => { return m.Groups["text"].Value; },
			 //m => { return Cache.Translations.Word(m.Groups["text"].Value); },
 RegexOptions.Singleline
			);

			sw.Write(s);
			sw.Flush();
			sw.Close();
			base.Close();
		}
	}

}


text:
package com.intellij.ui;

import com.intellij.ui.components.panels.OpaquePanel;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.accessibility.AccessibleContextUtil;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.TreeCellRenderer;
import java.awt.*;

public abstract class GroupedElementsRenderer {
  public static final Color POPUP_SEPARATOR_FOREGROUND = new JBColor(Color.gray.brighter(), Gray.x51);
  public static final Color POPUP_SEPARATOR_TEXT_FOREGROUND = Color.gray;
  public static final Color SELECTED_FRAME_FOREGROUND = Color.black;

  protected SeparatorWithText mySeparatorComponent = createSeparator();

  protected abstract JComponent createItemComponent();

  protected JComponent myComponent;
  protected MyComponent myRendererComponent;

  protected ErrorLabel myTextLabel;

  public GroupedElementsRenderer() {
    myRendererComponent = new MyComponent();

    myComponent = createItemComponent();

    layout();
  }

  protected abstract void layout();

  protected SeparatorWithText createSeparator() {
    return new SeparatorWithText();
  }

  protected final JComponent configureComponent(String text, String tooltip, Icon icon, Icon disabledIcon, boolean isSelected, boolean hasSeparatorAbove, String separatorTextAbove, int preferredForcedWidth) {
    mySeparatorComponent.setVisible(hasSeparatorAbove);
    mySeparatorComponent.setCaption(separatorTextAbove);
    mySeparatorComponent.setMinimumWidth(preferredForcedWidth);

    myTextLabel.setText(text);
    myRendererComponent.setToolTipText(tooltip);
    AccessibleContextUtil.setName(myRendererComponent, myTextLabel);
    AccessibleContextUtil.setDescription(myRendererComponent, myTextLabel);

    myTextLabel.setIcon(icon);
    myTextLabel.setDisabledIcon(disabledIcon);

    setSelected(myComponent, isSelected);
    setSelected(myTextLabel, isSelected);

    myRendererComponent.setPrefereedWidth(preferredForcedWidth);

    return myRendererComponent;
  }

  /** @deprecated backgrounds are set uniformly via setSelected() / setDeselected() (to be removed in IDEA 16) */
  @SuppressWarnings("UnusedDeclaration")
  protected static void adjustOpacity(JComponent component, boolean selected) {
    if (selected) {
      if (UIUtil.isUnderNimbusLookAndFeel()) {
        component.setOpaque(true);
      }
    }
    else {
      if (UIUtil.isUnderGTKLookAndFeel() || UIUtil.isUnderNimbusLookAndFeel()) {
        component.setOpaque(false);
      }
    }
  }

  protected final void setSelected(JComponent aComponent) {
    setSelected(aComponent, true);
  }

  protected final void setDeselected(JComponent aComponent) {
    setSelected(aComponent, false);
  }

  protected final void setSelected(JComponent aComponent, boolean selected) {
    UIUtil.setBackgroundRecursively(aComponent, selected ? getSelectionBackground() : getBackground());
    aComponent.setForeground(selected ? getSelectionForeground() : getForeground());
  }

  protected abstract Color getSelectionBackground();

  protected abstract Color getSelectionForeground();

  protected abstract Color getBackground();

  protected abstract Color getForeground();

  protected Border getDefaultItemComponentBorder() {
    return getBorder();
  }

  private static Border getSelectedBorder() {
    return UIUtil.isToUseDottedCellBorder() ? new DottedBorder(UIUtil.getListCellPadding(), SELECTED_FRAME_FOREGROUND) : new EmptyBorder(UIUtil.getListCellPadding());
  }

  private static Border getBorder() {
    return new EmptyBorder(UIUtil.getListCellPadding());
  }

  public abstract static class List extends GroupedElementsRenderer {
    @Override
    protected void layout() {
      myRendererComponent.add(mySeparatorComponent, BorderLayout.NORTH);
      myRendererComponent.add(myComponent, BorderLayout.CENTER);
    }

    @Override
    protected final Color getSelectionBackground() {
      return UIUtil.getListSelectionBackground();
    }

    @Override
    protected final Color getSelectionForeground() {
      return UIUtil.getListSelectionForeground();
    }

    @Override
    protected Color getBackground() {
      return UIUtil.getListBackground();
    }

    @Override
    protected Color getForeground() {
      return UIUtil.getListForeground();
    }
  }

  public abstract static class Tree extends GroupedElementsRenderer implements TreeCellRenderer {

    @Override
    protected void layout() {
      myRendererComponent.add(mySeparatorComponent, BorderLayout.NORTH);
      myRendererComponent.add(myComponent, BorderLayout.WEST);
    }

    @Override
    protected Color getSelectionBackground() {
      return UIUtil.getTreeSelectionBackground();
    }

    @Override
    protected Color getSelectionForeground() {
      return UIUtil.getTreeSelectionForeground();
    }

    @Override
    protected Color getBackground() {
      return UIUtil.getTreeTextBackground();
    }

    @Override
    protected Color getForeground() {
      return UIUtil.getTreeTextForeground();
    }
  }

  protected class MyComponent extends OpaquePanel {

    private int myPrefWidth = -1;

    public MyComponent() {
      super(new BorderLayout(), GroupedElementsRenderer.this.getBackground());
    }

    public void setPrefereedWidth(final int minWidth) {
      myPrefWidth = minWidth;
    }

    @Override
    public Dimension getPreferredSize() {
      final Dimension size = super.getPreferredSize();
      size.width = myPrefWidth == -1 ? size.width : myPrefWidth;
      return size;
    }
  }

}


text:
<?php

namespace Proxies\__CG__\sosFSO\GRHBundle\Entity;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class Service extends \sosFSO\GRHBundle\Entity\Service implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function setIntitule($intitule)
    {
        $this->__load();
        return parent::setIntitule($intitule);
    }

    public function getIntitule()
    {
        $this->__load();
        return parent::getIntitule();
    }

    public function setDescription($description)
    {
        $this->__load();
        return parent::setDescription($description);
    }

    public function getDescription()
    {
        $this->__load();
        return parent::getDescription();
    }

    public function setMembre(\sosFSO\GRHBundle\Entity\Affectation $membre = NULL)
    {
        $this->__load();
        return parent::setMembre($membre);
    }

    public function getMembre()
    {
        $this->__load();
        return parent::getMembre();
    }

    public function addMembre(\sosFSO\GRHBundle\Entity\Affectation $membres)
    {
        $this->__load();
        return parent::addMembre($membres);
    }

    public function removeMembre(\sosFSO\GRHBundle\Entity\Affectation $membres)
    {
        $this->__load();
        return parent::removeMembre($membres);
    }

    public function getMembres()
    {
        $this->__load();
        return parent::getMembres();
    }

    public function __sleep()
    {
        return array('__isInitialized__', 'id', 'intitule', 'description', 'membres');
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}


text:
package com.example;

public class Shared {
    @Override
    public String toString() {
        return "'Shared' Java Class OK";
    }
}


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">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="http://localhost:5500/select2/dist/css/select2-poncho.css">
  <link rel="stylesheet" href="../../../dist/css/poncho.min.css" />
  <title>Demo Poncho Ubicación</title>

<form method="post">

Form

            Provincia

          <input
              required="required"
              class="form-control form-text required"
              type="text"
              id="edit-submitted-provincia-entidad"
              name="submitted[provincia_entidad]"
              value=""
              size="60"
              maxlength="128">

            Localidad

          <input
              required="required"
              class="form-control form-text required"
              type="text"
              id="edit-submitted-localidad-entidad"
              name="submitted[localidad_entidad]"
              value=""
              size="60"
              maxlength="128">

            <input type="submit" class="btn bt-primary" value="Enviar">

</form>


text:
Site map

<?php
	$max_columns = 4; // change to number of columns you want to add to your footer
	$text_domain = 'lobbybytes'; // the text domain to use for translating the strings
?>

<?php foreach ( range(1, $max_columns, 1) as $number ) { ?>

     <?php $sidebar_name = sprintf(__('Footer Column %d', $text_domain), $number ); ?>

             <?php dynamic_sidebar( $sidebar_name ); ?>

<?php } ?>

Contact Us

								<address>355 W 16th Street
 NY, New York 10011</address>
								(212) 229-2559

<a href="<?php the_field('facebook','option');?>">Facebook

<a href="<?php the_field('twitter','option'); ?>">Twitter

<a href="<?php the_field('instagram','option'); ?>">Instagram

<a href="<?php the_field('vimeo','option'); ?>">vimeo

<a href="<?php the_field('mixcloud','option'); ?>">mixcloud

							<a class="homebtn" href="<?php echo site_url(); ?>">Dream Downtown

<?php _e('Content © Copyright', $text_domain); ?> <?php echo date_i18n('Y'); ?> <?php bloginfo('name'); ?> <?php _e('Dream Downtown  All rights reserved.', $text_domain); ?>Site Design by TVI

    <?php wp_footer(); ?>


text:
// Mesh file I/O

#include <geode/mesh/io.h>
#include <geode/mesh/PolygonSoup.h>
#include <geode/array/view.h>
#include <geode/geometry/Triangle3d.h>
#include <geode/python/cast.h>
#include <geode/python/wrap.h>
#include <geode/utility/endian.h>
#include <geode/utility/function.h>
#include <geode/utility/path.h>
#include <errno.h>
namespace geode {

typedef real T;
typedef Vector<T,3> TV;
typedef Vector<T,2> TV2;
using std::cout;
using std::endl;

namespace {
struct File {
  FILE* const f;

  File(const string& filename, const char* mode)
    : f(fopen(filename.c_str(),mode)) {
    if (!f)
      throw IOError(format("can't open '%s' for %s: %s",filename,
        mode[0]=='r' ? "reading" : mode[0]=='w' ? "writing" : mode[0]=='a' ? "append" : format("mode %s",mode),
        strerror(errno)));
  }

  File(const File&) = delete;
  void operator=(const File&) = delete;

  ~File() {
    fclose(f);
  }

  operator FILE*() const {
    return f;
  }
};
}

// Determine whether a file is probably binary or ascii
static bool is_binary(const string& filename) {
  File f(filename,"rb");
  char data[512];
  const int n = int(fread(data,1,sizeof(data),f));
  for (int i=0;i<n;i++)
    if (!isascii(data[i]))
      return true;
  return false;
}

static const char* skip_white(const char* p) {
  while (isspace(*p))
    p++;
  return p;
}

// Can't use a simple struct since StlTri has bad alignment
struct StlTriData {
  Vector<float,3> n;
  Vector<float,3> x[3];
};
struct StlTri {
  char d[sizeof(StlTriData)];
  uint16_t c;
};
static_assert(sizeof(StlTri)==12*4+2,"");

// See http://en.wikipedia.org/wiki/STL_file for details
static Tuple<Ref<TriangleSoup>,Array<TV>> read_stl(const string& filename) {
  if (is_binary(filename)) {
    File f(filename,"rb");

    // Skip header
    char header[80];
    const auto nh = fread(header,1,sizeof(header),f);
    if (nh < sizeof(header))
      throw IOError(format("invalid binary stl '%s': %s",filename,
        ferror(f) ? format("read failed: %s",strerror(errno)) : "incomplete header"));

    // Read count
    uint32_t count;
    const auto nc = fread(&count,sizeof(count),1,f);
    if (nc < 1)
      throw IOError(format("invalid binary stl '%s': failed to read count",filename));
    if (count > (1u<<31)/3-1)
      throw IOError(format("binary stl has too many triangles: %u > 2^31/3-1",count));

    // Read triangles
    Array<StlTri> data(count,uninit);
    const auto nt = fread(data.data(),sizeof(StlTri),count,f);
    if (nt < count)
      throw IOError(format("invalid binary stl '%s': failed to read triangles",filename));

    // Deduplicate
    Hashtable<Vector<float,3>,int> id;
    Array<Vector<int,3>> tris;
    Array<TV> X;
    for (auto& t : data) {
      StlTriData d;
      memcpy(&d,t.d,sizeof(d));
      Vector<int,3> tri;
      for (int a=0;a<3;a++) {
        const int i = id.get_or_insert(d.x[a],X.size());
        if (i == X.size())
          X.append(TV(d.x[a]));
        tri[a] = i;
      }
      tris.append(tri);
    }
    return tuple(new_<TriangleSoup>(tris),X);
  } else { // ASCII
    File f(filename,"r");

    // Prepare for deduplication
    Hashtable<Vector<double,3>,int> id;
    Array<Vector<int,3>> tris;
    Array<TV> X;

    // Read
    int ns = 0, nl = 0;
    char line[1024];
    for (;;) {
      nl++;
      if (!fgets(line,sizeof(line),f)) {
        if (!ns)
          throw IOError(format("invalid ascii stl %s: no solids found",filename));
        break;
      }
      {
        const char* p = skip_white(line);
        if (!*p) continue;
        if (strncmp(p,"solid ",6))
          throw IOError(format("invalid ascii stl %s:%d: expected 'solid ', got: %s",filename,nl,repr(p)));
      }
      for (;;) {
        nl++;
        if (!fgets(line,sizeof(line),f))
          throw IOError(format("invalid ascii stl %s:%d: file ended inside solid",filename,nl));
        {
          const char* p = skip_white(line);
          if (!*p) continue;
          if (!strncmp(p,"endsolid",8))
            break;
          if (strncmp(p,"facet normal ",13))
            throw IOError(format("invalid ascii stl %s:%d: expected 'endsolid' or 'facet normal ', got: %s",
              filename,nl,repr(p)));
        }
        static const int len[6] = {10,7,7,7,7,8};
        static const char* expect[6] = {"outer loop","vertex ","vertex ","vertex ","endloop","endfacet"};
        Vector<int,3> tri;
        for (int a=0;a<6;a++) {
          nl++;
          if (!fgets(line,sizeof(line),f))
            throw IOError(format("invalid ascii stl %s:%d: file ended inside facet",filename,nl));
          const char* p = skip_white(line);
          if (!*p) { a--; continue; }
          if (strncmp(p,expect[a],len[a]))
            throw IOError(format("invalid ascii stl %s:%d: expected '%s', got: %s",filename,nl,expect[a],repr(p)));
          if (1<=a && a<4) {
            Vector<double,3> x;
            if (sscanf(p+7,"%lg %lg %lg",&x.x,&x.y,&x.z) != 3)
              throw IOError(format("invalid ascii stl %s:%d: invalid vertex line: %s",filename,nl,repr(p)));
            const int i = id.get_or_insert(x,X.size());
            if (i == X.size()) {
              if (X.size()==numeric_limits<int>::max())
                throw IOError(format("ascii stl %s has too many vertices, our limit is 2^31-1",filename));
              X.append(x);
            }
            tri[a-1] = i;
          }
        }
        if (tris.size()==numeric_limits<int>::max())
          throw IOError(format("ascii stl %s has too many vertices, our limit is 2^31-1",filename));
        tris.append(tri);
      }
      ns++;
    }
    return tuple(new_<TriangleSoup>(tris),X);
  }
}

static void write_stl(const string& filename, RawArray<const Vector<int,3>> tris, RawArray<const TV> X) {
  // We unconditionally write .stl files in binary.  Text formats for large data are silly.
  File f(filename,"wb");
  fprintf(f,"%-79s\n","Binary STL triangle mesh: http://en.wikipedia.org/wiki/STL_file");
  const uint32_t count = tris.size();
  fwrite(&count,sizeof(count),1,f);
  for (const auto nodes : tris) {
    StlTriData d;
    d.n = to_little_endian(Vector<float,3>(normal(X[nodes[0]],X[nodes[1]],X[nodes[2]])));
    for (int i=0;i<3;i++)
      d.x[i] = to_little_endian(Vector<float,3>(X[nodes[i]]));
    StlTri t;
    memcpy(t.d,&d,sizeof(d));
    t.c = 0;
    fwrite(&t,sizeof(t),1,f);
  }
}

static const char* white = " \t\v\f\r\n";

static Tuple<Ref<PolygonSoup>,Array<TV>> read_obj(const string& filename) {
  File f(filename,"r");

  // Parse file
  Array<TV> X, normals;
  Array<TV2> texcoords;
  Array<int> counts, vertices;
  char orig[1024], line[1024];
  int nl = 0;
  while (fgets(orig,sizeof(orig),f)) {
    nl++;
    strcpy(line,orig);
    char* save;
    const char* cmd = strtok_r(line,white,&save);
    if (!cmd || cmd[0] == '#')
      continue;
    else if (cmd[0]=='v' && (!cmd[1] || ((cmd[1]=='n' || cmd[1]=='t') && !cmd[2]))) { // cmd = v, vn, or vt
      int n = 0;
      double x[4];
      for (int i=0;i<4;i++)
        if (const char* q = strtok_r(0,white,&save)) {
          char* end;
          x[n++] = strtod(q,&end);
          if (*end)
            throw IOError(format("invalid obj file %s:%d: bad %s line: %s",filename,nl,cmd,repr(orig)));
        }
      const int ne = !cmd[1] ? 3 : cmd[1]=='n' ? 3 : /*cmd[1]=='t'*/ 2;
      if (n != ne)
        throw IOError(format("invalid obj file %s:%d: %s expected 3 floats, got %s",filename,nl,cmd,ne,repr(orig)));
      if (!cmd[1]) { // v
        if (X.size()==numeric_limits<int>::max())
          throw IOError(format("unsupported obj file %s: too many vertices (our limit is 2^31-1)",filename));
        X.append(TV(x[0],x[1],x[2]));
      } else if (cmd[1]=='n') { // vn
        if (normals.size()==numeric_limits<int>::max())
          throw IOError(format("unsupported obj file %s: too many normals (our limit is 2^31-1)",filename));
        normals.append(TV(x[0],x[1],x[2]));
      } else { // vt
        if (texcoords.size()==numeric_limits<int>::max())
          throw IOError(format("unsupported obj file %s: too many texcoords (our limit is 2^31-1)",filename));
        texcoords.append(TV2(x[0],x[1]));
      }
    } else if (cmd[0]=='f' && !cmd[1]) { // cmd = f
      int n = 0;
      while (const char* q = strtok_r(0,white,&save)) {
        n++;
        char* end;
        const long v = strtol(q,&end,0);
        if (*end && *end != '/')
          throw IOError(format("invalid obj file %s:%d: f expected ints, got %s",filename,nl,repr(orig)));
        // TODO: Don't skip face normal or face texcoord information
        if (long(unsigned(int(v))) != v)
          throw IOError(format("unsupported obj file %s:%d: f got invalid vertex id %ld",filename,nl,v));
        vertices.append(int(v));
      }
      if (n < 3)
        throw IOError(format("invalid obj file %s:%d: f got fewer than 3 vertices",filename,nl));
      counts.append(n);
    } else if (strcmp(cmd,"usemtl") || strcmp(cmd,"usemat") || strcmp(cmd,"mtllib")) {
      // TODO: Don't skip these fields?
    } else
      throw IOError(format("invalid obj file %s:%d: invalid command %s",filename,nl,repr(cmd)));
  }

  // Adjust vertices and check consistency
  vertices -= 1;
  for (const int v : vertices)
    if (!X.valid(v))
      throw IOError(format("invalid obj file %s: face vertex %d out of valid range [1,%d]",filename,v+1,X.size()));
  if (normals.size() && normals.size() != X.size())
    throw IOError(format("invalid obj file %s: %d vertices != %d normals",filename,X.size(),normals.size()));
  if (texcoords.size() && texcoords.size() != X.size())
    throw IOError(format("invalid obj file %s: %d vertices != %d texcoords",filename,X.size(),texcoords.size()));

  // TODO: Don't discard normal and texcoord information
  return tuple(new_<PolygonSoup>(counts,vertices),X);
}

static void write_obj_helper(File& f, RawArray<const TV> X) {
  // Write format
  fputs("# Simple obj file format: http://en.wikipedia.org/wiki/Wavefront_.obj_file\n"
        "#   # Vertex at coordinates (x,y,z):\n"
        "#   v x y z\n"
        "#   # Triangle [quad] with vertices a,b,c[,d]:\n"
        "#   f a b c [d]\n"
        "#   # Vertices are indexed starting from 1\n",f);

  // Write vertices
  for (const auto x : X)
    fprintf(f,"v %g %g %g\n",x.x,x.y,x.z);
}
static void write_obj(const string& filename, RawArray<const Vector<int,3>> tris, RawArray<const TV> X) {
  File f(filename,"wb");
  write_obj_helper(f,X);
  for (const auto t : tris)
    fprintf(f,"f %d %d %d\n",t.x+1,t.y+1,t.z+1);
}
static void write_obj(const string& filename, const PolygonSoup& soup, RawArray<const TV> X) {
  File f(filename,"wb");
  write_obj_helper(f,X);
  int offset = 0;
  for (const auto n : soup.counts) {
    fputc('f',f);
    for (int i=0;i<n;i++)
      fprintf(f," %d",soup.vertices[offset++]+1);
  }
}

namespace {
struct Line {
  int lineno;
  Array<char> line, split;
  Array<const char*> words;

  // TODO: Allow for longer lines
  Line()
    : lineno(0), line(1024), split(1024) {}

  bool read(File& f) {
    lineno++;
    if (!fgets(line.data(),line.size(),f))
      return false;
    strcpy(split.data(),line.data());
    char* p = split.data();
    char* save;
    words.clear();
    while (const char* w = strtok_r(p,white,&save)) {
      words.append(w);
      p = 0;
    }
    return true;
  }

  string repr() const {
    return geode::repr(line.data());
  }
};

struct PlyProp : public Object {
  GEODE_NEW_FRIEND
  const string name;
protected:
  PlyProp(const string& name)
    : name(name) {}
public:
  virtual void read_ascii(RawArray<const char*> words, int& i) = 0;
  virtual void read_binary_same_endian(FILE* f) = 0;
  virtual void read_binary_flip_endian(FILE* f) = 0;
  virtual string type() const = 0;
};

template<class T> static const char* ply_type_name();
#define PLY_TYPE_NAME(name,T) \
  template<> const char* ply_type_name<T>() { return #name; }
#define PLY_SIMPLE_TYPE(name) PLY_TYPE_NAME(name,name##_t)
PLY_SIMPLE_TYPE(int8)
PLY_SIMPLE_TYPE(uint8)
PLY_SIMPLE_TYPE(int16)
PLY_SIMPLE_TYPE(uint16)
PLY_SIMPLE_TYPE(int32)
PLY_SIMPLE_TYPE(uint32)
PLY_TYPE_NAME(float,float)
PLY_TYPE_NAME(double,double)

#define PLY_TYPE_NAMES(f) \
  f(char,int8_t) \
  f(uchar,uint8_t) \
  f(short,int16_t) \
  f(ushort,uint16_t) \
  f(int,int32_t) \
  f(uint,uint32_t) \
  f(float,float) \
  f(double,double) \
  f(int8,int8_t) \
  f(uint8,uint8_t) \
  f(int16,int16_t) \
  f(uint16,uint16_t) \
  f(int32,int32_t) \
  f(uint32,uint32_t) \
  f(float32,float) \
  f(float64,double)

template<class T> static inline typename enable_if<is_integral<T>,T>::type parse(const char* s) {
  char* end;
  const long long n = strtoll(s,&end,0);
  if (end[0])
    throw IOError(format("invalid %s value %s",ply_type_name<T>(),repr(s)));
  if ((long long)(T)n != n)
    throw IOError(format("out of range %s value %s",ply_type_name<T>(),repr(s)));
  return T(n);
}

template<class T> static inline typename enable_if<is_floating_point<T>,T>::type parse(const char* s) {
  char* end;
  const double x = strtod(s,&end);
  if (end[0])
    throw IOError(format("invalid %s value %s",ply_type_name<T>(),repr(s)));
  return x;
}

template<class T> struct PlyPropSingle : public PlyProp {
  GEODE_NEW_FRIEND
  Array<T> a;
protected:
  PlyPropSingle(const string& name, const int count)
    : PlyProp(name) {
    a.preallocate(count);
  }

  void read_ascii(RawArray<const char*> words, int& i) {
    if (i==words.size())
      throw IOError(format("incomplete element (no %s)",name));
    a.append_assuming_enough_space(parse<T>(words[i++]));
  }

  void read_binary_same_endian(FILE* f) {
    T x;
    if (fread(&x,sizeof(T),1,f) < 1)
      throw IOError(format("incomplete element (no %s)",name));
    a.append(x);
  }

  void read_binary_flip_endian(FILE* f) {
    T x;
    if (fread(&x,sizeof(T),1,f) < 1)
      throw IOError(format("incomplete element (no %s)",name));
    a.append(flip_endian(x));
  }

  string type() const {
    return ply_type_name<T>();
  }
};

template<class L,class T> struct PlyPropList : public PlyProp {
  GEODE_NEW_FRIEND
  static_assert(is_same<L,uint8_t>::value,"L must be uint8_t for now");
  Array<int> counts;
  Array<T> flat;
protected:
  PlyPropList(const string& name, const int n)
    : PlyProp(name) {
    counts.preallocate(n);
  }

  void read_ascii(RawArray<const char*> words, int& i) {
    if (i==words.size())
      throw IOError(format("incomplete element: no %s size",name));
    const auto n = parse<L>(words[i++]);
    counts.append_assuming_enough_space(n);
    flat.preallocate(flat.size()+n);
    for (int j=0;j<n;j++) {
      if (i==words.size())
        throw IOError(format("incomplete element: %s expected %d entries, got %d",name,n,j));
      flat.append_assuming_enough_space(parse<T>(words[i++]));
    }
  }

  void read_binary_same_endian(FILE* f) {
    L n;
    if (fread(&n,sizeof(L),1,f) < 1)
      throw IOError(format("incomplete element (no %s size)",name));
    counts.append_assuming_enough_space(n);
    const int offset = flat.size();
    flat.resize(flat.size()+n);
    if (fread(flat.data()+offset,sizeof(T),n,f) < n)
      throw IOError(format("incomplete element (incomplete %s list)",name));
  }

  void read_binary_flip_endian(FILE* f) {
    L n;
    if (fread(&n,sizeof(L),1,f) < 1)
      throw IOError(format("incomplete element (no %s size)",name));
    n = flip_endian(n);
    counts.append_assuming_enough_space(n);
    const int offset = flat.size();
    flat.resize(flat.size()+n);
    if (fread(flat.data()+offset,sizeof(T),n,f) < n)
      throw IOError(format("incomplete element (incomplete %s list)",name));
    for (int i=0;i<n;i++)
      flat[offset+i] = flip_endian(flat[offset+i]);
  }

  string type() const {
    return ply_type_name<T>();
  }
};

struct PlyElement : public Object {
  GEODE_NEW_FRIEND
  const string name;
  const int count;
  vector<Ref<PlyProp>> props;
  Hashtable<string,Ref<PlyProp>> prop_names;
protected:
  PlyElement(const string& name, const int count)
    : name(name)
    , count(count) {}
};
}

static Tuple<Ref<PolygonSoup>,Array<TV>> read_ply(const string& filename) {
  File f(filename,"rb");
  Line line;
  try {
    // Read magic string
    if (!line.read(f) || line.words.size()!=1 || strcmp(line.words[0],"ply")) {
      cout << "words = "<<line.words<<endl;
      throw IOError(format("expected magic string 'ply', got %s",repr(line)));
    }

    // Read rest of header
    int fmt = 0; // 1 for ascii, 2 for binary little endian, 3 for binary big endian
    vector<Ref<PlyElement>> elements;
    Hashtable<string,Ref<PlyElement>> element_names;
    for (;;) {
      if (!line.read(f))
        throw IOError("eof before end of header");
      const auto words = line.words.raw();
      if (!words.size() || !strcmp(words[0],"comment"))
        continue;
      else if (!strcmp(words[0],"format")) {
        if (fmt)
          throw IOError("duplicate format line");
        if (words.size() != 3)
          throw IOError(format("invalid format line %s",repr(line)));
        try {
          const double version = parse<double>(words[2]);
          if (version != 1)
            throw IOError("");
        } catch (const IOError&) {
          throw IOError(format("unsupported version %s",repr(words[2])));
        }
        if      (!strcmp(words[1],"ascii"))                fmt = 1;
        else if (!strcmp(words[1],"binary_little_endian")) fmt = 2;
        else if (!strcmp(words[1],"binary_big_endian"))    fmt = 3;
      } else if (!strcmp(words[0],"element")) {
        try {
          if (words.size() != 3)
            throw IOError("expected 'element <name> <count>'");
          const auto E = new_<PlyElement>(words[1],parse<int>(words[2]));
          if (!element_names.set(E->name,E))
            throw IOError(format("duplicate element name %s",repr(E->name)));
          elements.push_back(E);
        } catch (const IOError& e) {
          throw IOError(format("invalid element declaration %s: %s",repr(line),e.what()));
        }
      } else if (!strcmp(words[0],"property")) {
        if (!elements.size())
          throw IOError("property before element");
        PlyElement& E = elements.back();
        if (words.size() < 3)
          throw IOError("incomplete property declaration, expected 'property [list uchar] type name'");
        Ptr<PlyProp> prop;
        #define SINGLE_CASE(name,T) \
          else if (!strcmp(words[1],#name)) \
            prop = new_<PlyPropSingle<T>>(words[2],E.count);
        #define LIST_CASE(name,T) \
          else if (!strcmp(words[3],#name)) \
            prop = new_<PlyPropList<uint8_t,T>>(words[4],E.count);
        if (!strcmp(words[1],"list")) {
          if (words.size() != 5)
            throw IOError("invalid list property declaration, expected 'property list uchar type name'");
          if (strcmp(words[2],"uchar"))
            throw IOError(format("unsupported list property declaration, only uchar sizes are supported, got %s",
              repr(words[2])));
          PLY_TYPE_NAMES(LIST_CASE)
          else
            throw IOError(format("invalid list property type %s",repr(words[3])));
        } else {
          if (words.size() != 3)
            throw IOError("invalid single property declaration, expected 'property type name'");
          PLY_TYPE_NAMES(SINGLE_CASE)
          else
            throw IOError(format("invalid property type %s",repr(words[1])));
        }
        if (!E.prop_names.set(prop->name,ref(prop)))
          throw IOError(format("duplicate property name %s for element %s",repr(prop->name),repr(E.name)));
        E.props.push_back(ref(prop));
      } else if (!strcmp(words[0],"end_header"))
        break;
      else
        throw IOError(format("invalid header command %s",repr(words[0])));
    }
    if (!fmt)
      throw IOError("missing format declaration");

    #if GEODE_ENDIAN == GEODE_LITTLE_ENDIAN
      const int native = 2;
    #elif GEODE_ENDIAN == GEODE_BIG_ENDIAN
      const int native = 3;
    #endif

    // Read all elements
    if (fmt == 1) {
      for (const auto& E : elements) {
        for (const int i : range(E->count)) {
          if (!line.read(f))
            throw IOError(format("failed to read element %s, index %d: unexpected end of file",repr(E->name),i));
          int n = 0;
          for (const auto& prop : E->props) {
            try {
              prop->read_ascii(line.words,n);
            } catch (const IOError& e) {
              throw IOError(format("failed to read element %s, index %d, prop %s: %s",
                repr(E->name),i,repr(prop->name),e.what()));
            }
          }
          if (n != line.words.size())
            throw IOError(format("failed to read element %s, index %d: extra fields",repr(E->name),i));
        }
      }
    } else if (fmt == native) {
      for (const auto& E : elements) {
        for (const int i : range(E->count)) {
          for (const auto& prop : E->props) {
            try {
              prop->read_binary_same_endian(f);
            } catch (const IOError& e) {
              throw IOError(format("failed to read element %s, index %d, prop %s: %s",
                repr(E->name),i,repr(prop->name),e.what()));
            }
          }
        }
      }
    } else { // fmt == nonnative
      for (const auto& E : elements) {
        for (const int i : range(E->count)) {
          for (const auto& prop : E->props) {
            try {
              prop->read_binary_flip_endian(f);
            } catch (const IOError& e) {
              throw IOError(format("failed to read element %s, index %d, prop %s: %s",
                repr(E->name),i,repr(prop->name),e.what()));
            }
          }
        }
      }
    }

    // Pull out all the data we need
    // TODO: Don't discard all the rest of the data
    if (!element_names.contains("vertex"))
      throw IOError("missing vertex element");
    const auto vertex = element_names.get("vertex");
    Array<TV> X(vertex->count,uninit);
    for (const int i : range(3)) {
      const string c(1,"xyz"[i]);
      if (!vertex->prop_names.contains(c))
        throw IOError(format("vertex element missing property %s",c));
      const auto x_ = vertex->prop_names.get(c);
      if (const auto* x = dynamic_cast<PlyPropSingle<float>*>(&*x_)) {
        for (const int j : range(X.size()))
          X[j][i] = x->a[j];
      } else if (const auto& x = dynamic_cast<PlyPropSingle<double>*>(&*x_)) {
        for (const int j : range(X.size()))
          X[j][i] = x->a[j];
      } else
        throw IOError(format("vertex.%s has invalid type %s",c,x_->type()));
    }
    if (!element_names.contains("face"))
      throw IOError("missing face element");
    const auto face = element_names.get("face");
    if (!face->prop_names.contains("vertex_indices"))
      throw IOError("face element missing vertex_indices");
    const auto vertices = face->prop_names.get("vertex_indices");
    if (const auto* v = dynamic_cast<PlyPropList<uint8_t,int>*>(&*vertices))
      return tuple(new_<PolygonSoup>(v->counts,v->flat),X);
    else
      throw IOError(format("face.vertex_indices has unsupported type %s",vertices->type()));
  } catch (const IOError& e) {
    throw IOError(format("invalid ply file %s:%d: %s",filename,line.lineno,e.what()));
  }
}

static void write_ply_helper(File& f, const int nfaces, RawArray<const TV> X) {
  fprintf(f,"ply\n"
            "format binary_little_endian 1.0\n"
            "comment Binary .ply file: http://en.wikipedia.org/wiki/PLY_(file_format)\n"
            "element vertex %d\n"
            "property float x\n"
            "property float y\n"
            "property float z\n"
            "element face %d\n"
            "property list uchar int vertex_indices\n"
            "end_header\n",X.size(),nfaces);
  for (const auto& x : X) {
    const auto y = to_little_endian(Vector<float,3>(x));
    fwrite(&y,sizeof(y),1,f);
  }
}

static void write_ply(const string& filename, RawArray<const Vector<int,3>> tris, RawArray<const TV> X) {
  File f(filename,"wb");
  write_ply_helper(f,tris.size(),X);
  for (const Vector<int,3>& t : tris) {
    const uint8_t n = 3;
    fwrite(&n,1,1,f);
    fwrite(&to_little_endian(t),sizeof(t),1,f);
  }
}

static void write_ply(const string& filename, const PolygonSoup& soup, RawArray<const TV> X) {
  File f(filename,"wb");
  write_ply_helper(f,soup.counts.size(),X);
  int offset = 0;
  for (const int c : soup.counts) {
    const uint8_t cb(c);
    if (int(c)!=c)
      throw IOError(format("write_ply: can't write face with %d > 255 vertices",c));
    fwrite(&cb,1,1,f);
    for (int i=0;i<c;i++) {
      const int v = to_little_endian(soup.vertices[offset++]);
      fwrite(&v,sizeof(v),1,f);
    }
  }
}

static void write_x3d_helper(const string& filename, const function<void(File&)>& write_topology, RawArray<const TV> X) {
  File f(filename,"wb");
  fputs("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
        "<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.1//EN\" \"http://www.web3d.org/specifications/x3d-3.1.dtd\">\n"
        "<X3D profile=\"Immersive\" version=\"3.1\" "
            "xsd:noNamespaceSchemaLocation=\"http://www.web3d.org/specifications/x3d-3.1.xsd\" "
            "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
        " <head>\n"
        "  <meta content=\".x3d format: http://en.wikipedia.org/wiki/X3d\" name=\"description\"/>\n"
        " </head>\n"
        " <Scene>\n"
        "  <Shape>\n"
        "   <IndexedFaceSet coordIndex=\"",f);
  write_topology(f);
  fputs("\" solid=\"false\">\n"
        "    <Coordinate point=\"",f);
  const auto flat = scalar_view(X);
  if (flat.size())
    fprintf(f,"%g",flat[0]);
  for (int i=1;i<flat.size();i++)
    fprintf(f," %g",flat[i]);
  fputs("\"/>\n"
        "   </IndexedFaceSet>\n"
        "  </Shape>\n"
        " </Scene>\n"
        "</X3D>\n",f);
}

static void write_x3d(const string& filename, RawArray<const Vector<int,3>> tris, RawArray<const TV> X) {
  write_x3d_helper(filename,[=](File& f){
    bool first = true;
    for (const auto& t : tris) {
      if (!first)
        fputc(' ',f);
      first = false;
      fprintf(f,"%d %d %d -1",t.x,t.y,t.z);
    }
  },X);
}
static void write_x3d(const string& filename, const PolygonSoup& soup, RawArray<const TV> X) {
  write_x3d_helper(filename,[&](File& f){
    int offset = 0;
    for (const int c : soup.counts) {
      for (int i=0;i<c;i++)
        fprintf(f,"%d ",soup.vertices[offset++]);
      fputs(offset==soup.vertices.size() ? "-1" : "-1 ",f);
    }
  },X);
}

static Tuple<Ref<TriangleSoup>,Array<TV>> convert(const Tuple<Ref<PolygonSoup>,Array<TV>>& d) {
  return tuple(d.x->triangle_mesh(),d.y);
}

static Tuple<Ref<PolygonSoup>,Array<TV>> convert(const Tuple<Ref<TriangleSoup>,Array<TV>>& d) {
  return tuple(new_<PolygonSoup>(arange(d.x->elements.size()).copy(),scalar_view_own(d.x->elements)),d.y);
}

Tuple<Ref<TriangleSoup>,Array<TV>> read_soup(const string& filename) {
  const auto ext = path::extension(filename);
  if      (ext == ".stl") return         read_stl(filename);
  else if (ext == ".obj") return convert(read_obj(filename));
  else if (ext == ".ply") return convert(read_ply(filename));
  else
    throw ValueError(format("unsupported mesh filename '%s', expected one of .stl, .obj, .ply",filename));
}

Tuple<Ref<PolygonSoup>,Array<TV>> read_polygon_soup(const string& filename) {
  const auto ext = path::extension(filename);
  if      (ext == ".stl") return convert(read_stl(filename));
  else if (ext == ".obj") return         read_obj(filename);
  else if (ext == ".ply") return         read_ply(filename);
  else
    throw ValueError(format("unsupported mesh filename '%s', expected one of .stl, .obj, .ply",filename));
}

Tuple<Ref<TriangleTopology>,Array<TV>> read_mesh(const string& filename) {
  const auto soup = read_soup(filename);
  return tuple(new_<TriangleTopology>(soup.x),soup.y);
}

static void write_helper(const string& filename, RawArray<const Vector<int,3>> tris, RawArray<const TV> X) {
  const auto ext = path::extension(filename);
  if      (ext == ".stl") write_stl(filename,tris,X);
  else if (ext == ".obj") write_obj(filename,tris,X);
  else if (ext == ".ply") write_ply(filename,tris,X);
  else if (ext == ".x3d") write_x3d(filename,tris,X);
  else
    throw ValueError(format("unsupported mesh filename '%s', expected one of .stl, .obj, .ply, .x3d",filename));
}

void write_mesh(const string& filename, const TriangleSoup& soup, RawArray<const TV> X) {
  GEODE_ASSERT(X.size()>=soup.nodes());
  write_helper(filename,soup.elements,X);
}

void write_mesh(const string& filename, const PolygonSoup& soup, RawArray<const TV> X) {
  GEODE_ASSERT(X.size()>=soup.nodes());
  const auto ext = path::extension(filename);
  if      (ext == ".obj") write_obj(filename,soup,X);
  else if (ext == ".ply") write_ply(filename,soup,X);
  else if (ext == ".x3d") write_x3d(filename,soup,X);
  else
    throw ValueError(format("unsupported polygon mesh filename '%s', expected one of .obj, .ply, .x3d",filename));
}

void write_mesh(const string& filename, const TriangleTopology& mesh, RawArray<const TV> X) {
  write_helper(filename,mesh.elements(),X);
}

void write_mesh(const string& filename, const MutableTriangleTopology& mesh) {
  FieldId<Vector<real,3>, VertexId> pos_id(vertex_position_id);
  GEODE_ASSERT(mesh.has_field(pos_id));
  write_helper(filename,mesh.elements(),mesh.field(pos_id).flat);
}

static void write_mesh_py(const string& filename, PyObject* mesh, RawArray<const TV> X) {
  if (auto* soup = python_cast<TriangleSoup*>(mesh))
    write_mesh(filename,*soup,X);
  else if (auto* soup = python_cast<PolygonSoup*>(mesh))
    write_mesh(filename,*soup,X);
  else if (auto* top = python_cast<TriangleTopology*>(mesh))
    write_mesh(filename,*top,X);
  else
    throw TypeError(format("expected TriangleSoup or TriangleTopology, got %s",mesh->ob_type->tp_name));
}

}
using namespace geode;

void wrap_mesh_io() {
  GEODE_FUNCTION(read_soup)
  GEODE_FUNCTION(read_polygon_soup)
  GEODE_FUNCTION(read_mesh)
  GEODE_FUNCTION_2(write_mesh,write_mesh_py)
}


text:
@class SPEventListener;

@interface SPEventDispatcher (Internal)

- (void)addEventListener:(SPEventListener *)listener forType:(NSString *)eventType;
- (void)removeEventListenersForType:(NSString *)eventType withTarget:(id)object andSelector:(SEL)selector orBlock:(SPEventBlock)block;

@end


text:
from __future__ import print_function

import os
import sys
import time
from datetime import datetime
from flask import Flask
from flask_restful import Api

from cufacesearch.api import api
from cufacesearch.searcher import searcher_lopqhbase

template_dir = os.path.abspath('../../../www/templates')
app = Flask(__name__, template_folder=template_dir)
#app = Flask(__name__)
DEFAULT_PORT = 5000

# DEFAULT_ENDPOINT = "cuimgsearch"
# DEFAULT_INPUT = "image"

def setup_app(app):
  print("[gunicorn_api] Setting up application...")
  app.secret_key = "secret_key"
  app.config['SESSION_TYPE'] = 'filesystem'

  searchapi = Api(app)
  app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024

  # Set parameters
  options = dict()
  # Get parameters from environment variables
  options["conf"] = os.environ['SEARCH_CONF_FILE']
  options["endpoint"] = os.environ['SEARCH_ENDPOINT']
  options["input"] = os.environ['SEARCH_INPUT']
  options["port"] = os.getenv('SEARCH_PORT', DEFAULT_PORT)
  print("[gunicorn_api] options: ",options)

  api.global_start_time = datetime.now()
  # This will change the name of the fields in the output, i.e. AllSimilarImages vs AllSimilarFaces
  api.input_type = options["input"]

  # Initialize searcher object only once
  while True:
    try:
      api.global_searcher = searcher_lopqhbase.SearcherLOPQHBase(options["conf"])
      break
    except Exception as inst:
      err_msg = "Failed to initialized searcher ({}): {}".format(type(inst), inst)
      print(err_msg)
      sys.stdout.flush()
      time.sleep(60)

  # Setup API
  searchapi.add_resource(api.APIResponder, '/' + options["endpoint"] + '/<string:mode>')

  # Would that help prevent double requests from browser?
  #searchapi.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon.ico'))

  @app.after_request
  def after_request(response):
    """ Adds appropriate headers to the HTTP response.

    :type response: HTTP response object.
    """
    response.headers.add('Access-Control-Allow-Headers',
                         'Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,x-requested-with,Content-Type,origin,authorization,accept,client-security-token')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response

setup_app(app)

if __name__ == '__main__':
  app.run()


text:
<!DOCTYPE html>

<link href="synthetic-pinch-zoom-gesture.css" rel="stylesheet">


text:
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef;

import com.intellij.lang.ASTNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrInterfaceDefinition;
import org.jetbrains.plugins.groovy.lang.psi.stubs.GrTypeDefinitionStub;

/**
 * @author Dmitry.Krasilschikov
 * @date 16.03.2007
 */
public class GrInterfaceDefinitionImpl extends GrTypeDefinitionImpl implements GrInterfaceDefinition {

  public GrInterfaceDefinitionImpl(GrTypeDefinitionStub stub) {
    super(stub, GroovyElementTypes.INTERFACE_DEFINITION);
  }

  public GrInterfaceDefinitionImpl(@NotNull ASTNode node) {
    super(node);
  }

  public String toString() {
    return "Interface definition";
  }

  public boolean isInterface() {
    return true;
  }

  @Override
  public void accept(GroovyElementVisitor visitor) {
    visitor.visitInterfaceDefinition(this);
  }
}


text:
package com.learning.designpattern.behavioral.visitor;

public interface ComputerPart {
    public void accept(ComputerPartVisitor computerPartVisitor);
}


text:
#include <linux/sizes.h>

#include "ddk750_help.h"
#include "ddk750_reg.h"
#include "ddk750_chip.h"
#include "ddk750_power.h"

logical_chip_type_t getChipType(void)
{
	unsigned short physicalID;
	char physicalRev;
	logical_chip_type_t chip;

	physicalID = devId750; /* either 0x718 or 0x750 */
	physicalRev = revId750;

	if (physicalID == 0x718)
		chip = SM718;
	else if (physicalID == 0x750) {
		chip = SM750;
		/* SM750 and SM750LE are different in their revision ID only. */
		if (physicalRev == SM750LE_REVISION_ID)
			chip = SM750LE;
	} else
		chip = SM_UNKNOWN;

	return chip;
}

static unsigned int get_mxclk_freq(void)
{
	unsigned int pll_reg;
	unsigned int M, N, OD, POD;

	if (getChipType() == SM750LE)
		return MHz(130);

	pll_reg = PEEK32(MXCLK_PLL_CTRL);
	M = FIELD_GET(pll_reg, PANEL_PLL_CTRL, M);
	N = FIELD_GET(pll_reg, PANEL_PLL_CTRL, N);
	OD = FIELD_GET(pll_reg, PANEL_PLL_CTRL, OD);
	POD = FIELD_GET(pll_reg, PANEL_PLL_CTRL, POD);

	return DEFAULT_INPUT_CLOCK * M / N / (1 << OD) / (1 << POD);
}

/*
 * This function set up the main chip clock.
 *
 * Input: Frequency to be set.
 */
static void setChipClock(unsigned int frequency)
{
	pll_value_t pll;
	unsigned int ulActualMxClk;

	/* Cheok_0509: For SM750LE, the chip clock is fixed. Nothing to set. */
	if (getChipType() == SM750LE)
		return;

	if (frequency) {
		/*
		* Set up PLL, a structure to hold the value to be set in clocks.
		*/
		pll.inputFreq = DEFAULT_INPUT_CLOCK; /* Defined in CLOCK.H */
		pll.clockType = MXCLK_PLL;

		/*
		* Call calcPllValue() to fill up the other fields for PLL structure.
		* Sometime, the chip cannot set up the exact clock required by User.
		* Return value from calcPllValue() gives the actual possible clock.
		*/
		ulActualMxClk = calcPllValue(frequency, &pll);

		/* Master Clock Control: MXCLK_PLL */
		POKE32(MXCLK_PLL_CTRL, formatPllReg(&pll));
	}
}

static void setMemoryClock(unsigned int frequency)
{
	unsigned int ulReg, divisor;

	/* Cheok_0509: For SM750LE, the memory clock is fixed. Nothing to set. */
	if (getChipType() == SM750LE)
		return;

	if (frequency) {
		/* Set the frequency to the maximum frequency that the DDR Memory can take
		which is 336MHz. */
		if (frequency > MHz(336))
			frequency = MHz(336);

		/* Calculate the divisor */
		divisor = roundedDiv(get_mxclk_freq(), frequency);

		/* Set the corresponding divisor in the register. */
		ulReg = PEEK32(CURRENT_GATE);
		switch (divisor) {
		default:
		case 1:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, M2XCLK, DIV_1);
			break;
		case 2:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, M2XCLK, DIV_2);
			break;
		case 3:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, M2XCLK, DIV_3);
			break;
		case 4:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, M2XCLK, DIV_4);
			break;
		}

		setCurrentGate(ulReg);
	}
}

/*
 * This function set up the master clock (MCLK).
 *
 * Input: Frequency to be set.
 *
 * NOTE:
 *      The maximum frequency the engine can run is 168MHz.
 */
static void setMasterClock(unsigned int frequency)
{
	unsigned int ulReg, divisor;

	/* Cheok_0509: For SM750LE, the memory clock is fixed. Nothing to set. */
	if (getChipType() == SM750LE)
		return;

	if (frequency) {
		/* Set the frequency to the maximum frequency that the SM750 engine can
		run, which is about 190 MHz. */
		if (frequency > MHz(190))
			frequency = MHz(190);

		/* Calculate the divisor */
		divisor = roundedDiv(get_mxclk_freq(), frequency);

		/* Set the corresponding divisor in the register. */
		ulReg = PEEK32(CURRENT_GATE);
		switch (divisor) {
		default:
		case 3:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, MCLK, DIV_3);
			break;
		case 4:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, MCLK, DIV_4);
			break;
		case 6:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, MCLK, DIV_6);
			break;
		case 8:
			ulReg = FIELD_SET(ulReg, CURRENT_GATE, MCLK, DIV_8);
			break;
		}

		setCurrentGate(ulReg);
		}
}

unsigned int ddk750_getVMSize(void)
{
	unsigned int reg;
	unsigned int data;

	/* sm750le only use 64 mb memory*/
	if (getChipType() == SM750LE)
		return SZ_64M;

	/* for 750,always use power mode0*/
	reg = PEEK32(MODE0_GATE);
	reg = FIELD_SET(reg, MODE0_GATE, GPIO, ON);
	POKE32(MODE0_GATE, reg);

	/* get frame buffer size from GPIO */
	reg = FIELD_GET(PEEK32(MISC_CTRL), MISC_CTRL, LOCALMEM_SIZE);
	switch (reg) {
	case MISC_CTRL_LOCALMEM_SIZE_8M:
		data = SZ_8M;  break; /* 8  Mega byte */
	case MISC_CTRL_LOCALMEM_SIZE_16M:
		data = SZ_16M; break; /* 16 Mega byte */
	case MISC_CTRL_LOCALMEM_SIZE_32M:
		data = SZ_32M; break; /* 32 Mega byte */
	case MISC_CTRL_LOCALMEM_SIZE_64M:
		data = SZ_64M; break; /* 64 Mega byte */
	default:
		data = 0;
		break;
	}
	return data;
}

int ddk750_initHw(initchip_param_t *pInitParam)
{
	unsigned int ulReg;

	if (pInitParam->powerMode != 0)
		pInitParam->powerMode = 0;
	setPowerMode(pInitParam->powerMode);

	/* Enable display power gate & LOCALMEM power gate*/
	ulReg = PEEK32(CURRENT_GATE);
	ulReg = FIELD_SET(ulReg, CURRENT_GATE, DISPLAY, ON);
	ulReg = FIELD_SET(ulReg, CURRENT_GATE, LOCALMEM, ON);
	setCurrentGate(ulReg);

	if (getChipType() != SM750LE) {
		/*	set panel pll and graphic mode via mmio_88 */
		ulReg = PEEK32(VGA_CONFIGURATION);
		ulReg = FIELD_SET(ulReg, VGA_CONFIGURATION, PLL, PANEL);
		ulReg = FIELD_SET(ulReg, VGA_CONFIGURATION, MODE, GRAPHIC);
		POKE32(VGA_CONFIGURATION, ulReg);
	} else {
#if defined(__i386__) || defined(__x86_64__)
		/* set graphic mode via IO method */
		outb_p(0x88, 0x3d4);
		outb_p(0x06, 0x3d5);
#endif
	}

	/* Set the Main Chip Clock */
	setChipClock(MHz((unsigned int)pInitParam->chipClock));

	/* Set up memory clock. */
	setMemoryClock(MHz(pInitParam->memClock));

	/* Set up master clock */
	setMasterClock(MHz(pInitParam->masterClock));

	/* Reset the memory controller. If the memory controller is not reset in SM750,
	   the system might hang when sw accesses the memory.
	   The memory should be resetted after changing the MXCLK.
	 */
	if (pInitParam->resetMemory == 1) {
		ulReg = PEEK32(MISC_CTRL);
		ulReg = FIELD_SET(ulReg, MISC_CTRL, LOCALMEM_RESET, RESET);
		POKE32(MISC_CTRL, ulReg);

		ulReg = FIELD_SET(ulReg, MISC_CTRL, LOCALMEM_RESET, NORMAL);
		POKE32(MISC_CTRL, ulReg);
	}

	if (pInitParam->setAllEngOff == 1) {
		enable2DEngine(0);

		/* Disable Overlay, if a former application left it on */
		ulReg = PEEK32(VIDEO_DISPLAY_CTRL);
		ulReg = FIELD_SET(ulReg, VIDEO_DISPLAY_CTRL, PLANE, DISABLE);
		POKE32(VIDEO_DISPLAY_CTRL, ulReg);

		/* Disable video alpha, if a former application left it on */
		ulReg = PEEK32(VIDEO_ALPHA_DISPLAY_CTRL);
		ulReg = FIELD_SET(ulReg, VIDEO_ALPHA_DISPLAY_CTRL, PLANE, DISABLE);
		POKE32(VIDEO_ALPHA_DISPLAY_CTRL, ulReg);

		/* Disable alpha plane, if a former application left it on */
		ulReg = PEEK32(ALPHA_DISPLAY_CTRL);
		ulReg = FIELD_SET(ulReg, ALPHA_DISPLAY_CTRL, PLANE, DISABLE);
		POKE32(ALPHA_DISPLAY_CTRL, ulReg);

		/* Disable DMA Channel, if a former application left it on */
		ulReg = PEEK32(DMA_ABORT_INTERRUPT);
		ulReg = FIELD_SET(ulReg, DMA_ABORT_INTERRUPT, ABORT_1, ABORT);
		POKE32(DMA_ABORT_INTERRUPT, ulReg);

		/* Disable DMA Power, if a former application left it on */
		enableDMA(0);
	}

	/* We can add more initialization as needed. */

	return 0;
}

/*
	monk liu @ 4/6/2011:
		   re-write the calculatePLL function of ddk750.
		   the original version function does not use some mathematics tricks and shortcut
		   when it doing the calculation of the best N,M,D combination
		   I think this version gives a little upgrade in speed

	750 pll clock formular:
	Request Clock = (Input Clock * M )/(N * X)

	Input Clock = 14318181 hz
	X = 2 power D
	D ={0,1,2,3,4,5,6}
	M = {1,...,255}
	N = {2,...,15}
*/
unsigned int calcPllValue(unsigned int request_orig, pll_value_t *pll)
{
	/* as sm750 register definition, N located in 2,15 and M located in 1,255	*/
	int N, M, X, d;
	int mini_diff;
	unsigned int RN, quo, rem, fl_quo;
	unsigned int input, request;
	unsigned int tmpClock, ret;
	const int max_OD = 3;
	int max_d;

	if (getChipType() == SM750LE) {
		/* SM750LE don't have prgrammable PLL and M/N values to work on.
		Just return the requested clock. */
		return request_orig;
	}

	ret = 0;
	mini_diff = ~0;
	request = request_orig / 1000;
	input = pll->inputFreq / 1000;

	/* for MXCLK register , no POD provided, so need be treated differently	*/
	if (pll->clockType == MXCLK_PLL)
		max_d = 3;

	for (N = 15; N > 1; N--) {
		/* RN will not exceed maximum long if @request <= 285 MHZ (for 32bit cpu) */
		RN = N * request;
		quo = RN / input;
		rem = RN % input;/* rem always small than 14318181 */
		fl_quo = (rem * 10000 / input);

		for (d = max_d; d >= 0; d--) {
			X = (1 << d);
			M = quo * X;
			M += fl_quo * X / 10000;
			/* round step */
			M += (fl_quo * X % 10000) > 5000 ? 1 : 0;
			if (M < 256 && M > 0) {
				unsigned int diff;

				tmpClock = pll->inputFreq * M / N / X;
				diff = absDiff(tmpClock, request_orig);
				if (diff < mini_diff) {
					pll->M = M;
					pll->N = N;
					pll->POD = 0;
					if (d > max_OD)
						pll->POD = d - max_OD;
					pll->OD = d - pll->POD;
					mini_diff = diff;
					ret = tmpClock;
				}
			}
		}
	}
	return ret;
}

unsigned int formatPllReg(pll_value_t *pPLL)
{
	unsigned int ulPllReg = 0;

    /* Note that all PLL's have the same format. Here, we just use Panel PLL parameter
       to work out the bit fields in the register.
       On returning a 32 bit number, the value can be applied to any PLL in the calling function.
    */
	ulPllReg =
	FIELD_SET(0, PANEL_PLL_CTRL, BYPASS, OFF)
	| FIELD_SET(0, PANEL_PLL_CTRL, POWER,  ON)
	| FIELD_SET(0, PANEL_PLL_CTRL, INPUT,  OSC)
#ifndef VALIDATION_CHIP
	| FIELD_VALUE(0, PANEL_PLL_CTRL, POD,    pPLL->POD)
#endif
	| FIELD_VALUE(0, PANEL_PLL_CTRL, OD,     pPLL->OD)
	| FIELD_VALUE(0, PANEL_PLL_CTRL, N,      pPLL->N)
	| FIELD_VALUE(0, PANEL_PLL_CTRL, M,      pPLL->M);

	return ulPllReg;
}


text:
/**
 * divWindow 对象
 */

function divWindow(windowId){
	if(windowId)
		this.id = windowId;
	else
		return null;
	this.status = 0;
	this.height = 300;
	this.width = 400;

	var instance = this;

	if($("#"+this.id).length == 0){

		this.divNode = $("
");
		this.divNode.attr({id:this.id});
		this.divNode.attr({"class":"divWindow"});

		this.backGroundDiv = $("
");
		this.backGroundDiv.attr({id:this.id+"_BackGroundDiv"});
		this.backGroundDiv.attr({"class":"outDivWindow"});

		this.divNode.appendTo("body");
		this.backGroundDiv.appendTo("body");

	}else{
		this.divNode = $("#"+this.id).eq(0);
		this.backGroundDiv = $("#"+this.id+"_BackGroundDiv").eq(0);
	}

	//this.divNode.append($(""));
		   //$("#body").append($(""));

	/*
	closeDiv= $("

");

	closeImg = $("");

	closeDiv.append(closeImg);

	closeImg.click(function (){
		instance.close();
	});

	closeDiv.appendTo(this.divNode);
	*/

}

/**
 * 设置divWindow 的内容
 */
divWindow.prototype.set = function(node){
	    if(typeof node == "string"){
			this.divNode.append($(node));
		}else if(typeof node == "object"){
				this.divNode.append(node);
		}else{
				alert("非法参数");
	    }
}

/**
 * divWindow 展示函数
 */
divWindow.prototype.show = function(){

	//debugger;
	this.divNode.height(this.height);
	this.divNode.width(this.width);
	var windowWidth = window.screen.availWidth;
	var windowHeight = window.screen.availHeight;
	var popupHeight = this.divNode.height();
	var popupWidth = this.divNode.width();

	this.divNode.css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});

	//this.backGroundDiv.css({
	//	"height": windowHeight
	//});

    //show
	if(status==0){
		this.backGroundDiv.css({
			"filter": "Alpha(Opacity=30)"
		});
		this.backGroundDiv.fadeIn("fast");
		this.divNode.fadeIn("fast",this.beforeShow);
		status = 1;
	}

}

/**
 * divWindow 关闭函数
 */
divWindow.prototype.close = function(){
	if(status==1){
		this.backGroundDiv.fadeOut("fast");
		this.divNode.fadeOut("fast",this.beforeClose);

		status = 0;
	}

}

/**
 * divWindow 展示前的回调
 */
divWindow.prototype.beforeShow = function( func){
	this.beforeShow = func;
}

/**
 * divWindow 关闭之前的回调
 */
divWindow.prototype.beforeClose = function( func){
	this.beforeClose = func;
}


text:
package unicon.matthews.dataloader.canvas.io.converter;

import static unicon.matthews.dataloader.canvas.io.converter.EventBuilderUtils.usingCourseSectionGroup;
import static unicon.matthews.dataloader.canvas.io.converter.EventBuilderUtils.usingMembership;
import static unicon.matthews.dataloader.canvas.io.converter.EventBuilderUtils.usingPersonType;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import unicon.matthews.caliper.Entity;
import unicon.matthews.caliper.Event;
import unicon.matthews.dataloader.canvas.model.CanvasPageRequest;
import unicon.matthews.oneroster.Enrollment;
import unicon.matthews.oneroster.User;

@Component
public class CanvasPageRequestFavoritesShowToNavigatedToEventConverter
  implements Converter<CanvasPageRequest, Optional<Event>> {

  private static Logger logger = LoggerFactory.getLogger(CanvasPageRequestFavoritesShowToNavigatedToEventConverter.class);

  @Override
  public boolean supports(CanvasPageRequest source) {
    return (
            (source.getWebApplicationController().equalsIgnoreCase("favorites")) &&
            (source.getWebApplicationAction().equalsIgnoreCase("show")) &&
            (source.getHttpStatus().equals(String.valueOf(HttpStatus.OK.value()))
                || source.getHttpStatus().equals(String.valueOf(HttpStatus.NOT_MODIFIED.value())))
           );
  }

  @Override
  public Optional<Event> convert(CanvasPageRequest source, SupportingEntities supportingEntities) {

    logger.debug("Source: {}",source);

    Optional<Event> result = null;

    Optional<Long> userId = source.getUserId();

    if (!userId.isPresent()) {
        result = Optional.empty();
    } else {

        Optional<User> maybeUser = supportingEntities.getUsers().values().stream().filter(u -> u.getSourcedId().equalsIgnoreCase(
            String.valueOf(userId.get()))).findFirst();

        if (maybeUser != null & maybeUser.isPresent()) {
          User user = maybeUser.get();

          LocalDateTime eventTime = LocalDateTime.ofInstant(source.getTimestamp(), ZoneId.of("UTC"));

          Event event;
          Enrollment enrollment = null;
          if (source.getCourseId().isPresent()) {
              String courseId = source.getCourseId().get().toString();
              enrollment
              = supportingEntities.getEnrollments()
                .values().stream()
                .filter(
                        e -> e.getKlass().getSourcedId().equalsIgnoreCase(courseId)
                          && e.getUser().getSourcedId().equalsIgnoreCase(user.getSourcedId())
                    ).findFirst().get();

              Map<String, String> entityMetadata
              = new HashMap<>();
              entityMetadata.put("CANVAS_ACTION", source.getWebApplicationAction());
              entityMetadata.put("CANVAS_CONTROLLER", source.getWebApplicationController());

              Entity resource = new Entity.Builder()
                .withId(source.getUrl())
                .withType(EventBuilderUtils.CaliperV1p1Vocab.Entity.DIGITAL_RESOURCE)
                .withExtensions(entityMetadata)
                .build();

              event = EventBuilderUtils.usingNavigationEventType()
                      .withObject(resource)
                      .withEventTime(eventTime)
                      .withAgent(usingPersonType(user, user.getUserId(), supportingEntities.getUserEmailMap().get(
                              user.getSourcedId()), source.getRootAccountId().toString()).build())
                      .withGroup(usingCourseSectionGroup(enrollment).build())
                      .withMembership(usingMembership(enrollment).build())
                      .withFederatedSession(source.getSessionId())
                      .build();

              result = Optional.of(event);
          }
          else {
            result = Optional.empty();
          }
        }
        else {
          result = Optional.empty();
        }
    }

    return result;
  }
}