text:
var Event = (function () {
    function Event() {
        var _this = this;
        this.startDate = function () {
            return new Date(_this.start);
        };
    }
    return Event;
})();
exports.Event = Event;
/**
 * A feature is a single object that is show on a map (e.g. point, polyline, etc)
 * Features are part of a layer and filtered and styled using group filters and styles
 *
 */
var Feature = (function () {
    function Feature() {
    }
    return Feature;
})();
exports.Feature = Feature;
(function (DrawingModeType) {
    DrawingModeType[DrawingModeType["None"] = 0] = "None";
    DrawingModeType[DrawingModeType["Image"] = 1] = "Image";
    DrawingModeType[DrawingModeType["Point"] = 2] = "Point";
    DrawingModeType[DrawingModeType["Square"] = 3] = "Square";
    DrawingModeType[DrawingModeType["Rectangle"] = 4] = "Rectangle";
    DrawingModeType[DrawingModeType["Line"] = 5] = "Line";
    DrawingModeType[DrawingModeType["Circle"] = 6] = "Circle";
    DrawingModeType[DrawingModeType["Freehand"] = 7] = "Freehand";
    DrawingModeType[DrawingModeType["Polyline"] = 8] = "Polyline";
    DrawingModeType[DrawingModeType["Polygon"] = 9] = "Polygon";
    DrawingModeType[DrawingModeType["MultiPolygon"] = 10] = "MultiPolygon";
})(exports.DrawingModeType || (exports.DrawingModeType = {}));
var DrawingModeType = exports.DrawingModeType;
//export enum propertyTypeType {
//    Text,
//    TextArea,
//    Rating,
//    Number,
//    Bbcode,
//    Boolean,
//    Bit,
//    Sensor,
//    Xml,
//    Options,
//    Unknown,
//    Image,
//    DateTime,
//    Mediafolder
//}
(function (featureFilterType) {
    /** Turn filtering off */
    featureFilterType[featureFilterType["none"] = 0] = "none";
    /** Default for numbers: histogram */
    featureFilterType[featureFilterType["bar"] = 1] = "bar";
    /** Default for text */
    featureFilterType[featureFilterType["text"] = 2] = "text";
})(exports.featureFilterType || (exports.featureFilterType = {}));
var featureFilterType = exports.featureFilterType;
var PropertyInfo = (function () {
    function PropertyInfo() {
    }
    return PropertyInfo;
})();
exports.PropertyInfo = PropertyInfo;


text:
package com.amazonaws.services.rekognition.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Allows you to opt in or opt out to share data with Rekognition to improve model performance. You can choose this
 * option at the account level or on a per-stream basis. Note that if you opt out at the account level this setting is
 * ignored on individual streams.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StreamProcessorDataSharingPreference implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * If this option is set to true, you choose to share data with Rekognition to improve model performance.
     *

     */
    private Boolean optIn;

    /**
     *

     * If this option is set to true, you choose to share data with Rekognition to improve model performance.
     *

     *
     * @param optIn
     *        If this option is set to true, you choose to share data with Rekognition to improve model performance.
     */

    public void setOptIn(Boolean optIn) {
        this.optIn = optIn;
    }

    /**
     *

     * If this option is set to true, you choose to share data with Rekognition to improve model performance.
     *

     *
     * @return If this option is set to true, you choose to share data with Rekognition to improve model performance.
     */

    public Boolean getOptIn() {
        return this.optIn;
    }

    /**
     *

     * If this option is set to true, you choose to share data with Rekognition to improve model performance.
     *

     *
     * @param optIn
     *        If this option is set to true, you choose to share data with Rekognition to improve model performance.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StreamProcessorDataSharingPreference withOptIn(Boolean optIn) {
        setOptIn(optIn);
        return this;
    }

    /**
     *

     * If this option is set to true, you choose to share data with Rekognition to improve model performance.
     *

     *
     * @return If this option is set to true, you choose to share data with Rekognition to improve model performance.
     */

    public Boolean isOptIn() {
        return this.optIn;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getOptIn() != null)
            sb.append("OptIn: ").append(getOptIn());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StreamProcessorDataSharingPreference == false)
            return false;
        StreamProcessorDataSharingPreference other = (StreamProcessorDataSharingPreference) obj;
        if (other.getOptIn() == null ^ this.getOptIn() == null)
            return false;
        if (other.getOptIn() != null && other.getOptIn().equals(this.getOptIn()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getOptIn() == null) ? 0 : getOptIn().hashCode());
        return hashCode;
    }

    @Override
    public StreamProcessorDataSharingPreference clone() {
        try {
            return (StreamProcessorDataSharingPreference) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.rekognition.model.transform.StreamProcessorDataSharingPreferenceMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.zstack.kvm;

import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.vm.VmInstanceInventory;

public interface KVMRebootVmExtensionPoint {
    void beforeRebootVmOnKvm(KVMHostInventory host, VmInstanceInventory vm) throws KVMException;

    void rebootVmOnKvmSuccess(KVMHostInventory host, VmInstanceInventory vm);

    void rebootVmOnKvmFailed(KVMHostInventory host, VmInstanceInventory vm, ErrorCode err);
}


text:
package com.datatorrent.lib.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.datatorrent.lib.util.PojoUtils.Getter;
import com.datatorrent.lib.util.PojoUtils.Setter;

/**
 * @since 3.3.0
 */
public class FieldValueGenerator<T extends FieldInfo>
{
  public static interface FieldValueHandler<T extends FieldInfo>
  {
    public void handleFieldValue(T fieldInfo, Object value);
  }

  public static interface ValueConverter<T extends FieldInfo>
  {
    public Object convertValue(T fieldInfo, Object value);
  }

  protected Map<T, Getter<Object, Object>> fieldGetterMap = new HashMap<T, Getter<Object, Object>>();
  protected Map<T, Setter<Object, Object>> fieldSetterMap = new HashMap<T, Setter<Object, Object>>();

  protected Map<String, T> fieldInfoMap = new HashMap<String, T>();

  protected FieldValueGenerator()
  {
  }

  @SuppressWarnings("unchecked")
  public static <T extends FieldInfo> FieldValueGenerator<T> getFieldValueGenerator(final Class<?> clazz, List<T> fieldInfos)
  {
    return new FieldValueGenerator<T>(clazz, fieldInfos);
  }

  protected FieldValueGenerator(final Class<?> clazz, List<T> fieldInfos)
  {
    for (T fieldInfo : fieldInfos) {
      fieldInfoMap.put(fieldInfo.getColumnName(), fieldInfo);

      Getter<Object, Object> getter = PojoUtils.createGetter(clazz, fieldInfo.getPojoFieldExpression(), fieldInfo.getType().getJavaType());
      fieldGetterMap.put(fieldInfo, getter);
    }

    for (T fieldInfo : fieldInfos) {
      Setter<Object, Object> setter = PojoUtils.createSetter(clazz, fieldInfo.getPojoFieldExpression(), fieldInfo.getType().getJavaType());
      fieldSetterMap.put(fieldInfo, setter);
    }
  }

  /**
   * use FieldValueHandler handle the value
   * @param obj
   * @param fieldValueHandler
   * @return
   * @since 3.0.0
 */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void handleFieldsValue(Object obj, FieldValueHandler fieldValueHandler)
  {
    for (Map.Entry<T, Getter<Object, Object>> entry : fieldGetterMap.entrySet()) {
      Getter<Object, Object> getter = entry.getValue();
      if (getter != null) {
        Object value = getter.get(obj);
        fieldValueHandler.handleFieldValue(entry.getKey(), value);
      }
    }
  }

  public Map<String, Object> getFieldsValueAsMap(Object obj)
  {
    Map<String, Object> fieldsValue = new HashMap<String, Object>();
    for (Map.Entry<T, Getter<Object, Object>> entry : fieldGetterMap.entrySet()) {
      Getter<Object, Object> getter = entry.getValue();
      if (getter != null) {
        Object value = getter.get(obj);
        fieldsValue.put(entry.getKey().getColumnName(), value);
      }
    }
    return fieldsValue;
  }

  public void setColumnValue(Object instance, String columnName, Object value, ValueConverter<T> valueConverter)
  {
    T fieldInfo = fieldInfoMap.get(columnName);
    Setter<Object, Object> setter = fieldSetterMap.get(fieldInfo);
    setter.set(instance, valueConverter == null ? value : valueConverter.convertValue(fieldInfo, value));
  }
}


text:
/**
 * create the client or web page interface to run tests in the context of a page.
 */
var webPage = require('webpage'),
    fs = require('fs'),
    util = require('util'),
    log = require('log').init("client","debug");

var defaultOptions = {
    url:"",
    host: "localhost",
    path: "/blank"
}
var Client = function(test, opts){
  this.test = test;
  this.options = util.extend({},defaultOptions, opts);
  this.url = "";
  this.page = webPage.create();
  this._init();
  this.isLoaded = false;
  this.testHandlers = [];
};

Client.prototype = {
    /**
     * binding event to page
     */
    _init: function(){
      log.debug("_init");
      createInitScript();
      createScriptServer();
      this.url = this.options.url || "http://"+this.options.host+":"+randPort + this.options.path;
      var self = this;

      this.page.onInitialized = function(){
        log.debug("page.onInitialized");
        self.page.evaluateJavaScript("function(){"+initScript+"}");
        log.debug("page.onInitialized: after initScript");
        self.page.evaluate(function(){
          //console.log("page.onInitialized one client side");
          //initialize test object
          jsUnit.test = jsUnit.require("client_test");
          jsUnit.test.done = function(){
            window.callPhantom({ op: "done"});
          }
          //initialize testResults.
          var testResults = jsUnit.require('test_results');
          Object.defineProperty(testResults, "totalAssert",{
            get: function(){
              return this._totalAssert;
            },
            set: function(val){
              this._totalAssert = val;
              window.callPhantom({ op: "assert"});
            }
          });
        });
        log.debug("initialized");
      };
      this.page.open(this.url, function(){
        log.debug("page loaded on %s", self.page.url);
      });
      this.page.onLoadFinished = function(status){
        log.debug("page load finished: %s", status);
        self.isLoaded = true;
        if(self.testHandlers.length>0){
          self.invokeTestHandler();
        }
      }
      this.page.onCallback = function(data){
        //log.debug("page.onCallback: %j", data);
        if(!util.isObject(data)) return;
        switch(data.op){
          case "done":
            self.test.done();
            break;
          case "assert":
            self.test.assert();
            break;
          case "failed":
            setTimeout(function(){
              self.test.error = {type:"failed", message: data.message}
            },10);
            break;
          case "error":
            setTimeout(function(){
              self.test.error = {type:"error", message: data.message, stack: data.stack};
            },10);
            break;
          case "next":
            self.invokeTestHandler();
            break;
        }
      }
      this.page.onConsoleMessage = function(msg){
        console.log("client message: " + msg);
      }
    },

    run: function(testHandler){
      log.debug("run")
      if(this.isLoaded){
        self.invokeTestHandler();
      }
      else{
        log.debug("page is not ready");
        this.testHandlers.push(testHandler);
      }
    },
    invokeTestHandler: function(){
      log.debug("invokeTestHandler");
      var nextHandler = this.testHandlers.shift();
      if(!nextHandler) {
        log.info("no more test handler");
        this.test.done();
      }
      var testHandlerStr = nextHandler.toString();
      this.page.evaluate(function(testStr){
        console.log("invokeTestHandler on client side");
        try{
          var testHandler;
          eval("testHandler = " + testStr);
          testHandler(jsUnit.test);
        }catch(e){
          console.log("error");
          if(e.type == "failed"){
            window.callPhantom({ op: "failed", message: e.message});
          }
          else{
            window.callPhantom({ op: "error", message: e.message, stack: e.stack});
          }
        }
      }, testHandlerStr);
    }
}

module.exports = Client;

//======================

var WebServer = require('web_server');
var initScript = "";
var randPort = 0;
var scriptServer = null;

function createScriptServer(){
  if(scriptServer) return;
  log.info("createScriptServer");
  randPort = Math.floor(Math.random()*55535) + 1000;
  scriptServer = new WebServer(randPort);
  log.info("script server running on port: %d", randPort);
}

function createInitScript(){
  if(initScript) return;
  log.info("createInitScript");
//load module and shim no need to encapsulate the scope
  var list = ["module.js","shim.js"];
  for(var x = 0; x < list.length; x++){
      var file = "modules/client/" + list[x];
      initScript += fs.read(file) + "\n";
  }
  //load share script.
  list = ["share/util.js","share/log.js","share/cc.js","share/test_results.js","share/test.js","client/client_test.js"];

  for(var x = 0; x < list.length; x++){
      var file = "modules/" + list[x];
      var i = list[x].indexOf("/")+1;
      var content = "(function(module, require) {\n";
      content += "module.loadingName = '" + list[x].slice(i,-3) +"';\n";
      content += fs.read(file);
      content += "\n})(jsUnit.module, jsUnit.require);\n";
      initScript += content;
  }
  //log.debug("initScript: %s", initScript);
}


text:
description("Test of exception forwarding for NodeIterator and TreeWalker, derived from an early version of Acid3");

var iteration = 0;
function test(node)
{
    iteration += 1;
    switch (iteration) {
        case 1: case 3: case 4: case 6: case 7: case 8: case 9: case 12: throw "Roses";
        case 2: case 5: case 10: case 11: return true;
        default: throw 0;
    }
}

var i = document.createNodeIterator(document.documentElement, 0xFFFFFFFF, test, true);
shouldThrow("i.nextNode()"); // 1
shouldBe("i.nextNode()", "document.documentElement"); // 2
shouldThrow("i.previousNode()"); // 3
var w = document.createTreeWalker(document.documentElement, 0xFFFFFFFF, test, true);
shouldThrow("w.nextNode()"); // 4
shouldBe("w.nextNode()", "document.documentElement.firstChild"); // 5
shouldThrow("w.previousNode()"); // 6
shouldThrow("w.firstChild()"); // 7
shouldThrow("w.lastChild()"); // 8
shouldThrow("w.nextSibling()"); // 9
shouldBe("w.previousSibling()", "null");
shouldBe("w.nextSibling()", "document.body.previousSibling"); // 10
shouldBe("w.previousSibling()", "document.head"); // 11
shouldBe("iteration", "11");

var successfullyParsed = true;


text:
LunaTMX - Unity2D Tilemap Importer
===========

A small library to import and render tilemap in Unity2D, only support TMX file format.

### Features

1. Import TMX Map into a Texture2D
2. Support Auto-Detect Collision with Polygon Collider 2D
3. Support as many as you want tilesets for a layer

### Usage

##### Tiles
Draw and naming your layers, be careful with naming, layer with **[C]** prefix will have a collider component.

##### Collision
Name your layer with **[C]** prefix for automatically detecting collision.

##### Save TMX
Use CSV data type and save with **.TMX** extension, then change that extension into **.XML**.

##### Unity Usage
1. Create a folder inside Asset directory named **Resources**
2. Import all scripts, also import **TMX** files
3. Import all Tilesets image into a folder inside **Resources** directory we created above, also set those Texture Type to Advanced and tick Read/Write Enabled box
4. Add **TileMap.cs** to an empty Game Object and follow the instruction.

### License and Credit
© 2014, SuppaYami - Cuong Nguyen
Released under the MIT license
Check LICENSE for more details.


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

using System;
using NUnit.Framework;

namespace NUnit.Runner.Tests
{
    [TestFixture]
    [Author("Rob Prouse")]
    public class TestsSample
    {
        [SetUp]
        public void Setup() { }

        [TearDown]
        public void Tear() { }

        [Test]
        [Category("Passing")]
        public void Pass()
        {
            TestContext.WriteLine("Capture some output");
            Assert.True(true);
        }

        [Test]
        [Category("Failing")]
        [Author("Code Monkey")]
        public void Fail()
        {
            Assert.False(true);
        }

        [Test]
        [Ignore("another time")]
        public void Ignore()
        {
            Assert.True(false);
        }

        [Test]
        public void Inconclusive()
        {
            Assert.Inconclusive("Inconclusive");
        }

        [Test]
        public void Error()
        {
            TestContext.WriteLine("I am about to throw!!!");
            throw new NotSupportedException("This method isn't ready yet");
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
	         http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.edu.hdu.pichen</groupId>
	<artifactId>infosys</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>infosys Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<spring-version>4.3.4.RELEASE</spring-version>
		<mybatis-version>3.2.8</mybatis-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<!-- http://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
		<!-- Simple Logging Facade for Java,简单日志门面 ,允许最终用户在部署其应用时使用其所希望的日志系统,本身并不是日志解决方案 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.21</version>
		</dependency>
		<!-- http://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.21</version>
		</dependency>
		<!-- http://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<!-- http://mvnrepository.com/artifact/com.google.code.gson/gson -->
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.6.2</version>
		</dependency>
		<!-- http://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>

		<!--spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.7</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.15</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis-version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.5</version>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.4.1</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.3</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.9.1</version>
		</dependency>

		<!-- JavaMail -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>javax.mail-api</artifactId>
			<version>1.5.5</version>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.7</version>
		</dependency>

		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.23</version>
		</dependency>

		<dependency>
			<groupId>edu.uci.ics</groupId>
			<artifactId>crawler4j</artifactId>
			<version>4.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
		<dependency>
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>1.10.1</version>
		</dependency>

		    <dependency>
		        <groupId>org.apdplat</groupId>
		        <artifactId>word</artifactId>
		        <version>1.2</version>
		    </dependency>

	</dependencies>
	<build>
		<finalName>infosys</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.1</version>
			</plugin>
		</plugins>
	</build>
</project>


text:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\UnidadMedidaProductos */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'unidad_medida')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'tipo')->textInput() ?>

    <?= $form->field($model, 'estatus')->textInput() ?>

	<?php if (!Yii::$app->request->isAjax){ ?>

	        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

	<?php } ?>

    <?php ActiveForm::end(); ?>


text:
#include "twoDModel/engine/model/model.h"

#include <qrkernel/settingsManager.h>
#include <qrgui/plugins/toolPluginInterface/usedInterfaces/errorReporterInterface.h>
#include <kitBase/interpreterControlInterface.h>

#include "src/engine/constraints/constraintsChecker.h"
#include "src/robotModel/nullTwoDRobotModel.h"

#include "physics/simplePhysicsEngine.h"
#include "physics/box2DPhysicsEngine.h"

using namespace twoDModel::model;

Model::Model(QObject *parent)
	: QObject(parent)
	, mChecker(nullptr)
	, mErrorReporter(nullptr)
	, mRealisticPhysicsEngine(nullptr)
	, mSimplePhysicsEngine(nullptr)
{
	initPhysics();
	connect(&mSettings, &Settings::physicsChanged, this, &Model::resetPhysics);
	resetPhysics();
}

Model::~Model()
{
	delete mRealisticPhysicsEngine;
	delete mSimplePhysicsEngine;
}

void Model::init(qReal::ErrorReporterInterface &errorReporter
		, kitBase::InterpreterControlInterface &interpreterControl)
{
	mErrorReporter = &errorReporter;
	mWorldModel.init(errorReporter);
	mChecker.reset(new constraints::ConstraintsChecker(errorReporter, *this));
	connect(mChecker.data(), &constraints::ConstraintsChecker::success, this, [&]() {
		errorReporter.addInformation(tr("The task is accomplished!"));
		// Stopping cannot be performed immediately because we still have constraints to check in event loop
		// and they need scene to be alive (in checker stopping interpretation means deleting all).
		QTimer::singleShot(0, &interpreterControl, SIGNAL(stopAllInterpretation()));
	});
	connect(mChecker.data(), &constraints::ConstraintsChecker::fail, this, [&](const QString &message) {
		errorReporter.addError(message);
		// Stopping cannot be performed immediately because we still have constraints to check in event loop
		// and they need scene to be alive (in checker stopping interpretation means deleting all).
		QTimer::singleShot(0, &interpreterControl, SLOT(stopAllInterpretation()));
	});
	connect(mChecker.data(), &constraints::ConstraintsChecker::checkerError
			, this, [&errorReporter](const QString &message) {
				errorReporter.addCritical(tr("Error in checker: %1").arg(message));
	});
}

WorldModel &Model::worldModel()
{
	return mWorldModel;
}

Timeline &Model::timeline()
{
	return mTimeline;
}

QList<RobotModel *> Model::robotModels() const
{
	return mRobotModels;
}

Settings &Model::settings()
{
	return mSettings;
}

qReal::ErrorReporterInterface *Model::errorReporter()
{
	return mErrorReporter;
}

QDomDocument Model::serialize() const
{
	QDomDocument save;
	QDomElement root = save.createElement("root");
	save.appendChild(root);
	mWorldModel.serializeWorld(root);

	QDomElement robots = save.createElement("robots");
	for (RobotModel *robotModel : mRobotModels) {
		robotModel->serialize(robots);
	}

	root.appendChild(robots);
	mChecker->serializeConstraints(root);

	return save;
}

void Model::deserialize(const QDomDocument &wordModel, const QDomDocument &blobs)
{
	const QDomNodeList worldList = wordModel.elementsByTagName("world");
	const QDomNodeList robotsList = wordModel.elementsByTagName("robots");
	const QDomElement constraints = wordModel.documentElement().firstChildElement("constraints");

	if (mChecker) {
		/// @todo: should we handle if it returned false?
		mChecker->parseConstraints(constraints);
	}

	if (worldList.count() == 0 && !mRobotModels.empty()) {
		for (auto *model : mRobotModels) {
			QSizeF modelSize = model->info().size() / 2;
			model->startPositionMarker()->setPos(modelSize.height(), modelSize.width());
			model->startPositionMarker()->setRotation(0);
		}
	}

	if (worldList.count() != 1) {
		return;
	}

	mWorldModel.deserialize(worldList.at(0).toElement(), blobs.documentElement().firstChildElement("blobs"));

	if (robotsList.count() != 1) {
		// need for backward compatibility with old format
		const QDomNodeList robotList = wordModel.elementsByTagName("robot");

		if (robotList.count() != 1) {
			/// @todo Report error
			return;
		}

		mRobotModels.at(0)->deserialize(robotList.at(0).toElement());
		mRobotModels.at(0)->configuration().deserialize(robotList.at(0).toElement());

		return;
	}

	QMutableListIterator<RobotModel *> iterator(mRobotModels);

	const bool oneRobot = robotsList.at(0).toElement().elementsByTagName("robot").size() == 1
			&& mRobotModels.size() == 1;

	while (iterator.hasNext()) {
		bool exist = false;
		RobotModel *robotModel = iterator.next();

		for (QDomElement element = robotsList.at(0).firstChildElement("robot"); !element.isNull();
				element = element.nextSiblingElement("robot")) {
			if (robotModel->info().robotId() == element.toElement().attribute("id")) {
				robotModel->deserialize(element);
				robotModel->configuration().deserialize(element);
				exist = true;
				robotsList.at(0).removeChild(static_cast<QDomNode>(element));
				break;
			}
		}

		if (!exist && !oneRobot) {
			iterator.remove();
			emit robotRemoved(robotModel);
			delete robotModel;
		}
	}

	if (oneRobot && !robotsList.at(0).firstChildElement("robot").isNull()) {
		QDomElement element = robotsList.at(0).firstChildElement("robot");
		mRobotModels.at(0)->deserialize(element);
	} else {
		for (QDomElement element = robotsList.at(0).firstChildElement("robot"); !element.isNull();
				element = element.nextSiblingElement("robot")) {
			twoDModel::robotModel::NullTwoDRobotModel *robotModel = new twoDModel::robotModel::NullTwoDRobotModel(
					element.attribute("id"));
			addRobotModel(*robotModel);
			mRobotModels.last()->deserialize(element);
		}
	}
}

void Model::addRobotModel(robotModel::TwoDRobotModel &robotModel, const QPointF &pos)
{
	RobotModel *robot = new RobotModel(robotModel, mSettings, this);
	robot->setPosition(pos);

	connect(&mTimeline, &Timeline::started, robot, &RobotModel::reinit);
	connect(&mTimeline, &Timeline::stopped, robot, &RobotModel::stopRobot);
	connect(&mTimeline, &Timeline::stopped, mRealisticPhysicsEngine, &physics::PhysicsEngineBase::clearForcesAndStop);

	connect(&mTimeline, &Timeline::tick, robot, &RobotModel::recalculateParams);
	connect(&mTimeline, &Timeline::nextFrame, robot, &RobotModel::nextFragment);
	connect(&mTimeline, &Timeline::nextFrame, mRealisticPhysicsEngine, &physics::PhysicsEngineBase::nextFrame);

	robot->setPhysicalEngine(mSettings.realisticPhysics() ? *mRealisticPhysicsEngine : *mSimplePhysicsEngine);

	mRobotModels.append(robot);

	emit robotAdded(robot);
}

void Model::removeRobotModel(const twoDModel::robotModel::TwoDRobotModel &robotModel)
{
	const int index = findModel(robotModel);

	if (index == -1) {
		return;
	}

	RobotModel *robot = mRobotModels.at(index);
	mRobotModels.removeOne(mRobotModels.at(index));
	emit robotRemoved(robot);
	delete robot;
}

void Model::replaceRobotModel(const twoDModel::robotModel::TwoDRobotModel &oldModel
		, twoDModel::robotModel::TwoDRobotModel &newModel)
{
	const int index = findModel(oldModel);

	if (index == -1) {
		return;
	}

	const QPointF pos = mRobotModels.at(index)->position();
	removeRobotModel(oldModel);
	addRobotModel(newModel, pos);
}

bool Model::hasConstraints() const
{
	return mChecker->hasConstraints();
}

void Model::setConstraintsEnabled(bool enabled)
{
	mChecker->setEnabled(enabled);
}

void Model::resetPhysics()
{
	auto engine = mSettings.realisticPhysics() ? mRealisticPhysicsEngine : mSimplePhysicsEngine;
	for (RobotModel * const robot : mRobotModels) {
		robot->setPhysicalEngine(*engine);
	}

	engine->wakeUp();
}

int Model::findModel(const twoDModel::robotModel::TwoDRobotModel &robotModel)
{
	for (int i = 0; i < mRobotModels.count(); i++) {
		if (mRobotModels.at(i)->info().robotId() == robotModel.robotId()) {
			return i;
		}
	}

	return -1;
}

void Model::initPhysics()
{
	mRealisticPhysicsEngine = new physics::Box2DPhysicsEngine(mWorldModel, mRobotModels);
	mSimplePhysicsEngine = new physics::SimplePhysicsEngine(mWorldModel, mRobotModels);
	connect(this, &model::Model::robotAdded, mRealisticPhysicsEngine, &physics::PhysicsEngineBase::addRobot);
	connect(this, &model::Model::robotRemoved, mRealisticPhysicsEngine, &physics::PhysicsEngineBase::removeRobot);
	connect(this, &model::Model::robotAdded, mSimplePhysicsEngine, &physics::PhysicsEngineBase::addRobot);
	connect(this, &model::Model::robotRemoved, mSimplePhysicsEngine, &physics::PhysicsEngineBase::removeRobot);

	connect(&mTimeline, &Timeline::tick, this, &Model::recalculatePhysicsParams);
	connect(&mTimeline, &Timeline::nextFrame, this, [this](){ mRealisticPhysicsEngine->nextFrame();	});
}

void Model::recalculatePhysicsParams()
{
	if (mSettings.realisticPhysics()) {
		mRealisticPhysicsEngine->recalculateParameters(Timeline::timeInterval);
	} else {
		mSimplePhysicsEngine->recalculateParameters(Timeline::timeInterval);
	}
}


text:
using Caliburn.Micro;

namespace BudgetManager.Settings
{
    public class SettingsWorkspaceViewModel : Screen
    {
        public override string ToString()
        {
            return DisplayName;
        }
    }
}


text:
'''minimizers for functions of 1 variable

FUNCTIONS
golden_section(fun, low, high, interval_size) -> low*, high*

ARGS
fun(x) -> number
low: number
high: number
interval_size: search stops when high* - low* < interval_size
'''
from minimize_1d_golden_section import golden_section

if False:
    # use imports, to avoid pyflakes warning
    golden_section()


text:
using System;

namespace Science.Cryptography.Ciphers;

public struct StraddlingCheckerboard
{
	private StraddlingCheckerboard(char[,] buffer, int[] indexes)
	{
		_buffer = buffer;
		_indexes = indexes;
		_height = buffer.GetLength(0);
	}

	public const int Width = 10;

	public const char EmptyValue = default;
	public const char FullStop = '.';
	public const char NumericEscape = '/';

	public const int EmptyIndex = -1;

	private readonly char[,] _buffer;
	private readonly int[] _indexes;
	private readonly int _height;

	public int Height => _height;

	private int TranslateRowIndexFromNamedToNumerical(int rowNamedIndex) => rowNamedIndex switch
	{
		EmptyIndex => 0,
		_ when _indexes.AsSpan().IndexOf(rowNamedIndex) is int translated and not -1 => 1 + translated,
		_ => throw new ArgumentOutOfRangeException(nameof(rowNamedIndex))
	};

	private int TranslateRowIndexFromNumericalToNamed(int rowNumericalIndex) => rowNumericalIndex switch
	{
		0 => EmptyIndex,
		_ => _indexes[rowNumericalIndex - 1]
	};

	/// <summary>
	/// Gets a <see cref="char"/> at a specified position.
	/// </summary>
	/// <param name="row">The custom index of the row of the checkerboard.</param>
	/// <param name="column">The column of the checkerboard.</param>
	/// <returns></returns>
	public char this[int namedRow, int column] => _buffer[TranslateRowIndexFromNamedToNumerical(namedRow), column];

	public static StraddlingCheckerboard CreateFromCharacters(ReadOnlySpan<char> source, params int[] namedRowIndexes)
	{
		var (quotient, remainder) = Math.DivRem(source.Length, Width);
		if (remainder != 0)
		{
			throw new ArgumentOutOfRangeException(nameof(source), $"Size of input characters must be a multiplier of {Width}.");
		}

		var buffer = new char[quotient, Width];
		ArrayHelper.FillFast(buffer, source, quotient, Width);
		return new(buffer, namedRowIndexes);
	}

	public static StraddlingCheckerboard Create(char[,] source, params int[] namedRowIndexes)
	{
		if (source.GetLength(1) != 10)
		{
			throw new ArgumentOutOfRangeException(nameof(source));
		}

		if (source.GetLength(0) != 1 + namedRowIndexes.Length)
		{
			throw new ArgumentOutOfRangeException(nameof(source));
		}

		foreach (var rowIndex in namedRowIndexes.AsSpan())
		{
			if (source[0, rowIndex] != EmptyValue)
			{
				throw new ArgumentException($"Top row of source at index {rowIndex} must be empty.", nameof(source));
			}
		}

		return new(source, namedRowIndexes);
	}

	public bool TryFindOffsets(char ch, out (int namedRow, int column) position)
	{
		if (ArrayHelper.TryFindOffsets(_buffer, ch, out position, _height, Width))
		{
			position.namedRow = TranslateRowIndexFromNumericalToNamed(position.namedRow);
			return true;
		}

		return false;
	}

	public ReadOnlySpan<char> GetRow(int namedRowIndex) =>
		_buffer.AsSpan(_height, Width).Slice(TranslateRowIndexFromNamedToNumerical(namedRowIndex) * Width, Width);

	public ReadOnlySpan<int> GetNamedIndexes() => _indexes;

	public char[,] ToCharArray() => (char[,])_buffer.Clone();
}


text:
angular.module('orka.featurelist')
/**
 * @ngdoc directive
 * @name orka.featurelist.directive:orkaFeatureList
 *
 * @requires $filter
 * @requires $timeout
 * @requires anolApi/anol.map.MapService
 * @requires anolApi/anol.map.LayersService
 * @requires LayertreeService
 * @requires orka.config.ConfigService
 *
 * @description
 * Add a list of currently visible POIs. When clicking on list entry, corresponding POI in map will be highlighted.
 */
.directive('orkaFeatureList', ['$filter', '$timeout', 'MapService', 'LayersService', 'LayertreeService', 'ConfigService', function($filter, $timeout, MapService, LayersService, LayertreeService, ConfigService) {
    return {
        restrict: 'A',
        replace: true,
        scope: {},
        transclude: true,
        templateUrl: 'src/modules/featurelist/templates/featurelist.html',
        link: {
            pre: function(scope, element, attr) {
                scope.map = MapService.getMap();
                scope.featureGroups = false;
                scope.featureLayer = LayersService.layersByProperty('layer', ConfigService.config.poi.layerName)[0];

                scope.typeMap = {};

                LayertreeService.poisLoaded.then(function() {
                    scope.typeMap = LayertreeService.typeMap;
                });

                // TODO simplify
                scope.toggleMarker = function(feature) {
                    if(scope.markerFeature !== undefined) {
                        var markerVisible = ol.extent.containsCoordinate(scope.extent, scope.markerFeature.getGeometry().getCoordinates());
                        if(!markerVisible && feature === undefined) {
                            scope.markerFeature.set('highlightMarker', false);
                            return;
                        } else if(!markerVisible && feature !== undefined) {
                            scope.markerFeature.set('highlightMarker', false);
                            scope.markerFeature = feature;
                            scope.markerFeature.set('highlightMarker', true);
                            return;
                        } else if(feature === undefined) {
                            scope.markerFeature.set('highlightMarker', true);
                            return;
                        }
                        if(feature === undefined) {
                            scope.markerFeature.set('highlightMarker', false);
                            scope.markerFeature = feature;
                            return;
                        }
                        if(feature !== scope.markerFeature) {
                            scope.markerFeature.set('highlightMarker', false);
                            scope.markerFeature = feature;
                            scope.markerFeature.set('highlightMarker', true);
                            return;
                        } else {
                            scope.markerFeature.set('highlightMarker', false);
                            scope.markerFeature = undefined;
                            return;
                        }
                    } else if(feature !== undefined) {
                        scope.markerFeature = feature;
                        scope.markerFeature.set('highlightMarker', true);
                    }
                };

                scope.moveContentOutofOverflow = function() {
                    var id;
                    if(scope.showFeatureContent !== false) {
                        id = 'feature_' + scope.showFeatureContent;
                        scope.scrollToFeatureById(id);
                    }
                };
                scope.scrollToFeatureById = function(id) {
                    var featureElement = element.find('#' + id);
                    if(featureElement.length > 0) {
                        var currentScrollTop = element.scrollTop();
                        var containerTop = element.offset().top;
                        var elementTop = featureElement.offset().top;
                        var scrollTo = (elementTop + currentScrollTop) - containerTop;
                        element.scrollTop(scrollTo);
                    }
                };
                scope.toggleFeatureContent = function(feature) {
                    scope.showFeatureContent = scope.showFeatureContent === feature.get('osm_id') ? false : feature.get('osm_id');

                    if(scope.markerFeature !== undefined || scope.showFeatureContent !== false) {
                        scope.toggleMarker(feature);
                    }

                    if(angular.isDefined(scope.popupScope)) {
                        scope.popupScope.popupVisible = false;
                    }
                };
                // minimum requirements for address are street and city
                scope.hasAddress = function(feature) {
                    return feature.get('addr:street') !== undefined && feature.get('addr:city') !== undefined;
                };
                scope.byName = function(feature) {
                    return feature.get('name');
                };
            },
            post: function(scope, element, attr) {
                var calculateExtent = function(map) {
                    return map.getView().calculateExtent(map.getSize());
                };
                var featuresByExtent = function() {
                    var featureGroups = {};
                    if(scope.featureLayer.getVisible()) {
                        var _features = scope.featureLayer.getSource().getFeatures();
                        angular.forEach(_features, function(feature) {
                            if(ol.extent.intersects(scope.extent, feature.getGeometry().getExtent())) {
                                var featureType = feature.get('type');
                                if(scope.markerFeature !== undefined && scope.markerFeature.get('osm_id') === feature.get('osm_id')) {
                                    scope.markerFeature = feature;
                                }
                                if(featureGroups[featureType] === undefined) {
                                    featureGroups[featureType] = [];
                                }
                                featureGroups[featureType].push(feature);
                            }
                        });
                    }
                    if(Object.keys(featureGroups).length === 0) {
                        return false;
                    }
                    return featureGroups;
                };

                scope.map.on('moveend', function(evt) {
                    var extent = calculateExtent(evt.target);
                    scope.$apply(function() {
                        scope.extent = extent;
                    });
                });

                scope.featureLayer.getSource().on('anolSourceUpdated', function() {
                    var features = featuresByExtent();
                    scope.$apply(function() {
                        scope.featureGroups = features;
                    });
                    scope.toggleMarker();
                });

                scope.$watch('extent', function(newVal, oldVal) {
                    scope.featureGroups = featuresByExtent();
                });

                scope.$watch(function() {
                    return LayertreeService.selectedPoiTypes;
                }, function(newVal, oldVal) {
                    if(newVal.length === 0) {
                        scope.featureGroups = featuresByExtent();
                    }
                    scope.toggleMarker();
                });

                scope.$watch('featureGroups', function(newVal, oldVal) {
                    if(scope.showFeatureContent !== false) {
                        $timeout(scope.moveContentOutofOverflow, 0, false);
                    }
                });

                scope.extent = calculateExtent(scope.map);
            }
        },
        controller: function($scope, $element, $attrs) {
            this.showListFeature = function(feature) {
                var type, osmId;
                if($scope.markerFeature !== undefined) {
                    $scope.markerFeature.set('highlightMarker', false);
                    $scope.markerFeature = undefined;
                }
                $scope.toggleMarker();

                if(feature !== undefined) {
                    type = feature.get('type');
                    osmId = feature.get('osm_id');
                    $scope.$apply(function() {
                        $scope.showGroup = type;
                        $scope.showFeatureContent = osmId;
                    });
                    $timeout($scope.moveContentOutofOverflow, 0, false);
                } else {
                    $scope.showFeatureContent = osmId;
                }

            };
            this.registerPopupScope = function(popupScope) {
                $scope.popupScope = popupScope;
            };
        }
    };
}]);


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

namespace Pug.Availability
{
	public interface ICheckerFactory
	{
		IChecker Create(IDictionary<string, string> parameters);
	}
}


text:
'use strict';

var GeometricUtil = require('./GeometricUtil');

var getDistance = require('./GeometricUtil').getDistancePointPoint;

var getAttachment = require('./LineAttachmentUtil').getAttachment;

function findNewLabelLineStartIndex(oldWaypoints, newWaypoints, attachment, hints) {

  var index = attachment.segmentIndex;

  var offset = newWaypoints.length - oldWaypoints.length;

  // segmentMove happend
  if (hints.segmentMove) {

    var oldSegmentStartIndex = hints.segmentMove.segmentStartIndex,
        newSegmentStartIndex = hints.segmentMove.newSegmentStartIndex;

    // if label was on moved segment return new segment index
    if (index === oldSegmentStartIndex) {
      return newSegmentStartIndex;
    }

    // label is after new segment index
    if (index >= newSegmentStartIndex) {
      return (index+offset < newSegmentStartIndex) ? newSegmentStartIndex : index+offset;
    }

    // if label is before new segment index
    return index;
  }

  // bendpointMove happend
  if (hints.bendpointMove) {

    var insert = hints.bendpointMove.insert,
        bendpointIndex = hints.bendpointMove.bendpointIndex,
        newIndex;

    // waypoints length didnt change
    if (offset === 0) {
      return index;
    }

    // label behind new/removed bendpoint
    if (index >= bendpointIndex) {
      newIndex = insert ? index + 1 : index - 1;
    }

    // label before new/removed bendpoint
    if (index < bendpointIndex) {

      newIndex = index;

      // decide label should take right or left segment
      if (insert && attachment.type !== 'bendpoint' && bendpointIndex-1 === index) {

        var rel = relativePositionMidWaypoint(newWaypoints, bendpointIndex);

        if (rel < attachment.relativeLocation) {
          newIndex++;
        }
      }
    }

    return newIndex;
  }

  // start/end changed
  if (offset === 0) {
    return index;
  }

  if (hints.connectionStart) {
    return (index === 0) ? 0 : null;
  }

  if (hints.connectionEnd) {
    return (index === oldWaypoints.length - 2) ? newWaypoints.length - 2 : null;
  }

  // if nothing fits, return null
  return null;
}

module.exports.findNewLabelLineStartIndex = findNewLabelLineStartIndex;

/**
 * Calculate the required adjustment (move delta) for the given label
 * after the connection waypoints got updated.
 *
 * @param {djs.model.Label} label
 * @param {Array<Point>} newWaypoints
 * @param {Array<Point>} oldWaypoints
 * @param {Object} hints
 *
 * @return {Point} delta
 */
function getLabelAdjustment(label, newWaypoints, oldWaypoints, hints) {

  var x = 0,
      y = 0;

  var labelPosition = getLabelMid(label);

  // get closest attachment
  var attachment = getAttachment(labelPosition, oldWaypoints),
      oldLabelLineIndex = attachment.segmentIndex,
      newLabelLineIndex = findNewLabelLineStartIndex(oldWaypoints, newWaypoints, attachment, hints);

  if ( newLabelLineIndex === null ) {
    return { x: x, y: y };
  }

  // should never happen
  // TODO(@janstuemmel): throw an error here when connectionSegmentMove is refactored
  if (newLabelLineIndex < 0 ||
      newLabelLineIndex > newWaypoints.length - 2) {
    return { x: x, y: y };
  }

  var oldLabelLine = getLine(oldWaypoints, oldLabelLineIndex),
      newLabelLine = getLine(newWaypoints, newLabelLineIndex),
      oldFoot = attachment.position;

  var relativeFootPosition = getRelativeFootPosition(oldLabelLine, oldFoot),
      angleDelta = getAngleDelta(oldLabelLine, newLabelLine);

  // special rule if label on bendpoint
  if (attachment.type === 'bendpoint') {

    var offset = newWaypoints.length - oldWaypoints.length,
        oldBendpointIndex = attachment.bendpointIndex,
        oldBendpoint = oldWaypoints[oldBendpointIndex];

    // bendpoint position hasnt changed, return same position
    if (newWaypoints.indexOf(oldBendpoint) !== -1) {
      return { x: x, y: y };
    }

    // new bendpoint and old bendpoint have same index, then just return the offset
    if (offset === 0) {
      var newBendpoint = newWaypoints[oldBendpointIndex];

      return {
        x: newBendpoint.x - attachment.position.x,
        y: newBendpoint.y - attachment.position.y
      };
    }

    // if bendpoints get removed
    if (offset < 0 && oldBendpointIndex !== 0 && oldBendpointIndex < oldWaypoints.length - 1) {
      relativeFootPosition = relativePositionMidWaypoint(oldWaypoints, oldBendpointIndex);
    }
  }

  var newFoot = {
    x: (newLabelLine[1].x - newLabelLine[0].x) * relativeFootPosition + newLabelLine[0].x,
    y: (newLabelLine[1].y - newLabelLine[0].y) * relativeFootPosition + newLabelLine[0].y
  };

  // the rotated vector to label
  var newLabelVector = GeometricUtil.rotateVector({
    x: labelPosition.x - oldFoot.x,
    y: labelPosition.y - oldFoot.y
  }, angleDelta);

  // the new relative position
  x = newFoot.x + newLabelVector.x - labelPosition.x;
  y = newFoot.y + newLabelVector.y - labelPosition.y;

  return { x: x, y: y };
}

module.exports.getLabelAdjustment = getLabelAdjustment;

//// HELPERS ///////

function relativePositionMidWaypoint(waypoints, idx) {

  var distanceSegment1 = getDistance(waypoints[idx-1], waypoints[idx]),
      distanceSegment2 = getDistance(waypoints[idx], waypoints[idx+1]);

  var relativePosition = distanceSegment1 / ( distanceSegment1 + distanceSegment2 );

  return relativePosition;

}

function getLabelMid(label) {
  return {
    x: label.x + label.width / 2,
    y: label.y + label.height / 2
  };
}

function getAngleDelta(l1, l2) {
  var a1 = GeometricUtil.getAngle(l1),
      a2 = GeometricUtil.getAngle(l2);
  return a2 - a1;
}

function getLine(waypoints, idx) {
  return [ waypoints[idx], waypoints[idx+1] ];
}

function getRelativeFootPosition(line, foot) {
  var length = GeometricUtil.getDistancePointPoint(line[0], line[1]),
      lengthToFoot = GeometricUtil.getDistancePointPoint(line[0], foot);
  return lengthToFoot / length;
}


text:
"""Test task extraction for autotvm"""

import nnvm.testing
import nnvm.compiler
from tvm import autotvm

def get_network(name, batch_size):
    """Get the symbol definition and random weight of a network"""
    input_shape = (batch_size, 3, 224, 224)
    output_shape = (batch_size, 1000)

    if name == 'resnet-18':
        net, params = nnvm.testing.resnet.get_workload(num_layers=18, batch_size=batch_size)
    elif name == 'mobilenet':
        net, params = nnvm.testing.mobilenet.get_workload(batch_size=batch_size)
    elif name == 'squeezenet v1.1':
        net, params = nnvm.testing.squeezenet.get_workload(batch_size=batch_size, version='1.1')
    elif name == 'vgg-16':
        net, params = nnvm.testing.vgg.get_workload(num_layers=16, batch_size=batch_size)
    elif name == 'dcgan':
        net, params = nnvm.testing.dcgan.get_workload(batch_size=batch_size)
        input_shape = (batch_size, 100)
    else:
        raise ValueError("Unsupported network: " + name)

    return net, params, input_shape, output_shape

def test_task_extraction():
    target = 'llvm'
    dtype = 'float32'

    net, params, input_shape, out_shape = get_network('resnet-18', batch_size=1)
    tasks = autotvm.task.extract_from_graph(net, target=target,
                                            shape={'data': input_shape}, dtype=dtype,
                                            symbols=(nnvm.sym.conv2d,))
    assert len(tasks) == 12

    net, params, input_shape, out_shape = get_network('resnet-18', batch_size=1)
    tasks = autotvm.task.extract_from_graph(net, target=target,
                                            shape={'data': input_shape}, dtype=dtype,
                                            symbols=(nnvm.sym.dense,))
    assert len(tasks) == 1

    net, params, input_shape, out_shape = get_network('resnet-18', batch_size=1)
    tasks = autotvm.task.extract_from_graph(net, target=target,
                                            shape={'data': input_shape}, dtype=dtype,
                                            symbols=(nnvm.sym.conv2d, nnvm.sym.dense))
    assert len(tasks) == 13

    net, params, input_shape, out_shape = get_network('mobilenet', batch_size=1)
    tasks = autotvm.task.extract_from_graph(net, target=target,
                                            shape={'data': input_shape}, dtype=dtype,
                                            symbols=(nnvm.sym.conv2d, nnvm.sym.dense))
    assert len(tasks) == 20

    net, params, input_shape, out_shape = get_network('dcgan', batch_size=1)
    tasks = autotvm.task.extract_from_graph(net, target=target,
                                            shape={'data': input_shape}, dtype=dtype,
                                            symbols=(nnvm.sym.conv2d_transpose,))
    assert len(tasks) == 4

if __name__ == '__main__':
    test_task_extraction()


text:
<?php
/**
 * Created by PhpStorm.
 * User: phpcyy
 * Date: 21/12/2017
 * Time: 2:54 PM
 */

namespace Strategy;

class Add extends Compute
{
    public function getResult(): float
    {
        return $this->number1 + $this->number2;
    }
}


text:
package water.api.schemas3;

import hex.ModelMetricsRegressionGeneric;
import water.api.API;

public class ModelMetricsRegressionGenericV3<I extends ModelMetricsRegressionGeneric, S extends ModelMetricsRegressionGenericV3<I, S>> extends ModelMetricsBaseV3<I, S> {

  @API(help="The mean residual deviance for this scoring run.", direction=API.Direction.OUTPUT)
  public double mean_residual_deviance;

  @API(help="The mean absolute error for this scoring run.", direction=API.Direction.OUTPUT)
  public double mae;

  @API(help="The root mean squared log error for this scoring run.", direction=API.Direction.OUTPUT)
  public double rmsle;

  @Override
  public S fillFromImpl(I modelMetrics) {
    super.fillFromImpl(modelMetrics);
    mae = modelMetrics._mean_absolute_error;
    rmsle = modelMetrics._root_mean_squared_log_error;
    mean_residual_deviance = modelMetrics._mean_residual_deviance;
    return (S) this;
  }
}


text:
package io.backchat.http

case class HttpException(failure: HttpFailure, reason: String = "") extends RuntimeException(reason)

object HttpException {
  def apply(failure: HttpFailure) = new HttpException(failure, failure.defaultMessage)
  def apply(failure: HttpFailure, cause: Throwable) = new HttpException(failure, cause.getMessage)
}


text:
package oncall

import (
	"fmt"
	"log"
	"github.com/wm/go_pager"
	"net/http"
	"strconv"
	"strings"
)

func Welcome(config *go_pager.Config) string {
	list := ""

	for _, contact := range(config.Contacts) {
		list += contact.Name + ": "
		list += contact.Number + ", "
	}

	return fmt.Sprintf(`here is: %v`, list)
}

func AttemptCall(req *http.Request, w http.ResponseWriter, config *go_pager.Config) string {
	var commands string

	dialCallStatus := req.PostFormValue("DialCallStatus")
	numberIndexStr := req.FormValue("number_index")

	if numberIndexStr == "" {
		numberIndexStr = "0"
	}

	numberIndex, _ := strconv.Atoi(numberIndexStr)
	log.Printf("param[`DialCallStatus`] %v", dialCallStatus)

	if dialCallStatus == "completed"{
		commands = hangUp()
	} else if (numberIndex < len(config.Contacts)) {
		commands = dialContact(numberIndex + 1, (config.Contacts)[numberIndex])
	} else {
		commands = appologise() + hangUp()
	}

	return respond(commands)
}

func ScreenForMachine() string {
	return `
	<Gather action='/oncall/complete_call'>
	<Say>Press any key to accept this call</Say>
	</Gather>
	<Hangup/>
	`
}

func CompleteCall() string {
	return `<Say>Connecting</Say>`
}

func respond(commands string) string {
	response := fmt.Sprintf(`
	<?xml version='1.0' encoding='UTF-8'?>
	<Response>%v</Response>
	`, commands)

	log.Printf("response: %v", response)

	return strings.TrimSpace(response)
}

func hangUp() string {
	return `<Hangup/>`
}

func appologise() string {
	return `
	<Say>
	We are sorry but we are unable to connect you with an on call Engineer.
	Please try again.
	</Say>
	`
}

func dialContact(nextContactIndex int, contact go_pager.Contact) string {
	log.Printf("Forwarding to contact: %v", contact.Name)

	return fmt.Sprintf(`
	<Say>Attempting to connect you with %v, today's on call engineer.</Say>
	<Dial action='/oncall/attempt_call?number_index=%v'>
		<Number url='/oncall/screen_for_machine'>%v</Number>
	</Dial>
	`, contact.Name, strconv.Itoa(nextContactIndex), contact.Number)
}


text:
package pl.grzeslowski.jsupla.protocoljava.api.parsers.sc;

import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannel;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sc.Channel;

@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
public interface ChannelParser extends ServerClientParser<Channel, SuplaChannel> {
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="manifest" href="site.webmanifest">
        <link rel="apple-touch-icon" href="icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">

Nienna

Half-Elf Ranger

lvl 4

                <button class="expand-character-details">...</button>

1

2

3

4

5

6

Ability Scores

                            STR 12
                            +1

                            DEX 18
                            +4

                            CON 12
                            +1

                            INT 16
                            +3

                            WIS 14
                            +2

                            CHA 14
                            +2

                            Proficiency +2

                            Passive Wisdom 12

Skills

                            STR 12
                            +1


text:
module ProMotion
  module ScreenNavigation
    include ProMotion::Support

    def open_screen(screen, args = {})
      args = { animated: true }.merge(args)

      # Apply properties to instance
      screen = set_up_screen_for_open(screen, args)
      ensure_wrapper_controller_in_place(screen, args)

      opened ||= open_in_split_screen(screen, args) if self.split_screen
      opened ||= open_root_screen(screen) if args[:close_all]
      opened ||= present_modal_view_controller(screen, args) if args[:modal]
      opened ||= open_in_tab(screen, args[:in_tab]) if args[:in_tab]
      opened ||= push_view_controller(screen, self.navigationController, !!args[:animated]) if self.navigationController
      opened ||= open_root_screen(screen.navigationController || screen)
      screen
    end
    alias :open :open_screen

    def open_in_split_screen(screen, args)
      self.split_screen.detail_screen = screen if args[:in_detail]
      self.split_screen.master_screen = screen if args[:in_master]
      args[:in_detail] || args[:in_master]
    end

    def open_root_screen(screen)
      app_delegate.open_root_screen(screen)
    end

    def open_modal(screen, args = {})
      open screen, args.merge({ modal: true })
    end

    def close_screen(args = {})
      args ||= {}
      args = { sender: args } unless args.is_a?(Hash)
      args[:animated] = true unless args.has_key?(:animated)

      if self.modal?
        close_nav_screen args if self.navigationController
        close_modal_screen args

      elsif self.navigationController
        close_nav_screen args
        send_on_return(args)

      else
        mp "Tried to close #{self.to_s}; however, this screen isn't modal or in a nav bar.", force_color: :yellow
      end
    end
    alias :close :close_screen

    def send_on_return(args = {})
      return unless self.parent_screen
      if self.parent_screen.respond_to?(:on_return)
        if args && self.parent_screen.method(:on_return).arity != 0
          self.parent_screen.send(:on_return, args)
        else
          self.parent_screen.send(:on_return)
        end
      elsif self.parent_screen.private_methods.include?(:on_return)
        mp "#{self.parent_screen.inspect} has an `on_return` method, but it is private and not callable from the closing screen.", force_color: :yellow
      end
    end

    def push_view_controller(vc, nav_controller=nil, animated=true)
      unless self.navigationController
        mp "You need a nav_bar if you are going to push #{vc.to_s} onto it.", force_color: :red
      end
      nav_controller ||= self.navigationController
      return if nav_controller.topViewController == vc
      vc.first_screen = false if vc.respond_to?(:first_screen=)
      nav_controller.pushViewController(vc, animated: animated)
    end

  protected

    def set_up_screen_for_open(screen, args={})

      # Instantiate screen if given a class
      screen = screen.new if screen.respond_to?(:new)

      # Store screen options
      screen.instance_variable_set(:@screen_options, args)

      # Set parent
      screen.parent_screen = self if screen.respond_to?(:parent_screen=)

      # Set title & modal properties
      screen.title = args[:title] if args[:title] && screen.respond_to?(:title=)
      screen.modal = args[:modal] if args[:modal] && screen.respond_to?(:modal=)

      # Hide bottom bar?
      screen.hidesBottomBarWhenPushed = args[:hide_tab_bar] == true

      # Wrap in a PM::NavigationController?
      screen.add_nav_bar(args) if args[:nav_bar] && screen.respond_to?(:add_nav_bar)

      # Return modified screen instance
      screen

    end

    def ensure_wrapper_controller_in_place(screen, args={})
      unless args[:close_all] || args[:modal] || args[:in_detail] || args[:in_master]
        screen.navigationController ||= self.navigationController if screen.respond_to?("navigationController=")
        screen.tab_bar ||= self.tab_bar if screen.respond_to?("tab_bar=")
      end
    end

    def present_modal_view_controller(screen, args={})
      self.presentViewController((screen.navigationController || screen), animated: args[:animated], completion: args[:completion])
    end

    def open_in_tab(screen, tab_name)
      vc = open_tab(tab_name)
      return mp("No tab bar item '#{tab_name}'", force_color: :red) && nil unless vc
      if vc.is_a?(UINavigationController)
        push_view_controller(screen, vc)
      else
        replace_view_controller(screen, vc)
      end
    end

    def replace_view_controller(new_vc, old_vc)
      self.tab_bar.viewControllers = self.tab_bar.viewControllers.map do |vc|
        vc == old_vc ? new_vc : vc
      end
    end

    def close_modal_screen(args={})
      args[:animated] = true unless args.has_key?(:animated)
      self.parent_screen.dismissViewControllerAnimated(args[:animated], completion: lambda {
        send_on_return(args)
      })
    end

    def close_nav_screen(args={})
      args[:animated] = true unless args.has_key?(:animated)
      if args[:to_screen] == :root
        self.parent_screen = self.navigationController.viewControllers.first
        self.navigationController.popToRootViewControllerAnimated args[:animated]
      elsif args[:to_screen] && args[:to_screen].is_a?(UIViewController)
        self.parent_screen = args[:to_screen]
        self.navigationController.popToViewController(args[:to_screen], animated: args[:animated])
      else
        self.navigationController.popViewControllerAnimated(args[:animated])
      end
      self.navigationController = nil
    end

  end
end


text:
using System;
using Agiil.Domain.Activity;
using Agiil.Domain.Tickets;
using AutoMapper;

namespace Agiil.ObjectMaps.Resolvers
{
    public class TotalWorkLoggedForTicketResolver : IValueResolver<Ticket,object,TimeSpan>
    {
        readonly IGetsSumOfLoggedWorkForTicket workLogProvider;

        public TimeSpan Resolve(Ticket source, object destination, TimeSpan destMember, ResolutionContext context)
            => workLogProvider.GetTotalTimeLogged(source);

        public TotalWorkLoggedForTicketResolver(IGetsSumOfLoggedWorkForTicket workLogProvider)
        {
            this.workLogProvider = workLogProvider ?? throw new ArgumentNullException(nameof(workLogProvider));
        }
    }
}


text:
package com.arialyy.absadapter;

/**
 * Created by lyy on 2016/7/11.
 */
public class AbsConstance {

    public static class PATH {
        private static final String rootPath = System.getProperty("user.dir") + "/cache/build/";
        public static final String TEMP_PARAMS_PATH = rootPath + "mPro.properties";
    }

    public static class KEY {
        public static final String CLASS_NAME = "CLASS_NAME";
        public static final String CLASS_TYPE = "CLASS_TYPE";
    }

    public static class PARAMS {
        public static final String CLASS_NAME = "CLASS_NAME";
        public static final String CLASS_TYPE = "CLASS_TYPE";
        public static final String CONFIG_CLASS_NAME = "AbsParamsTemp";
        public static final String TEMP_CLASS_PACKAGE = "com.arialyy.temp";
    }

}


text:
package org.wildfly.swarm;

import org.jboss.modules.MavenArtifactUtil;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.FileAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.impl.base.importer.zip.ZipImporterImpl;

import java.io.*;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Bob McWhirter
 */
public class ArtifactManager {

    public static JavaArchive artifact(String gav) throws IOException, ModuleLoadException {
        File file = findFile(gav);
        JavaArchive archive = ShrinkWrap.create(JavaArchive.class, file.getName());
        new ZipImporterImpl(archive).importFrom(file);
        return archive;
    }

    public static JavaArchive artifact(String gav, String asName) throws IOException, ModuleLoadException {
        File file = findFile(gav);
        JavaArchive archive = ShrinkWrap.create(JavaArchive.class, asName);
        new ZipImporterImpl(archive).importFrom(file);
        return archive;
    }

    public static List<JavaArchive> allArtifacts() throws IOException {
        List<JavaArchive> archives  = new ArrayList<>();

        InputStream depsTxt = ClassLoader.getSystemClassLoader().getResourceAsStream("META-INF/wildfly-swarm-dependencies.txt");

        if (depsTxt != null) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(depsTxt))) {

                String line = null;

                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.length() > 0) {
                        File artifact = MavenArtifactUtil.resolveJarArtifact(line);

                        JavaArchive archive = ShrinkWrap.create(JavaArchive.class, artifact.getName());
                        new ZipImporterImpl(archive).importFrom(artifact);
                        archives.add( archive );
                    }
                }
            }
        } else {
            String classpath = System.getProperty("java.class.path");
            String javaHome = System.getProperty("java.home");
            Path pwd = Paths.get( System.getProperty("user.dir" ) );
            if (classpath != null) {
                String[] elements = classpath.split(File.pathSeparator);

                for (int i = 0; i < elements.length; ++i) {
                    if (!elements[i].startsWith(javaHome)) {
                        File artifact = new File(elements[i]);
                        if (artifact.isFile()) {
                            JavaArchive archive = ShrinkWrap.create(JavaArchive.class, artifact.getName());
                            new ZipImporterImpl(archive).importFrom(artifact);
                            archives.add( archive );
                        }  else {
                            if ( artifact.toPath().startsWith( pwd ) ) {
                                continue;
                            }

                            JavaArchive archive = ShrinkWrap.create(JavaArchive.class);
                            Path basePath = artifact.toPath();
                            Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
                                @Override
                                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                                    //System.err.println(  basePath.relativize(file).toString() );
                                    archive.add(new FileAsset(file.toFile()), basePath.relativize(file).toString());
                                    return FileVisitResult.CONTINUE;
                                }
                            });
                            archives.add(archive);
                        }
                    }
                }
            }

        }

        return archives;
    }

    private static File findFile(String gav) throws IOException, ModuleLoadException {
        String[] parts = gav.split(":");

        if (parts.length < 2) {
            throw new RuntimeException("GAV must includes at least 2 segments");
        }

        String groupId = parts[0];
        String artifactId = parts[1];
        String version = null;
        String classifier = "";

        if (parts.length > 3) {
            classifier = parts[3];
        }

        if (parts.length > 2) {
            version = parts[2];
        } else {
            version = determineVersionViaModule(groupId, artifactId, classifier);
        }

        if (version == null) {
            version = determineVersionViaClasspath(groupId, artifactId, classifier);
        }

        if (version == null) {
            throw new RuntimeException("Unable to determine version number from 2-part GAV.  Try three!");
        }

        return MavenArtifactUtil.resolveJarArtifact(groupId + ":" + artifactId + ":" + version + (classifier == null ? "" : ":" + classifier));
    }

    private static String determineVersionViaModule(String groupId, String artifactId, String classifier) throws ModuleLoadException {
        Module module = Module.getBootModuleLoader().loadModule(ModuleIdentifier.create("APP", "dependencies"));
        return module.getProperty("version." + groupId + ":" + artifactId + "::" + classifier);
    }

    private static String determineVersionViaClasspath(String groupId, String artifactId, String classifier) {

        String regexp = ".*" + artifactId + "-(.+)" + (classifier.length() == 0 ? "" : "-" + classifier) + ".jar";
        Pattern pattern = Pattern.compile(regexp);

        String classpath = System.getProperty("java.class.path");
        String[] elements = classpath.split(File.pathSeparator);

        for (int i = 0; i < elements.length; ++i) {
            Matcher matcher = pattern.matcher(elements[i]);
            if (matcher.matches()) {
                return matcher.group(1);
            }
        }

        return null;
    }

}


text:
package nl.yacht.lakesideresort.manager;

import nl.yacht.lakesideresort.exception.AlreadyExistException;
import nl.yacht.lakesideresort.repository.BookingRepository;
import nl.yacht.lakesideresort.repository.GuestRepository;
import nl.yacht.lakesideresort.repository.RoomRepository;
import nl.yacht.lakesideresort.domain.Booking;
import nl.yacht.lakesideresort.domain.Guest;
import nl.yacht.lakesideresort.domain.Room;
import nl.yacht.lakesideresort.exception.NotFoundException;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.HashMap;

@Component
public class BookingManager {

    private final BookingRepository bookingRepository;
    private final GuestRepository guestRepository;
    private final RoomRepository roomRepository;
    private final AvailabilityManager availabilityManager;

    BookingManager(BookingRepository bookingRepository, GuestRepository guestRepository, RoomRepository roomRepository, AvailabilityManager availabilityManager) {
        this.bookingRepository = bookingRepository;
        this.guestRepository = guestRepository;
        this.roomRepository = roomRepository;
        this.availabilityManager = availabilityManager;
    }

    public Iterable<Booking> getBookings(){
        return bookingRepository.findAll();
    }

    public Booking getBooking(long id) {
        Booking booking = bookingRepository.findOne(id);
        if (booking == null)
            throw new NotFoundException();
        return booking;
    }

    public Booking insertBooking(Booking booking) {
        if(booking == null) {
            System.out.println("booking is null");
            throw new NotFoundException();
        }
        Guest foundGuest = guestRepository.findOne(booking.getGuest().getGuestNumber());
        if(foundGuest == null) {
            System.out.println("guest is null");
            throw new NotFoundException();
        }
        booking.setGuest(foundGuest);
        Room foundRoom = roomRepository.findOne(booking.getRoom().getId());
        if(foundRoom == null) {
            System.out.println("room is null");
            throw new NotFoundException();
        }
        booking.setRoom(foundRoom);
        if(!checkAvailable(booking.getRoom().getRoomNumber(), booking.getStartDate(), booking.getEndDate())){
            System.out.println("room is not available");
            throw new AlreadyExistException();
        }
        bookingRepository.save(booking);
        return booking;
    }

    public Booking changeBooking(long id, Booking booking){
        if(booking == null) throw new NotFoundException();

        Booking foundBooking = bookingRepository.findOne(id);
        if(foundBooking == null) throw new NotFoundException();

        Guest guest = guestRepository.findOne(booking.getGuest().getGuestNumber());
        if(guest == null) throw new NotFoundException();
        foundBooking.setGuest(guest);

        Room room = roomRepository.findOne(booking.getRoom().getId());
        if(room == null) throw new NotFoundException();
        foundBooking.setRoom(room);

        foundBooking.setStartDate(booking.getStartDate());
        foundBooking.setEndDate(booking.getEndDate());

        if(!checkAvailable(foundBooking.getRoom().getRoomNumber(), foundBooking.getStartDate(), foundBooking.getEndDate())){
            System.out.println("room is not available");
            throw new AlreadyExistException();
        }

        bookingRepository.save(booking);

        return foundBooking;
    }

    public void deleteBooking(long id) {
        Booking foundBooking = bookingRepository.findOne(id);
        if (foundBooking == null) throw new NotFoundException();
        bookingRepository.delete(foundBooking);
    }

    private boolean checkAvailable(String roomNumber, LocalDate startDate, LocalDate endDate){
        boolean available = true;
        HashMap<String, Boolean> availability = availabilityManager.getAvailabilityOfRoom(roomNumber, startDate, endDate);
        LocalDate date = startDate;
        while((date.isBefore(endDate) || date.isEqual(endDate)) && available){
            date = date.plusDays(1);
            if(availability.getOrDefault(date.toString(),false)) available = false;
        }
        return available;
    }
}


text:
import * as React from "react";
import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils } from "aphrodite";

const styles = StyleSheet.create({
    red: {
        backgroundColor: 'red'
    },
    blue: {
        backgroundColor: 'blue'
    },
    hover: {
        ':hover': {
            backgroundColor: 'red'
        }
    },
    small: {
        '@media (max-width: 600px)': {
            backgroundColor: 'red',
        }
    }
});

const coolFont = {
    fontFamily: "CoolFont",
    fontStyle: "normal",
    fontWeight: "normal",
    src: "url('coolfont.woff2') format('woff2')"
};

const withFont = StyleSheet.create({
    headingText: {
        fontFamily: coolFont,
        fontSize: 20
    },
    bodyText: {
        fontFamily: [coolFont, "sans-serif"],
        fontSize: 12
    }
});

class App extends React.Component<{}, {}> {
    render() {
        return

                This is red.

                This turns red on hover.

                This turns red when the browser is less than 600px width.

                This is blue.

                This is blue and turns red when the browser is less than
                600px width.

                With font

;
    }
}

const output = StyleSheetServer.renderStatic(() => {
    return "test";
});

output.css.content;
output.css.renderedClassNames;
output.html;

StyleSheet.rehydrate(output.css.renderedClassNames);

StyleSheetTestUtils.suppressStyleInjection();
StyleSheetTestUtils.clearBufferAndResumeStyleInjection();


text:
package main

import (
  "github.com/trevex/golem"
  "fmt"
)

type User struct {
  Name string `json:"name"`
  conn *golem.Connection
}

type Message struct {
  Name string `json:"from"`
  Message string `json:"msg"`
}

type Chat struct {
  users []*User
}

func initializeChat(r *golem.Router) {
  chat := Chat{}
  r.On("hello", chat.join)
  r.On("client", chat.message)
  r.OnClose(chat.leave)
}

func (chat *Chat) join(conn *golem.Connection, data *User) {
  // add user to list
  data.conn = conn
  chat.users = append(chat.users, data)

  // send list of users to all clients
  for _, v := range chat.users {
    v.conn.Emit("users", chat.users)
  }

  fmt.Println(data.Name, "connected.")
}

func (chat *Chat) leave(conn *golem.Connection) {
  // remove user for users list
  for i, v := range chat.users {
    if v.conn == conn {
      chat.users = append(chat.users[:i], chat.users[i+1:]...)
      fmt.Println(v.Name, "disconnected.")
      break
    }
  }

  // send list of users to all clients
  for _, v := range chat.users {
    v.conn.Emit("users", chat.users)
  }
}

func (chat *Chat) message(conn *golem.Connection, data *Message) {
  for _, v := range chat.users {
    if v.conn != conn {
      v.conn.Emit("server", data)
    }
  }
  fmt.Println(data.Name, "said", data.Message)
}


text:
<title>Numeric Arguments - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Bindable-Readline-Commands.html#Bindable-Readline-Commands" title="Bindable Readline Commands">
<link rel="prev" href="Commands-For-Killing.html#Commands-For-Killing" title="Commands For Killing">
<link rel="next" href="Commands-For-Completion.html#Commands-For-Completion" title="Commands For Completion">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

<link rel="stylesheet" type="text/css" href="../cs.css">

Next: Commands For Completion,
Previous: Commands For Killing,
Up: Bindable Readline Commands

32.4.5 Specifying Numeric Arguments

digit-argument (M-0, M-1, ... M--)
Add this digit to the argument already accumulating, or start a new
argument.  M-- starts a negative argument.

universal-argument ()
This is another way to specify an argument.
If this command is followed by one or more digits, optionally with a
leading minus sign, those digits define the argument.
If the command is followed by digits, executing universal-argument
again ends the numeric argument, but is otherwise ignored.
As a special case, if this command is immediately followed by a
character that is neither a digit or minus sign, the argument count
for the next command is multiplied by four.
The argument count is initially one, so executing this function the
first time makes the argument count four, a second time makes the
argument count sixteen, and so on.
By default, this is not bound to a key.


text:
package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class MoviePage extends InternalPage {

	public MoviePage(PageManager pages) {
		super(pages);
	}

	public MoviePage ensurePageLoaded() {
	    super.ensurePageLoaded();
	    wait.until(presenceOfElementLocated(By.name("imdbid")));
	    return this;
	}

	@FindBy(css = "label[for='name']")
	private WebElement errorMovieTitle;

	@FindBy(css = "label[for='year']")
	private WebElement errorMovieYear;

	public String getMovieTitleError() {
		return errorMovieTitle.getText();
	}

	public String getMovieYearError() {
		return errorMovieYear.getText();
	}
}


text:
#pragma once

#include <pdal/plugin.hpp>
#include <pdal/Reader.hpp>

extern "C" int32_t FauxReader_ExitFunc();
extern "C" PF_ExitFunc FauxReader_InitPlugin();

namespace pdal
{

enum Mode
{
    Constant,
    Random,
    Ramp,
    Uniform,
    Normal
};

// The FauxReader doesn't read from disk, but instead just makes up data for its
// points.  The reader is constructed with a given bounding box and a given
// number of points.
//
// This reader knows about these fields (Dimensions):
//    X,Y,Z - floats
//    Time  - uint64
//    ReturnNumber (optional) - uint8
//    NumberOfReturns (optional) - uint8
//
// It supports a few modes:
//   - "random" generates points that are randomly distributed within the
//     given bounding box
//   - "constant" generates its points to always be at the minimum of the
//      bounding box
//   - "ramp" generates its points as a linear ramp from the minimum of the
//     bbox to the maximum
//   - "uniform" generates points that are uniformly distributed within the
//     given bounding box
//   - "normal" generates points that are normally distributed with a given
//     mean and standard deviation in each of the XYZ dimensions
// In all these modes, however, the Time field is always set to the point
// number.
//
// ReturnNumber and NumberOfReturns are not included by default, but can be
// activated by passing a numeric value as "number_of_returns" to the
// reader constructor.
//
class PDAL_DLL FauxReader : public Reader
{
public:
    FauxReader();

    static void * create();
    static int32_t destroy(void *);
    std::string getName() const;

    static Dimension::IdList getDefaultDimensions();
    Options getDefaultOptions();

private:
    Mode m_mode;
    double m_minX;
    double m_maxX;
    double m_minY;
    double m_maxY;
    double m_minZ;
    double m_maxZ;
    double m_mean_x;
    double m_mean_y;
    double m_mean_z;
    double m_stdev_x;
    double m_stdev_y;
    double m_stdev_z;
    double m_delX;
    double m_delY;
    double m_delZ;
    uint64_t m_time;
    int m_numReturns;
    int m_returnNum;
    point_count_t m_index;
    uint32_t m_seed;

    virtual void processOptions(const Options& options);
    virtual void addDimensions(PointLayoutPtr layout);
    virtual void ready(PointTableRef table);
    virtual bool processOne(PointRef& point);
    virtual point_count_t read(PointViewPtr view, point_count_t count);
    virtual bool eof()
        { return false; }

    FauxReader& operator=(const FauxReader&); // not implemented
    FauxReader(const FauxReader&); // not implemented
};

} // namespace pdal


text:
package org.jretty.util.resource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.jretty.util.UrlUtils;

/**
 * Abstract base class for resources which resolve URLs into File references,
 * such as {@link UrlResource} or {@link ClassPathResource}.
 *
 *
Detects the "file" protocol as well as the JBoss "vfs" protocol in URLs,
 * resolving file system references accordingly.
 *
 * @author Juergen Hoeller
 * @since 3.0
 */
public abstract class AbstractFileResolvingResource extends AbstractResource {

    /**
     * This implementation returns a File reference for the underlying class path
     * resource, provided that it refers to a file in the file system.
     * @see org.springframework.util.UrlUtils#getFile(java.net.URL, String)
     */
    @Override
    public File getFile() throws IOException {
        URL url = getURL();
        if (url.getProtocol().startsWith(UrlUtils.URL_PROTOCOL_VFS)) {
            return VfsResourceDelegate.getResource(url).getFile();
        }
        return UrlUtils.getFile(url, getDescription());
    }

    /**
     * This implementation determines the underlying File
     * (or jar file, in case of a resource in a jar/zip).
     */
    @Override
    protected File getFileForLastModifiedCheck() throws IOException {
        URL url = getURL();
        if (UrlUtils.isJarURL(url)) {
            URL actualUrl = UrlUtils.extractJarFileURL(url);
            if (actualUrl.getProtocol().startsWith(UrlUtils.URL_PROTOCOL_VFS)) {
                return VfsResourceDelegate.getResource(actualUrl).getFile();
            }
            return UrlUtils.getFile(actualUrl, "Jar URL");
        }
        else {
            return getFile();
        }
    }

    /**
     * This implementation returns a File reference for the underlying class path
     * resource, provided that it refers to a file in the file system.
     * @see org.springframework.util.UrlUtils#getFile(java.net.URI, String)
     */
    protected File getFile(URI uri) throws IOException {
        if (uri.getScheme().startsWith(UrlUtils.URL_PROTOCOL_VFS)) {
            return VfsResourceDelegate.getResource(uri).getFile();
        }
        return UrlUtils.getFile(uri, getDescription());
    }

    @Override
    public boolean exists() {
        try {
            URL url = getURL();
            if (UrlUtils.isFileURL(url)) {
                // Proceed with file system resolution...
                return getFile().exists();
            }
            else {
                // Try a URL connection content-length header...
                URLConnection con = url.openConnection();
                customizeConnection(con);
                HttpURLConnection httpCon =
                        (con instanceof HttpURLConnection ? (HttpURLConnection) con : null);
                if (httpCon != null) {
                    int code = httpCon.getResponseCode();
                    if (code == HttpURLConnection.HTTP_OK) {
                        return true;
                    }
                    else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
                        return false;
                    }
                }
                if (con.getContentLength() >= 0) {
                    return true;
                }
                if (httpCon != null) {
                    // no HTTP OK status, and no content-length header: give up
                    httpCon.disconnect();
                    return false;
                }
                else {
                    // Fall back to stream existence: can we open the stream?
                    InputStream is = getInputStream();
                    is.close();
                    return true;
                }
            }
        }
        catch (Exception ex) {
            return false;
        }
    }

    @Override
    public boolean isReadable() {
        try {
            URL url = getURL();
            if (UrlUtils.isFileURL(url)) {
                // Proceed with file system resolution...
                File file = getFile();
                return (file.canRead() && !file.isDirectory());
            }
            else {
                return true;
            }
        }
        catch (Exception ex) {
            return false;
        }
    }

    @Override
    public long contentLength() throws IOException {
        URL url = getURL();
        if (UrlUtils.isFileURL(url)) {
            // Proceed with file system resolution...
            return getFile().length();
        }
        else {
            // Try a URL connection content-length header...
            URLConnection con = url.openConnection();
            customizeConnection(con);
            return con.getContentLength();
        }
    }

    @Override
    public long lastModified() throws IOException {
        URL url = getURL();
        if (UrlUtils.isFileURL(url) || UrlUtils.isJarURL(url)) {
            // Proceed with file system resolution...
            return super.lastModified();
        }
        else {
            // Try a URL connection last-modified header...
            URLConnection con = url.openConnection();
            customizeConnection(con);
            return con.getLastModified();
        }
    }

    /**
     * Customize the given {@link URLConnection}, obtained in the course of an
     * {@link #exists()}, {@link #contentLength()} or {@link #lastModified()} call.
     *
Calls {@link UrlUtils#useCachesIfNecessary(URLConnection)} and
     * delegates to {@link #customizeConnection(HttpURLConnection)} if possible.
     * Can be overridden in subclasses.
     * @param con the URLConnection to customize
     * @throws IOException if thrown from URLConnection methods
     */
    protected void customizeConnection(URLConnection con) throws IOException {
        UrlUtils.useCachesIfNecessary(con);
        if (con instanceof HttpURLConnection) {
            customizeConnection((HttpURLConnection) con);
        }
    }

    /**
     * Customize the given {@link HttpURLConnection}, obtained in the course of an
     * {@link #exists()}, {@link #contentLength()} or {@link #lastModified()} call.
     *
Sets request method "HEAD" by default. Can be overridden in subclasses.
     * @param con the HttpURLConnection to customize
     * @throws IOException if thrown from HttpURLConnection methods
     */
    protected void customizeConnection(HttpURLConnection con) throws IOException {
        con.setRequestMethod("HEAD");
    }

    /**
     * Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime.
     */
    private static class VfsResourceDelegate {

        public static Resource getResource(URL url) throws IOException {
            return new VfsResource(VfsUtils.getRoot(url));
        }

        public static Resource getResource(URI uri) throws IOException {
            return new VfsResource(VfsUtils.getRoot(uri));
        }
    }

}


text:
@interface NSString (ORKurls)
-(NSURL*) ork_url;
-(BOOL) ork_isURL;
-(BOOL) ork_containsOnlyValidURLChars;
-(BOOL) ork_canBeTurnedIntoURL;
-(NSString*) ork_coerceIntoURL;
@end


text:
package de.jpaw.bonaparte.coretests.initializers;

import java.util.HashMap;
import java.util.HashSet;

import de.jpaw.bonaparte.pojos.mapTests.AlphaColor;
import de.jpaw.bonaparte.pojos.mapTests.Maps1;
import de.jpaw.bonaparte.pojos.mapTests.Sets1;
import de.jpaw.bonaparte.pojos.mapTests.Unrelated;

public class FillMaps {

    static public Maps1 test1() {
        Maps1 x = new Maps1();

        x.primes = new HashMap<Integer, Integer>(8);
        x.primes.put(1, 2);
        x.primes.put(2, 3);
        x.primes.put(3, 5);
        x.primes.put(4, 7);
        x.primes.put(5, 11);

        x.ccConverter = new HashMap<String, String>(9);
        x.ccConverter.put("DE", "Germany");
        x.ccConverter.put("IE", "Ireland");
        x.ccConverter.put("US", "United States");
        x.ccConverter.put("NA", null);

        x.primaryColor = new HashMap<String, AlphaColor>(11);
        x.primaryColor.put("orange", AlphaColor.RED);
        x.primaryColor.put("deepgreen", AlphaColor.GREEN);

        x.longToBonaPortable = new HashMap<Long, Unrelated>(12);
        x.longToBonaPortable.put(Long.valueOf(42L), new Unrelated(4242, "Fortytwotimestwo"));
        x.longToBonaPortable.put(Long.valueOf(101L), new Unrelated(-1, "oneoone"));
        return x;
    }

    static public Sets1 testSets1() {
        Sets1 x = new Sets1();
        x.iSet = new HashSet<Integer>(10);
        x.iSet.add(7);
        x.iSet.add(11);
        x.iSet.add(13);
        x.iSet.add(17);
        x.iSet.add(19);
        x.sSet = new HashSet<String>(10);
        x.sSet.add("EUR");
        x.sSet.add("USD");
        x.sSet.add("GBP");
        x.sSet.add("JPY");
        x.bSet = new HashSet<Unrelated>(5);
        x.bSet.add(new Unrelated(4242, "Fortytwotimestwo"));
        x.bSet.add(new Unrelated(-1, "oneoone"));
        return x;
    }

}