text:
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

import React, { Component } from "react";
import PropTypes from "prop-types";
import { line, curveStepBefore } from "d3-shape";

import GenericChartComponent from "../GenericChartComponent";
import { getAxisCanvas } from "../GenericComponent";
import { isDefined, isNotDefined } from "../utils";

var KagiSeries = function (_Component) {
	_inherits(KagiSeries, _Component);

	function KagiSeries(props) {
		_classCallCheck(this, KagiSeries);

		var _this = _possibleConstructorReturn(this, (KagiSeries.__proto__ || Object.getPrototypeOf(KagiSeries)).call(this, props));

		_this.renderSVG = _this.renderSVG.bind(_this);
		_this.drawOnCanvas = _this.drawOnCanvas.bind(_this);
		return _this;
	}

	_createClass(KagiSeries, [{
		key: "drawOnCanvas",
		value: function drawOnCanvas(ctx, moreProps) {
			var xAccessor = moreProps.xAccessor;

			_drawOnCanvas(ctx, this.props, moreProps, xAccessor);
		}
	}, {
		key: "render",
		value: function render() {
			return React.createElement(GenericChartComponent, {
				svgDraw: this.renderSVG,
				canvasToDraw: getAxisCanvas,
				canvasDraw: this.drawOnCanvas,
				drawOn: ["pan"]
			});
		}
	}, {
		key: "renderSVG",
		value: function renderSVG(moreProps) {
			var xAccessor = moreProps.xAccessor;
			var xScale = moreProps.xScale,
			    yScale = moreProps.chartConfig.yScale,
			    plotData = moreProps.plotData;
			var _props = this.props,
			    className = _props.className,
			    stroke = _props.stroke,
			    fill = _props.fill,
			    strokeWidth = _props.strokeWidth;

			var paths = helper(plotData, xAccessor).map(function (each, i) {
				var dataSeries = line().x(function (item) {
					return xScale(item[0]);
				}).y(function (item) {
					return yScale(item[1]);
				}).curve(curveStepBefore);

				dataSeries(each.plot);

				return React.createElement("path", { key: i, d: dataSeries(each.plot), className: each.type,
					stroke: stroke[each.type], fill: fill[each.type], strokeWidth: strokeWidth });
			});
			return React.createElement(
				"g",
				{ className: className },
				paths
			);
		}
	}]);

	return KagiSeries;
}(Component);

KagiSeries.propTypes = {
	className: PropTypes.string,
	stroke: PropTypes.object,
	fill: PropTypes.object,
	strokeWidth: PropTypes.number.isRequired
};

KagiSeries.defaultProps = {
	className: "react-stockcharts-kagi",
	strokeWidth: 2,
	stroke: {
		yang: "#6BA583",
		yin: "#E60000"
	},
	fill: {
		yang: "none",
		yin: "none"
	},
	currentValueStroke: "#000000"
};

function _drawOnCanvas(ctx, props, moreProps, xAccessor) {
	var stroke = props.stroke,
	    strokeWidth = props.strokeWidth,
	    currentValueStroke = props.currentValueStroke;
	var xScale = moreProps.xScale,
	    yScale = moreProps.chartConfig.yScale,
	    plotData = moreProps.plotData;

	var paths = helper(plotData, xAccessor);

	var begin = true;

	paths.forEach(function (each) {
		ctx.strokeStyle = stroke[each.type];
		ctx.lineWidth = strokeWidth;

		ctx.beginPath();
		var prevX = void 0;
		each.plot.forEach(function (d) {
			var _ref = [xScale(d[0]), yScale(d[1])],
			    x = _ref[0],
			    y = _ref[1];

			if (begin) {
				ctx.moveTo(x, y);
				begin = false;
			} else {
				if (isDefined(prevX)) {
					ctx.lineTo(prevX, y);
				}
				ctx.lineTo(x, y);
			}
			prevX = x;
			// console.log(d);
		});
		ctx.stroke();
	});
	var lastPlot = paths[paths.length - 1].plot;
	var last = lastPlot[lastPlot.length - 1];
	ctx.beginPath();
	// ctx.strokeStyle = "black";
	ctx.lineWidth = 1;

	var _ref2 = [xScale(last[0]), yScale(last[2]), yScale(last[3])],
	    x = _ref2[0],
	    y1 = _ref2[1],
	    y2 = _ref2[2];
	// console.log(last, x, y);

	ctx.moveTo(x, y1);
	ctx.lineTo(x + 10, y1);
	ctx.stroke();

	ctx.beginPath();
	ctx.strokeStyle = currentValueStroke;
	ctx.moveTo(x - 10, y2);
	ctx.lineTo(x, y2);
	ctx.stroke();
}

function helper(plotData, xAccessor) {
	var kagiLine = [];
	var kagi = {};
	var d = plotData[0];
	var idx = xAccessor(d);

	for (var i = 0; i < plotData.length; i++) {
		d = plotData[i];

		if (isNotDefined(d.close)) continue;
		if (isNotDefined(kagi.type)) kagi.type = d.startAs;
		if (isNotDefined(kagi.plot)) kagi.plot = [];

		idx = xAccessor(d);
		kagi.plot.push([idx, d.open]);

		if (isDefined(d.changeTo)) {
			kagi.plot.push([idx, d.changePoint]);
			kagi.added = true;
			kagiLine.push(kagi);

			kagi = {
				type: d.changeTo,
				plot: [],
				added: false
			};
			kagi.plot.push([idx, d.changePoint]);
		}
	}

	if (!kagi.added) {
		kagi.plot.push([idx, d.close, d.current, d.reverseAt]);
		kagiLine.push(kagi);
	}

	// console.log(d.reverseAt);

	return kagiLine;
}

export default KagiSeries;


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:stateListAnimator="@drawable/appbarlayout_elevated"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingtoolbarlayout"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:titleEnabled="false">

            <ImageView
                android:id="@+id/imageview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:gravity="top"
                android:minHeight="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:titleMarginTop="15dp" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tabLayout"
                style="@style/TabLayoutStyle"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_gravity="bottom"
                app:tabMode="scrollable" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

</merge>

redpajama_set_name: RedPajamaGithub


text:
require "spec_helper"
require "chef/data_collector/messages/helpers"

class TestMessage
  extend Chef::DataCollector::Messages::Helpers
end

describe Chef::DataCollector::Messages::Helpers do
  describe "#organization" do
    context "when the run is a solo run" do
      it "returns the data collector organization" do
        allow(TestMessage).to receive(:solo_run?).and_return(true)
        expect(TestMessage).to receive(:data_collector_organization).and_return("org1")
        expect(TestMessage.organization).to eq("org1")
      end
    end

    context "when the run is not a solo run" do
      it "returns the data collector organization" do
        allow(TestMessage).to receive(:solo_run?).and_return(false)
        expect(TestMessage).to receive(:chef_server_organization).and_return("org2")
        expect(TestMessage.organization).to eq("org2")
      end
    end
  end

  describe "#data_collector_organization" do
    context "when the org is specified in the config" do
      it "returns the org from the config" do
        Chef::Config[:data_collector][:organization] = "org1"
        expect(TestMessage.data_collector_organization).to eq("org1")
      end
    end

    context "when the org is not specified in the config" do
      it "returns the default chef_solo org" do
        expect(TestMessage.data_collector_organization).to eq("chef_solo")
      end
    end
  end

  describe "#chef_server_organization" do
    context "when the URL is properly formatted" do
      it "returns the org from the parsed URL" do
        Chef::Config[:chef_server_url] = "http://mycompany.com/organizations/myorg"
        expect(TestMessage.chef_server_organization).to eq("myorg")
      end
    end

    context "when the URL is not properly formatted" do
      it "returns unknown_organization" do
        Chef::Config[:chef_server_url] = "http://mycompany.com/what/url/is/this"
        expect(TestMessage.chef_server_organization).to eq("unknown_organization")
      end
    end
  end

  describe "#collector_source" do
    context "when the run is a solo run" do
      it "returns chef_solo" do
        allow(TestMessage).to receive(:solo_run?).and_return(true)
        expect(TestMessage.collector_source).to eq("chef_solo")
      end
    end

    context "when the run is not a solo run" do
      it "returns chef_client" do
        allow(TestMessage).to receive(:solo_run?).and_return(false)
        expect(TestMessage.collector_source).to eq("chef_client")
      end
    end
  end

  describe "#solo_run?" do
    context "when :solo is set in Chef::Config" do
      it "returns true" do
        Chef::Config[:solo] = true
        Chef::Config[:local_mode] = nil
        expect(TestMessage.solo_run?).to be_truthy
      end
    end

    context "when :local_mode is set in Chef::Config" do
      it "returns true" do
        Chef::Config[:solo] = nil
        Chef::Config[:local_mode] = true
        expect(TestMessage.solo_run?).to be_truthy
      end
    end

    context "when neither :solo or :local_mode is set in Chef::Config" do
      it "returns false" do
        Chef::Config[:solo] = nil
        Chef::Config[:local_mode] = nil
        expect(TestMessage.solo_run?).to be_falsey
      end
    end
  end

  describe "#node_uuid" do
    context "when the node UUID can be read" do
      it "returns the read-in node UUID" do
        allow(TestMessage).to receive(:read_node_uuid).and_return("read_uuid")
        expect(TestMessage.node_uuid).to eq("read_uuid")
      end
    end

    context "when the node UUID cannot be read" do
      it "generated a new node UUID" do
        allow(TestMessage).to receive(:read_node_uuid).and_return(nil)
        allow(TestMessage).to receive(:generate_node_uuid).and_return("generated_uuid")
        expect(TestMessage.node_uuid).to eq("generated_uuid")
      end
    end
  end

  describe "#generate_node_uuid" do
    it "generates a new UUID, stores it, and returns it" do
      expect(SecureRandom).to receive(:uuid).and_return("generated_uuid")
      expect(TestMessage).to receive(:update_metadata).with("node_uuid", "generated_uuid")
      expect(TestMessage.generate_node_uuid).to eq("generated_uuid")
    end
  end

  describe "#read_node_uuid" do
    it "reads the node UUID from metadata" do
      expect(TestMessage).to receive(:metadata).and_return({ "node_uuid" => "read_uuid" })
      expect(TestMessage.read_node_uuid).to eq("read_uuid")
    end
  end

  describe "metadata" do
    let(:metadata_filename) { "fake_metadata_file.json" }

    before do
      allow(TestMessage).to receive(:metadata_filename).and_return(metadata_filename)
    end

    context "when the metadata file exists" do
      it "returns the contents of the metadata file" do
        expect(Chef::FileCache).to receive(:load).with(metadata_filename).and_return('{"foo":"bar"}')
        expect(TestMessage.metadata["foo"]).to eq("bar")
      end
    end

    context "when the metadata file does not exist" do
      it "returns an empty hash" do
        expect(Chef::FileCache).to receive(:load).with(metadata_filename).and_raise(Chef::Exceptions::FileNotFound)
        expect(TestMessage.metadata).to eq({})
      end
    end
  end

  describe "#update_metadata" do
    it "updates the file" do
      allow(TestMessage).to receive(:metadata_filename).and_return("fake_metadata_file.json")
      allow(TestMessage).to receive(:metadata).and_return({ "key" => "current_value" })
      expect(Chef::FileCache).to receive(:store).with(
        "fake_metadata_file.json",
        '{"key":"updated_value"}',
        0644
      )

      TestMessage.update_metadata("key", "updated_value")
    end
  end
end


text:
 package com.indeed.lsmtree.core;

/**
 * @author jplaisance
 */
public enum StorageType {
    INLINE,
    BLOCK_COMPRESSED
}


text:
define(["dojo/ready", "dojo/_base/declare", "dojo/query",  "dojo/dom-style", "dojo/_base/lang", "dojo/on", "dojo/dom", "dojo/dom-class", "dojo/dom-construct", "dijit/registry", "dijit/layout/ContentPane", "esri/arcgis/utils", "esri/dijit/Legend", "esri/layers/FeatureLayer", "esri/dijit/Scalebar", "esri/dijit/Measurement", "esri/units", "esri/IdentityManager", "application/ElevationsProfile/Widget"], function (ready, declare, dojoQuery, domStyle, lang, on, dom, domClass, domConstruct, registry, ContentPane, arcgisUtils, Legend, FeatureLayer, Scalebar, Measurement, Units, IdentityManager, ElevationsProfile) {
    return declare([], {
        config: {},
        startup: function (config) {
            this.config = config;
            //supply either the webmap id or, if available, the item info
            var itemInfo = this.config.itemInfo || this.config.webmap;
            this._createWebMap(itemInfo);

            if (config) {
                this.config = config;
                this._createWebMap(itemInfo);
            } else {
                var error = new Error("Main:: Config is not defined");
                this.reportError(error);
            }
        },
        reportError: function (error) {
            // remove loading class from body
            domClass.remove(document.body, "app-loading");
            domClass.add(document.body, "app-error");
            // an error occurred - notify the user. In this example we pull the string from the
            // resource.js file located in the nls folder because we've set the application up
            // for localization. If you don't need to support multiple languages you can hardcode the
            // strings here and comment out the call in index.html to get the localization strings.
            // set message
            var node = dom.byId("loading_message");
            if (node) {
                if (this.config && this.config.i18n) {
                    node.innerHTML = this.config.i18n.map.error + ": " + error.message;
                } else {
                    node.innerHTML = "Unable to create map: " + error.message;
                }
            }
        },
        /**
         * CREATE MAP FROM WEBMAP
         *
         * @private
         */
        _createWebMap: function (itemInfo) {
            // CREATE MAP FROM WEBMAP //
            arcgisUtils.createMap(itemInfo, "mapPane", {
                mapOptions: {
                    wrapAround180: true
                },
                editable: false,
                ignorePopups: false,
                usePopupManager:true,
                bingMapsKey: this.config.bingmapskey
            }).then(lang.hitch(this, function (response) {
                this.config.response = response;

                var descNode = null;
                if (this.config.titleInHeader) {
                    descNode = dom.byId("topContainer");
                    domStyle.set(descNode, "height", "60px");

                } else {
                    descNode = dom.byId("descriptionPane");
                    domStyle.set(dom.byId("topContainer"), "display", "none");
                }

                var titleNode = domConstruct.create("div", {
                    id: "titleNode",
                    innerHTML: response.itemInfo.item.title || ""
                }, descNode, "first");
                var snippetNode = domConstruct.create("div", {
                    id: "snippetNode",
                    innerHTML: response.itemInfo.item.snippet || ""
                }, descNode);
                registry.byId("mainContainer").layout();

                dom.byId("descriptionNode").innerHTML = response.itemInfo.item.description || "";
                registry.byId("infoContainer").layout();

                this.map = response.map;

                //Enable snapping
                this.map.enableSnapping();

                //Enable/disable popups
                if (!this.config.displaypopups) {
                    this.map.infoWindow.set("popupWindow", false);
                }

                //Map Cursor
                this.map.on("update-start", lang.hitch(this.map, this.map.setMapCursor, "wait"));
                this.map.on("update-end", lang.hitch(this.map, this.map.setMapCursor, "default"));

                var scalebar = new Scalebar({
                    map: this.map,
                    scalebarUnit: this.config.scalebarUnits || "dual"
                });

                var legendLayers = arcgisUtils.getLegendLayers(response);
                if(legendLayers && legendLayers.length > 0){
                  var legendDijit = new Legend({
                      map: this.map,
                      layerInfos: legendLayers
                  }, "legendNode");
                  legendDijit.startup();

                }

                //Create the Geocoder
                if (this.config.geocoder) {

                    //Add the location search widget
                    require(["esri/dijit/Search", "esri/tasks/locator", "dojo/_base/array", "esri/lang"], lang.hitch(this, function (Search, Locator, array, esriLang) {
                        if (!Search && !Locator) {
                            return;
                        }
                        var options = {
                            map: this.map,
                            addLayersFromMap: false
                        };
                        var searchLayers = false;
                        var search = new Search(options, domConstruct.create("div", {
                            id: "search"
                        }, "mapPane"));
                        var defaultSources = [];

                        //setup geocoders defined in common config
                        if (this.config.helperServices.geocode && this.config.locationSearch) {
                            var geocoders = lang.clone(this.config.helperServices.geocode);
                            array.forEach(geocoders, lang.hitch(this, function (geocoder) {
                                if (geocoder.url.indexOf(".arcgis.com/arcgis/rest/services/World/GeocodeServer") > -1) {

                                    geocoder.hasEsri = true;
                                    geocoder.locator = new Locator(geocoder.url);

                                    geocoder.singleLineFieldName = "SingleLine";

                                    geocoder.name = geocoder.name || "Esri World Geocoder";

                                    if (this.config.searchExtent) {
                                        geocoder.searchExtent = this.map.extent;
                                        geocoder.localSearchOptions = {
                                            minScale: 300000,
                                            distance: 50000
                                        };
                                    }
                                    defaultSources.push(geocoder);
                                } else if (esriLang.isDefined(geocoder.singleLineFieldName)) {

                                    //Add geocoders with a singleLineFieldName defined
                                    geocoder.locator = new Locator(geocoder.url);

                                    defaultSources.push(geocoder);
                                }
                            }));
                        }
                        //add configured search layers to the search widget
                        var configuredSearchLayers = (this.config.searchLayers instanceof Array) ? this.config.searchLayers : JSON.parse(this.config.searchLayers);
                        array.forEach(configuredSearchLayers, lang.hitch(this, function (layer) {

                            var mapLayer = this.map.getLayer(layer.id);
                            if (mapLayer) {
                                var source = {};
                                source.featureLayer = mapLayer;

                                if (layer.fields && layer.fields.length && layer.fields.length > 0) {
                                    source.searchFields = layer.fields;
                                    source.displayField = layer.fields[0];
                                    source.outFields = ["*"];
                                    searchLayers = true;
                                    defaultSources.push(source);
                                    if (mapLayer.infoTemplate) {
                                        source.infoTemplate = mapLayer.infoTemplate;
                                    }
                                }
                            }
                        }));
                        //Add search layers defined on the web map item
                        if (this.config.response.itemInfo.itemData && this.config.response.itemInfo.itemData.applicationProperties && this.config.response.itemInfo.itemData.applicationProperties.viewing && this.config.response.itemInfo.itemData.applicationProperties.viewing.search) {
                            var searchOptions = this.config.response.itemInfo.itemData.applicationProperties.viewing.search;

                            array.forEach(searchOptions.layers, lang.hitch(this, function (searchLayer) {
                                //we do this so we can get the title specified in the item
                                var operationalLayers = this.config.itemInfo.itemData.operationalLayers;
                                var layer = null;
                                array.some(operationalLayers, function (opLayer) {
                                    if (opLayer.id === searchLayer.id) {
                                        layer = opLayer;
                                        return true;
                                    }
                                });
                                if (layer && layer.hasOwnProperty("url")) {
                                    var source = {};
                                    var url = layer.url;
                                    var name = layer.title || layer.name;

                                    if (esriLang.isDefined(searchLayer.subLayer)) {
                                        url = url + "/" + searchLayer.subLayer;
                                        array.some(layer.layerObject.layerInfos, function (info) {
                                            if (info.id == searchLayer.subLayer) {
                                                name += " - " + layer.layerObject.layerInfos[searchLayer.subLayer].name;
                                                return true;
                                            }
                                        });
                                    }

                                    source.featureLayer = new FeatureLayer(url);

                                    source.name = name;

                                    source.exactMatch = searchLayer.field.exactMatch;
                                    source.displayField = searchLayer.field.name;
                                    source.searchFields = [searchLayer.field.name];
                                    source.placeholder = searchOptions.hintText;
                                    defaultSources.push(source);
                                    searchLayers = true;
                                }

                            }));
                        }

                        search.set("sources", defaultSources);
                        search.startup();

                        //set the first non esri layer as active if search layers are defined.
                        var activeIndex = 0;
                        if (searchLayers) {
                            array.some(defaultSources, function (s, index) {
                                if (!s.hasEsri) {
                                    activeIndex = index;
                                    return true;
                                }
                            });

                            if (activeIndex > 0) {
                                search.set("activeSourceIndex", activeIndex);
                            }
                        }

                    }));
                }

                var elevationObj = {
                    "elevationSync": {
                      "url": location.protocol + "//elevation.arcgis.com/arcgis/rest/services/Tools/ElevationSync/GPServer"
                    }
                };

                //Elevation service configured in app.
                if (this.config.elevationSync) {
                    elevationObj.elevationSync.url = this.config.elevationSync;
                    lang.mixin(this.config.helperServices, elevationObj);
                }

                //No elevation service in self call or configured. This happens in portal which doesn't have
                //an elevation service defined.
                if(!this.config.helperServices.hasOwnProperty("elevationSync")){
                    lang.mixin(this.config.helperServices, elevationObj);
                }

                var profileParams = {
                    map: this.map,
                    profileTaskUrl: this.config.helperServices.elevationSync.url,
                    scalebarUnits: this.config.scalebarUnits,
                    showHelpAtStartup: this.config.showHelpOnLoad
                };

                var elevationsProfile = new ElevationsProfile(profileParams, dom.byId("profileChartNode"));
                //Send errors to the console
                elevationsProfile.on("error", console.warn);
                //disable popups when measure tool is used.
                elevationsProfile.on("measure-distance-checked", lang.hitch(this, function (evt) {
                    if (evt.checked) {
                      this.map.setInfoWindowOnClick(false);
                    } else {
                      this.map.setInfoWindowOnClick(true);
                    }
                }));
                elevationsProfile.startup();

            }), lang.hitch(this, function (error) {
                if (this.config && this.config.i18n) {
                    alert(this.config.i18n.map.error + ": " + error.message);
                } else {
                    alert("Unable to create map: " + error.message);
                }
            }));
        }
    });
});


text:
class PlayerTurnPolicy
  def initialize(game:, active_player: nil)
    @game, @active_player = game, active_player
  end

  # Policy for determining if it is a player's turn
  def turn_of?(player)
    @game.ongoing? && active_player == player
  end

  private

  def active_player
    @active_player || GetActivePlayerService.new(game: @game).call
  end
end


text:
var mongoose = require('mongoose');
var extend = require('mongoose-schema-extend');
var Schema = mongoose.Schema;
var ad_objects = require('./additionalModels.js');
var Element = require('mongoose').model('Element').schema;
var ElementVersion = require('mongoose').model('ElementVersion').schema;
var RecordVersion = require('mongoose').model('RecordVersion').schema;

var InvasivenessAtomized = Element.extend({
	origin : String,
	presence : String,
	persistence : String,
	distribution : [String],
	harmful : String,
	modified : {type : Date, default : Date.now},
	startValidateDate : {type : Date, default : Date.now},
	endValidateDate : {type : Date, default : Date.now},
	countryCode : String,
	stateProvince : String,
	county : String,
	localityName : String,
	language : String,
	citation : String,
	abundance : String,
	trend : String,
	rateOfSpread : String,
	regulatoryListing : String,
	memo : String,
	localityType : String,
	locationValue : String,
	publicationDatePrecision : String,
	whatImpact : String,
	vector : String,
	route : String,
	target : String,
	mechanism : String
});

var Invasiveness = Element.extend({
	invasivenessAtomized : [InvasivenessAtomized],
	invasivenessUnstructured : String
},{collection: 'invasiveness'});

var InvasivenessVersion = ElementVersion.extend({
	invasiveness : Invasiveness
},{ collection: 'InvasivenessVersion' });

module.exports = mongoose.model('InvasivenessVersion', InvasivenessVersion );


text:
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace ExternalProviderAuthentication.iOS
{
	public class Application
	{
		// This is the main entry point of the application.
		static void Main (string[] args)
		{
			// if you want to use a different Application Delegate class from "AppDelegate"
			// you can specify it here.
			UIApplication.Main (args, null, "AppDelegate");
		}
	}
}


text:
package codegen_test

import (
	"bytes"
	"strconv"
	"testing"

	"github.com/corestoreio/pkg/util/assert"
	"github.com/corestoreio/pkg/util/codegen"
)

func TestNewProto(t *testing.T) {
	t.Parallel()

	g := codegen.NewProto("config")
	g.AddImport("github.com/gogo/protobuf/gogoproto/gogo.proto", "")
	g.C("These constants", "are used for testing.", "Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.")
	g.AddOptions(
		"(gogoproto.typedecl_all)", "false",
		"go_package", "dmltestgenerated",
	)

	g.Pln("message", "CoreConfigData", "{")
	g.In()
	g.Pln("uint32", "config_id", "= 1 [(gogoproto.customname)=", strconv.Quote("ConfigID"), "];")
	g.Pln(`google.protobuf.Timestamp`, `version_te`, `= 8 [(gogoproto.customname)=`, strconv.Quote(`VersionTe`), `,(gogoproto.stdtime)=true,(gogoproto.nullable)=false];`)
	g.Out()
	g.Pln("}")

	var buf bytes.Buffer
	err := g.GenerateFile(&buf)
	assert.NoError(t, err)

	assert.Exactly(t, `// Code generated by codegen. DO NOT EDIT.
syntax = "proto3";
package config;
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
option (gogoproto.typedecl_all) = dmltestgenerated;
option false = go_package;
// These constants are used for testing. Unless required by applicable law or
// agreed to in writing, software distributed under the License is distributed on
// an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions
// and limitations under the License.
message CoreConfigData {
	uint32 config_id = 1 [(gogoproto.customname)= "ConfigID" ];
	google.protobuf.Timestamp version_te = 8 [(gogoproto.customname)= "VersionTe" ,(gogoproto.stdtime)=true,(gogoproto.nullable)=false];
}
`, buf.String())
}


text:
package cmd

import (
	"crypto/rand"
	"fmt"
	"os"
	"strings"

	"github.com/coreos/etcd/clientv3"
)

var (
	// dialTotal counts the number of mustCreateConn calls so that endpoint
	// connections can be handed out in round-robin order
	dialTotal int
)

func mustCreateConn() *clientv3.Client {
	eps := strings.Split(endpoints, ",")
	endpoint := eps[dialTotal%len(eps)]
	dialTotal++
	client, err := clientv3.NewFromURL(endpoint)
	if err != nil {
		fmt.Fprintf(os.Stderr, "dial error: %v\n", err)
		os.Exit(1)
	}
	return client
}

func mustCreateClients(totalClients, totalConns uint) []*clientv3.Client {
	conns := make([]*clientv3.Client, totalConns)
	for i := range conns {
		conns[i] = mustCreateConn()
	}

	clients := make([]*clientv3.Client, totalClients)
	for i := range clients {
		clients[i] = conns[i%int(totalConns)].Clone()
	}
	return clients
}

func mustRandBytes(n int) []byte {
	rb := make([]byte, n)
	_, err := rand.Read(rb)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to generate value: %v\n", err)
		os.Exit(1)
	}
	return rb
}


text:
@interface ConcurrentProcessor ()

@property (nonatomic, assign) NSInteger computeResult;

@end

@implementation ConcurrentProcessor {
    NSString *_computeID;
    NSUInteger _computeTasks;
    NSLock *_computeLock;
}
-(instancetype)init{
    self = [super init];
    if (self) {
        _isFinished = NO;
        _computeResult = 0;
        _computeLock = [NSLock new];
        _computeID = @"1";
        _computeTasks = 0;
    }
    return self;
}

-(void)computeTask:(id)data{
    NSAssert([data isKindOfClass:[NSNumber class]], @"not an number instance");
    NSUInteger computation = [data unsignedIntegerValue];
    @autoreleasepool {
        @try {
            if ([[NSThread currentThread] isCancelled]) {
                return;
            }
            @synchronized(_computeID){
                _computeTasks++;
            }

            [_computeLock lock];
            if ([[NSThread currentThread] isCancelled]) {
                [_computeLock unlock];
                return;
            }

            for (int i = 0; i < computation; i++) {
                self.computeResult = self.computeResult + 1;
            }
            [_computeLock unlock];

            [NSThread sleepForTimeInterval:1.0f];

            @synchronized(_computeID) {
                _computeTasks--;
                if (_computeTasks == 0) {
                    self.isFinished = YES;
                }
            }
        }
        @catch (NSException *exception) {

        }
        @finally {

        }
    }
}
@end


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

#ifndef __mozilla_widget_GfxInfoCollector_h__
#define __mozilla_widget_GfxInfoCollector_h__

#include "jsapi.h"

namespace mozilla {
namespace widget {

/* this is handy wrapper around JSAPI to make it more pleasant to use.
 * We collect the JSAPI errors and so that callers don't need to */
class InfoObject
{
  friend class GfxInfoBase;

  public:
  void DefineProperty(const char *name, int value)
  {
    if (!mOk)
      return;

    mOk = JS_DefineProperty(mCx, mObj, name, INT_TO_JSVAL(value), NULL, NULL, JSPROP_ENUMERATE);
  }

  void DefineProperty(const char *name, nsAString &value)
  {
    if (!mOk)
      return;

    const nsString &flat = PromiseFlatString(value);
    JSString *string = JS_NewUCStringCopyN(mCx, static_cast<const jschar*>(flat.get()), flat.Length());
    if (!string)
      mOk = JS_FALSE;

    if (!mOk)
      return;

    mOk = JS_DefineProperty(mCx, mObj, name, STRING_TO_JSVAL(string), NULL, NULL, JSPROP_ENUMERATE);
  }

  void DefineProperty(const char *name, const char *value)
  {
    nsAutoString string = NS_ConvertASCIItoUTF16(value);
    DefineProperty(name, string);
  }

  private:
  // We need to ensure that this object lives on the stack so that GC sees it properly
  InfoObject(JSContext *aCx) : mCx(aCx), mOk(JS_TRUE)
  {
    mObj = JS_NewObject(mCx, NULL, NULL, NULL);
    if (!mObj)
      mOk = JS_FALSE;
  }
  InfoObject(InfoObject&);

  JSContext *mCx;
  JSObject *mObj;
  JSBool mOk;
};

/*

   Here's an example usage:

   class Foo {
   Foo::Foo() : mInfoCollector(this, &Foo::GetAweseomeness) {}

   void GetAwesomeness(InfoObject &obj) {
     obj.DefineProperty("awesome", mAwesome);
   }

   int mAwesome;

   GfxInfoCollector<Foo> mInfoCollector;
   }

   This will define a property on the object
   returned from calling getInfo() on a
   GfxInfo object. e.g.

       gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo);
       info = gfxInfo.getInfo();
       if (info.awesome)
          alert(info.awesome);

*/

class GfxInfoCollectorBase
{
  public:
  GfxInfoCollectorBase();
  virtual void GetInfo(InfoObject &obj) = 0;
  virtual ~GfxInfoCollectorBase();
};

template<class T>
class GfxInfoCollector : public GfxInfoCollectorBase
{
  public:
  GfxInfoCollector(T* aPointer, void (T::*aFunc)(InfoObject &obj)) : mPointer(aPointer), mFunc(aFunc) {
  }
  virtual void GetInfo(InfoObject &obj) {
    (mPointer->*mFunc)(obj);
  }

  protected:
  T* mPointer;
  void (T::*mFunc)(InfoObject &obj);

};

}
}

#endif


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors;
using Microsoft.ServiceFabric.Actors.Runtime;
using Microsoft.ServiceFabric.Actors.Client;

using FailureDetector.Interfaces;

namespace FailureDetector.Actors
{
    public class SafetyMonitor : Actor, ISafetyMonitor
    {
        private Dictionary<int, int> Pending;

        protected override async Task OnActivateAsync()
        {
            if (this.Pending == null)
            {
                this.Pending = new Dictionary<int, int>();
            }

            await base.OnActivateAsync();
        }

        public async Task NotifyPing(int senderId)
        {
            await Task.Run(() =>
            {
                if (!this.Pending.ContainsKey(senderId))
                {
                    this.Pending[senderId] = 0;
                }

                this.Pending[senderId] = this.Pending[senderId] + 1;

                ActorEventSource.Current.ActorMessage(this, "[Monitor] Notifies ping to node {0}", senderId);

                Contract.Assert(this.Pending[senderId] <= 3, "Pending set " +
                    $"for '{senderId}' contains more than 3 requests.");
            });
        }

        public async Task NotifyPong(int nodeId)
        {
            await Task.Run(() =>
            {
                ActorEventSource.Current.ActorMessage(this, "[Monitor] Notifies pong from node {0}", nodeId);

                Contract.Assert(this.Pending.ContainsKey(nodeId), "Pending " +
                $"set does not contain '{nodeId}'.");
                Contract.Assert(this.Pending[nodeId] > 0, "Pending set " +
                    $"for '{nodeId}' is empty.");
                this.Pending[nodeId] = this.Pending[nodeId] - 1;
            });
        }
    }
}


text:
import React from "react";
import clsx from "clsx";
import Link from "@docusaurus/Link";
import useBaseUrl from "@docusaurus/useBaseUrl";

import styles from "../styles/hero.module.scss";

import RoundedImage from "./RoundedImage";

const Hero = ({}) => (

                The Metadata Platform for the Modern Data Stack

                Data ecosystems are diverse — too diverse. DataHub's
                extensible metadata platform enables data discovery, data
                observability and federated governance that helps you tame this
                complexity.

              <Link
                className="button button--primary button--lg"
                to={useBaseUrl("docs/")}
              >
                Get Started →
              </Link>
              <Link
                className="button button--secondary button--outline button--lg"
                to="https://slack.datahubproject.io"
              >
                Join our Slack
              </Link>

          <RoundedImage
            img={require("/img/screenshots/entity.png")}
            alt="DataHub Entity Screenshot"
          />

);

export default Hero;


text:
package org.sakaiproject.gradebookng.tool.panels;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.Radio;
import org.apache.wicket.markup.html.form.RadioGroup;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.convert.ConversionException;
import org.apache.wicket.util.convert.IConverter;
import org.sakaiproject.gradebookng.business.GbCategoryType;
import org.sakaiproject.gradebookng.business.GradebookNgBusinessService;
import org.sakaiproject.gradebookng.business.util.FormatHelper;
import org.sakaiproject.gradebookng.tool.model.GbSettings;
import org.sakaiproject.gradebookng.tool.pages.SettingsPage;
import org.sakaiproject.service.gradebook.shared.Assignment;
import org.sakaiproject.service.gradebook.shared.CategoryDefinition;
import org.sakaiproject.service.gradebook.shared.GradebookInformation;

public class SettingsCategoryPanel extends Panel {

	private static final long serialVersionUID = 1L;

	@SpringBean(name = "org.sakaiproject.gradebookng.business.GradebookNgBusinessService")
	protected GradebookNgBusinessService businessService;

	IModel<GbSettings> model;

	boolean isDropHighest = false;
	boolean isDropLowest = false;
	boolean isKeepHighest = false;
	boolean expanded = false;

	Radio<Integer> categoriesAndWeighting;

	public SettingsCategoryPanel(final String id, final IModel<GbSettings> model, final boolean expanded) {
		super(id, model);
		this.model = model;
		this.expanded = expanded;
	}

	@Override
	public void onInitialize() {
		super.onInitialize();

		final SettingsPage settingsPage = (SettingsPage) getPage();

		// get categories, passed in
		final List<CategoryDefinition> categories = this.model.getObject().getGradebookInformation().getCategories();

		// parse the categories and see if we have any drophighest/lowest/keep highest and set the flags for the checkboxes to use
		// also build a map that we can use to add/remove from
		for (final CategoryDefinition category : categories) {

			if (category.getDropHighest() != null && category.getDropHighest() > 0) {
				this.isDropHighest = true;
			}
			if (category.getDrop_lowest() != null && category.getDrop_lowest() > 0) {
				this.isDropLowest = true;
			}
			if (category.getKeepHighest() != null && category.getKeepHighest() > 0) {
				this.isKeepHighest = true;
			}
		}

		// if categories enabled but we don't have any yet, add a default one
		if (this.model.getObject().getGradebookInformation().getCategoryType() != GbCategoryType.NO_CATEGORY.getValue()
				&& categories.isEmpty()) {
			this.model.getObject().getGradebookInformation().getCategories().add(stubCategoryDefinition());
		}

		final WebMarkupContainer settingsCategoriesPanel = new WebMarkupContainer("settingsCategoriesPanel");
		// Preserve the expand/collapse state of the panel
		settingsCategoriesPanel.add(new AjaxEventBehavior("shown.bs.collapse") {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onEvent(final AjaxRequestTarget ajaxRequestTarget) {
				settingsCategoriesPanel.add(new AttributeModifier("class", "panel-collapse collapse in"));
				SettingsCategoryPanel.this.expanded = true;
			}
		});
		settingsCategoriesPanel.add(new AjaxEventBehavior("hidden.bs.collapse") {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onEvent(final AjaxRequestTarget ajaxRequestTarget) {
				settingsCategoriesPanel.add(new AttributeModifier("class", "panel-collapse collapse"));
				SettingsCategoryPanel.this.expanded = false;
			}
		});
		if (this.expanded) {
			settingsCategoriesPanel.add(new AttributeModifier("class", "panel-collapse collapse in"));
		}
		add(settingsCategoriesPanel);

		// category types (note categoriesAndWeighting treated differently due to inter panel updates)
		final RadioGroup<Integer> categoryType = new RadioGroup<>("categoryType",
				new PropertyModel<Integer>(this.model, "gradebookInformation.categoryType"));
		final Radio<Integer> none = new Radio<>("none", new Model<>(GbCategoryType.NO_CATEGORY.getValue()));
		final Radio<Integer> categoriesOnly = new Radio<>("categoriesOnly", new Model<>(GbCategoryType.ONLY_CATEGORY.getValue()));
		this.categoriesAndWeighting = new Radio<>("categoriesAndWeighting",
				new Model<>(GbCategoryType.WEIGHTED_CATEGORY.getValue()));

		categoryType.add(none);
		categoryType.add(categoriesOnly);
		categoryType.add(this.categoriesAndWeighting);

		categoryType.setRequired(true);
		settingsCategoriesPanel.add(categoryType);

		// render category related form fields
		final WebMarkupContainer categoriesWrap = new WebMarkupContainer("categoriesWrap") {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isVisible() {
				// don't show if 'no categories' OR if course points is set
				final GradebookInformation settings = SettingsCategoryPanel.this.model.getObject().getGradebookInformation();
				return (GbCategoryType.valueOf(settings.getCategoryType()) != GbCategoryType.NO_CATEGORY
						|| settings.isCoursePointsDisplayed());
			}

		};
		categoriesWrap.setOutputMarkupPlaceholderTag(true);

		// wrapper for the options
		final WebMarkupContainer categoriesOptionsWrap = new WebMarkupContainer("categoriesOptionsWrap");

		// enable drop highest
		final AjaxCheckBox dropHighest = new AjaxCheckBox("dropHighest", Model.of(this.isDropHighest)) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onUpdate(final AjaxRequestTarget target) {
				SettingsCategoryPanel.this.isDropHighest = getModelObject();

				// reset
				if (!SettingsCategoryPanel.this.isDropHighest) {
					for (final CategoryDefinition c : SettingsCategoryPanel.this.model.getObject().getGradebookInformation()
							.getCategories()) {
						c.setDropHighest(0);
					}
					target.appendJavaScript("$('.gb-category-drophighest').hide();");
				}

				target.add(categoriesWrap);
			}
		};

		dropHighest.setOutputMarkupId(true);
		categoriesOptionsWrap.add(dropHighest);

		// enable drop lowest
		final AjaxCheckBox dropLowest = new AjaxCheckBox("dropLowest", Model.of(this.isDropLowest)) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onUpdate(final AjaxRequestTarget target) {
				SettingsCategoryPanel.this.isDropLowest = getModelObject();

				// reset
				if (!SettingsCategoryPanel.this.isDropLowest) {
					for (final CategoryDefinition c : SettingsCategoryPanel.this.model.getObject().getGradebookInformation()
							.getCategories()) {
						c.setDrop_lowest(0);
					}
					target.appendJavaScript("$('.gb-category-droplowest').hide();");
				}

				target.add(categoriesWrap);
			}
		};
		dropLowest.setOutputMarkupId(true);
		categoriesOptionsWrap.add(dropLowest);

		// enable keep highest
		final AjaxCheckBox keepHighest = new AjaxCheckBox("keepHighest", Model.of(this.isKeepHighest)) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onUpdate(final AjaxRequestTarget target) {
				SettingsCategoryPanel.this.isKeepHighest = getModelObject();

				// reset
				if (!SettingsCategoryPanel.this.isKeepHighest) {
					for (final CategoryDefinition c : SettingsCategoryPanel.this.model.getObject().getGradebookInformation()
							.getCategories()) {
						c.setKeepHighest(0);
					}
					target.appendJavaScript("$('.gb-category-keephighest').hide();");
				}

				target.add(categoriesWrap);
			}
		};
		keepHighest.setOutputMarkupId(true);
		categoriesOptionsWrap.add(keepHighest);

		// add the options wrapper
		categoriesOptionsWrap.setOutputMarkupPlaceholderTag(true);
		categoriesWrap.add(categoriesOptionsWrap);

		// When category type changes, ensure form is updated to reflect new value
		categoryType.add(new AjaxFormChoiceComponentUpdatingBehavior() {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onUpdate(final AjaxRequestTarget target) {

				// adjust visibility of items depending on category type
				final GbCategoryType type = GbCategoryType
						.valueOf(SettingsCategoryPanel.this.model.getObject().getGradebookInformation().getCategoryType());

				categoriesWrap.setVisible(type != GbCategoryType.NO_CATEGORY);
				categoriesOptionsWrap.setVisible(type != GbCategoryType.NO_CATEGORY);

				// if categories only (2), the categories table will be visible but the weighting column and tally will not
				if (type == GbCategoryType.ONLY_CATEGORY) {
					target.appendJavaScript("$('.gb-category-weight').hide();");
					target.appendJavaScript("$('.gb-category-runningtotal').hide();");
				}

				// switching to categories but we don't have any, add a default one
				if (type != GbCategoryType.NO_CATEGORY && categories.isEmpty()) {
					SettingsCategoryPanel.this.model.getObject().getGradebookInformation().getCategories().add(stubCategoryDefinition());
				}

				// if categories and weighting, disable course grade points
				final AjaxCheckBox points = settingsPage.getSettingsGradeReleasePanel().getPointsCheckBox();
				if (type == GbCategoryType.WEIGHTED_CATEGORY) {
					points.setEnabled(false);
				} else {
					points.setEnabled(true);
				}
				target.add(points);

				// reinitialize any custom behaviour
				target.appendJavaScript("sakai.gradebookng.settings.categories = new GradebookCategorySettings($('#settingsCategories'));");

				target.add(categoriesWrap);
			}
		});

		// running total
		final WebMarkupContainer runningTotalMessage = new WebMarkupContainer("runningTotalMessage");
		runningTotalMessage.setOutputMarkupPlaceholderTag(true);
		categoriesWrap.add(runningTotalMessage);
		final Label runningTotal = new Label("runningTotal");
		runningTotal.setOutputMarkupId(true);
		updateRunningTotal(runningTotal, runningTotalMessage);
		categoriesWrap.add(runningTotal);

		// categories list
		final ListView<CategoryDefinition> categoriesView = new ListView<CategoryDefinition>("categoriesView",
				this.model.getObject().getGradebookInformation().getCategories()) {

			private static final long serialVersionUID = 1L;

			/*
			 * @Override public final List<CategoryDefinition> getList() { List<CategoryDefinition> categories = super.getList();
			 *
			 * Collections.sort(categories, businessService.getCategoryOrderComparator()); return categories; }
			 */

			@Override
			protected void populateItem(final ListItem<CategoryDefinition> item) {

				final ListView<CategoryDefinition> lv = this; // reference to self

				final CategoryDefinition category = item.getModelObject();

				// note that all of these fields must have an ajaxform behaviour attached
				// so that their data is persisted into the model.
				// if they don't, when the listview repaints, they will be cleared
				// this can be either an OnChangeAjaxBehavior for those that need something to happen
				// or an AjaxFormComponentUpdatingBehavior for those that just need the data kept

				// name
				final TextField<String> name = new TextField<String>("name", new PropertyModel<String>(category, "name"));
				name.add(new AjaxFormComponentUpdatingBehavior("blur") {
					private static final long serialVersionUID = 1L;

					@Override
					protected void onUpdate(final AjaxRequestTarget target) {
					}
				});
				item.add(name);

				// weight
				final TextField<Double> weight = new TextField<Double>("weight", new PropertyModel<Double>(category, "weight")) {
					private static final long serialVersionUID = 1L;

					@SuppressWarnings("unchecked")
					@Override
					public <C> IConverter<C> getConverter(final Class<C> type) {
						return (IConverter<C>) new PercentConverter();
					}

				};

				// onchange, update the running total
				weight.add(new OnChangeAjaxBehavior() {
					private static final long serialVersionUID = 1L;

					@Override
					protected void onUpdate(final AjaxRequestTarget target) {
						updateRunningTotal(target, runningTotal, runningTotalMessage);
					}
				});
				item.add(weight);

				// num assignments
				final Label numItems = new Label("numItems", new StringResourceModel("settingspage.categories.items", null,
						new Object[] { category.getAssignmentList().size() }));
				item.add(numItems);

				// extra credit
				final CheckBox extraCredit = new CheckBox("extraCredit", new PropertyModel<Boolean>(category, "extraCredit"));
				extraCredit.setOutputMarkupId(true);

				// onchange, update the running total as extra credit items are excluded, and disable the weighting box
				extraCredit.add(new OnChangeAjaxBehavior() {
					private static final long serialVersionUID = 1L;

					@Override
					protected void onUpdate(final AjaxRequestTarget target) {
						updateRunningTotal(target, runningTotal, runningTotalMessage);
					}
				});
				item.add(extraCredit);

				// drop highest
				final TextField<Integer> categoryDropHighest = new TextField<Integer>("categoryDropHighest",
						new PropertyModel<Integer>(category, "dropHighest"));
				categoryDropHighest.setOutputMarkupId(true);
				categoryDropHighest.add(new AjaxFormComponentUpdatingBehavior("blur") {
					private static final long serialVersionUID = 1L;

					@Override
					protected void onUpdate(final AjaxRequestTarget target) {
					}
				});
				item.add(categoryDropHighest);

				// drop lowest
				final TextField<Integer> categoryDropLowest = new TextField<Integer>("categoryDropLowest",
						new PropertyModel<Integer>(category, "drop_lowest"));
				categoryDropLowest.setOutputMarkupId(true);
				categoryDropLowest.add(new AjaxFormComponentUpdatingBehavior("blur") {
					private static final long serialVersionUID = 1L;

					@Override
					protected void onUpdate(final AjaxRequestTarget target) {
					}
				});
				item.add(categoryDropLowest);

				// keep highest
				final TextField<Integer> categoryKeepHighest = new TextField<Integer>("categoryKeepHighest",
						new PropertyModel<Integer>(category, "keepHighest"));
				categoryKeepHighest.setOutputMarkupId(true);
				categoryKeepHighest.add(new AjaxFormComponentUpdatingBehavior("blur") {
					private static final long serialVersionUID = 1L;

					@Override
					protected void onUpdate(final AjaxRequestTarget target) {
					}
				});
				item.add(categoryKeepHighest);

				// remove button
				final AjaxButton remove = new AjaxButton("remove") {
					private static final long serialVersionUID = 1L;

					@Override
					public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {

						// remove this category from the model
						final CategoryDefinition current = item.getModelObject();

						SettingsCategoryPanel.this.model.getObject().getGradebookInformation().getCategories().remove(current);
						int categoryIndex = 0;
						for (final CategoryDefinition category : SettingsCategoryPanel.this.model.getObject().getGradebookInformation()
								.getCategories()) {
							category.setCategoryOrder(Integer.valueOf(categoryIndex));
							categoryIndex++;
						}

						// indicate to the listview that its model has changed and to rerender correctly
						lv.modelChanged();
						lv.removeAll();

						target.add(categoriesWrap);

						// update running total
						updateRunningTotal(target, runningTotal, runningTotalMessage);

						// reinitialize any custom behaviour
						target.appendJavaScript(
								"sakai.gradebookng.settings.categories = new GradebookCategorySettings($('#settingsCategories'));");
					}
				};
				remove.setDefaultFormProcessing(false);
				item.add(remove);

				final HiddenField<Integer> categoryOrderField = new HiddenField<Integer>("categoryOrder",
						new PropertyModel<Integer>(category, "categoryOrder"));
				/*
				 * categoryOrderField.add(new AjaxFormComponentUpdatingBehavior("orderupdate.sakai") { private static final long
				 * serialVersionUID = 1L;
				 *
				 * @Override protected void onUpdate(final AjaxRequestTarget target) { Integer categoryOrder =
				 * categoryOrderField.getValue();
				 *
				 * } });
				 */
				item.add(categoryOrderField);
			}

			@Override
			public void renderHead(final IHeaderResponse response) {
				super.renderHead(response);

				final GbCategoryType type = GbCategoryType
						.valueOf(SettingsCategoryPanel.this.model.getObject().getGradebookInformation().getCategoryType());
				if (type == GbCategoryType.ONLY_CATEGORY) {
					response.render(OnDomReadyHeaderItem.forScript("$('.gb-category-weight').hide();"));
					response.render(OnDomReadyHeaderItem.forScript("$('.gb-category-runningtotal').hide();"));
				}

				if (!SettingsCategoryPanel.this.isDropHighest) {
					response.render(OnDomReadyHeaderItem.forScript("$('.gb-category-drophighest').hide();"));
				}
				if (!SettingsCategoryPanel.this.isDropLowest) {
					response.render(OnDomReadyHeaderItem.forScript("$('.gb-category-droplowest').hide();"));
				}
				if (!SettingsCategoryPanel.this.isKeepHighest) {
					response.render(OnDomReadyHeaderItem.forScript("$('.gb-category-keephighest').hide();"));
				}
			}
		};
		categoriesView.setReuseItems(true);
		categoriesWrap.add(categoriesView);
		categoriesWrap.setOutputMarkupId(true);
		settingsCategoriesPanel.add(categoriesWrap);

		// add category button
		final AjaxButton addCategory = new AjaxButton("addCategory") {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(final AjaxRequestTarget target, final Form<?> f) {

				// add a new empty category to the model
				SettingsCategoryPanel.this.model.getObject().getGradebookInformation().getCategories().add(stubCategoryDefinition());
				target.add(categoriesWrap);

				// reinitialize any custom behaviour
				target.appendJavaScript("sakai.gradebookng.settings.categories = new GradebookCategorySettings($('#settingsCategories'));");
				// focus the new category input
				target.appendJavaScript("sakai.gradebookng.settings.categories.focusLastRow();");
			}
		};
		addCategory.setDefaultFormProcessing(false);
		categoriesWrap.add(addCategory);

	}

	/**
	 * Create a new category definition stub
	 *
	 * @return CategoryDefinition
	 */
	private CategoryDefinition stubCategoryDefinition() {
		final CategoryDefinition cd = new CategoryDefinition();
		cd.setExtraCredit(false);
		cd.setWeight(new Double(0));
		cd.setAssignmentList(Collections.<Assignment> emptyList());

		final GbSettings settings = this.model.getObject();
		cd.setCategoryOrder(settings.getGradebookInformation().getCategories().size());
		return cd;
	}

	/**
	 * Custom converter to flip between percentage for display and double for model object storage Trims off any trailing .0
	 *
	 */
	class PercentConverter implements IConverter<Double> {

		private static final long serialVersionUID = 1L;

		/**
		 * Back to object for the model.
		 *
		 * this is persisted as a fraction between 0 and 1 so for two decimal place precision in the UI we need 4 here.
		 *
		 * String will be a percentage, get it back to a decimal fraction.
		 */
		@Override
		public Double convertToObject(final String value, final Locale locale) throws ConversionException {

			// convert
			Double d;
			try {
				d = Double.valueOf(value) / 100;
			} catch (final NumberFormatException e) {
				throw new ConversionException(e).setResourceKey("settingspage.update.failure.categoryweightnumber");
			}

			// want this truncated to four decimal places, or less
			// format, then parse back into a double
			final DecimalFormat df = new DecimalFormat();
			df.setMinimumFractionDigits(0);
			df.setMaximumFractionDigits(4);
			df.setRoundingMode(RoundingMode.HALF_UP);

			final String s = df.format(d);

			try {
				return df.parse(s).doubleValue();
			} catch (final ParseException e) {
				throw new ConversionException(e).setResourceKey("settingspage.update.failure.categoryweightnumber");
			}

		}

		/**
		 * Convert to percentage for display
		 *
		 * Double will be a decimal fraction between 0 and 1 inclusive.
		 */
		@Override
		public String convertToString(final Double value, final Locale locale) {

			// set the decimal precision
			final NumberFormat df = NumberFormat.getInstance();
			df.setMinimumFractionDigits(0);
			df.setMaximumFractionDigits(2);
			df.setRoundingMode(RoundingMode.DOWN);

			// convert to percentage representation
			final Double rval = value * 100;

			return df.format(rval);
		}

	}

	/**
	 * Helper to handle the value and style updates of the running total label
	 *
	 * @param runningTotal label component to update
	 * @param runningTotalMessage error message component
	 * @return
	 */
	private void updateRunningTotal(final Component runningTotal, final Component runningTotalMessage) {

		final List<CategoryDefinition> categories = this.model.getObject().getGradebookInformation().getCategories();

		BigDecimal total = BigDecimal.ZERO;
		for (final CategoryDefinition categoryDefinition : categories) {

			Double catWeight = categoryDefinition.getWeight();
			if (catWeight == null) {
				catWeight = 0D;
			}

			BigDecimal weight = BigDecimal.valueOf(catWeight);
			if (weight == null) {
				weight = BigDecimal.ZERO;
			}

			if (!categoryDefinition.isExtraCredit()) {
				total = total.add(weight);
			}
		}

		// if comparison passes, we have '1' as the value
		if (total.compareTo(BigDecimal.ONE) == 0) {
			runningTotal.add(new AttributeModifier("class", "text-success"));
			runningTotalMessage.setVisible(false);
		} else {
			runningTotal.add(new AttributeModifier("class", "text-danger"));
			runningTotalMessage.setVisible(true);
		}

		runningTotal.setDefaultModel(Model.of(FormatHelper.formatDoubleAsPercentage(total.doubleValue() * 100)));
	}

	/**
	 * Helper to handle the value and style updates of the running total label and add to AJAX target
	 *
	 * @param target AJAX request target
	 * @param runningTotal label component to update
	 * @param runningTotalMessage error message component
	 * @return
	 */
	private void updateRunningTotal(final AjaxRequestTarget target, final Component runningTotal, final Component runningTotalMessage) {
		updateRunningTotal(runningTotal, runningTotalMessage);
		target.add(runningTotal);
		target.add(runningTotalMessage);
	}

	public boolean isExpanded() {
		return this.expanded;
	}

	// to enable inter panel comms
	Radio<Integer> getCategoriesAndWeightingRadio() {
		return this.categoriesAndWeighting;
	}
}


text:
package io.vertx.resourceadapter.impl;

import javax.resource.spi.ConfigProperty;

/**
 * @author Lin Gao <lgao@redhat.com>
 *
 */
public abstract class AbstractJcaBase {

  private final VertxPlatformConfiguration vertxPlatformConfig = new VertxPlatformConfiguration();

  /**
   * @return the clusterPort
   */
  public Integer getClusterPort() {
    return this.vertxPlatformConfig.getClusterPort();
  }

  /**
   * @param clusterPort
   *          the clusterPort to set
   */
  @ConfigProperty
  public void setClusterPort(Integer clusterPort) {
    this.vertxPlatformConfig.setClusterPort(clusterPort);
  }

  /**
   * @return the clusterHost
   */
  public String getClusterHost() {
    return this.vertxPlatformConfig.getClusterHost();
  }

  /**
   * @param clusterHost
   *          the clusterHost to set
   */
  @ConfigProperty(defaultValue = "localhost")
  public void setClusterHost(String clusterHost) {
    this.vertxPlatformConfig.setClusterHost(clusterHost);
  }

  @ConfigProperty(defaultValue = "false")
  public void setClustered(Boolean clustered){
    this.vertxPlatformConfig.setClustered(clustered);
  }

  public Boolean isClustered(){
    return this.vertxPlatformConfig.isClustered();
  }

  public VertxPlatformConfiguration getVertxPlatformConfig() {
    return this.vertxPlatformConfig;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
        + ((vertxPlatformConfig == null) ? 0 : vertxPlatformConfig.hashCode());
    return result;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    AbstractJcaBase other = (AbstractJcaBase) obj;
    if (vertxPlatformConfig == null) {
      if (other.vertxPlatformConfig != null)
        return false;
    } else if (!vertxPlatformConfig.equals(other.vertxPlatformConfig))
      return false;
    return true;
  }

}


text:
/* ==========================================================================
   Media Queries
   ========================================================================== */
/*
   =========================================================================
*/
@media only screen and (min-width: 800px) {
  /* General */
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
@media only screen and (min-width: 1024px) {
  /* General */
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
@media only screen and (min-width: 1024px) and (max-width: 1280px) {
  /* General */
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
@media only screen and (max-width: 1024px) {
  /* General */
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
@media only screen and (min-width: 640px) and (max-width: 800px) {
  /* Tables */
  /* Classic Tables */
  #myDocument .my-framework table.uk-datepicker-table {
    display: table;
  }
  #myDocument .my-framework table.uk-datepicker-table thead {
    float: none;
    display: table-header-group;
  }
  #myDocument .my-framework table.uk-datepicker-table tbody {
    display: table-row-group;
  }
  #myDocument .my-framework table.uk-datepicker-table tr {
    display: table-row;
    margin: 0;
  }
  #myDocument .my-framework table.uk-datepicker-table tr td, #myDocument .my-framework table.uk-datepicker-table tr th {
    display: table-cell;
    min-width: inherit;
    border-bottom: none;
  }
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
@media only screen and (max-width: 640px) {
  #myDocument .my-framework .uikit-component .uk-sortable > * {
    width: 49%;
    float: left;
    margin-right: 2%;
  }
  #myDocument .my-framework .uikit-component .uk-sortable > *:nth-child(2n) {
    margin-right: 0;
  }

  /* Buttons and Controls */
  #myDocument .my-framework .uikit-dropdown {
    max-width: 100%;
  }
  #myDocument .my-framework .uikit-dropdown .button {
    display: block;
    width: 100%;
  }

  #myDocument .my-framework .uikit-component.uk-button-group > a, #myDocument .my-framework .uikit-component.uk-button-group > .button {
    width: 75%;
    float: left;
  }
  #myDocument .my-framework .uikit-component.uk-button-group .uikit-dropdown {
    width: 25%;
    float: left !important;
  }
  #myDocument .my-framework .uikit-component.uk-button-group .uikit-dropdown .uikit-trigger {
    float: left;
    width: 100%;
    margin-bottom: 0;
    padding-bottom: 0.5em;
    padding-top: 0.5em;
    text-align: center;
  }
  #myDocument .my-framework .uikit-component.uk-button-group .uikit-dropdown .uikit-trigger .icon {
    float: none;
    margin: 0;
  }
  #myDocument .my-framework .uikit-component.uk-button-group .uikit-dropdown .uk-dropdown {
    min-width: 400%;
  }

  /* Tables */
  /* Classic Tables */
  #myDocument .my-framework table.uk-datepicker-table {
    display: table;
  }
  #myDocument .my-framework table.uk-datepicker-table thead {
    float: none;
    display: table-header-group;
  }
  #myDocument .my-framework table.uk-datepicker-table tbody {
    display: table-row-group;
  }
  #myDocument .my-framework table.uk-datepicker-table tr {
    display: table-row;
    margin: 0;
  }
  #myDocument .my-framework table.uk-datepicker-table tr td, #myDocument .my-framework table.uk-datepicker-table tr th {
    display: table-cell;
    min-width: inherit;
    border-bottom: none;
  }

  #myDocument .my-framework .uk-autocomplete, #myDocument .my-framework .uk-search {
    width: 100%;
  }

  #myDocument .my-framework .uikit-component .uk-search .uk-search-field {
    width: 100% !important;
  }

  #myDocument .my-framework .uikit-component .uk-htmleditor .uk-htmleditor-toolbar {
    width: 100%;
  }
  #myDocument .my-framework .uikit-component .uk-htmleditor .uk-htmleditor-navbar-flip {
    width: 100%;
  }
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
@media only screen and (max-width: 639px) {
  /* General */
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
@media only screen and (max-width: 480px) {
  /* General */
  #myDocument .my-framework .uikit-component .uk-sortable > * {
    width: 100%;
    float: none;
    margin-right: 0;
  }
  #myDocument .my-framework .uikit-component .uk-sortable > *:nth-child(2n) {
    margin-right: 0;
  }
}
/*
   =========================================================================
*/
/*
   =========================================================================
*/
/*
   =========================================================================
*/

/*# sourceMappingURL=responsive.css.map */


text:
class ExportPosition{

public:

  ExportPosition(const EmaCoilAccess& coil, const EmaInfo& info) :

    coil(coil),
    info(info) {

  }

  void to(const std::string& fileName) const {

    std::ofstream outFile(fileName);

    Json::Value jsonList(Json::arrayValue);

    for(int i = 0; i < this->info.sample_amount(); ++i) {

      Json::Value entry(Json::objectValue);
      entry["time"] = this->info.time_stamps().at(i);

      entry["x"] = this->coil.position(i)(0);
      entry["y"] = this->coil.position(i)(1);
      entry["z"] = this->coil.position(i)(2);

      jsonList.append(entry);

    }

    outFile << jsonList << std::endl;

    outFile.close();

  }

private:

  const EmaCoilAccess& coil;
  const EmaInfo& info;

};
#endif


text:
var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World from Express!');
});

app.listen(3000, function () {
  console.log('Hello World app listening on port 3000!');
});


text:
"""Extension to python-markdown to support LaTeX (rather than html) output.

Authored by Rufus Pollock: <http://www.rufuspollock.org/>
Reworked by Julian Wulfheide (ju.wulfheide@gmail.com) and
Indico Project (indico-team@cern.ch)

Usage:
======

1. Command Line. A script entitled markdown2latex.py is automatically
installed. For details of usage see help::

    $ markdown2latex.py -h

2. As a python-markdown extension::

    >>> import markdown
    >>> md = markdown.Markdown(None, extensions=['latex'])
    >>> # text is input string ...
    >>> latex_out = md.convert(text)

3. Directly as a module (slight inversion of std markdown extension setup)::

    >>> import markdown
    >>> import mdx_latex
    >>> md = markdown.Markdown()
    >>> latex_mdx = mdx_latex.LaTeXExtension()
    >>> latex_mdx.extendMarkdown(md, markdown.__dict__)
    >>> out = md.convert(text)

History
=======

Version: 1.0 (November 15, 2006)

  * First working version (compatible with markdown 1.5)
  * Includes support for tables

Version: 1.1 (January 17, 2007)

  * Support for verbatim and images

Version: 1.2 (June 2008)

  * Refactor as an extension.
  * Make into a proper python/setuptools package.
  * Tested with markdown 1.7 but should work with 1.6 and (possibly) 1.5
    (though pre/post processor stuff not as worked out there)

Version 1.3: (July 2008)
  * Improvements to image output (width)

Version 1.3.1: (August 2009)
  * Tiny bugfix to remove duplicate keyword argument and set zip_safe=False
  * Add [width=\textwidth] by default for included images

Version 2.0: (June 2011)
  * PEP8 cleanup
  * Major rework since this was broken by new Python-Markdown releases

Version 2.1: (August 2013)
  * Add handler for non locally referenced images, hyperlinks and horizontal rules
  * Update math delimiters
"""

import os
import re
import textwrap
import uuid
from io import BytesIO
from mimetypes import guess_extension
from tempfile import NamedTemporaryFile
from urllib.parse import urljoin, urlparse
from xml.etree import ElementTree as etree

import markdown
import requests
from lxml.html import html5parser
from PIL import Image
from requests.exceptions import ConnectionError, InvalidURL

__version__ = '2.1'

start_single_quote_re = re.compile(r"""(^|\s|")'""")
start_double_quote_re = re.compile(r'''(^|\s|'|`)"''')
end_double_quote_re = re.compile(r'"(,|\.|\s|$)')

Image.init()
IMAGE_FORMAT_EXTENSIONS = {format: ext for (ext, format) in Image.EXTENSION.items()}

safe_mathmode_commands = {
    'above', 'abovewithdelims', 'acute', 'aleph', 'alpha', 'amalg', 'And', 'angle', 'approx', 'arccos', 'arcsin',
    'arctan', 'arg', 'array', 'Arrowvert', 'arrowvert', 'ast', 'asymp', 'atop', 'atopwithdelims', 'backslash',
    'backslash', 'bar', 'Bbb', 'begin', 'beta', 'bf', 'Big', 'big', 'bigcap', 'bigcirc', 'bigcup', 'Bigg', 'bigg',
    'Biggl', 'biggl', 'Biggm', 'biggm', 'Biggr', 'biggr', 'Bigl', 'bigl', 'Bigm', 'bigm', 'bigodot', 'bigoplus',
    'bigotimes', 'Bigr', 'bigr', 'bigsqcup', 'bigtriangledown', 'bigtriangleup', 'biguplus', 'bigvee', 'bigwedge',
    'bmod', 'bot', 'bowtie', 'brace', 'bracevert', 'brack', 'breve', 'buildrel', 'bullet', 'cap', 'cases', 'cdot',
    'cdotp', 'cdots', 'check', 'chi', 'choose', 'circ', 'clubsuit', 'colon', 'cong', 'coprod', 'cos', 'cosh', 'cot',
    'coth', 'cr', 'csc', 'cup', 'dagger', 'dashv', 'ddagger', 'ddot', 'ddots', 'deg', 'Delta', 'delta', 'det',
    'diamond', 'diamondsuit', 'dim', 'displaylines', 'displaystyle', 'div', 'dot', 'doteq', 'dots', 'dotsb', 'dotsc',
    'dotsi', 'dotsm', 'dotso', 'Downarrow', 'downarrow', 'ell', 'emptyset', 'end', 'enspace', 'epsilon', 'eqalign',
    'eqalignno', 'equiv', 'eta', 'exists', 'exp', 'fbox', 'flat', 'forall', 'frac', 'frak', 'frown', 'Gamma', 'gamma',
    'gcd', 'ge', 'geq', 'gets', 'gg', 'grave', 'gt', 'gt', 'hat', 'hbar', 'hbox', 'hdashline', 'heartsuit', 'hline',
    'hom', 'hookleftarrow', 'hookrightarrow', 'hphantom', 'hskip', 'hspace', 'Huge', 'huge', 'iff', 'iiint', 'iint',
    'Im', 'imath', 'in', 'inf', 'infty', 'int', 'intop', 'iota', 'it', 'jmath', 'kappa', 'ker', 'kern', 'Lambda',
    'lambda', 'land', 'langle', 'LARGE', 'Large', 'large', 'LaTeX', 'lbrace', 'lbrack', 'lceil', 'ldotp', 'ldots', 'le',
    'left', 'Leftarrow', 'leftarrow', 'leftharpoondown', 'leftharpoonup', 'Leftrightarrow', 'leftrightarrow',
    'leftroot', 'leq', 'leqalignno', 'lfloor', 'lg', 'lgroup', 'lim', 'liminf', 'limits', 'limsup', 'll', 'llap',
    'lmoustache', 'ln', 'lnot', 'log', 'Longleftarrow', 'longleftarrow', 'Longleftrightarrow', 'longleftrightarrow',
    'longmapsto', 'Longrightarrow', 'longrightarrow', 'lor', 'lower', 'lt', 'lt', 'mapsto', 'mathbb', 'mathbf',
    'mathbin', 'mathcal', 'mathclose', 'mathfrak', 'mathinner', 'mathit', 'mathop', 'mathopen', 'mathord', 'mathpunct',
    'mathrel', 'mathrm', 'mathscr', 'mathsf', 'mathstrut', 'mathtt', 'matrix', 'max', 'mbox', 'mid', 'middle', 'min',
    'mit', 'mkern', 'mod', 'models', 'moveleft', 'moveright', 'mp', 'mskip', 'mspace', 'mu', 'nabla', 'natural', 'ne',
    'nearrow', 'neg', 'negthinspace', 'neq', 'newline', 'ni', 'nolimits', 'normalsize', 'not', 'notin', 'nu', 'nwarrow',
    'odot', 'oint', 'oldstyle', 'Omega', 'omega', 'omicron', 'ominus', 'oplus', 'oslash', 'otimes', 'over', 'overbrace',
    'overleftarrow', 'overleftrightarrow', 'overline', 'overrightarrow', 'overset', 'overwithdelims', 'owns',
    'parallel', 'partial', 'perp', 'phantom', 'Phi', 'phi', 'Pi', 'pi', 'pm', 'pmatrix', 'pmb', 'pmod', 'pod', 'Pr',
    'prec', 'preceq', 'prime', 'prod', 'propto', 'Psi', 'psi', 'qquad', 'quad', 'raise', 'rangle', 'rbrace', 'rbrack',
    'rceil', 'Re', 'rfloor', 'rgroup', 'rho', 'right', 'Rightarrow', 'rightarrow', 'rightharpoondown', 'rightharpoonup',
    'rightleftharpoons', 'rlap', 'rm', 'rmoustache', 'root', 'S', 'scr', 'scriptscriptstyle', 'scriptsize',
    'scriptstyle', 'searrow', 'sec', 'setminus', 'sf', 'sharp', 'Sigma', 'sigma', 'sim', 'simeq', 'sin', 'sinh', 'skew',
    'small', 'smallint', 'smash', 'smile', 'Space', 'space', 'spadesuit', 'sqcap', 'sqcup', 'sqrt', 'sqsubseteq',
    'sqsupseteq', 'stackrel', 'star', 'strut', 'subset', 'subseteq', 'succ', 'succeq', 'sum', 'sup', 'supset',
    'supseteq', 'surd', 'swarrow', 'tan', 'tanh', 'tau', 'TeX', 'text', 'textbf', 'textit', 'textrm', 'textsf',
    'textstyle', 'texttt', 'Theta', 'theta', 'thinspace', 'tilde', 'times', 'tiny', 'to', 'top', 'triangle',
    'triangleleft', 'triangleright', 'tt', 'underbrace', 'underleftarrow', 'underleftrightarrow', 'underline',
    'underrightarrow', 'underset', 'Uparrow', 'uparrow', 'Updownarrow', 'updownarrow', 'uplus', 'uproot', 'Upsilon',
    'upsilon', 'varepsilon', 'varphi', 'varpi', 'varrho', 'varsigma', 'vartheta', 'vcenter', 'vdash', 'vdots', 'vec',
    'vee', 'Vert', 'vert', 'vphantom', 'wedge', 'widehat', 'widetilde', 'wp', 'wr', 'Xi', 'xi', 'zeta', '\\'
}

class ImageURLException(Exception):
    pass

def unescape_html_entities(text):
    out = text.replace('&', '&')
    out = out.replace('<', '<')
    out = out.replace('>', '>')
    out = out.replace('"', '"')
    return out

def latex_escape(text, ignore_math=True, ignore_braces=False):
    if text is None:
        return ''

    chars = {
        '#': r'\#',
        '$': r'\$',
        '%': r'\%',
        '&': r'\&',
        '~': r'\~{}',
        '_': r'\_',
        '^': r'\^{}',
        '\\': r'\textbackslash{}',
        '\x0c': '',
        '\x0b': ''
    }

    if not ignore_braces:
        chars.update({
            '{': r'\{',
            '}': r'\}'})

    math_segments = []

    def substitute(x):
        return chars[x.group()]

    math_placeholder = f'[*LaTeXmath-{str(uuid.uuid4())}*]'

    def math_replace(m):
        math_segments.append(m.group(0))
        return math_placeholder

    if ignore_math:
        # Extract math-mode segments and replace with placeholder
        text = re.sub(r'\$[^\$]+\$|\$\$(^\$)\$\$', math_replace, text)

    pattern = re.compile('|'.join(re.escape(k) for k in chars.keys()))
    res = pattern.sub(substitute, text)

    if ignore_math:
        # Sanitize math-mode segments and put them back in place
        math_segments = list(map(sanitize_mathmode, math_segments))
        res = re.sub(re.escape(math_placeholder), lambda _: '\\protect ' + math_segments.pop(0), res)

    return res

def sanitize_mathmode(text):
    def _escape_unsafe_command(m):
        command = m.group(1)
        return m.group(0) if command in safe_mathmode_commands else r'\\' + command

    return re.sub(r'\\([a-zA-Z]+|\\)', _escape_unsafe_command, text)

def escape_latex_entities(text):
    """Escape latex reserved characters."""
    out = text
    out = unescape_html_entities(out)
    out = start_single_quote_re.sub(r'\g<1>`', out)
    out = start_double_quote_re.sub(r'\g<1>``', out)
    out = end_double_quote_re.sub(r"''\g<1>", out)

    out = latex_escape(out)

    return out

def unescape_latex_entities(text):
    """Limit ourselves as this is only used for maths stuff."""
    out = text
    out = out.replace('\\&', '&')
    return out

def latex_render_error(message):
    """Generate nice error box in LaTeX document.

    :param message: The error message
    :returns: LaTeX code for error box
    """
    return textwrap.dedent(r'''
       \begin{tcolorbox}[width=\textwidth,colback=red!5!white,colframe=red!75!black,title={Indico rendering error}]
          \begin{verbatim}%s\end{verbatim}
       \end{tcolorbox}''' % latex_escape(message))

def latex_render_image(src, alt, tmpdir, strict=False):
    """Generate LaTeX code that includes an arbitrary image from a URL.

    This involves fetching the image from a web server and figuring out its
    MIME type. A temporary file will be created, which is not immediately
    deleted since it has to be included in the LaTeX code. It should be handled
    by the enclosing code.

    :param src: source URL of the image
    :param alt: text to use as ``alt="..."``
    :param tmpdir: the directory where to put any temporary files
    :param strict: whether a faulty URL should break the whole process
    :returns: a ``(latex_code, file_path)`` tuple, containing the LaTeX code
              and path to the temporary image file.
    """
    from indico.core.config import config
    try:
        info = urlparse(src)
        if not info.scheme and not info.netloc and info.path.startswith('/'):
            # make relative links absolute
            src = urljoin(config.BASE_URL, src)
        if urlparse(src).scheme not in ('http', 'https'):
            raise ImageURLException(f'URL scheme not supported: {src}')
        else:
            try:
                resp = requests.get(src, verify=False, timeout=5)
            except InvalidURL:
                raise ImageURLException(f"Cannot understand URL '{src}'")
            except (requests.Timeout, ConnectionError):
                raise ImageURLException(f'Problem downloading image ({src})')
            except requests.TooManyRedirects:
                raise ImageURLException(f'Too many redirects downloading image ({src})')
            extension = None

            if resp.status_code != 200:
                raise ImageURLException(f'[{resp.status_code}] Error fetching image')

            if resp.headers.get('content-type'):
                extension = guess_extension(resp.headers['content-type'])
                # as incredible as it might seem, '.jpe' will be the answer in some Python environments
                if extension == '.jpe':
                    extension = '.jpg'
            if not extension:
                try:
                    # Try to use PIL to get file type
                    image = Image.open(BytesIO(resp.content))
                    # Worst case scenario, assume it's PNG
                    extension = IMAGE_FORMAT_EXTENSIONS.get(image.format, '.png')
                except OSError:
                    raise ImageURLException('Cannot read image data. Maybe not an image file?')
            with NamedTemporaryFile(prefix='indico-latex-', suffix=extension, dir=tmpdir, delete=False) as tempfile:
                tempfile.write(resp.content)
    except ImageURLException as exc:
        if strict:
            raise
        else:
            return latex_render_error(f'Could not include image: {exc}'), None

    # Using graphicx and ajustbox package for *max width*
    return (textwrap.dedent(r'''
        \begin{figure}[H]
          \centering
          \includegraphics[max width=\linewidth]{%s}
          \caption{%s}
        \end{figure}
        ''' % (os.path.basename(tempfile.name), latex_escape(alt))), tempfile.name)

def makeExtension(configs=None):
    return LaTeXExtension(configs=configs)

class LaTeXExtension(markdown.Extension):
    def __init__(self, configs=None):
        self.configs = configs
        self.reset()

    def extendMarkdown(self, md, md_globals):
        self.md = md

        # remove escape pattern -- \\(.*) -- as this messes up any embedded
        # math and we don't need to escape stuff any more for html
        self.md.inlinePatterns.deregister('escape')

        latex_tp = LaTeXTreeProcessor(self.configs)
        math_pp = MathTextPostProcessor()
        link_pp = LinkTextPostProcessor()
        unescape_html_pp = UnescapeHtmlTextPostProcessor()

        md.treeprocessors.register(latex_tp, 'latex', md.treeprocessors._priority[-1].priority - 1)
        md.postprocessors.register(unescape_html_pp, 'unescape_html', md.postprocessors._priority[-1].priority - 1)
        md.postprocessors.register(math_pp, 'math', md.postprocessors._priority[-1].priority - 1)
        md.postprocessors.register(link_pp, 'link', md.postprocessors._priority[-1].priority - 1)

        # Needed for LaTeX postprocessors not to choke on URL-encoded urls
        md.inlinePatterns.register(NonEncodedAutoMailPattern(markdown.inlinepatterns.AUTOMAIL_RE, md), 'automail', 110)

    def reset(self):
        pass

class NonEncodedAutoMailPattern(markdown.inlinepatterns.Pattern):
    """Reimplementation of AutoMailPattern to avoid URL-encoded links."""

    def handleMatch(self, m):
        el = etree.Element('a')
        email = self.unescape(m.group(2))
        email.removeprefix('mailto:')
        el.text = markdown.util.AtomicString(''.join(email))
        el.set('href', f'mailto:{email}')
        return el

class LaTeXTreeProcessor(markdown.treeprocessors.Treeprocessor):
    def __init__(self, configs):
        self.configs = configs

    def run(self, doc):
        """
        Walk the dom converting relevant nodes to text nodes with relevant
        content.
        """
        latex_text = self.tolatex(doc)
        doc.clear()
        doc.text = latex_text

    def tolatex(self, ournode):
        buffer = ''
        subcontent = ''

        if ournode.text:
            subcontent += escape_latex_entities(ournode.text)

        for child in ournode:
            subcontent += self.tolatex(child)

        if ournode.tag == 'h1':
            buffer += '\n\n\\section{%s}\n' % subcontent
        elif ournode.tag == 'h2':
            buffer += '\n\n\\subsection{%s}\n' % subcontent
        elif ournode.tag == 'h3':
            buffer += '\n\\subsubsection{%s}\n' % subcontent
        elif ournode.tag == 'h4':
            buffer += '\n\\paragraph{%s}\n' % subcontent
        elif ournode.tag == 'hr':
            buffer += r'\noindent\makebox[\linewidth]{\rule{\paperwidth}{0.4pt}}'
        elif ournode.tag == 'ul':
            # no need for leading \n as one will be provided by li
            buffer += '''
\\begin{itemize}%s
\\end{itemize}
''' % subcontent
        elif ournode.tag == 'ol':
            # no need for leading \n as one will be provided by li
            buffer += '''
\\begin{enumerate}%s
\\end{enumerate}
''' % subcontent
        elif ournode.tag == 'li':
            buffer += '''
  \\item %s''' % subcontent.strip()
        elif ournode.tag == 'blockquote':
            # use quotation rather than quote as quotation can support multiple
            # paragraphs
            buffer += '''
\\begin{quotation}
%s
\\end{quotation}
''' % subcontent.strip()
        # ignore 'code' when inside pre tags
        # (mkdn produces

)
        elif (ournode.tag == 'pre' or (ournode.tag == 'pre' and ournode.parentNode.tag != 'pre')):
            buffer += '''
\\begin{verbatim}
%s
\\end{verbatim}
''' % subcontent.strip()
        elif ournode.tag == 'q':
            buffer += "`%s'" % subcontent.strip()
        elif ournode.tag == 'p':
            if self.configs.get('apply_br'):
                subcontent = subcontent.replace('\n', '\\\\\\relax\n')
            buffer += '\n%s\n' % subcontent.strip()
        elif ournode.tag == 'strong':
            buffer += '\\textbf{%s}' % subcontent.strip()
        elif ournode.tag == 'em':
            buffer += '\\emph{%s}' % subcontent.strip()
        elif ournode.tag in ('table', 'thead', 'tbody', 'tr', 'th', 'td'):
            raise RuntimeError('Unexpected table in markdown data for LaTeX')
        elif ournode.tag == 'img':
            buffer += latex_render_image(ournode.get('src'), ournode.get('alt'), tmpdir=self.configs.get('tmpdir'))[0]
        elif ournode.tag == 'a':
            # this one gets escaped in convert_link_to_latex
            buffer += '{}'.format(ournode.get('href'), subcontent)
        else:
            buffer = subcontent

        if ournode.tail:
            buffer += escape_latex_entities(ournode.tail)

        return buffer

class UnescapeHtmlTextPostProcessor(markdown.postprocessors.Postprocessor):

    def run(self, text):
        return unescape_html_entities(text)

# ========================= MATH =================================

class MathTextPostProcessor(markdown.postprocessors.Postprocessor):

    def run(self, instr):
        """
        Convert all math sections in {text} whether latex, asciimathml or
        latexmathml formatted to latex.

        This assumes you are using $$ as your mathematics delimiter (*not* the
        standard asciimathml or latexmathml delimiter).
        """
        def repl_1(matchobj):
            text = unescape_latex_entities(matchobj.group(1))
            tmp = text.strip()
            if tmp.startswith('\\[') or tmp.startswith('\\begin'):
                return text
            else:
                return '\\[%s\\]\n' % text

        def repl_2(matchobj):
            text = unescape_latex_entities(matchobj.group(1))
            return f'${text}${matchobj.group(2)}'

        # $$ ..... $$
        pat = re.compile(r'^\$\$([^$]*)\$\$\s*$', re.MULTILINE)
        out = pat.sub(repl_1, instr)
        # Jones, $x=3$, is ...
        pat3 = re.compile(r'\$([^$]+)\$(\s|$)')
        out = pat3.sub(repl_2, out)
        # # $100 million
        # pat2 = re.compile('([^\$])\$([^\$])')
        # out = pat2.sub('\g<1>\\$\g<2>', out)
        # some extras due to asciimathml
        # out = out.replace('\\lt', '<')
        # out = out.replace(' * ', ' \\cdot ')
        # out = out.replace('\\del', '\\partial')
        return out

# ========================== LINKS =================================

class LinkTextPostProcessor(markdown.postprocessors.Postprocessor):
    def run(self, instr):
        new_blocks = [re.sub(r']*>([^<]+)', lambda m: convert_link_to_latex(m.group(0)).strip(), block)
                      for block in instr.split('\n\n')]
        return '\n\n'.join(new_blocks)

def convert_link_to_latex(instr):
    dom = html5parser.fragment_fromstring(instr)
    return '\\href{%s}{%s}' % (latex_escape(dom.get('href'), ignore_math=True), dom.text)