text:
/* ==========================================================================
   $BASE-DATE-PICKER
   ========================================================================== */
/**
 * The picker box.
 */
div.wpforms-container .wpforms-form .picker__box {
  padding: 0 1em;
}
/**
 * The header containing the month and year stuff.
 */
div.wpforms-container .wpforms-form .picker__header {
  text-align: center;
  position: relative;
  margin-top: .75em;
}
/**
 * The month and year labels.
 */
div.wpforms-container .wpforms-form .picker__month,
div.wpforms-container .wpforms-form .picker__year {
  font-weight: 500;
  display: inline-block;
  margin-left: .25em;
  margin-right: .25em;
}
div.wpforms-container .wpforms-form .picker__year {
  color: #999999;
  font-size: .8em;
  font-style: italic;
}
/**
 * The month and year selectors.
 */
div.wpforms-container .wpforms-form .picker__select--month,
div.wpforms-container .wpforms-form .picker__select--year {
  border: 1px solid #b7b7b7;
  height: 2em;
  padding: .5em;
  margin-left: .25em;
  margin-right: .25em;
}
@media (min-width: 24.5em) {
  div.wpforms-container .wpforms-form .picker__select--month,
  div.wpforms-container .wpforms-form .picker__select--year {
    margin-top: -0.5em;
  }
}
div.wpforms-container .wpforms-form .picker__select--month {
  width: 35%;
}
div.wpforms-container .wpforms-form .picker__select--year {
  width: 22.5%;
}
div.wpforms-container .wpforms-form .picker__select--month:focus,
div.wpforms-container .wpforms-form .picker__select--year:focus {
  border-color: #0089ec;
}
/**
 * The month navigation buttons.
 */
div.wpforms-container .wpforms-form .picker__nav--prev,
div.wpforms-container .wpforms-form .picker__nav--next {
  position: absolute;
  padding: .5em 1.25em;
  width: 1em;
  height: 1em;
  box-sizing: content-box;
  top: -0.25em;
}
@media (min-width: 24.5em) {
  div.wpforms-container .wpforms-form .picker__nav--prev,
  div.wpforms-container .wpforms-form .picker__nav--next {
    top: -0.33em;
  }
}
div.wpforms-container .wpforms-form .picker__nav--prev {
  left: -1em;
  padding-right: 1.25em;
}
@media (min-width: 24.5em) {
  div.wpforms-container .wpforms-form .picker__nav--prev {
    padding-right: 1.5em;
  }
}
div.wpforms-container .wpforms-form .picker__nav--next {
  right: -1em;
  padding-left: 1.25em;
}
@media (min-width: 24.5em) {
  div.wpforms-container .wpforms-form .picker__nav--next {
    padding-left: 1.5em;
  }
}
div.wpforms-container .wpforms-form .picker__nav--prev:before,
div.wpforms-container .wpforms-form .picker__nav--next:before {
  content: " ";
  border-top: .5em solid transparent;
  border-bottom: .5em solid transparent;
  border-right: 0.75em solid #000000;
  width: 0;
  height: 0;
  display: block;
  margin: 0 auto;
}
div.wpforms-container .wpforms-form .picker__nav--next:before {
  border-right: 0;
  border-left: 0.75em solid #000000;
}
div.wpforms-container .wpforms-form .picker__nav--prev:hover,
div.wpforms-container .wpforms-form .picker__nav--next:hover {
  cursor: pointer;
  color: #000000;
  background: #b1dcfb;
}
div.wpforms-container .wpforms-form .picker__nav--disabled,
div.wpforms-container .wpforms-form .picker__nav--disabled:hover,
div.wpforms-container .wpforms-form .picker__nav--disabled:before,
div.wpforms-container .wpforms-form .picker__nav--disabled:before:hover {
  cursor: default;
  background: none;
  border-right-color: #f5f5f5;
  border-left-color: #f5f5f5;
}
/**
 * The calendar table of dates
 */
div.wpforms-container .wpforms-form .picker__table {
  text-align: center;
  border-collapse: collapse;
  border-spacing: 0;
  table-layout: fixed;
  font-size: inherit;
  width: 100%;
  margin-top: .75em;
  margin-bottom: .5em;
}
@media (min-height: 33.875em) {
  div.wpforms-container .wpforms-form .picker__table {
    margin-bottom: .75em;
  }
}
div.wpforms-container .wpforms-form .picker__table td {
  margin: 0;
  padding: 0;
}
/**
 * The weekday labels
 */
div.wpforms-container .wpforms-form .picker__weekday {
  width: 14.285714286%;
  font-size: .75em;
  padding-bottom: .25em;
  color: #999999;
  font-weight: 500;
  /* Increase the spacing a tad */
}
@media (min-height: 33.875em) {
  div.wpforms-container .wpforms-form .picker__weekday {
    padding-bottom: .5em;
  }
}
/**
 * The days on the calendar
 */
div.wpforms-container .wpforms-form .picker__day {
  padding: .3125em 0;
  font-weight: 200;
  border: 1px solid transparent;
}
div.wpforms-container .wpforms-form .picker__day--today {
  position: relative;
}
div.wpforms-container .wpforms-form .picker__day--today:before {
  content: " ";
  position: absolute;
  top: 2px;
  right: 2px;
  width: 0;
  height: 0;
  border-top: 0.5em solid #0059bc;
  border-left: .5em solid transparent;
}
div.wpforms-container .wpforms-form .picker__day--disabled:before {
  border-top-color: #aaaaaa;
}
div.wpforms-container .wpforms-form .picker__day--outfocus {
  color: #dddddd;
}
div.wpforms-container .wpforms-form .picker__day--infocus:hover,
div.wpforms-container .wpforms-form .picker__day--outfocus:hover {
  cursor: pointer;
  color: #000000;
  background: #b1dcfb;
}
div.wpforms-container .wpforms-form .picker__day--highlighted {
  border-color: #0089ec;
}
div.wpforms-container .wpforms-form .picker__day--highlighted:hover,
div.wpforms-container .wpforms-form .picker--focused .picker__day--highlighted {
  cursor: pointer;
  color: #000000;
  background: #b1dcfb;
}
div.wpforms-container .wpforms-form .picker__day--selected,
div.wpforms-container .wpforms-form .picker__day--selected:hover,
div.wpforms-container .wpforms-form .picker--focused .picker__day--selected {
  background: #0089ec;
  color: #ffffff;
}
div.wpforms-container .wpforms-form .picker__day--disabled,
div.wpforms-container .wpforms-form .picker__day--disabled:hover,
div.wpforms-container .wpforms-form .picker--focused .picker__day--disabled {
  background: #f5f5f5;
  border-color: #f5f5f5;
  color: #dddddd;
  cursor: default;
}
div.wpforms-container .wpforms-form .picker__day--highlighted.picker__day--disabled,
div.wpforms-container .wpforms-form .picker__day--highlighted.picker__day--disabled:hover {
  background: #bbbbbb;
}
/**
 * The footer containing the "today", "clear", and "close" buttons.
 */
div.wpforms-container .wpforms-form .picker__footer {
  text-align: center;
}
div.wpforms-container .wpforms-form .picker__button--today,
div.wpforms-container .wpforms-form .picker__button--clear,
div.wpforms-container .wpforms-form .picker__button--close {
  border: 1px solid #ffffff;
  background: #ffffff;
  font-size: .8em;
  padding: .66em 0;
  font-weight: bold;
  width: 33%;
  display: inline-block;
  vertical-align: bottom;
}
div.wpforms-container .wpforms-form .picker__button--today:hover,
div.wpforms-container .wpforms-form .picker__button--clear:hover,
div.wpforms-container .wpforms-form .picker__button--close:hover {
  cursor: pointer;
  color: #000000;
  background: #b1dcfb;
  border-bottom-color: #b1dcfb;
}
div.wpforms-container .wpforms-form .picker__button--today:focus,
div.wpforms-container .wpforms-form .picker__button--clear:focus,
div.wpforms-container .wpforms-form .picker__button--close:focus {
  background: #b1dcfb;
  border-color: #0089ec;
  outline: none;
}
div.wpforms-container .wpforms-form .picker__button--today:before,
div.wpforms-container .wpforms-form .picker__button--clear:before,
div.wpforms-container .wpforms-form .picker__button--close:before {
  position: relative;
  display: inline-block;
  height: 0;
}
div.wpforms-container .wpforms-form .picker__button--today:before,
div.wpforms-container .wpforms-form .picker__button--clear:before {
  content: " ";
  margin-right: .45em;
}
div.wpforms-container .wpforms-form .picker__button--today:before {
  top: -0.05em;
  width: 0;
  border-top: 0.66em solid #0059bc;
  border-left: .66em solid transparent;
}
div.wpforms-container .wpforms-form .picker__button--clear:before {
  top: -0.25em;
  width: .66em;
  border-top: 3px solid #ee2200;
}
div.wpforms-container .wpforms-form .picker__button--close:before {
  content: "\D7";
  top: -0.1em;
  vertical-align: top;
  font-size: 1.1em;
  margin-right: .35em;
  color: #777777;
}
div.wpforms-container .wpforms-form .picker__button--today[disabled],
div.wpforms-container .wpforms-form .picker__button--today[disabled]:hover {
  background: #f5f5f5;
  border-color: #f5f5f5;
  color: #dddddd;
  cursor: default;
}
div.wpforms-container .wpforms-form .picker__button--today[disabled]:before {
  border-top-color: #aaaaaa;
}

/* ==========================================================================
   $CLASSIC-DATE-PICKER
   ========================================================================== */


text:
namespace ReactiveDomain.Messaging.Bus
{
    public interface IPublisher
    {
        /// <summary>
        /// Publishes a Message
        /// Does not block
        /// </summary>
        /// <param name="message">the message to publish</param>
        void Publish(IMessage message);
    }

    /// <summary>
    /// Marks <see cref="IPublisher"/> as being OK for
    /// cross-thread publishing (e.g. in replying to envelopes).
    /// </summary>
    public interface IThreadSafePublisher
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace PedidosBundle\Dto;
use JMS\Serializer\Annotation\Type;

/**
 * Created by PhpStorm.
 * User: martin
 * Date: 10/30/17
 * Time: 15:32 PM
 */
class SugerenciaDto
{
    /**
     * @var int
     * @Type("int")
     */
    public $id;

    /**
     * @var string
     * @Type("string")
     */
    public $status;

    /**
     * @var string
     * @Type("string")
     */
    public $nombre;

    /**
     * @var string
     * @Type("string")
     */
    public $descripcion;

    /**
     * @var double
     * @Type("double")
     */
    public $precio;

    /**
     * @var MenuItemDto
     * @Type("PedidosBundle\Dto\MenuItemDto")
     */
    public $itemDeMenu;

    /**
     * @var int
     * @Type("int")
     */
    public $cantidadDisponible;

    /**
     * @var string
     * @Type("string")
     */
    public $fechaInicio;

    /**
     * @var string
     * @Type("string")
     */
    public $fechaFin;

    /**
     * @var string
     * @Type("string")
     */
    public $fechaCreacion;

    /**
     * @var string
     * @Type("string")
     */
    public $fechaUltimaModificacion;

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

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @param string $status
     */
    public function setStatus($status)
    {
        $this->status = $status;
    }

    /**
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * @param string $nombre
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;
    }

    /**
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * @param string $descripcion
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;
    }

    /**
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * @param float $precio
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;
    }

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

    /**
     * @param int $cantidadDisponible
     */
    public function setCantidadDisponible($cantidadDisponible)
    {
        $this->cantidadDisponible = $cantidadDisponible;
    }

    /**
     * @return string
     */
    public function getFechaInicio()
    {
        return $this->fechaInicio;
    }

    /**
     * @param string $fechaInicio
     */
    public function setFechaInicio($fechaInicio)
    {
        $this->fechaInicio = $fechaInicio;
    }

    /**
     * @return string
     */
    public function getFechaFin()
    {
        return $this->fechaFin;
    }

    /**
     * @param string $fechaFin
     */
    public function setFechaFin($fechaFin)
    {
        $this->fechaFin = $fechaFin;
    }

    /**
     * @return string
     */
    public function getFechaCreacion()
    {
        return $this->fechaCreacion;
    }

    /**
     * @param string $fechaCreacion
     */
    public function setFechaCreacion($fechaCreacion)
    {
        $this->fechaCreacion = $fechaCreacion;
    }

    /**
     * @return string
     */
    public function getFechaUltimaModificacion()
    {
        return $this->fechaUltimaModificacion;
    }

    /**
     * @param string $fechaUltimaModificacion
     */
    public function setFechaUltimaModificacion($fechaUltimaModificacion)
    {
        $this->fechaUltimaModificacion = $fechaUltimaModificacion;
    }

    /**
     * @return MenuItemDto
     */
    public function getItemDeMenu()
    {
        return $this->itemDeMenu;
    }

    /**
     * @param MenuItemDto $itemDeMenu
     */
    public function setItemDeMenu($itemDeMenu)
    {
        $this->itemDeMenu = $itemDeMenu;
    }

}


text:
import React from 'react';
import { TreeSelectProps } from './interface';
export { TreeSelectProps };
declare const _default: React.ComponentClass<TreeSelectProps>;
export default _default;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 56(4,5): 295 (1915)

#### Original name
Ganoderma rugosum var. nigrozonatum Bres.

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RiceDoctor.FuzzyManager;
using RiceDoctor.InferenceEngine;
using RiceDoctor.OntologyManager;
using RiceDoctor.RuleManager;
using RiceDoctor.Shared;
using RiceDoctor.WebApp.Models;
using static RiceDoctor.InferenceEngine.ResponseType;
using static RiceDoctor.OntologyManager.GetType;
using JsonConvert = Newtonsoft.Json.JsonConvert;
using Request = RiceDoctor.InferenceEngine.Request;
using RequestType = RiceDoctor.InferenceEngine.RequestType;

namespace RiceDoctor.WebApp.Controllers
{
    public class AdvisoryController : Controller
    {
        private readonly IFuzzyManager _fuzzyManager;
        private readonly IOntologyManager _ontologyManager;
        private readonly IRuleManager _ruleManager;

        private readonly JsonSerializerSettings jsonSettings =
            new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.All};

        public AdvisoryController(
            [FromServices] [NotNull] IRuleManager ruleManager,
            [FromServices] [NotNull] IOntologyManager ontologyManager,
            [FromServices] [NotNull] IFuzzyManager fuzzyManager)
        {
            Check.NotNull(ruleManager, nameof(ruleManager));
            Check.NotNull(ontologyManager, nameof(ontologyManager));
            Check.NotNull(fuzzyManager, nameof(fuzzyManager));

            _ruleManager = ruleManager;
            _ontologyManager = ontologyManager;
            _fuzzyManager = fuzzyManager;
        }

        public IActionResult Index()
        {
            ViewData["Problems"] = _ruleManager.Problems;
            ViewData["Classes"] = _ontologyManager.GetSubClasses("Thing", GetAll);
            ViewData["Individuals"] = _ontologyManager.GetIndividuals();
            ViewData["FuzzyVariables"] = _fuzzyManager.Variables;

            var guid = Guid.NewGuid().ToString();
            var advisory = new Advisory {Guid = guid};
            HttpContext.Session.SetString(guid, JsonConvert.SerializeObject(advisory, jsonSettings));

            return View(advisory);
        }

        [HttpPost]
        public IActionResult SelectProblem(
            string guid,
            int problemId,
            List<string> inputs,
            List<string> fuzzyInputs,
            List<string> fuzzyValues,
            List<string> outputs)
        {
            if (string.IsNullOrWhiteSpace(guid))
                return RedirectToAction("Error", "Home", new {error = CoreStrings.MalformedArgument(nameof(guid))});
            guid = guid.Trim();

            if (inputs == null && (fuzzyValues == null || fuzzyValues.All(string.IsNullOrWhiteSpace)))
                return RedirectToAction("Error", "Home", new {error = CoreStrings.MalformedArgument(nameof(inputs))});
            var facts = new List<Fact>();
            foreach (var input in inputs)
            {
                var individual = _ontologyManager.GetIndividual(input);
                if (individual == null)
                    return RedirectToAction("Error", "Home", new {error = $"Individual \"{input}\" not found."});
                facts.Add(new IndividualFact(individual.GetDirectClass().Id, individual.Id));
            }

            if (fuzzyValues != null && !fuzzyValues.All(string.IsNullOrWhiteSpace))
                for (var i = 0; i < fuzzyValues.Count; ++i)
                {
                    if (string.IsNullOrWhiteSpace(fuzzyValues[i])) continue;
                    if (!double.TryParse(fuzzyValues[i].Trim(), out var number))
                        return RedirectToAction("Error", "Home",
                            new {error = CoreStrings.MalformedArgument(nameof(fuzzyValues))});

                    facts.Add(new FuzzyFact(fuzzyInputs[i], number));
                }

            if (problemId < -1 || problemId >= _ruleManager.Problems.Count)
                return RedirectToAction("Error", "Home",
                    new {error = CoreStrings.MalformedArgument(nameof(problemId))});
            Problem problem;
            if (problemId == -1)
            {
                if (outputs == null || outputs.Count == 0)
                    return RedirectToAction("Error", "Home",
                        new {error = CoreStrings.MalformedArgument(nameof(outputs))});
                var allTypes = new Dictionary<string, Class>();

                var goalTypes = new List<Class>();
                foreach (var output in outputs)
                {
                    if (!allTypes.TryGetValue(output, out Class goalType))
                    {
                        goalType = _ontologyManager.GetClass(output);
                        if (goalType == null)
                            return RedirectToAction("Error", "Home", new {error = CoreStrings.NonexistentType(output)});
                        allTypes.Add(output, goalType);
                    }
                    goalTypes.Add(goalType);
                }

                var suggestTypes = new List<Class>();
                foreach (var fact in facts)
                {
                    if (!allTypes.TryGetValue(fact.Name, out Class suggestType))
                    {
                        suggestType = _ontologyManager.GetClass(fact.Name);
                        if (suggestType == null)
                            return RedirectToAction("Error", "Home",
                                new {error = CoreStrings.NonexistentType(fact.Name)});
                        allTypes.Add(fact.Name, suggestType);
                    }
                    suggestTypes.Add(suggestType);
                }

                problem = new Problem("General", goalTypes, suggestTypes, true);
            }
            else
            {
                problem = _ruleManager.Problems[problemId];
            }

            var advisory = JsonConvert.DeserializeObject<Advisory>(HttpContext.Session.GetString(guid), jsonSettings);
            advisory.Request = new Request(problem, RequestType.IndividualFact);
            advisory.Engine = new Engine(_ruleManager, _ontologyManager, _fuzzyManager, advisory.Request);
            advisory.Engine.AddFactsToKnown(true, facts.ToArray());

            ((Engine) advisory.Engine)._ontologyManager = null;
            ((Engine) advisory.Engine)._ruleManager = null;
            ((Engine) advisory.Engine)._fuzzyManager = null;
            HttpContext.Session.SetString(guid, JsonConvert.SerializeObject(advisory, jsonSettings));

            return Infer(guid);
        }

        [HttpPost]
        public IActionResult GuessableFact(string guid, IReadOnlyCollection<Fact> guessableFacts)
        {
            if (string.IsNullOrWhiteSpace(guid))
                return RedirectToAction("Error", "Home", new {error = CoreStrings.MalformedArgument(nameof(guid))});
            guid = guid.Trim();

            if (guessableFacts == null)
                return RedirectToAction("Error", "Home",
                    new {error = CoreStrings.MalformedArgument(nameof(guessableFacts))});

            var advisory = JsonConvert.DeserializeObject<Advisory>(HttpContext.Session.GetString(guid), jsonSettings);
            ((Engine) advisory.Engine)._ontologyManager = _ontologyManager;
            ((Engine) advisory.Engine)._ruleManager = _ruleManager;
            ((Engine) advisory.Engine)._fuzzyManager = _fuzzyManager;

            if (guessableFacts.Count == 0) return View("Infer");

            ViewData["GuessableFacts"] = guessableFacts.ToList();

            return View("GuessableFact", advisory);
        }

        [HttpPost]
        public IActionResult Infer(string guid, IReadOnlyCollection<GuessableFact> guessableFacts = null)
        {
            if (string.IsNullOrWhiteSpace(guid))
                return RedirectToAction("Error", "Home", new {error = CoreStrings.MalformedArgument(nameof(guid))});
            guid = guid.Trim();

            var advisory = JsonConvert.DeserializeObject<Advisory>(HttpContext.Session.GetString(guid), jsonSettings);
            ((Engine) advisory.Engine)._ontologyManager = _ontologyManager;
            ((Engine) advisory.Engine)._ruleManager = _ruleManager;
            ((Engine) advisory.Engine)._fuzzyManager = _fuzzyManager;

            if (guessableFacts != null)
            {
                var facts = new List<Tuple<Fact, bool?>>();
                foreach (var fact in guessableFacts)
                {
                    if (string.IsNullOrWhiteSpace(fact.ClassName))
                        return RedirectToAction("Error", "Home",
                            new {error = CoreStrings.MalformedArgument(nameof(fact.ClassName))});
                    fact.ClassName = fact.ClassName.Trim();

                    if (string.IsNullOrWhiteSpace(fact.IndividualName))
                        return RedirectToAction("Error", "Home",
                            new {error = CoreStrings.MalformedArgument(nameof(fact.IndividualName))});
                    fact.IndividualName = fact.IndividualName.Trim();

                    bool? exist = null;
                    if (fact.IsGuessable == 1) exist = true;
                    else if (fact.IsGuessable == 0) exist = false;
                    else if (fact.IsGuessable != -1)
                        return RedirectToAction("Error", "Home",
                            new {error = CoreStrings.MalformedArgument(nameof(fact.IsGuessable))});

                    facts.Add(new Tuple<Fact, bool?>(new IndividualFact(fact.ClassName, fact.IndividualName), exist));
                }

                advisory.Engine.HandleGuessableFacts(facts);
            }

            var response = advisory.Engine.Infer();

            ((Engine) advisory.Engine)._ontologyManager = null;
            ((Engine) advisory.Engine)._ruleManager = null;
            ((Engine) advisory.Engine)._fuzzyManager = null;
            HttpContext.Session.SetString(guid, JsonConvert.SerializeObject(advisory, jsonSettings));

            switch (response.Type)
            {
                case AskGuessableFacts:
                    return GuessableFact(guid, response.GuessableFacts);
                case ShowCompleteResults:
                    ViewData["CompleteResults"] = response.ResultFacts.OrderByDescending(r => r.Value).ToList();
                    break;
                case ShowIncompleteResults:
                    ViewData["IncompleteResults"] = response.ResultFacts.OrderByDescending(r => r.Value).ToList();
                    break;
            }

            return View("Infer");
        }
    }
}


text:
fm.Package("jfm.hash");
fm.AbstractClass("HashChange");
jfm.hash.HashChange = function (me){this.setMe=function(_me){me=_me;};

	function onHashChange(){
		var hash = location.hash.substring(1);
		var found = false;
		var hashArr = hash.split("/"), s, keyValue = {};
		for(var k=0; k < me.route.length; k++){
			s = me.route[k].path.split("/");
			if(s.length == hashArr.length){
				for(var i= 0; i < s.length; i++){
					if(s[i] == hashArr[i]){
						continue;
					}else if(s[i].indexOf(":") == 0){
						keyValue[s[i].substring(1)] = hashArr[i];
						continue;
					}
					else {
						break;
					}
				}
				if(i == s.length){
					me.onUrlChange( me.route[k], keyValue );
					found = true;
					break;
				}
			}
		}
		if(!found && me.defaultRoute){
			location.hash = me.defaultRoute;
		}
	}

	this.activateCurrent = function () {
		onHashChange();
	};
	function setTemplates(){
        $("[fm-controller]").each(function(){
            var controller = fm.isExist(this.getAttribute('fm-controller'));
            var url = "" + controller.getClass();
            controller.setTemplate(this,  url);
            new jfm.dom.DomManager($(this), new controller);
         });
    }
    var currentView;

    var oldKeyValue;
    this.onUrlChange = function(url, keyValue){
        if(currentView && url.view.toString() === currentView.toString() ){
            currentView.onChange(keyValue, oldKeyValue);
            oldKeyValue = keyValue;
            return;
        }else if(currentView){
            currentView.onStop();
        }
        var view = new url.view(keyValue);
        view.onStart(keyValue);
        currentView = view;
    };

	this.HashChange = function(  ) {
		this.route = [];
		this.defaultRoute = "";
		window.onhashchange = onHashChange
		setTemplates();
	};
};


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/transparent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.project.quiz.activities.ActivityHomeScreen">

</RelativeLayout>


text:
layout: post
title: HTTPS proof comes to Prebid and all its adaptors

description: Prebid.js and all its adaptors now fully support HTTPS.

permalink: /blog/prebid-https

---

### Background

Many publishers require their users load some of, or all of their pages securely via HTTPS. The main motivation for HTTPS is authentication of the visited website and protection of the privacy and integrity of the exchanged data. [source](https://en.wikipedia.org/wiki/HTTPS).

### What does it mean that HTTPS has come to Prebid and all its adaptors?

**1. Prebid.js library can be loaded securely via HTTPS.**

When the prebid.js library is loaded securely via HTTPS, it will auto ensure the adaptors are also loaded securely via HTTPS. The adaptors should also return the bid responses and ads securely via HTTPS.

**2. All adaptors that Prebid.js supports can be loaded securely.**

Some adaptors may load external Javascript. During the prebid.js adaptor certification process, we ensure these external Javascript are also loaded securely via HTTPS.

**3. All bid responses and ads returned by the adaptors are via HTTPS.**

When a page is loaded securely via HTTPS, all the data exchange and communication have to be in HTTPS. This includes the data coming back from the servers as well.

### How to turn on HTTPS for prebid?

Load prebid.js library via HTTPS. [All examples](/dev-docs/examples/basic-example.html) documented on Prebid.org provide examples for how to load prebid.js via HTTPS.


text:
<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<script>
  var p = Object.create(HTMLElement.prototype);
  p.createdCallback = function() {
    console.warn(this.localName, 'created');
  }
  p.attachedCallback = function() {
    this.report();
  }
  p.report = function() {
    console.group(this.localName, 'report');
    console.log('offsetParent is', this.offsetParent);
    console.log('parentNode', this.parentNode, 'has position',
      window.getComputedStyle(this.parentNode).position);
    console.groupEnd(this.localName);
  }
  document.registerElement('some-thing', {prototype: p});
</script>


text:
Get the version of your computer's _globally_ installed Sails command-line tool (i.e. the version you installed with `npm install -g sails`).

```usage
sails --version
```

### Example

```text
$ sails --version
1.0.0
```

### Notes
> + Different Sails apps can have different local Sails installs at different versions, since each project encapsulates its dependencies in its `node_modules/` folder.  To get the _locally_ installed version of Sails from within a particular project, run `npm ls sails`.

<docmeta name="displayName" value="sails --version">
<docmeta name="pageType" value="command">


text:
#include "GameObject.h"
#include "Window.h"
#include <SDL_render.h>
#include "TextureLocator.h"
using Framework::GameObject;

GameObject::GameObject(const std::string& objectID) : ObjectID(objectID), Frame(0), TotalFrames(1), ImageWidth(0), ImageHeight(0) {}

GameObject::~GameObject() {}

bool GameObject::Initialise()
{
	// Query dimensions
	if (!TextureID.empty() && TotalFrames != 0)
	{
		SDL_QueryTexture(Textures->Find(TextureID), nullptr, nullptr, &ImageWidth, &ImageHeight);
		ImageWidth /= TotalFrames;
	}

	return true;
}

void GameObject::Terminate()
{

}

void GameObject::Update()
{

}

void GameObject::Render()
{
	if (!TextureID.empty())
	{
		SDL_Rect scrRect;
		SDL_Rect destRect;

		scrRect.x = ImageWidth * Frame;
		scrRect.y = 0;
		scrRect.w = destRect.w = ImageWidth;
		scrRect.h = destRect.h = ImageHeight;
		destRect.x = static_cast<int>(Position.x) - 0;
		destRect.y = static_cast<int>(Position.y) - 0;

		SDL_RenderCopyEx(Window->GetRenderer(), Textures->Find(TextureID), &scrRect, &destRect, 0, nullptr, SDL_RendererFlip::SDL_FLIP_NONE);
	}
}


text:
<?php

namespace Google\AdsApi\Examples\Dfp\v201705\CustomFieldService;

require '../../../../vendor/autoload.php';

use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Dfp\DfpServices;
use Google\AdsApi\Dfp\DfpSession;
use Google\AdsApi\Dfp\DfpSessionBuilder;
use Google\AdsApi\Dfp\Util\v201705\StatementBuilder;
use Google\AdsApi\Dfp\v201705\CustomFieldService;

/**
 * This example gets all custom fields.
 *
 * <p>It is meant to be run from a command line (not as a webpage) and requires
 * that you've setup an `adsapi_php.ini` file in your home directory with your
 * API credentials and settings. See README.md for more info.
 */
class GetAllCustomFields {

  public static function runExample(DfpServices $dfpServices,
      DfpSession $session) {
    $customFieldService =
        $dfpServices->get($session, CustomFieldService::class);

    // Create a statement to select custom fields.
    $pageSize = StatementBuilder::SUGGESTED_PAGE_LIMIT;
    $statementBuilder = (new StatementBuilder())
        ->orderBy('id ASC')
        ->limit($pageSize);

    // Retrieve a small amount of custom fields at a time, paging
    // through until all custom fields have been retrieved.
    $totalResultSetSize = 0;
    do {
      $page = $customFieldService->getCustomFieldsByStatement(
          $statementBuilder->toStatement());

      // Print out some information for each custom field.
      if ($page->getResults() !== null) {
        $totalResultSetSize = $page->getTotalResultSetSize();
        $i = $page->getStartIndex();
        foreach ($page->getResults() as $customField) {
          printf(
              "%d) Custom field with ID %d and name '%s' was found.\n",
              $i++,
              $customField->getId(),
              $customField->getName()
          );
        }
      }

      $statementBuilder->increaseOffsetBy($pageSize);
    } while ($statementBuilder->getOffset() < $totalResultSetSize);

    printf("Number of results found: %d\n", $totalResultSetSize);
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new DfpSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();

    self::runExample(new DfpServices(), $session);
  }
}

GetAllCustomFields::main();


text:
INIT_LOG_LEVEL_INFO

STRING_KEY(PPDeviceRegistryAddedPusher);
STRING_KEY(PPDeviceRegistryUpdatedPusher);
STRING_KEY(PPDeviceRegistryRemovedPusher);

static const int32_t kDiscoveryPort = 7331;
static const int32_t kDisconnectTimeout = 10;
static const int64_t kExpiryTimerInterval = 1;

static int64_t gTotalPower = 0;
static int64_t gTotalPowerLimit = -1;
static float gPowerScale = 1.0;
static BOOL gAutoThrottle = NO;
static PPDeviceRegistry *gSharedRegistry;

@interface PPDeviceRegistry () <GCDAsyncUdpSocketDelegate> {
	NSMutableDictionary *_pusherMap;
}
@property (nonatomic, strong) NSMutableDictionary *pusherLastSeenMap;
@property (nonatomic, strong) NSMutableDictionary *groupMap;
@property (nonatomic, strong) NSMutableOrderedSet *sortedPushers;
@property (nonatomic, strong) NSMutableArray *stripsCache;

@property (nonatomic, strong) GCDAsyncUdpSocket	*discoverySocket;
@property (nonatomic, strong) PPScene *scene;

@end

@implementation PPDeviceRegistry

+ (PPDeviceRegistry*)sharedRegistry {
	if (!gSharedRegistry) gSharedRegistry = PPDeviceRegistry.new;
	return gSharedRegistry;
}

- (int64_t)totalPower {
	return gTotalPower;
}

- (void)setTotalPowerLimit:(int64_t)powerLimit {
	gTotalPowerLimit = powerLimit;
}

- (int64_t)totalPowerLimit {
	return gTotalPowerLimit;
}

- (float)powerScale {
	return gPowerScale;
}

- (void)setExtraDelay:(NSTimeInterval)delay {
	[self.scene setExtraDelay:delay];
}

- (void)setFrameDelegate:(id<PPFrameDelegate>)frameDelegate {
	self.scene.frameDelegate = frameDelegate;
}

- (void)setAutoThrottle:(BOOL)autothrottle {
	gAutoThrottle = autothrottle;
	[self.scene setAutoThrottle:autothrottle];
}

- (void)setGlobalBrightness:(float)globalBrightness {
	self.scene.globalBrightness = globalBrightness;
}

- (float)globalBrightness {
	return self.scene.globalBrightness;
}

- (int64_t)getTotalBandwidth {
	return self.scene.totalBandwidth;
}

- (BOOL)record {
	return self.scene.record;
}

- (void)setRecord:(BOOL)record {
	self.scene.record = record;
}

- (id)init
{
    self = [super init];
    if (self) {
		self.frameRateLimit = 60;
		_pusherMap = NSMutableDictionary.new;
		self.groupMap = NSMutableDictionary.new;
		self.sortedPushers = NSMutableOrderedSet.new;
		self.pusherLastSeenMap = NSMutableDictionary.new;
		self.scene = PPScene.new;

		[self bind];

		// monitor pushers' timeouts
		[NSTimer scheduledTimerWithTimeInterval:kExpiryTimerInterval
										 target:self
									   selector:@selector(deviceExpiryTask:)
									   userInfo:nil
										repeats:YES];

		[NSNotificationCenter.defaultCenter addObserver:self
											   selector:@selector(appDidBackground)
												   name:UIApplicationDidEnterBackgroundNotification
												 object:nil];
		[NSNotificationCenter.defaultCenter addObserver:self
											   selector:@selector(appDidActivate)
												   name:UIApplicationDidBecomeActiveNotification
												 object:nil];

    }
    return self;
}

- (void)appDidActivate {
	// delay 1s in case we were switched in from another PP app
	[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(bind) userInfo:nil repeats:NO];
}

- (void)appDidBackground {
//	[self unbind];
}

- (void)bind {
	if (!self.discoverySocket) {
		// setup the discovery service
		self.discoverySocket = [GCDAsyncUdpSocket.alloc initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
		[self.discoverySocket setIPv6Enabled:NO];
		NSError *error;
		[self.discoverySocket enableReusePort:YES error:&error];
		if (error) {
			[NSException raise:NSGenericException format:@"error enabling reuse port on discovery port: %@", error];
		}
		[self.discoverySocket enableBroadcast:YES error:&error];
		if (error) {
			[NSException raise:NSGenericException format:@"error enabling broadcast on discovery port: %@", error];
		}
		[self.discoverySocket bindToPort:kDiscoveryPort error:&error];
		if (error) {
			UIAlertView *alert = [UIAlertView.alloc initWithTitle:@"PixelPusher"
														  message:@"Another PixelPusher app is preventing me from finding PixelPushers.  Be a lamb and kill it for me?"
														 delegate:nil
												cancelButtonTitle:@"Sure thing, honey"
												otherButtonTitles:nil, nil];
			[alert show];
			return;
//			self.discoverySocket = nil;
		}
		[self.discoverySocket beginReceiving:&error];
		if (error) {
			[NSException raise:NSGenericException format:@"error beginning receive on discovery port: %@", error];
		}
	}
}

- (void)unbind {
	if (self.discoverySocket) {
		[self.discoverySocket close];
		self.discoverySocket = nil;
	}
}

- (NSArray*)strips {
	if (!self.stripsCache) {
		self.stripsCache = NSMutableArray.new;
		[self.sortedPushers forEach:^(PPPixelPusher *pusher, NSUInteger idx, BOOL *stop) {
			[self.stripsCache addObjectsFromArray:pusher.strips];
		}];
	}
	return self.stripsCache;
}

- (NSArray*)pushers {
	return self.sortedPushers.array;
}

- (NSArray*)pushersInGroup:(int32_t)groupNumber {
	NSMutableArray *pushers = NSMutableArray.new;
	[self.sortedPushers forEach:^(PPPixelPusher *pusher, NSUInteger idx, BOOL *stop) {
		if (pusher.groupOrdinal == groupNumber) [pushers addObject:pusher];
	}];
	return pushers;
}

- (NSArray*)stripsInGroup:(int32_t)groupNumber {
	id group = self.groupMap[@(groupNumber)];

	if (group != nil)	return [group strips];
	else				return @[];
}

- (void)deviceExpiryTask:(NSTimer*)timer {
	NSMutableArray *toKill = NSMutableArray.new;
	[self.pusherMap forEach:^(NSString *deviceMac, PPPixelPusher *pusher, BOOL *stop) {
		NSTimeInterval lastSeenSeconds = fabs( [self.pusherLastSeenMap[deviceMac] timeIntervalSinceNow] );
		if (lastSeenSeconds > kDisconnectTimeout) [toKill addObject:deviceMac];
	}];
	[toKill forEach:^(NSString *doomedIndividual, NSUInteger idx, BOOL *stop) {
		[self expireDevice:doomedIndividual];
	}];
}

- (void)expireDevice:(NSString*)macAddr {
	DDLogInfo(@"Device gone: %@", macAddr);
	PPPixelPusher *pusher = self.pusherMap[macAddr];
	if (pusher) {
		[_pusherMap removeObjectForKey:macAddr];
		[self.pusherLastSeenMap removeObjectForKey:macAddr];
		[self.sortedPushers removeObject:pusher];
		self.stripsCache = nil;
		[self.groupMap[@(pusher.groupOrdinal)] removePusher:pusher];
		if (self.scene.isRunning) [self.scene removePusher:pusher];

		[NSNotificationCenter.defaultCenter postNotificationName:PPDeviceRegistryRemovedPusher object:pusher];
	}
}

- (void)setStrip:(NSString*)macAddress index:(int32_t)stripNumber pixels:(NSArray*)pixels {
//	[self.pusherMap[macAddress] setStrip:stripNumber pixels:pixels];
}

- (void)startPushing {
	if (!self.scene.isRunning) [self.scene start];
}

- (void)stopPushing {
	if (self.scene.isRunning) [self.scene cancel];
}

- (void)receive:(NSData*)data {
    // This is for the UDP callback, this should not be called directly
	PPDeviceHeader *header = [PPDeviceHeader.alloc initWithPacket:data];
	NSString *macAddr = header.macAddressString;
	if (header.deviceType != ePixelPusher) {
		DDLogInfo(@"Ignoring non-PixelPusher discovery packet from %@", header);
		return;
	}
	PPPixelPusher *device = [PPPixelPusher.alloc initWithHeader:header];
	DDLogVerbose(@"squitter %@", device);
	// Set the timestamp for the last time this device checked in
	self.pusherLastSeenMap[macAddr] = NSDate.date;
	if (!self.pusherMap[macAddr]) {
		// We haven't seen this device before
		[self addNewPusher:device macAddress:macAddr];
	} else {
		PPPixelPusher *existing = self.pusherMap[macAddr];
		if (![existing isEqualToPusher:device]) { // we already saw it
			[self updatePusher:device macAddress:macAddr];
		} else {
			// The device is identical, nothing has changed
			DDLogVerbose(@"Device still present: %@", existing.ipAddress);
			// if we dropped more than occasional packets, slow down a little
			if (device.deltaSequence > 3) {
				DDLogInfo(@"packet loss %lld on %@", device.deltaSequence, existing.ipAddress);
				[existing increaseExtraDelay:0.002];
			} else if (device.deltaSequence < 1) {
				[existing decreaseExtraDelay:0.001];
			}
		}
	}

	// update the power limit variables
	if (gTotalPowerLimit > 0) {
		gTotalPower = 0;
		[self.sortedPushers forEach:^(PPPixelPusher *pusher, NSUInteger idx, BOOL *stop) {
			gTotalPower += pusher.powerTotal;
		}];
		if (gTotalPower > gTotalPowerLimit) {
			gPowerScale = gTotalPowerLimit / gTotalPower;
		} else {
			gPowerScale = 1.0;
		}
	}
}

- (void)updatePusher:(PPPixelPusher*)device macAddress:(NSString*)macAddr {
	// We already knew about this device at the given MAC, but its details
	// have changed
	DDLogVerbose(@"Device changed: %@", macAddr);
	PPPixelPusher *pusher = self.pusherMap[macAddr];
	[pusher copyHeader:device];
	[self.sortedPushers sortUsingComparator:self.pusherComparator];

	// NOTE: dispatch on main queue if ever udp receive is handled on non-main queue
	[NSNotificationCenter.defaultCenter postNotificationName:PPDeviceRegistryUpdatedPusher object:pusher];
}

- (void)addNewPusher:(PPPixelPusher*)pusher macAddress:(NSString*)macAddr {
	// tell the pusher to finish allocating itself
	[pusher allocateStrips];
	DDLogInfo(@"new pusher: %@", pusher);
	DDLogVerbose(@"New device: %@ has group ordinal %d", macAddr, pusher.groupOrdinal);
	_pusherMap[macAddr] = pusher;
	[self.sortedPushers addObject:pusher];
	// TODO: would be nice to use a tree-based set that inserts in sort order
	[self.sortedPushers sortUsingComparator:self.pusherComparator];
	self.stripsCache = nil;

	if (self.groupMap[@(pusher.groupOrdinal)] != nil) {
		DDLogVerbose(@"Adding pusher to group %d", pusher.groupOrdinal);
		[self.groupMap[@(pusher.groupOrdinal)] addPusher:pusher];
	} else {
		// we need to create a PusherGroup since it doesn't exist yet.
		PPPusherGroup *pg = PPPusherGroup.new;
		DDLogVerbose(@"Creating group and adding pusher to group %d", pusher.groupOrdinal);
		[pg addPusher:pusher];
		self.groupMap[@(pusher.groupOrdinal)] = pg;
	}
	pusher.autoThrottle = gAutoThrottle;

	[NSNotificationCenter.defaultCenter postNotificationName:PPDeviceRegistryAddedPusher object:pusher];
}

- (NSComparator)pusherComparator {
	return ^NSComparisonResult(PPPixelPusher *obj1, PPPixelPusher *obj2) {
		int32_t group0 = obj1.groupOrdinal;
		int32_t group1 = obj2.groupOrdinal;
		if (group0 != group1) {
			if (group0 < group1) return NSOrderedAscending;
			return NSOrderedDescending;
		}

		int32_t ord1 = obj1.controllerOrdinal;
		int32_t ord2 = obj2.controllerOrdinal;
		if (ord1 != ord2) {
			if (ord1 < ord2) return NSOrderedAscending;
			return NSOrderedDescending;
		}

		return [obj1.macAddress compare:obj2.macAddress];
	};
}

#pragma mark - GCDAsyncUdpSocketDelegate methods

- (void)udpSocket:(GCDAsyncUdpSocket *)sock
   didReceiveData:(NSData *)data
	  fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
	[self receive:data];
}

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error {
	DDLogError(@"updSocketDidClose: %@", error);
}

@end


text:
function outbreak_historgram(div,div_input,r0){
    //special functions
    var poisson = function(mean){
        var L = Math.exp(-mean);
        var p = 1.0;
        var k = 0;

        do {
            k++;
            p *= Math.random();
        } while (p > L);

        return (k - 1);

    }

    var bernoulli = function(p){
        return(Math.random() < p)
    }

    var outbreak_simulation = function(r0,generations){
        var sim_generation = function(xs){
            // xs - number in previous generation
            if (xs == 0){
                return 0;
            } else {
                var ns = 0;
                for(var i=0;i<xs;i++){
                    ns += poisson(r0);
                }
            }
            return(ns);
        }
        // set initial outbreak size
        var x_prev = 1;
        var n = x_prev;
        //simulate each generation to maximum number of generations
        for(i=0;i<generations;i++){
            x_prev = sim_generation(x_prev);
            n += x_prev;
        }
        return(x_prev);
    }

    var color = "steelblue";
    var dur_ms = 200;

    // Generate a 10 data points using outbreak simulation
    var values = d3.range(10).map(function(x){return outbreak_simulation(r0, 3)});

    // A formatter for counts.
    var formatCount = d3.format(",.0f");

    var width = d3.select(div).node().getBoundingClientRect().width,
        height = 0.5*width,
        margin = {top: 20, right: 30, bottom: 30, left: 40};

    // var margin = {top: 20, right: 30, bottom: 30, left: 30},
    //     width = 960 - margin.left - margin.right,
    //     height = 500 - margin.top - margin.bottom;

    var max = d3.max(values);
    var min = d3.min(values);
    var x = d3.scale.linear()
          .domain([0, 100])
          .range([0, width]);

    // Generate a histogram using twenty uniformly-spaced bins.
    var data = d3.layout.histogram()
        .bins(x.ticks(100))
        (values);

    var yMax = d3.max(data, function(d){return d.length});
    var yMin = d3.min(data, function(d){return d.length});
    var colorScale = d3.scale.linear()
                .domain([yMin, yMax])
                .range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);

    var y = d3.scale.linear()
        .domain([0, yMax])
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(function(d, i) {
            if(d!="100"){
                return d;
            }else{
                return ">100";
            }

        });

    var svg = d3.select(div).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var bar = svg.selectAll(".bar")
        .data(data)
      .enter().append("g")
        .attr("class", "bar")
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    bar.append("rect")
        .attr("x", 1)
        .attr("width", (x(data[0].dx) - x(0)) - 1)
        .attr("height", function(d) { return height - y(d.y); })
        .attr("fill", function(d) { return colorScale(d.y) });

    // bar.append("text")
    //     .attr("dy", ".75em")
    //     .attr("y", -12)
    //     .attr("x", (x(data[0].dx) - x(0)) / 2)
    //     .attr("text-anchor", "middle")
    //     .text(function(d) { return formatCount(d.y); });

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);
    // Add title
    svg.append("text")
        .attr("x", (width / 2))
        .attr("y", 0 + (margin.top)/2)
        .attr("text-anchor", "middle")
        .style("font-size", "16px")
        .text("Distribution of simulated outbreaks");
    /*
    * Adding refresh method to reload new data
    */
    function refresh_histogram(values){
      // var values = d3.range(1000).map(d3.random.normal(20, 5));
      var data = d3.layout.histogram()
        .bins(x.ticks(100))
        (values);

      // Reset y domain using new data
      var yMax = d3.max(data, function(d){return d.length});
      var yMin = d3.min(data, function(d){return d.length});
      y.domain([0, yMax]);

      // Reset x domain using new Data
      //var max = d3.max(values);
      //var min = d3.min(values);
      //x.domain([min, max]);

      var colorScale = d3.scale.linear()
                  .domain([yMin, yMax])
                  .range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);

      var bar = svg.selectAll(".bar").data(data);

      // Remove object with data
      bar.exit().remove();

      bar.transition()
        .duration(dur_ms)
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

      bar.select("rect")
          .transition()
          .duration(dur_ms)
          .attr("height", function(d) { return height - y(d.y); })
          .attr("fill", function(d) { return colorScale(d.y) });

      // bar.select("text")
      //     .transition()
      //     .duration(dur_ms)
      //     .text(function(d) { return formatCount(d.y); });

    }

    // Calling refresh repeatedly.
    setInterval(function() {
      if(values.length < 10000){
          values = values.concat(d3.range(100).map(
              function(x){
                  return outbreak_simulation(r0, 3);
              }))
          refresh_histogram(values);
    }
    }, dur_ms);

    // update r0 on change in slider
    document.getElementById(div_input).oninput = function() {
      $('#'+div_input+"-label").text('R0: '+(this.value/100).toFixed(2));
      r0 = this.value/100;
      values = d3.range(10).map(function(x){return outbreak_simulation(r0, 3)});
    }

    //Line chart mouse over
    var mlistener = svg.append('svg:rect')
        .attr('width', width) // the whole width of g/svg
        .attr('height', height) // the whole heigh of g/svg
        .attr('fill', 'none')
        .attr('pointer-events', 'all');

    var vertical = svg
      .append("path")
      .attr("class", "remove").style({stroke:'#000', 'stroke-width': '1px', 'pointer-events': 'none'});

      var vertical_text = svg
                       .append("text")
                       .text("");

    mlistener.on("mousemove", function(){
       mousex = d3.mouse(this);
       vertical.style("display", null).attr("d", function () {
       var d = "M" + mousex[0] + "," + (height);
       d += " " + mousex[0] + "," + 0;
       return d;
    });

    vertical_text
        .style("display", null)
        .style("opacity",1)
        .attr("x", mousex[0]+10)
        .attr("y", mousex[1]+10)
        .text(function(){
            var osize = x.invert(mousex[0]);
            var prob = values.map(function(n){return n> osize})
                .reduce((previous, current) => current += previous);
                var prob = 100*prob/values.length;
                return("Prob. of outbreak greater\n than "+osize.toFixed(0) + " is " + prob.toFixed(0)+"%")
            }());

    }).on("mouseout", function(){
       mousex = d3.mouse(this);
       mousex = mousex[0] + 5;
       vertical.style("display", "none");
       vertical_text.style("display", "none")
        .style("opacity",0);
   });

}

var div = "#outbreak-simulation";
var r0 = 2.5;
var div_input = "input-outbreakr0";
outbreak_historgram(div,div_input,r0);


text:
@interface PodsDummy_Pods_QwikJson_Example : NSObject
@end
@implementation PodsDummy_Pods_QwikJson_Example
@end


text:
"""Deprecated cros_sdk wrapper"""

from __future__ import print_function

import os
import sys

def main():
  # Bypass all of chromite_wrappers attempted 'help', and execve to the actual
  # cros_sdk wrapper/helper chromite has.
  location = os.path.dirname(os.path.abspath(__file__))
  location = os.path.join(location, 'cros_sdk')
  os.execv(location, [location] + sys.argv[1:])

if __name__ == '__main__':
  main()


text:
<?php

namespace Cosma\SimpleStateMachine\Tests\Example\States;

use Cosma\SimpleStateMachine\AbstractState;
use Cosma\SimpleStateMachine\Tests\Example\Price;

class Subst10 extends AbstractState
{

    /**
     * @return string
     */
    public function getLabel()
    {
        return 'Subst 10';
    }

    /**
     * @return mixed|void
     */
    protected function process()
    {
        /** @var Price $price */
        $price = $this->getData();
        $price->setValue($price->getValue() - 10);
    }

    protected function configureAvailableTransitions()
    {}
}


text:
typedef void(^EventSaveCompletionBlockType)(BOOL);

@interface MGCEventKitSupport : NSObject

@property (nonatomic, readonly) EKEventStore *eventStore;
@property (nonatomic, readonly) BOOL accessGranted;

- (instancetype)initWithEventStore:(EKEventStore*)eventStore;
- (void)checkEventStoreAccessForCalendar:(void (^)(BOOL accessGranted))completion;
- (void)saveEvent:(EKEvent*)event completion:(void (^)(BOOL saved))completion;
- (EKSource*)sourceInEventStore:(EKSourceType)type title:(NSString*)title;
- (EKCalendar*)calendarWithTitle:(NSString*)title type:(EKCalendarType)type eventType:(EKEntityType)eventType;

@end

@interface MGCEKEventViewController: EKEventViewController

@end


text:
layout: page
title: Diamond Media Party
date: 2016-05-24
author: Catherine Floyd
tags: weekly links, java
status: published
summary: Aenean sed pellentesque arcu. Vivamus vitae.
banner: images/banner/people.jpg
booking:
  startDate: 01/03/2018
  endDate: 01/04/2018
  ctyhocn: BNTRGHX
  groupCode: DMP
published: true
---
Duis hendrerit viverra purus, eget rutrum erat tincidunt nec. Mauris varius ligula et rhoncus dapibus. Donec ipsum est, posuere in rhoncus viverra, pretium nec sem. Sed ultrices urna risus, sit amet eleifend magna condimentum ullamcorper. Integer vitae ligula nisl. Donec interdum mauris ornare justo rhoncus rhoncus. Etiam eu orci eu elit elementum posuere. Integer quis vulputate eros, fringilla vehicula enim. Ut eget feugiat tortor. Curabitur ullamcorper sapien quis orci fermentum pretium. Sed finibus ut lorem ac porta. Mauris iaculis leo sit amet arcu hendrerit, eu vestibulum orci varius. Nunc eleifend sed leo ut pellentesque. Praesent facilisis hendrerit odio non laoreet.

* Sed dapibus metus dignissim erat sagittis mollis
* Nullam quis lacus congue, hendrerit magna ac, condimentum ex
* Morbi sodales lacus lacinia, elementum dolor a, cursus magna
* Aenean consectetur massa vel mauris mattis consectetur
* Nullam cursus libero id ante venenatis, et tempus nulla facilisis
* Aenean egestas arcu eu ex tempus ornare.

Vestibulum mattis eleifend ex scelerisque iaculis. Phasellus pulvinar sapien accumsan elementum elementum. Fusce semper massa tristique mauris finibus tincidunt. Maecenas vel interdum libero. In metus purus, sollicitudin sed venenatis id, porttitor sed turpis. Sed auctor luctus eros sit amet elementum. Suspendisse laoreet arcu eu lorem viverra, nec posuere libero ultricies.
Nulla facilisis convallis mauris facilisis blandit. Phasellus nulla nibh, vehicula vitae erat in, tempus sodales tortor. Nulla dignissim erat ac nibh vestibulum, consectetur suscipit ex cursus. Duis ultrices hendrerit tincidunt. Donec dignissim lorem purus, non tincidunt augue condimentum ut. Nulla et tempus odio, a pharetra risus. In nulla est, gravida non tincidunt sit amet, feugiat vitae ipsum. Cras vel erat enim. Donec eu dui in odio finibus iaculis. Pellentesque et urna et lorem commodo ullamcorper eu eu ipsum. Sed libero enim, luctus sed elementum sit amet, pretium at tortor. Quisque quis quam sit amet ante lacinia pulvinar auctor a ante. Mauris rhoncus euismod dapibus. Phasellus in est faucibus, mattis mi id, efficitur dolor. Proin venenatis pretium lacinia.


text:
/**
    To run from command line:

    node get-story username password projectId storyId

    https://www.pivotaltracker.com/help/api/rest/v5#Story
*/
var tracker  = require("../index.js"),
    username = process.argv[2],
    password = process.argv[3],
    projectId = process.argv[4],
    storyId = process.argv[5];

tracker.getToken(username, password, function(err, token) {

    if(err){
        console.error("Could not retrieve token");
        console.log(err);
    }
    else {
        var client = new tracker.Client({trackerToken:token});

        if (storyId) {

            client.project(projectId).story(storyId).get(function(error, story) {

                if (error) {
                    console.log(error);
                }
                else {
                    console.log(story);
                }
            });
        }
        else {

            client.project(projectId).stories.all(function(error, stories) {

                if (error) {
                    console.log(error);
                }
                else {
                    console.log(stories);
                }
            });
        }
    }
});


text:
"""TFX components module."""

# Components.
from tfx.components.bulk_inferrer.component import BulkInferrer
from tfx.components.evaluator.component import Evaluator
from tfx.components.example_diff.component import ExampleDiff
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
from tfx.components.example_gen.import_example_gen.component import ImportExampleGen
from tfx.components.example_validator.component import ExampleValidator
from tfx.components.infra_validator.component import InfraValidator
from tfx.components.pusher.component import Pusher
from tfx.components.schema_gen.component import SchemaGen
from tfx.components.schema_gen.import_schema_gen.component import ImportSchemaGen
from tfx.components.statistics_gen.component import StatisticsGen
from tfx.components.trainer.component import Trainer
from tfx.components.transform.component import Transform
from tfx.components.tuner.component import Tuner

# For UDF needs.
# pylint: disable=g-bad-import-order
from tfx.components.trainer.fn_args_utils import DataAccessor
from tfx.components.trainer.fn_args_utils import FnArgs
from tfx.components.tuner.component import TunerFnResult
# pylint: enable=g-bad-import-order


text:
PEAR_ErrorStack->getErrorMessage() no errors
--SKIPIF--
<?php
if (!getenv('PHP_PEAR_RUNTESTS')) {
    echo 'skip';
}
?>
--FILE--
<?php
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'setup.php.inc';
$phpunit->assertEquals(array(), $stack->getErrors(), 1);
$phpunit->assertEquals(array(), $stack->getErrors(true), 2);
echo 'tests done';
?>
--EXPECT--
tests done


text:
RSpec.describe Magick::Image, '#colorspace' do
  it 'works' do
    image1 = described_class.new(100, 100)

    expect { image1.colorspace }.not_to raise_error
    expect(image1.colorspace).to be_instance_of(Magick::ColorspaceType)
    expect(image1.colorspace).to eq(Magick::SRGBColorspace)
    image2 = image1.copy

    Magick::ColorspaceType.values do |colorspace|
      expect { image2.colorspace = colorspace }.not_to raise_error
    end
    expect { image1.colorspace = 2 }.to raise_error(TypeError)
    Magick::ColorspaceType.values.each do |cs|
      expect { image2.colorspace = cs }.not_to raise_error
    end
  end
end


text:
Command Line Password Manager
=============================

Command Line Password Manager is a tool to manage accounts/passwords in the command line.
All accounts/passwords are stored in an encrypted file, protected by user given passphrase.

Command line interface includes command history, keyboard shortcuts to copy password and other info,
and other nice command line UI features.

Encryption/decryption is done using Python cryptography library: https://cryptography.io/en/latest/.

Requirements
------------

CLI Password Manager requires Python 3.6.4 (or later, but previous Python 3 versions might work too).
Python packages *prompt-toolkit*, *cryptography* and *pyperclip* are required.

Environment variable CLIPWDMGR_DATA_DIR must be present and it must point to a directory that is
used to save password file and settings file.
Set CLIPWDMGR_DATA_DIR to Dropbox or other similar directory and you can use CLI Password Manager
across many computers.

Note to Windows-users:

- use cmder or conemu because prompt-toolkit might work better than the standard command window.
- prompt-toolkit in Cygwin does not work correctly.

Install
-------

Not yet available from PyPI (Python Package Index).

Installation steps:

- **pip install cryptography**
- **pip install pyperclip**
- **pip install prompt-toolkit**
- **pip install https://github.com/samisalkosuo/clipasswordmgr/archive/master.zip**

pip-installation creates executable: **clipwdmgr**.

You can also use CLI Password Manager from GitHub source:

- **git clone https://github.com/samisalkosuo/clipasswordmgr**
- cd to clipasswordmgr and **python clipwdmgr-runner.py**

Usage
-----

Using CLI Password Manager is as simple as using any shell.

- When starting the program, passphrase is asked.
- Type 'help' to get list of available commands.
- Add new account using 'add' command.
- List all accounts using 'list' command.
- View an account using 'view' command.
- Copy password or user name to clipboard.
- When viewing an account, password is copied to clipboard. This is very handy :-).
- There are keyboard shortcuts to copy password (and other fields) of last viewed account. This is also handy :-).
- Commands have options and help. For example: 'view -h' and 'copy -h'.
- Command history and completion is available.
- See help for more.

All accounts are stored to a password file in CLIPWDMGR_DATA_DIR directory. All accounts
are encrypted using your own passphrase.

About
-----

Some words about the origins of CLI Password Manager: http://sami.salkosuo.net/cli-password-manager/
and some other words about v0.4 http://sami.salkosuo.net/cli-password-manager-v0-4/.

Possible problems
-----------------

These problems were encountered when using v0.11. May apply to v0.12 and later as well.

**Known problem: Mac OS X**

When using Mac OS X El Capitan: install may fail with error: *fatal error: 'openssl/aes.h' file not found*.
Fix this by first installing OpenSSL using Homebrew and executing command::

	env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install cryptography

and then using: *pip install clipwdmgr*

Or, specifying only binary for cryptography **pip install clipwdmgr --only-binary cryptography** should work too.

See here: https://github.com/pyca/cryptography/issues/2350.

**Known problem: MS Windows**

When using pip install in Windows and Cygwin, install may fail to with error: *error: Setup script exited with error: Unable to find vcvarsall.bat*.

Workaround is to install prereq cryptography before clipwdmgr: **pip install cryptography**. Specifying only binary for cryptography **pip install clipwdmgr --only-binary cryptography** may also work.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Intents.Encode</title>
<meta name="date" content="2012-10-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.zxing.client.android

Class Intents.Encode

java.lang.Object

com.google.zxing.client.android.Intents.Encode

Enclosing class:

Intents

public static final class Intents.Encode
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
ACTION

Send this intent to encode a piece of data as a QR code and display it full screen, so
 that another person can scan the barcode from your screen.

static java.lang.String
DATA

The data to encode.

static java.lang.String
FORMAT

The barcode format to be displayed.

static java.lang.String
SHOW_CONTENTS

Normally the contents of the barcode are displayed to the user in a TextView.

static java.lang.String
TYPE

The type of data being supplied if the format is QR Code.

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

ACTION

public static final java.lang.String ACTION

Send this intent to encode a piece of data as a QR code and display it full screen, so
 that another person can scan the barcode from your screen.

See Also:

Constant Field Values

DATA

public static final java.lang.String DATA

The data to encode. Use Intent.putExtra(String, String) or
 Intent.putExtra(String, android.os.Bundle),
 depending on the type and format specified. Non-QR Code formats should
 just use a String here. For QR Code, see Contents for details.

See Also:

Constant Field Values

TYPE

public static final java.lang.String TYPE

The type of data being supplied if the format is QR Code. Use
 Intent.putExtra(String, String) with one of Contents.Type.

See Also:

Constant Field Values

FORMAT

public static final java.lang.String FORMAT

The barcode format to be displayed. If this isn't specified or is blank,
 it defaults to QR Code. Use Intent.putExtra(String, String), where
 format is one of BarcodeFormat.

See Also:

Constant Field Values

SHOW_CONTENTS

public static final java.lang.String SHOW_CONTENTS

Normally the contents of the barcode are displayed to the user in a TextView. Setting this
 boolean to false will hide that TextView, showing only the encode barcode.

See Also:

Constant Field Values

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@interface PodsDummy_Pods_AKGitViewControllers_Example : NSObject
@end
@implementation PodsDummy_Pods_AKGitViewControllers_Example
@end


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("members", "0026_auto_20181223_1855")]

    operations = [
        migrations.RenameField(
            model_name="settings", old_name="invoicing_busy", new_name="task_busy"
        ),
        migrations.AddField(
            model_name="settings",
            name="task_message",
            field=models.CharField(blank=True, max_length=100, null=True),
        ),
    ]


text:
<?xml version="1.0" encoding="UTF-8"?>
<nifty>
    <useStyles filename="nifty-default-styles.xml" />
    <useControls filename="nifty-default-controls.xml" />

    <controlDefinition name = "loadingbar" controller = "jme3test.TestLoadingScreen">
        <image filename="border.png" childLayout="absolute"
               imageMode="resize:15,2,15,15,15,2,15,2,15,2,15,15">
            <image id="progressbar" x="0" y="0" filename="inner.png" width="32px" height="100%"
                   imageMode="resize:15,2,15,15,15,2,15,2,15,2,15,15" />
        </image>
    </controlDefinition>

    <screen id="start" controller = "jme3test.TestLoadingScreen">
    </screen>

    <screen id="loadlevel" controller = "jme3test.TestLoadingScreen">
        <layer id="loadinglayer" childLayout="center" backgroundColor="#000000">
            <panel id = "loadingpanel" childLayout="vertical" align="center" valign="center" height="32px" width="70%">
                <control name="loadingbar" align="center" valign="center" width="100%" height="100%" />
                <control id="loadingtext" name="label" align="center"
                         text="Loading...                                    "/>
            </panel>
        </layer>
    </screen>

    <screen id="end" controller = "jme3test.TestLoadingScreen">
    </screen>

</nifty>


text:
typedef enum {
    TYWebViewControllerDefaultMode = 0,
    TYWebViewControllerAuthMode = 1,
    TYWebViewControllerPermissionMode = 2,
} TYWebViewMode;

@interface KBYTWebViewController : UIViewController <WKNavigationDelegate, UIActionSheetDelegate, WKScriptMessageHandler, UIWebViewDelegate >

@property (readwrite, assign) TYWebViewMode viewMode;
@property (strong, nonatomic) IBOutlet WKWebView *webView;
@property (nonatomic, strong) KBYTMedia *currentMedia;
@property (nonatomic, strong) NSString *previousVideoID;
@property (readwrite, assign) BOOL gettingDetails;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) NSTimer *airplayTimer;
@property (nonatomic, strong) NSString *airplayIP;
@property (nonatomic, strong) UISlider *airplaySlider;
@property (nonatomic, strong) UIView *sliderView;
@property (readwrite, assign) CGFloat airplayProgressPercent;
@property (readwrite, assign) CGFloat airplayDuration;

- (id)initWithURL:(NSString*)theURL;
- (id)initWithURL:(NSString*)theURL mode:(TYWebViewMode)mode;
@end


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

class Vendas extends CI_Controller
{
    public function index()
    {
        $usuario = autoriza();
        $this->load->model('produtos_model');
        $produtosVendidos = $this->produtos_model->buscaVendidos($usuario);
        $dados = array('produtosVendidos' => $produtosVendidos);
        $this->load->template('vendas/index', $dados);
    }

    public function nova()
    {
        $usuario = autoriza();
        $this->load->model(array('vendas_model', 'produtos_model', 'usuarios_model'));
        $venda = array(
            'produto_id' => $this->input->post('produto_id'),
            'comprador_id' => $usuario['id'],
            'data_de_entrega' => dataPtBrToMysql($this->input->post('data_de_entrega'))
        );
        $this->vendas_model->salva($venda);

        $produto = $this->produtos_model->busca($venda['produto_id']);
        $vendedor = $this->usuarios_model->busca($produto['usuario_id']);

        $dados = array('produto' => $produto);
        $conteudo = $this->load->view('vendas/email', $dados, TRUE);

        $this->load->library('email');

        $config['protocol'] = 'smtp';
        $config['smtp_host'] = 'ssl://smtp.gmail.com';
        $config['smtp_port'] = '465';
        $config['smtp_user'] = 'hfsandrade@gmail.com';
        $config['smtp_pass'] = 'goo000zzz';
        $config['charset'] = 'utf-8';
        $config['mailtype'] = 'html';
        $config['newline'] = "\r\n"; //deve ser declarado entre aspas dupla

        $this->email->initialize($config);
        $this->email->from('hfsandrade@gmail.com', 'Mercado');
        $this->email->to($vendedor['email']);
        $this->email->subject("Seu produto {$produto['nome']} foi vendido!");
        $this->email->message($conteudo);
        $this->email->send();

        $this->session->set_flashdata('mensagem', array('Produto comprado com sucesso', 'alert-success'));
        redirect('/');

    }
}


text:
'use strict';
const requestModificationMethods = require('./requestModificationMethods');
const RequestModificationPatterns = require('../../../../lib/RequestModificationPatterns');
const applyModificationMap = require('../../../../lib/applyHeaderModificationMap');

const scriptEnvUrl = browser.extension.getURL('/build/requestModification-script-env.js');

module.exports = async script => {
    const tabs = await script.include('tabs');
    const browserWindowId = await tabs.getScriptBrowserWindowId();
    const requestHeaderPatterns = new RequestModificationPatterns({
        browserWebRequestEmitter: browser.webRequest.onBeforeSendHeaders,
        extraInfoSpec: ['blocking', 'requestHeaders'],
        browserWindowId,
        listener: (modificationMap, {requestHeaders}) => {
            return {
                requestHeaders: applyModificationMap(requestHeaders, modificationMap),
            };
        },
    });
    const responseHeaderPatterns = new RequestModificationPatterns({
        browserWebRequestEmitter: browser.webRequest.onHeadersReceived,
        extraInfoSpec: ['blocking', 'responseHeaders'],
        browserWindowId,
        listener: (modificationMap, {responseHeaders}) => {
            return {
                responseHeaders: applyModificationMap(responseHeaders, modificationMap),
            };
        },
    });

    const handleRunEnd = async () => {
        requestHeaderPatterns.removeAll();
        responseHeaderPatterns.removeAll();
    };

    script.rpcRegisterMethods(requestModificationMethods({requestHeaderPatterns, responseHeaderPatterns}));
    script.on('core.runEnd', wait => wait(handleRunEnd()));
    script.importScripts(scriptEnvUrl);
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CestnoSoftware;

namespace ReactDemo.Models
{
    public class FormPageModel : BasePageModel
    {
        #region JSXControlName
        private string _JSXControlName;
        public string JSXControlName
        {
            get
            {
                return this._JSXControlName;
            }
            set
            {
                this._JSXControlName = value;
            }
        }
        #endregion

        #region JSXControlProps
        private object _JSXControlProps;
        public object JSXControlProps
        {
            get
            {
                return this._JSXControlProps;
            }
            set
            {
                this._JSXControlProps = value;
            }
        }
        #endregion
    }
}


text:
package org.nusco.narjillos.core.things;

import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;

import java.util.Random;
import java.util.Set;

import org.junit.Test;
import org.nusco.narjillos.core.geometry.Vector;

public class SpaceSearchTest {

	Space space = new Space();
	Random random = new Random(12345);

	@Test
	public void findsNeighboringThings() {
		Thing[] things = new Thing[7];
		things[0] = new TestThing(at(1, -1));
		things[1] = new TestThing(at(1, -1));
		things[2] = new TestThing(at(-1, -2));
		things[3] = new TestThing(at(2, -1));
		things[4] = new TestThing(at(2, -1));
		things[5] = new TestThing(at(2, 1));
		things[6] = new TestThing(at(3, 2));

		for (Thing thing : things)
			space.add(thing);

		Thing thing = things[0];
		Set<Thing> neighbors = space.getNearbyNeighbors(thing, "");

		assertThat(neighbors, contains(things[2], things[1], things[3], things[4], things[5]));
	}

	// A pseudorandom location in square "n, m" of the grid
	private Vector at(int gridX, int gridY) {
		return Vector.cartesian(at(gridX), at(gridY));
	}

	// A pseudorandom location in square "n" of the grid
	private double at(int gridCoordinate) {
		int gridMultiplier = gridCoordinate > 0 ? gridCoordinate - 1 : gridCoordinate;
		double firstCoordinateLocation = HashedLocation.GRID_SIZE * gridMultiplier;
		double offset = HashedLocation.GRID_SIZE * random.nextInt(100) * 0.01;
		return firstCoordinateLocation + offset;
	}
}


text:
package liquibase.ext.spanner.datatype;

import liquibase.database.Database;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.core.BooleanType;
import liquibase.ext.spanner.ICloudSpanner;

public class BoolTypeSpanner extends BooleanType {
  private static final DatabaseDataType BOOL = new DatabaseDataType("BOOL");

  @Override
  public boolean supports(Database database) {
    return database instanceof ICloudSpanner;
  }

  @Override
  public DatabaseDataType toDatabaseDataType(Database database) {
    if (database instanceof ICloudSpanner) {
      return BOOL;
    } else {
      return super.toDatabaseDataType(database);
    }
  }

  @Override
  public int getPriority() {
    return PRIORITY_DATABASE;
  }
}


text:
package org.apache.camel.processor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

public class SimpleSingleOutputMockTest extends ContextTestSupport {

    @Test
    public void testSimple() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedBodiesReceived("Hello World");

        Exchange out = template.request("direct:start", e -> e.getMessage().setBody("Hello World"));
        assertNotNull(out);
        assertEquals(ExchangePattern.InOut, out.getPattern());
        assertTrue(out.hasOut());

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").to("mock:result");
            }
        };
    }
}


text:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Matching;

namespace Microsoft.AspNetCore.Routing.Constraints;

/// <summary>
/// Constrains a route by several child constraints.
/// </summary>
public class CompositeRouteConstraint : IRouteConstraint, IParameterLiteralNodeMatchingPolicy
{
    /// <summary>
    /// Initializes a new instance of the <see cref="CompositeRouteConstraint" /> class.
    /// </summary>
    /// <param name="constraints">The child constraints that must match for this constraint to match.</param>
    public CompositeRouteConstraint(IEnumerable<IRouteConstraint> constraints)
    {
        if (constraints == null)
        {
            throw new ArgumentNullException(nameof(constraints));
        }

        Constraints = constraints;
    }

    /// <summary>
    /// Gets the child constraints that must match for this constraint to match.
    /// </summary>
    public IEnumerable<IRouteConstraint> Constraints { get; private set; }

    /// <inheritdoc />
    public bool Match(
        HttpContext? httpContext,
        IRouter? route,
        string routeKey,
        RouteValueDictionary values,
        RouteDirection routeDirection)
    {
        if (routeKey == null)
        {
            throw new ArgumentNullException(nameof(routeKey));
        }

        if (values == null)
        {
            throw new ArgumentNullException(nameof(values));
        }

        foreach (var constraint in Constraints)
        {
            if (!constraint.Match(httpContext, route, routeKey, values, routeDirection))
            {
                return false;
            }
        }

        return true;
    }

    bool IParameterLiteralNodeMatchingPolicy.MatchesLiteral(string parameterName, string literal)
    {
        foreach (var constraint in Constraints)
        {
            if (constraint is IParameterLiteralNodeMatchingPolicy literalConstraint && !literalConstraint.MatchesLiteral(parameterName, literal))
            {
                return false;
            }
        }

        return true;
    }
}


text:
require '2017-01-01/generated/azure_mgmt_customer_insights'
require '2017-04-26/generated/azure_mgmt_customer_insights'
require 'profiles/latest/customerinsights_latest_profile_client'


text:
"""Tools and arithmetics for monomials of distributed polynomials. """

from __future__ import print_function, division

from itertools import combinations_with_replacement, product
from textwrap import dedent

from sympy.core import Mul, S, Tuple, sympify
from sympy.core.compatibility import exec_, iterable, range
from sympy.polys.polyerrors import ExactQuotientFailed
from sympy.polys.polyutils import PicklableWithSlots, dict_from_expr
from sympy.utilities import public
from sympy.core.compatibility import is_sequence

@public
def itermonomials(variables, max_degrees, min_degrees=None):
    r"""
    `max_degrees` and `min_degrees` are either both integers or both lists.
    Unless otherwise specified, `min_degrees` is either 0 or [0,...,0].

    A generator of all monomials `monom` is returned, such that
    either
    min_degree <= total_degree(monom) <= max_degree,
    or
    min_degrees[i] <= degree_list(monom)[i] <= max_degrees[i], for all i.

    Case I:: `max_degrees` and `min_degrees` are both integers.
    ===========================================================
    Given a set of variables `V` and a min_degree `N` and a max_degree `M`
    generate a set of monomials of degree less than or equal to `N` and greater
    than or equal to `M`. The total number of monomials in commutative
    variables is huge and is given by the following formula if `M = 0`:

        .. math::

            \frac{(\#V + N)!}{\#V! N!}

    For example if we would like to generate a dense polynomial of
    a total degree `N = 50` and `M = 0`, which is the worst case, in 5
    variables, assuming that exponents and all of coefficients are 32-bit long
    and stored in an array we would need almost 80 GiB of memory! Fortunately
    most polynomials, that we will encounter, are sparse.

    Examples
    ========

    Consider monomials in commutative variables `x` and `y`
    and non-commutative variables `a` and `b`::

        >>> from sympy import symbols
        >>> from sympy.polys.monomials import itermonomials
        >>> from sympy.polys.orderings import monomial_key
        >>> from sympy.abc import x, y

        >>> sorted(itermonomials([x, y], 2), key=monomial_key('grlex', [y, x]))
        [1, x, y, x**2, x*y, y**2]

        >>> sorted(itermonomials([x, y], 3), key=monomial_key('grlex', [y, x]))
        [1, x, y, x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3]

        >>> a, b = symbols('a, b', commutative=False)
        >>> set(itermonomials([a, b, x], 2))
        {1, a, a**2, b, b**2, x, x**2, a*b, b*a, x*a, x*b}

        >>> sorted(itermonomials([x, y], 2, 1), key=monomial_key('grlex', [y, x]))
        [x, y, x**2, x*y, y**2]

    Case II:: `max_degrees` and `min_degrees` are both lists.
    =========================================================
    If max_degrees = [d_1, ..., d_n] and min_degrees = [e_1, ..., e_n],
    the number of monomials generated is:

        (d_1 - e_1 + 1) * ... * (d_n - e_n + 1)

    Example
    =======

    Let us generate all monomials `monom` in variables `x`, and `y`
    such that [1, 2][i] <= degree_list(monom)[i] <= [2, 4][i], i = 0, 1 ::

        >>> from sympy import symbols
        >>> from sympy.polys.monomials import itermonomials
        >>> from sympy.polys.orderings import monomial_key
        >>> from itertools import product
        >>> from sympy.core import Mul
        >>> from sympy.abc import x, y

        >>> sorted(itermonomials([x, y], [2, 4], [1, 2]), reverse=True, key=monomial_key('lex', [x, y]))
        [x**2*y**4, x**2*y**3, x**2*y**2, x*y**4, x*y**3, x*y**2]
    """
    n = len(variables)
    if is_sequence(max_degrees):
        if len(max_degrees) != n:
            raise ValueError('Argument sizes do not match')
        if min_degrees is None:
            min_degrees = [0]*n
        elif not is_sequence(min_degrees):
            raise ValueError('min_degrees is not a list')
        else:
            if len(min_degrees) != n:
                raise ValueError('Argument sizes do not match')
            if any(i < 0 for i in min_degrees):
                raise ValueError("min_degrees can't contain negative numbers")
        total_degree = False
    else:
        max_degree = max_degrees
        if max_degree < 0:
            raise ValueError("max_degrees can't be negative")
        if min_degrees is None:
            min_degree = 0
        else:
            if min_degrees < 0:
                raise ValueError("min_degrees can't be negative")
            min_degree = min_degrees
        total_degree = True
    if total_degree:
        if min_degree > max_degree:
            return
        if not variables or max_degree == 0:
            yield S.One
            return
        # Force to list in case of passed tuple or other incompatible collection
        variables = list(variables) + [S.One]
        if all(variable.is_commutative for variable in variables):
            monomials_list_comm = []
            for item in combinations_with_replacement(variables, max_degree):
                powers = dict()
                for variable in variables:
                    powers[variable] = 0
                for variable in item:
                    if variable != 1:
                        powers[variable] += 1
                if max(powers.values()) >= min_degree:
                    monomials_list_comm.append(Mul(*item))
            for mon in set(monomials_list_comm):
                yield mon
        else:
            monomials_list_non_comm = []
            for item in product(variables, repeat=max_degree):
                powers = dict()
                for variable in variables:
                    powers[variable] = 0
                for variable in item:
                    if variable != 1:
                        powers[variable] += 1
                if max(powers.values()) >= min_degree:
                    monomials_list_non_comm.append(Mul(*item))
            for mon in set(monomials_list_non_comm):
                yield mon
    else:
        if any(min_degrees[i] > max_degrees[i] for i in range(n)):
            raise ValueError('min_degrees[i] must be <= max_degrees[i] for all i')
        power_lists = []
        for var, min_d, max_d in zip(variables, min_degrees, max_degrees):
            power_lists.append([var**i for i in range(min_d, max_d + 1)])
        for powers in product(*power_lists):
            yield Mul(*powers)

def monomial_count(V, N):
    r"""
    Computes the number of monomials.

    The number of monomials is given by the following formula:

    .. math::

        \frac{(\#V + N)!}{\#V! N!}

    where `N` is a total degree and `V` is a set of variables.

    Examples
    ========

    >>> from sympy.polys.monomials import itermonomials, monomial_count
    >>> from sympy.polys.orderings import monomial_key
    >>> from sympy.abc import x, y

    >>> monomial_count(2, 2)
    6

    >>> M = list(itermonomials([x, y], 2))

    >>> sorted(M, key=monomial_key('grlex', [y, x]))
    [1, x, y, x**2, x*y, y**2]
    >>> len(M)
    6

    """
    from sympy import factorial
    return factorial(V + N) / factorial(V) / factorial(N)

def monomial_mul(A, B):
    """
    Multiplication of tuples representing monomials.

    Examples
    ========

    Lets multiply `x**3*y**4*z` with `x*y**2`::

        >>> from sympy.polys.monomials import monomial_mul

        >>> monomial_mul((3, 4, 1), (1, 2, 0))
        (4, 6, 1)

    which gives `x**4*y**5*z`.

    """
    return tuple([ a + b for a, b in zip(A, B) ])

def monomial_div(A, B):
    """
    Division of tuples representing monomials.

    Examples
    ========

    Lets divide `x**3*y**4*z` by `x*y**2`::

        >>> from sympy.polys.monomials import monomial_div

        >>> monomial_div((3, 4, 1), (1, 2, 0))
        (2, 2, 1)

    which gives `x**2*y**2*z`. However::

        >>> monomial_div((3, 4, 1), (1, 2, 2)) is None
        True

    `x*y**2*z**2` does not divide `x**3*y**4*z`.

    """
    C = monomial_ldiv(A, B)

    if all(c >= 0 for c in C):
        return tuple(C)
    else:
        return None

def monomial_ldiv(A, B):
    """
    Division of tuples representing monomials.

    Examples
    ========

    Lets divide `x**3*y**4*z` by `x*y**2`::

        >>> from sympy.polys.monomials import monomial_ldiv

        >>> monomial_ldiv((3, 4, 1), (1, 2, 0))
        (2, 2, 1)

    which gives `x**2*y**2*z`.

        >>> monomial_ldiv((3, 4, 1), (1, 2, 2))
        (2, 2, -1)

    which gives `x**2*y**2*z**-1`.

    """
    return tuple([ a - b for a, b in zip(A, B) ])

def monomial_pow(A, n):
    """Return the n-th pow of the monomial. """
    return tuple([ a*n for a in A ])

def monomial_gcd(A, B):
    """
    Greatest common divisor of tuples representing monomials.

    Examples
    ========

    Lets compute GCD of `x*y**4*z` and `x**3*y**2`::

        >>> from sympy.polys.monomials import monomial_gcd

        >>> monomial_gcd((1, 4, 1), (3, 2, 0))
        (1, 2, 0)

    which gives `x*y**2`.

    """
    return tuple([ min(a, b) for a, b in zip(A, B) ])

def monomial_lcm(A, B):
    """
    Least common multiple of tuples representing monomials.

    Examples
    ========

    Lets compute LCM of `x*y**4*z` and `x**3*y**2`::

        >>> from sympy.polys.monomials import monomial_lcm

        >>> monomial_lcm((1, 4, 1), (3, 2, 0))
        (3, 4, 1)

    which gives `x**3*y**4*z`.

    """
    return tuple([ max(a, b) for a, b in zip(A, B) ])

def monomial_divides(A, B):
    """
    Does there exist a monomial X such that XA == B?

    Examples
    ========

    >>> from sympy.polys.monomials import monomial_divides
    >>> monomial_divides((1, 2), (3, 4))
    True
    >>> monomial_divides((1, 2), (0, 2))
    False
    """
    return all(a <= b for a, b in zip(A, B))

def monomial_max(*monoms):
    """
    Returns maximal degree for each variable in a set of monomials.

    Examples
    ========

    Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`.
    We wish to find out what is the maximal degree for each of `x`, `y`
    and `z` variables::

        >>> from sympy.polys.monomials import monomial_max

        >>> monomial_max((3,4,5), (0,5,1), (6,3,9))
        (6, 5, 9)

    """
    M = list(monoms[0])

    for N in monoms[1:]:
        for i, n in enumerate(N):
            M[i] = max(M[i], n)

    return tuple(M)

def monomial_min(*monoms):
    """
    Returns minimal degree for each variable in a set of monomials.

    Examples
    ========

    Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`.
    We wish to find out what is the minimal degree for each of `x`, `y`
    and `z` variables::

        >>> from sympy.polys.monomials import monomial_min

        >>> monomial_min((3,4,5), (0,5,1), (6,3,9))
        (0, 3, 1)

    """
    M = list(monoms[0])

    for N in monoms[1:]:
        for i, n in enumerate(N):
            M[i] = min(M[i], n)

    return tuple(M)

def monomial_deg(M):
    """
    Returns the total degree of a monomial.

    Examples
    ========

    The total degree of `xy^2` is 3:

    >>> from sympy.polys.monomials import monomial_deg
    >>> monomial_deg((1, 2))
    3
    """
    return sum(M)

def term_div(a, b, domain):
    """Division of two terms in over a ring/field. """
    a_lm, a_lc = a
    b_lm, b_lc = b

    monom = monomial_div(a_lm, b_lm)

    if domain.is_Field:
        if monom is not None:
            return monom, domain.quo(a_lc, b_lc)
        else:
            return None
    else:
        if not (monom is None or a_lc % b_lc):
            return monom, domain.quo(a_lc, b_lc)
        else:
            return None

class MonomialOps(object):
    """Code generator of fast monomial arithmetic functions. """

    def __init__(self, ngens):
        self.ngens = ngens

    def _build(self, code, name):
        ns = {}
        exec_(code, ns)
        return ns[name]

    def _vars(self, name):
        return [ "%s%s" % (name, i) for i in range(self.ngens) ]

    def mul(self):
        name = "monomial_mul"
        template = dedent("""\
        def %(name)s(A, B):
            (%(A)s,) = A
            (%(B)s,) = B
            return (%(AB)s,)
        """)
        A = self._vars("a")
        B = self._vars("b")
        AB = [ "%s + %s" % (a, b) for a, b in zip(A, B) ]
        code = template % dict(name=name, A=", ".join(A), B=", ".join(B), AB=", ".join(AB))
        return self._build(code, name)

    def pow(self):
        name = "monomial_pow"
        template = dedent("""\
        def %(name)s(A, k):
            (%(A)s,) = A
            return (%(Ak)s,)
        """)
        A = self._vars("a")
        Ak = [ "%s*k" % a for a in A ]
        code = template % dict(name=name, A=", ".join(A), Ak=", ".join(Ak))
        return self._build(code, name)

    def mulpow(self):
        name = "monomial_mulpow"
        template = dedent("""\
        def %(name)s(A, B, k):
            (%(A)s,) = A
            (%(B)s,) = B
            return (%(ABk)s,)
        """)
        A = self._vars("a")
        B = self._vars("b")
        ABk = [ "%s + %s*k" % (a, b) for a, b in zip(A, B) ]
        code = template % dict(name=name, A=", ".join(A), B=", ".join(B), ABk=", ".join(ABk))
        return self._build(code, name)

    def ldiv(self):
        name = "monomial_ldiv"
        template = dedent("""\
        def %(name)s(A, B):
            (%(A)s,) = A
            (%(B)s,) = B
            return (%(AB)s,)
        """)
        A = self._vars("a")
        B = self._vars("b")
        AB = [ "%s - %s" % (a, b) for a, b in zip(A, B) ]
        code = template % dict(name=name, A=", ".join(A), B=", ".join(B), AB=", ".join(AB))
        return self._build(code, name)

    def div(self):
        name = "monomial_div"
        template = dedent("""\
        def %(name)s(A, B):
            (%(A)s,) = A
            (%(B)s,) = B
            %(RAB)s
            return (%(R)s,)
        """)
        A = self._vars("a")
        B = self._vars("b")
        RAB = [ "r%(i)s = a%(i)s - b%(i)s\n    if r%(i)s < 0: return None" % dict(i=i) for i in range(self.ngens) ]
        R = self._vars("r")
        code = template % dict(name=name, A=", ".join(A), B=", ".join(B), RAB="\n    ".join(RAB), R=", ".join(R))
        return self._build(code, name)

    def lcm(self):
        name = "monomial_lcm"
        template = dedent("""\
        def %(name)s(A, B):
            (%(A)s,) = A
            (%(B)s,) = B
            return (%(AB)s,)
        """)
        A = self._vars("a")
        B = self._vars("b")
        AB = [ "%s if %s >= %s else %s" % (a, a, b, b) for a, b in zip(A, B) ]
        code = template % dict(name=name, A=", ".join(A), B=", ".join(B), AB=", ".join(AB))
        return self._build(code, name)

    def gcd(self):
        name = "monomial_gcd"
        template = dedent("""\
        def %(name)s(A, B):
            (%(A)s,) = A
            (%(B)s,) = B
            return (%(AB)s,)
        """)
        A = self._vars("a")
        B = self._vars("b")
        AB = [ "%s if %s <= %s else %s" % (a, a, b, b) for a, b in zip(A, B) ]
        code = template % dict(name=name, A=", ".join(A), B=", ".join(B), AB=", ".join(AB))
        return self._build(code, name)

@public
class Monomial(PicklableWithSlots):
    """Class representing a monomial, i.e. a product of powers. """

    __slots__ = ['exponents', 'gens']

    def __init__(self, monom, gens=None):
        if not iterable(monom):
            rep, gens = dict_from_expr(sympify(monom), gens=gens)
            if len(rep) == 1 and list(rep.values())[0] == 1:
                monom = list(rep.keys())[0]
            else:
                raise ValueError("Expected a monomial got {}".format(monom))

        self.exponents = tuple(map(int, monom))
        self.gens = gens

    def rebuild(self, exponents, gens=None):
        return self.__class__(exponents, gens or self.gens)

    def __len__(self):
        return len(self.exponents)

    def __iter__(self):
        return iter(self.exponents)

    def __getitem__(self, item):
        return self.exponents[item]

    def __hash__(self):
        return hash((self.__class__.__name__, self.exponents, self.gens))

    def __str__(self):
        if self.gens:
            return "*".join([ "%s**%s" % (gen, exp) for gen, exp in zip(self.gens, self.exponents) ])
        else:
            return "%s(%s)" % (self.__class__.__name__, self.exponents)

    def as_expr(self, *gens):
        """Convert a monomial instance to a SymPy expression. """
        gens = gens or self.gens

        if not gens:
            raise ValueError(
                "can't convert %s to an expression without generators" % self)

        return Mul(*[ gen**exp for gen, exp in zip(gens, self.exponents) ])

    def __eq__(self, other):
        if isinstance(other, Monomial):
            exponents = other.exponents
        elif isinstance(other, (tuple, Tuple)):
            exponents = other
        else:
            return False

        return self.exponents == exponents

    def __ne__(self, other):
        return not self == other

    def __mul__(self, other):
        if isinstance(other, Monomial):
            exponents = other.exponents
        elif isinstance(other, (tuple, Tuple)):
            exponents = other
        else:
            raise NotImplementedError

        return self.rebuild(monomial_mul(self.exponents, exponents))

    def __div__(self, other):
        if isinstance(other, Monomial):
            exponents = other.exponents
        elif isinstance(other, (tuple, Tuple)):
            exponents = other
        else:
            raise NotImplementedError

        result = monomial_div(self.exponents, exponents)

        if result is not None:
            return self.rebuild(result)
        else:
            raise ExactQuotientFailed(self, Monomial(other))

    __floordiv__ = __truediv__ = __div__

    def __pow__(self, other):
        n = int(other)

        if not n:
            return self.rebuild([0]*len(self))
        elif n > 0:
            exponents = self.exponents

            for i in range(1, n):
                exponents = monomial_mul(exponents, self.exponents)

            return self.rebuild(exponents)
        else:
            raise ValueError("a non-negative integer expected, got %s" % other)

    def gcd(self, other):
        """Greatest common divisor of monomials. """
        if isinstance(other, Monomial):
            exponents = other.exponents
        elif isinstance(other, (tuple, Tuple)):
            exponents = other
        else:
            raise TypeError(
                "an instance of Monomial class expected, got %s" % other)

        return self.rebuild(monomial_gcd(self.exponents, exponents))

    def lcm(self, other):
        """Least common multiple of monomials. """
        if isinstance(other, Monomial):
            exponents = other.exponents
        elif isinstance(other, (tuple, Tuple)):
            exponents = other
        else:
            raise TypeError(
                "an instance of Monomial class expected, got %s" % other)

        return self.rebuild(monomial_lcm(self.exponents, exponents))