text:
<?php
/**
 * Get the relative path.
 * @see https://raw.githubusercontent.com/kingscreations/farm-to-you/master/php/lib/_header.php FarmToYou Header
 **/

// include the appropriate number of dirname() functions
// on line 8 to correctly resolve your directory's path
require_once(dirname(dirname(__DIR__)) . "/root-path.php");
$CURRENT_DEPTH = substr_count($CURRENT_DIR, "/");
$ROOT_DEPTH = substr_count($ROOT_PATH, "/");
$DEPTH_DIFFERENCE = $CURRENT_DEPTH - $ROOT_DEPTH;
$PREFIX = str_repeat("../", $DEPTH_DIFFERENCE);

require_once(dirname(__DIR__) . "/classes/autoloader.php");
if(session_status() !== PHP_SESSION_ACTIVE) {
	session_start();
}
?>

<!DOCTYPE html>
<html lang="en" ng-app="TimeCrunchers">
	<head>
		<meta charset="utf-8"/>

		<!-- IE Rendering Mode = Edge-->
		<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
		<meta name="viewport" content="width=device-width, initial-scale=1"/>

		<base href="<?php echo dirname($_SERVER['PHP_SELF']) . "/" ?>">

		<!--Angular JS-->
		<?php $ANGULAR_VERSION = "1.5.0"; ?>
		<script type="text/javascript"
				  src="//ajax.googleapis.com/ajax/libs/angularjs/<?php echo $ANGULAR_VERSION; ?>/angular.min.js"></script>
		<script type="text/javascript"
				  src="//ajax.googleapis.com/ajax/libs/angularjs/<?php echo $ANGULAR_VERSION; ?>/angular-route.min.js"></script>
		<script type="text/javascript"
				  src="//ajax.googleapis.com/ajax/libs/angularjs/<?php echo $ANGULAR_VERSION; ?>/angular-messages.min.js"></script>
		<script type="text/javascript"
				  src="//ajax.googleapis.com/ajax/libs/angularjs/<?php echo $ANGULAR_VERSION; ?>/angular-animate.js"></script>
		<script type="text/javascript"
				  src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.2.4/ui-bootstrap-tpls.min.js"></script>
		<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
		<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/interact.js/1.2.4/interact.min.js"></script>
		<script type="text/javascript"
				  src="//mattlewis92.github.io/angular-bootstrap-calendar/dist/js/angular-bootstrap-calendar-tpls.min.js"></script>

		<!-- Latest compiled and minified CSS -->
		<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
				integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
				crossorigin="anonymous"/>

		<!-- Time Crunchers custom style sheet -->
		<link href="css/style1.css" type="text/css" rel="stylesheet"/>

		<!-- Calendar CSS -->
		<link href="//mattlewis92.github.io/angular-bootstrap-calendar/dist/css/angular-bootstrap-calendar.min.css"
				rel="stylesheet">

		<!--Font Awesome CSS-->
		<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"
				integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous">

		<!--Angular application files must be mainjs, then services, then directives, then controllers-->
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/time-crunchers.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/page-route.js"></script>

		<!-- services -->
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/about-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/access-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/activation-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/company-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/crew-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/login-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/request-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/schedule-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/request-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/shift-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/signup-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/user-service.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/services/calendar-service.js"></script>

		<!-- directives-->
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/directives/bootstrap-breakpoint.js"></script>

		<!-- controllers -->
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/main-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/about-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/access-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/activation-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/adminonly-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/adminrequestview-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/company-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/crew-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/request-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/schedule-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/shift-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/signup-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/user-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/nav-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/datepick-controller.js"></script>
		<script type="text/javascript"
				  src="<?php echo $PREFIX; ?>angularjs/controllers/calendarhelper-controller.js"></script>
		<script type="text/javascript" src="<?php echo $PREFIX; ?>angularjs/controllers/calendar-controller.js"></script>

		<title><?php echo $PAGE_TITLE; ?></title>
	</head>


text:
package com.googlecode.totallylazy.functions;

import com.googlecode.totallylazy.Pair;

public interface Monoid<T> extends Combiner<T, T>, Associative<T> {
    @Override
    default T combine(T a, T b) throws Exception {
        return call(a, b);
    }

    static <T> Monoid<T> monoid(T identity, Binary<T> binary){
        return new Monoid<T>() {
            @Override
            public T call(T t, T t2) throws Exception {
                return binary.call(t, t2);
            }

            @Override
            public T identity() {
                return identity;
            }
        };
    }

    class functions {
        public static <A, B> CurriedMonoid<Pair<A, B>> pair(final Monoid<A> aMonoid, final Monoid<B> bMonoid) {
            return new CurriedMonoid<Pair<A, B>>() {
                @Override
                public Pair<A, B> call(Pair<A, B> a, Pair<A, B> b) throws Exception {
                    return Pair.pair(aMonoid.call(a.first(), b.first()), bMonoid.call(a.second(), b.second()));
                }

                @Override
                public Pair<A, B> identity() {
                    return Pair.pair(aMonoid.identity(), bMonoid.identity());
                }
            };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* Geolocation.js - panel for manual tests of LuneOS/webOS geolocation API & HTML5 geolocation API
 *
 */

enyo.kind({
	name: "Geolocation",
	layoutKind: "FittableRowsLayout",
	components: [
	    { kind: "onyx.Toolbar", layoutKind: "FittableColumnsLayout", components: [
	         {fit: true, content: $L("Geolocation")}
	    ]},
		{
			fit: true,
			kind: "Scroller",
			touch: true,
			horizontal: "hidden",
			components: [
				{style: "margin-left: auto; margin-right: auto; max-width: 35em; padding: 1rem;", components: [
				    {kind: "FittableColumns", components: [
   				        {content: $L("Accuracy: "), style: "color: white; line-height: 2.5rem;"},
					    {kind: "onyx.PickerDecorator", style: "margin-left: 1rem;", components: [
					        {},   // PickerButton
					        {name: "accuracyPckr", kind: "onyx.Picker", components: [
					            {content: $L("High (1)"), value: 1},
					            {content: $L("Medium (2)"), active: true, value: 2},
					            {content: $L("Low (3)"), value: 3}
					        ]}
					    ]}
   				    ]},
				    {kind: "FittableColumns", style: "margin-top: 1rem;", components: [
   				        {content: $L("Max age: "), style: "color: white; line-height: 2rem;"},
   					    {kind: "onyx.InputDecorator", style: "margin-left: 1rem;", components: [
    				        {name: "ageInpt", kind: "onyx.Input", type: "number", value: "0", attributes: {min: "0", step: "1"}, style: "width: 5rem;"}
    				    ]},
   				        {content: $L("sec."), style: "color: white; line-height: 2rem; margin-left: 1rem;"}
				    ]},
				    {kind: "FittableColumns", style: "margin-top: 1rem;", components: [
				        {content: $L("Response time: "), style: "color: white; line-height: 2.5rem;"},
					    {kind: "onyx.PickerDecorator", style: "margin-left: 1rem;", components: [
					        {},   // PickerButton
					        {name: "responseTimePckr", kind: "onyx.Picker", components: [
					            {content: $L("< 5 sec (1)"), value: 1},
					            {content: $L("5–20 sec (2)"), active: true, value: 2},
					            {content: $L("> 20 sec (3)"), value: 3}
					        ]}
					    ]}
					]},
					{kind: "onyx.Groupbox", style: "margin-top: 1rem;", components: [
						{kind: "onyx.Button", style: "width: 100%", content: $L("PalmBus (priv.) getCurrentPosition"), ontap: "singleLocation"},
						{name: "singleOut", content: "   ", allowHtml: true, style: "padding: 5px; color: white"}
					]}
				]},
				{tag: "hr"},
				{style: "margin-left: auto; margin-right: auto; max-width: 35em; padding: 1rem;", components: [
				    {kind: "FittableColumns", components: [
				        {content: $L("High accuracy"), fit: true, style: "color: white; line-height: 2rem;"},
						{name: "highAccuracyTgl", kind: "onyx.ToggleButton"}
					]},
				    {kind: "FittableColumns", style: "margin-top: 1rem;", components: [
      				        {content: $L("Max age: "), style: "color: white; line-height: 2rem;"},
      					    {kind: "onyx.InputDecorator", style: "margin-left: 1rem;", components: [
       				            {name: "html5AgeInpt", kind: "onyx.Input", type: "number", value: "0", attributes: {min: "0", step: "1"}, style: "width: 5rem;"}
       				        ]},
      				        {content: $L("sec."), style: "color: white; line-height: 2rem; margin-left: 1rem;"}
   				    ]},
				    {kind: "FittableColumns", style: "margin-top: 1rem;", components: [
     				        {content: $L("Timeout: "), style: "color: white; line-height: 2rem;"},
     					    {kind: "onyx.InputDecorator", style: "margin-left: 1rem;", components: [
      				            {name: "timeout", kind: "onyx.Input", type: "number", value: "0", attributes: {min: "0", step: "1"}, style: "width: 5rem;"}
      				        ]},
     				        {content: $L("sec."), style: "color: white; line-height: 2rem; margin-left: 1rem;"}
  				    ]},
   					{kind: "onyx.Groupbox", style: "margin-top: 1rem;", components: [
 						{kind: "onyx.Button", style: "width: 100%", content: $L("HTML5 getCurrentPosition"), ontap: "html5CurrentLocation"},
 						{name: "html5Out", content: " \xa0 ", allowHtml: true, style: "padding: 5px; color: white"}
 					]}
				]}
			]
		},

		{
			name: "singleLocationService",
			kind: "LunaService",
			service: "palm://com.palm.location/",
			method: "getCurrentPosition",
			subscribe: false,
			resubscribe: false,
			onResponse: "singleLocationSuccess",
			onError: "singleLocationFail"
		}
	],

	singleLocation: function (inSender, inEvent) {
		this.$.singleOut.setContent($L("requesting position..."));
		this.log("accuracy: ", typeof this.$.accuracyPckr.getSelected().value, this.$.accuracyPckr.getSelected().value,
				"   max age: ", typeof parseInt(this.$.ageInpt.getValue(), 10), parseInt(this.$.ageInpt.getValue(), 10),
				"   response time: ", typeof this.$.responseTimePckr.getSelected().value, this.$.responseTimePckr.getSelected().value);
		this.$.singleLocationService.send({accuracy: this.$.accuracyPckr.getSelected().value, maximumAge: parseInt(this.$.ageInpt.getValue(), 10), responseTime: this.$.responseTimePckr.getSelected().value});
	},
	singleLocationSuccess: function (inSender, inEvent) {
		this.log(inEvent);
		this.$.singleOut.setContent($L("position returned: ") + JSON.stringify(inEvent,
				["altitude", "heading", "horizAccuracy", "latitude", "longitude", "timestamp", "velocity", "vertAccuracy"], 1));
	},
	singleLocationFail: function (inSender, inEvent) {
		this.log(inEvent);
		var errorCode = inEvent.errorCode;
		var errorText = inEvent.errorText;
		var msg = "errorCode: " + errorCode + "
" +
				"errorText: " + errorText;
		if (this.errorCodes[errorCode]) {
			msg = this.errorCodes[errorCode] + "
" + msg;
		}
		this.$.singleOut.setContent(msg);
	},
	errorCodes: ["Success", "Timeout", "Position_Unavailable", "Unknown",
	             "GPS_Permanent_Error - No GPS fix but can still get the cell and Wifi fixes. A TouchPad without GPS returns this error.",
	             "LocationServiceOFF - No Location source available. Both Google and GPS are off.",
	             "Permission Denied - The user has not accepted the terms of use for the Google Location Service, or the Google Service is off.",
	             "The application already has a pending message ",
	             "The application has been temporarily blacklisted. (The user is not allowing this application to use this service.)"],

     html5CurrentLocation: function (inSender, inEvent) {
    	 var panel = this;
    	 var options = {
    		 enableHighAccuracy: this.$.highAccuracyTgl.get("value"),
    		 maximumAge: Number(this.$.html5AgeInpt.get("value"), 10) * 1000
    	 };
    	 if (this.$.timeout.get("value") > 0) {
    		 options.timeout = Number(this.$.timeout.get("value"), 10) * 1000;
    	 }
    	 this.log(options);
    	 navigator.geolocation.getCurrentPosition(html5Success, html5Error, options);
    	 panel.$.html5Out.setContent($L("requesting position..."));

         function html5Success (position) {
        	 var msg = "latitude: " + position.coords.latitude + "°" +
		 	 		"
longitude: " + position.coords.longitude + "°" +
        	 		"
altitude: " + (typeof position.coords.altitude === "number" ? position.coords.altitude + " m" : position.coords.altitude) +
	 				"
accuracy: " + position.coords.accuracy + " m" +
        	 		"
heading: " + (typeof position.coords.heading === "number" ? position.coords.heading + "°" : position.coords.heading) +
        		 	"
timestamp: " +  Date(position.timestamp);
        	 panel.log(msg);
//        	 panel.log("position:", position, position.coords, position.coords.latitude, position.coords.longitude);
        	 panel.$.html5Out.setContent(msg);
         }

		function html5Error(error) {
			var msg = "code: " + error.code + "
" + "message: " + error.message;
        	if (panel.html5ErrorCodes[error.code]) {
        		msg = panel.html5ErrorCodes[error.code] + "
" + msg;
        	}
        	panel.error(msg);
			panel.$.html5Out.setContent(msg);
		}
     },
     html5ErrorCodes: ["", "PERMISSION_DENIED", "POSITION_UNAVAILABLE", "TIMEOUT"]
});


text:
package org.apache.oodt.cas.catalog.page;

/**
 * @author bfoster
 * @version $Revision$
 *
 *

 * A pager for paging through a index
 *

 */
public class IndexPager {

	protected int pageSize;
	protected int pageNum;
	protected int totalPages;
	protected int numOfHits;

	public IndexPager() {
		this.pageSize = 20;
		this.pageNum = 1;
		this.totalPages = 0;
	}

	public IndexPager(ProcessedPageInfo processedPageInfo) {
		this.pageSize = processedPageInfo.getPageSize();
		this.pageNum = processedPageInfo.getPageNum();
		this.totalPages = processedPageInfo.getTotalPages();
		this.numOfHits = processedPageInfo.getNumOfHits();
	}

	public ProcessedPageInfo getProcessedPageInfo() {
		return new ProcessedPageInfo(this.pageSize, this.pageNum, this.numOfHits);
	}

	public int getPageSize() {
		return this.pageSize;
	}

	public int getPageNum() {
		return this.pageNum;
	}

	public int getTotalPages() {
		return this.totalPages;
	}

	public int getNumOfHits() {
		return this.numOfHits;
	}

	public void incrementPageNumber() {
		if (this.pageNum + 1 <= this.totalPages)
			this.pageNum++;
	}

	public boolean isLastPage() {
		return this.getProcessedPageInfo().isLastPage();
	}

}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
 Copyright (C) 2003, 2004, 2005, 2006, 2010 StatPro Italia srl
 Copyright (C) 2004, 2008 Ferdinando Ametrano

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#ifndef quantlib_config_msvc_hpp
#define quantlib_config_msvc_hpp

#include <ql/userconfig.hpp>

/*******************************************
   System configuration section:
   do not modify the following definitions.
 *******************************************/

// force undefining min and max macros
#ifndef NOMINMAX
#  define NOMINMAX
#endif
#ifdef min
#  undef min
#endif
#ifdef max
#  undef max
#endif

// leave outside here common configs

#define QL_PATCH_MSVC  // more granularity below

// prevent auto-link of Boost libs such as serialization
#define BOOST_ALL_NO_LIB

// select toolset:
#if (_MSC_VER < 1400)
#  error "versions of Visual C++ prior to VC++8 (2005) are not supported"
#elif (_MSC_VER == 1400)
// move inside here configs specific to VC++ 8 (2005)
#  ifndef _SCL_SECURE_NO_DEPRECATE
#    define _SCL_SECURE_NO_DEPRECATE
#  endif
#  ifndef _CRT_SECURE_NO_DEPRECATE
#    define _CRT_SECURE_NO_DEPRECATE
#  endif
#  define QL_PATCH_MSVC80
#  define QL_WORKING_BOOST_STREAMS
// see the corresponding pragmas in the 7.1 section
#  pragma warning(disable: 4267)
#  pragma warning(disable: 4224)
// non-ASCII characters - Disabling this warning here is ineffective
// and the change has been made instead under project properties
//#  pragma warning(disable: 4819)
#elif (_MSC_VER == 1500)
// move inside here configs specific to VC++ 9 (2008)
#  ifndef _SCL_SECURE_NO_DEPRECATE
#    define _SCL_SECURE_NO_DEPRECATE
#  endif
#  ifndef _CRT_SECURE_NO_DEPRECATE
#    define _CRT_SECURE_NO_DEPRECATE
#  endif
#  define QL_PATCH_MSVC90
#  define QL_WORKING_BOOST_STREAMS
// see the corresponding pragmas in the 7.1 section
#  pragma warning(disable: 4267)
#  pragma warning(disable: 4224)
#elif (_MSC_VER == 1600)
// move inside here configs specific to VC++ 10 (2010)
#  define QL_PATCH_MSVC100
#  define QL_WORKING_BOOST_STREAMS
#else
// Microsoft compiler we still don't know about.
// We treat it the same way as the latest and hope for the better.
#  define QL_PATCH_MSVC100
#  define QL_WORKING_BOOST_STREAMS
#endif

// Compilation on the x64 platform throws a lot of warnings assigning
// QuantLib::Size == size_t (64 bit) to QuantLib::Integer == int (32
// bit under x64 Windows). We disable this warning until a better
// solution is suggested.
#ifdef _M_X64
#pragma warning(disable : 4267)
#endif

#ifndef _CPPRTTI
#   if (_MSC_VER >= 1300) // VC++ 7.0 (.Net) and later
#       error Enable Run-Time Type Info (Property Pages | C/C++ | Language)
#   else
#       error Enable Run-Time Type Information (Project Settings | C/C++ | C++ Language)
#   endif
#endif

#endif


text:
using System.Windows;
using System;
namespace tainicom.WpfPropertyGrid
{
  /// <summary>
  /// Specifies the default category editor.
  /// </summary>
  public class CategoryEditor : Editor
  {
    private static readonly Type ThisType = typeof(CategoryEditor);

    /// <summary>
    /// Identifies the <see cref="DeclaringType"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty DeclaringTypeProperty =
      DependencyProperty.Register("DeclaringType", typeof(Type), ThisType);

    /// <summary>
    /// Gets or sets the declaring type. This is a dependency property.
    /// </summary>
    /// <value>The declaring type.</value>
    public Type DeclaringType
    {
      get { return (Type)GetValue(DeclaringTypeProperty); }
      set { SetValue(DeclaringTypeProperty, value); }
    }

    /// <summary>
    /// Identifies the <see cref="CategoryName"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty CategoryNameProperty =
      DependencyProperty.Register("CategoryName", typeof(string), ThisType);

    /// <summary>
    /// Gets or sets the name of the category. This is a dependency property.
    /// </summary>
    /// <value>The name of the category.</value>
    public string CategoryName
    {
      get { return (string)GetValue(CategoryNameProperty); }
      set { SetValue(CategoryNameProperty, value); }
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="CategoryEditor"/> class.
    /// </summary>
    public CategoryEditor()
    {
      // Default empty constructor
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="CategoryEditor"/> class.
    /// </summary>
    /// <param name="declaringType">Declaring type.</param>
    /// <param name="categoryName">Name of the category.</param>
    /// <param name="inlineTemplate">The inline template.</param>
    public CategoryEditor(Type declaringType, string categoryName, object inlineTemplate)
    {
      if (declaringType == null) throw new ArgumentNullException("declaringType");
      if (string.IsNullOrEmpty(categoryName)) throw new ArgumentNullException("categoryName");

      DeclaringType = declaringType;
      CategoryName = categoryName;
      InlineTemplate = inlineTemplate;
    }
  }
}


text:
package com.opengamma.financial.analytics.surface;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.opengamma.core.config.Config;
import com.opengamma.core.config.ConfigGroups;
import com.opengamma.financial.analytics.volatility.surface.SurfaceInstrumentProvider;
import com.opengamma.id.UniqueId;
import com.opengamma.id.UniqueIdentifiable;

/**
 * Specification for a surface - contains all available points on the surface.
 */
@Config(description = "Surface specification", group = ConfigGroups.MISC)
@BeanDefinition
public class SurfaceSpecification implements Bean, Serializable, UniqueIdentifiable {

  /** Serialization version */
  private static final long serialVersionUID = 1L;

  /**
   * The unique id.
   */
  @PropertyDefinition
  private UniqueId _uniqueId;

  /**
   * The surface name.
   */
  @PropertyDefinition(validate = "notNull")
  private String _name;

  /**
   * The quote units.
   */
  @PropertyDefinition(validate = "notNull")
  private String _quoteUnits;

  /**
   * The quote type.
   */
  @PropertyDefinition(validate = "notNull")
  private String _quoteType;

  /**
   * The surface instrument provider.
   */
  @PropertyDefinition(validate = "notNull")
  private SurfaceInstrumentProvider<?, ?> _surfaceInstrumentProvider;

  /**
   * For the builder.
   */
  SurfaceSpecification() {
  }

  /**
   * @param name The surface name, not null
   * @param quoteUnits The quote units, not null
   * @param quoteType The quote type, not null
   * @param surfaceInstrumentProvider The surface instrument provider, not null
   */
  public SurfaceSpecification(final String name, final String quoteUnits, final String quoteType,
      final SurfaceInstrumentProvider<?, ?> surfaceInstrumentProvider) {
    setName(name);
    setQuoteUnits(quoteUnits);
    setQuoteType(quoteType);
    setSurfaceInstrumentProvider(surfaceInstrumentProvider);
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code SurfaceSpecification}.
   * @return the meta-bean, not null
   */
  public static SurfaceSpecification.Meta meta() {
    return SurfaceSpecification.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(SurfaceSpecification.Meta.INSTANCE);
  }

  @Override
  public SurfaceSpecification.Meta metaBean() {
    return SurfaceSpecification.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the unique id.
   * @return the value of the property
   */
  public UniqueId getUniqueId() {
    return _uniqueId;
  }

  /**
   * Sets the unique id.
   * @param uniqueId  the new value of the property
   */
  public void setUniqueId(UniqueId uniqueId) {
    this._uniqueId = uniqueId;
  }

  /**
   * Gets the the {@code uniqueId} property.
   * @return the property, not null
   */
  public final Property<UniqueId> uniqueId() {
    return metaBean().uniqueId().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the surface name.
   * @return the value of the property, not null
   */
  public String getName() {
    return _name;
  }

  /**
   * Sets the surface name.
   * @param name  the new value of the property, not null
   */
  public void setName(String name) {
    JodaBeanUtils.notNull(name, "name");
    this._name = name;
  }

  /**
   * Gets the the {@code name} property.
   * @return the property, not null
   */
  public final Property<String> name() {
    return metaBean().name().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the quote units.
   * @return the value of the property, not null
   */
  public String getQuoteUnits() {
    return _quoteUnits;
  }

  /**
   * Sets the quote units.
   * @param quoteUnits  the new value of the property, not null
   */
  public void setQuoteUnits(String quoteUnits) {
    JodaBeanUtils.notNull(quoteUnits, "quoteUnits");
    this._quoteUnits = quoteUnits;
  }

  /**
   * Gets the the {@code quoteUnits} property.
   * @return the property, not null
   */
  public final Property<String> quoteUnits() {
    return metaBean().quoteUnits().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the quote type.
   * @return the value of the property, not null
   */
  public String getQuoteType() {
    return _quoteType;
  }

  /**
   * Sets the quote type.
   * @param quoteType  the new value of the property, not null
   */
  public void setQuoteType(String quoteType) {
    JodaBeanUtils.notNull(quoteType, "quoteType");
    this._quoteType = quoteType;
  }

  /**
   * Gets the the {@code quoteType} property.
   * @return the property, not null
   */
  public final Property<String> quoteType() {
    return metaBean().quoteType().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the surface instrument provider.
   * @return the value of the property, not null
   */
  public SurfaceInstrumentProvider<?, ?> getSurfaceInstrumentProvider() {
    return _surfaceInstrumentProvider;
  }

  /**
   * Sets the surface instrument provider.
   * @param surfaceInstrumentProvider  the new value of the property, not null
   */
  public void setSurfaceInstrumentProvider(SurfaceInstrumentProvider<?, ?> surfaceInstrumentProvider) {
    JodaBeanUtils.notNull(surfaceInstrumentProvider, "surfaceInstrumentProvider");
    this._surfaceInstrumentProvider = surfaceInstrumentProvider;
  }

  /**
   * Gets the the {@code surfaceInstrumentProvider} property.
   * @return the property, not null
   */
  public final Property<SurfaceInstrumentProvider<?, ?>> surfaceInstrumentProvider() {
    return metaBean().surfaceInstrumentProvider().createProperty(this);
  }

  //-----------------------------------------------------------------------
  @Override
  public SurfaceSpecification clone() {
    return JodaBeanUtils.cloneAlways(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      SurfaceSpecification other = (SurfaceSpecification) obj;
      return JodaBeanUtils.equal(getUniqueId(), other.getUniqueId()) &&
          JodaBeanUtils.equal(getName(), other.getName()) &&
          JodaBeanUtils.equal(getQuoteUnits(), other.getQuoteUnits()) &&
          JodaBeanUtils.equal(getQuoteType(), other.getQuoteType()) &&
          JodaBeanUtils.equal(getSurfaceInstrumentProvider(), other.getSurfaceInstrumentProvider());
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(getUniqueId());
    hash = hash * 31 + JodaBeanUtils.hashCode(getName());
    hash = hash * 31 + JodaBeanUtils.hashCode(getQuoteUnits());
    hash = hash * 31 + JodaBeanUtils.hashCode(getQuoteType());
    hash = hash * 31 + JodaBeanUtils.hashCode(getSurfaceInstrumentProvider());
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(192);
    buf.append("SurfaceSpecification{");
    int len = buf.length();
    toString(buf);
    if (buf.length() > len) {
      buf.setLength(buf.length() - 2);
    }
    buf.append('}');
    return buf.toString();
  }

  protected void toString(StringBuilder buf) {
    buf.append("uniqueId").append('=').append(JodaBeanUtils.toString(getUniqueId())).append(',').append(' ');
    buf.append("name").append('=').append(JodaBeanUtils.toString(getName())).append(',').append(' ');
    buf.append("quoteUnits").append('=').append(JodaBeanUtils.toString(getQuoteUnits())).append(',').append(' ');
    buf.append("quoteType").append('=').append(JodaBeanUtils.toString(getQuoteType())).append(',').append(' ');
    buf.append("surfaceInstrumentProvider").append('=').append(JodaBeanUtils.toString(getSurfaceInstrumentProvider())).append(',').append(' ');
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code SurfaceSpecification}.
   */
  public static class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code uniqueId} property.
     */
    private final MetaProperty<UniqueId> _uniqueId = DirectMetaProperty.ofReadWrite(
        this, "uniqueId", SurfaceSpecification.class, UniqueId.class);
    /**
     * The meta-property for the {@code name} property.
     */
    private final MetaProperty<String> _name = DirectMetaProperty.ofReadWrite(
        this, "name", SurfaceSpecification.class, String.class);
    /**
     * The meta-property for the {@code quoteUnits} property.
     */
    private final MetaProperty<String> _quoteUnits = DirectMetaProperty.ofReadWrite(
        this, "quoteUnits", SurfaceSpecification.class, String.class);
    /**
     * The meta-property for the {@code quoteType} property.
     */
    private final MetaProperty<String> _quoteType = DirectMetaProperty.ofReadWrite(
        this, "quoteType", SurfaceSpecification.class, String.class);
    /**
     * The meta-property for the {@code surfaceInstrumentProvider} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<SurfaceInstrumentProvider<?, ?>> _surfaceInstrumentProvider = DirectMetaProperty.ofReadWrite(
        this, "surfaceInstrumentProvider", SurfaceSpecification.class, (Class) SurfaceInstrumentProvider.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "uniqueId",
        "name",
        "quoteUnits",
        "quoteType",
        "surfaceInstrumentProvider");

    /**
     * Restricted constructor.
     */
    protected Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case -294460212:  // uniqueId
          return _uniqueId;
        case 3373707:  // name
          return _name;
        case 1273091667:  // quoteUnits
          return _quoteUnits;
        case -1482972202:  // quoteType
          return _quoteType;
        case -47731067:  // surfaceInstrumentProvider
          return _surfaceInstrumentProvider;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends SurfaceSpecification> builder() {
      return new DirectBeanBuilder<SurfaceSpecification>(new SurfaceSpecification());
    }

    @Override
    public Class<? extends SurfaceSpecification> beanType() {
      return SurfaceSpecification.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code uniqueId} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<UniqueId> uniqueId() {
      return _uniqueId;
    }

    /**
     * The meta-property for the {@code name} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> name() {
      return _name;
    }

    /**
     * The meta-property for the {@code quoteUnits} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> quoteUnits() {
      return _quoteUnits;
    }

    /**
     * The meta-property for the {@code quoteType} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> quoteType() {
      return _quoteType;
    }

    /**
     * The meta-property for the {@code surfaceInstrumentProvider} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<SurfaceInstrumentProvider<?, ?>> surfaceInstrumentProvider() {
      return _surfaceInstrumentProvider;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case -294460212:  // uniqueId
          return ((SurfaceSpecification) bean).getUniqueId();
        case 3373707:  // name
          return ((SurfaceSpecification) bean).getName();
        case 1273091667:  // quoteUnits
          return ((SurfaceSpecification) bean).getQuoteUnits();
        case -1482972202:  // quoteType
          return ((SurfaceSpecification) bean).getQuoteType();
        case -47731067:  // surfaceInstrumentProvider
          return ((SurfaceSpecification) bean).getSurfaceInstrumentProvider();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      switch (propertyName.hashCode()) {
        case -294460212:  // uniqueId
          ((SurfaceSpecification) bean).setUniqueId((UniqueId) newValue);
          return;
        case 3373707:  // name
          ((SurfaceSpecification) bean).setName((String) newValue);
          return;
        case 1273091667:  // quoteUnits
          ((SurfaceSpecification) bean).setQuoteUnits((String) newValue);
          return;
        case -1482972202:  // quoteType
          ((SurfaceSpecification) bean).setQuoteType((String) newValue);
          return;
        case -47731067:  // surfaceInstrumentProvider
          ((SurfaceSpecification) bean).setSurfaceInstrumentProvider((SurfaceInstrumentProvider<?, ?>) newValue);
          return;
      }
      super.propertySet(bean, propertyName, newValue, quiet);
    }

    @Override
    protected void validate(Bean bean) {
      JodaBeanUtils.notNull(((SurfaceSpecification) bean)._name, "name");
      JodaBeanUtils.notNull(((SurfaceSpecification) bean)._quoteUnits, "quoteUnits");
      JodaBeanUtils.notNull(((SurfaceSpecification) bean)._quoteType, "quoteType");
      JodaBeanUtils.notNull(((SurfaceSpecification) bean)._surfaceInstrumentProvider, "surfaceInstrumentProvider");
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
namespace OneHourSport.Web.Models.HomeTop
{
    using Complex;
    using Field;
    using System.Collections.Generic;

    public class HomeTop
    {
        public IEnumerable<FieldDisplayViewModel> TopFields { get; set; }

        public IEnumerable<ComplexDisplayViewModel> TopComplexes { get; set; }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

using Hydra.Framework;
using Hydra.Framework.Collections;
using Hydra.Framework.Extensions;

namespace Hydra.Framework.Reflection
{
	public abstract class ReflectiveVisitorBase<TVisitor>
		where TVisitor : class
	{
		const BindingFlags _methodBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
		static readonly Expression<Func<ReflectiveVisitorBase<TVisitor>, bool>> _defaultMemberName = x => x.Visit(null);

		[ThreadStatic]
		static Dictionary<int, Func<TVisitor, object, bool>> _argCache;

		[ThreadStatic]
		static MultiDictionary<string, MethodInfo> _methodNameCache;

		readonly string _methodName;

		protected ReflectiveVisitorBase()
			: this("Visit")
		{
		}

		protected ReflectiveVisitorBase(Expression<Func<TVisitor, object>> expression)
			: this(expression.MemberName())
		{
		}

		protected ReflectiveVisitorBase(string methodName)
		{
			_methodName = methodName;
		}

		static IEnumerable<MethodInfo> GetMethod(string name)
		{
			if (_methodNameCache == null)
			{
				_methodNameCache = new MultiDictionary<string, MethodInfo>(false);

				typeof(TVisitor).GetMethods(_methodBindingFlags).Each(method => _methodNameCache.Add(method.Name, method));
			}

			return _methodNameCache[name];
		}

		public virtual bool Visit(object obj)
		{
			return DispatchVisit(obj);
		}

		public virtual bool Visit(object obj, Func<bool> action)
		{
			bool result = DispatchVisit(obj);
			if (!result)
				return false;

			IncreaseDepth();
			result = action();
			DecreaseDepth();

			return result;
		}

		protected virtual void IncreaseDepth()
		{
		}

		protected virtual void DecreaseDepth()
		{
		}

		protected bool DispatchVisit(object obj)
		{
			var target = this as TVisitor;

			int key = obj.GetType().GetHashCode();

			Func<TVisitor, object, bool> invoker = GetInvoker(key, () =>
				{
					var args = new[] {obj};

					MethodInfo method = GetMethod(_methodName)
						.Where(x => x.ReturnType == typeof(bool))
						.MatchingArguments(args)
						.FirstOrDefault();

					if (method == null)
						return null;

					if (method.GetParameters().First().ParameterType == typeof(object))
						return null;

					return method.ToSpecializedMethod(args);
				});

			return invoker(target, obj);
		}

		static Func<TVisitor, object, bool> GetInvoker(int key, Func<MethodInfo> getMethodInfo)
		{
			if (_argCache == null)
				_argCache = new Dictionary<int, Func<TVisitor, object, bool>>();

			return _argCache.Retrieve(key, () =>
				{
					MethodInfo method = getMethodInfo();
					if (method == null)
						return (x, y) => true;

					ParameterExpression instanceParameter = Expression.Parameter(typeof(TVisitor), "target");
					ParameterExpression argParameter = Expression.Parameter(typeof(object), "arg");

					ParameterInfo parameter = method.GetParameters().First();

					UnaryExpression arg = (parameter.ParameterType.IsValueType)
					                      	? Expression.Convert(argParameter, parameter.ParameterType)
					                      	: Expression.TypeAs(argParameter, parameter.ParameterType);

					MethodCallExpression call = Expression.Call(instanceParameter, method, arg);

					return Expression.Lambda<Func<TVisitor, object, bool>>(call, new[] {instanceParameter, argParameter}).Compile();
				});
		}
	}
}


text:
<?php
include './conexion.php';

@session_start();
if (!empty($_SESSION['user'])) {
    include './securityPermisionHandle.php';
    if (!checkUserPermissions(array('matr'), $_SESSION['userid']))
    {
        /////// Accion de salida
        $data = array('estado' => 'ko',
        'msj' => 'Ha ocurrido un error de acceso.',
        'detalle' => 'Error en la confirmacion de permisos');
        print json_encode($data, JSON_FORCE_OBJECT);
        exit;
    }
} else {
    /////// Accion de salida
    $data = array('estado' => 'ko',
    'msj' => 'Ha ocurrido un error de acceso.',
    'detalle' => 'Error en la confirmacion de permisos');
    print json_encode($data, JSON_FORCE_OBJECT);
    exit;
}

$conn = dbConnect();

$id_Persona = $_POST['id_Persona'];
$id_Curso = $_POST['id_Curso'];

$sql_call = "CALL MATRICULAinsert(:id_Persona, :id_Curso);";

try {
    $stmt = $conn->prepare($sql_call);
    $stmt->bindParam(':id_Persona', $id_Persona);
    $stmt->bindParam(':id_Curso', $id_Curso);
    $stmt->execute();

    $data = array('estado' => 'ok',
                  'msj' => 'Datos ingresados correctamente.',
                  'detalle' => $sql_call);

    print json_encode($data, JSON_FORCE_OBJECT);
} catch (PDOException $e) {
    $data = array('estado' => 'ko',
                  'msj' => 'Ha ocurrido un error.',
                  'detalle' => $e->getMessage());

    print json_encode($data, JSON_FORCE_OBJECT);
}

?>


text:
module Joker
  module Generators
    class TranslateGenerator < ::Rails::Generators::NamedBase
      argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
      source_root File.expand_path("../templates", __FILE__)

      desc <<DESC
Description:
    Create a ScaffoldController to the model used in JokerJS.
DESC

      def inserting_model_translate
        I18n.available_locales.each do |locale|
          @locale = locale
          template 'models.yml', "config/locales/#{locale}/models.yml" unless File.exist? "config/locales/#{locale}/models.yml"
          append_to_file "config/locales/#{locale}/models.yml",
                         "\n      #{singular_table_name}: #{human_name}" \
                         "\n      #{plural_table_name}: #{human_name.pluralize}"
        end
      end

      def create_attribute_translate
        I18n.available_locales.each do |locale|
          @locale = locale
          template "model.yml", "config/locales/#{locale}/models/#{plural_table_name}.yml"
        end
      end
    end
  end
end


text:
package omrecorder;

import java.io.IOException;
import java.io.OutputStream;

/**
 * An Implementer class should use this interface to write encoded
 * audio chunk to OutputStream according to chosen audio format.
 *
 * @author Kailash Dabhi
 * @date 06-07-2016
 */
public interface WriteAction {
  /**
   * Implement this behaviour to provide custom Write Action for audio which
   * requires {@code data} to encode. So here One can encode the data
   * according to chosen audio format.
   */
  void execute(AudioChunk audioChunk, OutputStream outputStream) throws IOException;

  /**
   * Use this default implementation to write data directly without any encoding to OutputStream.
   */
  final class Default implements WriteAction {
    @Override public void execute(AudioChunk audioChunk, OutputStream outputStream)
        throws IOException {
      outputStream.write(audioChunk.toBytes());
    }
  }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DotNetty.Transport.Libuv.Tests
{
    using System;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    using DotNetty.Buffers;
    using DotNetty.Common.Concurrency;
    using DotNetty.Transport.Bootstrapping;
    using DotNetty.Transport.Channels;
    using Xunit;

    using static TestUtil;

    [Collection(LibuvTransport)]
    public sealed class DetectPeerCloseWithoutReadTests : IDisposable
    {
        readonly IEventLoopGroup group;
        IChannel serverChannel;
        IChannel clientChannel;

        public DetectPeerCloseWithoutReadTests()
        {
            this.group = new EventLoopGroup(1);
        }

        [Fact]
        public void ClientCloseWithoutServerReadIsDetected()
        {
            const int ExpectedBytes = 100;

            var serverHandler = new TestHandler(ExpectedBytes);
            ServerBootstrap sb = new ServerBootstrap()
                .Group(this.group)
                .Channel<TcpServerChannel>()
                .ChildOption(ChannelOption.AutoRead, false)
                .ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
                {
                    channel.Pipeline.AddLast(serverHandler);
                }));

            // start server
            Task<IChannel> task = sb.BindAsync(LoopbackAnyPort);
            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            Bootstrap cb = new Bootstrap()
                .Group(this.group)
                .Channel<TcpChannel>()
                .Handler(new ChannelHandlerAdapter());

            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            IByteBuffer buf = this.clientChannel.Allocator.Buffer(ExpectedBytes);
            buf.SetWriterIndex(buf.WriterIndex + ExpectedBytes);
            this.clientChannel.WriteAndFlushAsync(buf).ContinueWith(_ => this.clientChannel.CloseAsync());

            Task<int> completion = serverHandler.Completion;
            Assert.True(completion.Wait(DefaultTimeout));
            Assert.Equal(ExpectedBytes, completion.Result);
        }

        sealed class TestHandler : SimpleChannelInboundHandler<IByteBuffer>
        {
            readonly int expectedBytesRead;
            readonly TaskCompletionSource<int> completion;
            int bytesRead;

            public TestHandler(int expectedBytesRead)
            {
                this.expectedBytesRead = expectedBytesRead;
                this.completion = new TaskCompletionSource<int>();
            }

            public Task<int> Completion => this.completion.Task;

            public override void ChannelActive(IChannelHandlerContext ctx)
            {
                if (!ctx.Channel.Configuration.AutoRead)
                {
                    ctx.Read();
                }
            }

            protected override void ChannelRead0(IChannelHandlerContext ctx, IByteBuffer msg)
            {
                if (Interlocked.Add(ref this.bytesRead, msg.ReadableBytes) >= this.expectedBytesRead)
                {
                    this.completion.TrySetResult(this.bytesRead);
                }
                // Because autoread is off, we call read to consume all data until we detect the close.
                ctx.Read();
            }

            public override void ChannelInactive(IChannelHandlerContext ctx)
            {
                this.completion.TrySetResult(this.bytesRead);
                ctx.FireChannelInactive();
            }
        }

        [Fact]
        public void ServerCloseWithoutClientReadIsDetected()
        {
            const int ExpectedBytes = 100;

            var serverHandler = new WriteHandler(ExpectedBytes);
            ServerBootstrap sb = new ServerBootstrap()
                .Group(this.group)
                .Channel<TcpServerChannel>()
                .ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
                {
                    channel.Pipeline.AddLast(serverHandler);
                }));

            var address = new IPEndPoint(IPAddress.IPv6Loopback, 0);
            // start server
            // start server
            Task<IChannel> task = sb.BindAsync(address);
            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            var clientHandler = new TestHandler(ExpectedBytes);
            Bootstrap cb = new Bootstrap()
                .Group(this.group)
                .Channel<TcpChannel>()
                .Option(ChannelOption.AutoRead, false)
                .Handler(new ActionChannelInitializer<IChannel>(channel =>
                {
                    channel.Pipeline.AddLast(clientHandler);
                }));

            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            // Wait until server inactive to read on client
            Assert.True(serverHandler.Inactive.Wait(DefaultTimeout));
            this.clientChannel.Read();
            Task<int> completion = clientHandler.Completion;
            Assert.True(completion.Wait(DefaultTimeout));
            Assert.Equal(ExpectedBytes, completion.Result);
        }

        sealed class WriteHandler : ChannelHandlerAdapter
        {
            readonly int expectedBytesRead;
            readonly TaskCompletionSource completion;

            public WriteHandler(int expectedBytesRead)
            {
                this.expectedBytesRead = expectedBytesRead;
                this.completion = new TaskCompletionSource();
            }

            public Task Inactive => this.completion.Task;

            public override void ChannelActive(IChannelHandlerContext ctx)
            {
                IByteBuffer buf = ctx.Allocator.Buffer(this.expectedBytesRead);
                buf.SetWriterIndex(buf.WriterIndex + this.expectedBytesRead);
                ctx.WriteAndFlushAsync(buf).ContinueWith(_ => ctx.CloseAsync());
                ctx.FireChannelActive();
            }

            public override void ChannelInactive(IChannelHandlerContext context) => this.completion.TryComplete();
        }

        public void Dispose()
        {
            this.clientChannel?.CloseAsync().Wait(DefaultTimeout);
            this.serverChannel?.CloseAsync().Wait(DefaultTimeout);
            this.group.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero).Wait(DefaultTimeout);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Remotion.Linq.Clauses.ResultOperators;

namespace Remotion.Linq
{
	/// <summary>
	/// Constitutes the bridge between re-linq and a concrete query provider implementation. Concrete providers implement this interface
	/// and <see cref="QueryProviderBase"/> calls the respective method of the interface implementation when a query is to be executed.
	/// </summary>
	public interface IQueryExecutor
	{
		/// <summary>
		/// Executes the given <paramref name="queryModel"/> as a scalar query, i.e. as a query returning a scalar value of type <typeparamref name="T"/>.
		/// The query ends with a scalar result operator, for example a <see cref="CountResultOperator"/> or a <see cref="SumResultOperator"/>.
		/// </summary>
		/// <typeparam name="T">The type of the scalar value returned by the query.</typeparam>
		/// <param name="queryModel">The <see cref="QueryModel"/> representing the query to be executed. Analyze this via an
		/// <see cref="IQueryModelVisitor"/>.</param>
		/// <returns>A scalar value of type <typeparamref name="T"/> that represents the query's result.</returns>
		/// <remarks>
		/// The difference between <see cref="ExecuteSingle{T}"/> and <see cref="ExecuteScalar{T}"/> is in the kind of object that is returned.
		/// <see cref="ExecuteSingle{T}"/> is used when a query that would otherwise return a collection result set should pick a single value from the
		/// set, for example the first, last, minimum, maximum, or only value in the set. <see cref="ExecuteScalar{T}"/> is used when a value is
		/// calculated or aggregated from all the values in the collection result set. This applies to, for example, item counts, average calculations,
		/// checks for the existence of a specific item, and so on.
		/// </remarks>
		T ExecuteScalar<T>(QueryModel queryModel);

		/// <summary>
		/// Executes the given <paramref name="queryModel"/> as a single object query, i.e. as a query returning a single object of type
		/// <typeparamref name="T"/>.
		/// The query ends with a single result operator, for example a <see cref="FirstResultOperator"/> or a <see cref="SingleResultOperator"/>.
		/// </summary>
		/// <typeparam name="T">The type of the single value returned by the query.</typeparam>
		/// <param name="queryModel">The <see cref="QueryModel"/> representing the query to be executed. Analyze this via an
		/// <see cref="IQueryModelVisitor"/>.</param>
		/// <param name="returnDefaultWhenEmpty">If <see langword="true" />, the executor must return a default value when its result set is empty;
		/// if <see langword="false" />, it should throw an <see cref="InvalidOperationException"/> when its result set is empty.</param>
		/// <returns>A single value of type <typeparamref name="T"/> that represents the query's result.</returns>
		/// <remarks>
		/// The difference between <see cref="ExecuteSingle{T}"/> and <see cref="ExecuteScalar{T}"/> is in the kind of object that is returned.
		/// <see cref="ExecuteSingle{T}"/> is used when a query that would otherwise return a collection result set should pick a single value from the
		/// set, for example the first, last, minimum, maximum, or only value in the set. <see cref="ExecuteScalar{T}"/> is used when a value is
		/// calculated or aggregated from all the values in the collection result set. This applies to, for example, item counts, average calculations,
		/// checks for the existence of a specific item, and so on.
		/// </remarks>
		T ExecuteSingle<T>(QueryModel queryModel, bool returnDefaultWhenEmpty);

		/// <summary>
		/// Executes the given <paramref name="queryModel"/> as a collection query, i.e. as a query returning objects of type <typeparamref name="T"/>.
		/// The query does not end with a scalar result operator, but it can end with a single result operator, for example
		/// <see cref="SingleResultOperator"/> or <see cref="FirstResultOperator"/>. In such a case, the returned enumerable must yield exactly
		/// one object (or none if the last result operator allows empty result sets).
		/// </summary>
		/// <typeparam name="T">The type of the items returned by the query.</typeparam>
		/// <param name="queryModel">The <see cref="QueryModel"/> representing the query to be executed. Analyze this via an
		/// <see cref="IQueryModelVisitor"/>.</param>
		/// <returns>A scalar value of type <typeparamref name="T"/> that represents the query's result.</returns>
		IEnumerable<T> ExecuteCollection<T>(QueryModel queryModel);
	}
}


text:
from typing import List

import numpy as np
from abjad.tools.scoretools import Note

from counterpoint.composition_environment import CompositionState
from counterpoint.composition_state_action import CompositionAction
from rl.valuefunction.FeatureExtractor import StateFeatureExtractor, StateActionFeatureExtractor

class MusicStateFeatureExtractor(StateFeatureExtractor):
    def __init__(self, num_pitches_per_voice: List[int], history_length: int, position_invariant: bool = False):
        self.num_voices = len(num_pitches_per_voice)
        self.position_invariant = position_invariant
        # Include a null class for unpopulated features
        self.max_beats = 12
        self.options_per_voice = [num_pitches + 1 for num_pitches in num_pitches_per_voice]
        self.history_length = history_length

    def extract(self, state: CompositionState) -> np.array:
        features = np.zeros(self.num_features())
        if len(features) == 1:
            features[0] = 1
            return features
        position = 0
        for i in range(0, self.num_voices):
            for j in range(0, self.history_length):
                item = state.voices[i][j]
                if isinstance(item, Note):
                    # One pitch per voice
                    pitch = item.written_pitch
                    index = state.composition_parameters.pitch_indices[i][pitch]
                    features[position + index] = 1
                else:
                    index = self.options_per_voice[i] - 1
                    features[position + index] = 1
                position += self.options_per_voice[i]

        if not self.position_invariant:
            beat = int(float(state.preceding_duration) / 1.00)
            features[position + beat] = 1
        return features

    def num_features(self) -> int:
        if self.position_invariant:
            num = sum(self.options_per_voice) * self.history_length
        else:
            num = sum(self.options_per_voice) * self.history_length + self.max_beats
        #
        if num == 0:
            return 1
        return num

class MusicStateActionFeatureExtractor(StateActionFeatureExtractor):
    def __init__(self, num_pitches_per_voice: List[int], history_length: int, position_invariant: bool = False):
        self.num_voices = len(num_pitches_per_voice)
        self.position_invariant = position_invariant
        # Include a null class for unpopulated features
        self.max_beats = 12
        self.options_per_voice = [num_pitches + 1 for num_pitches in num_pitches_per_voice]
        self.history_length = history_length

    def extract(self, state: CompositionState, action: CompositionAction) -> np.array:
        features = np.zeros(self.num_features())
        if len(features) == 1:
            features[0] = 1
            return features
        position = 0
        for i in range(0, self.num_voices):
            for j in range(0, self.history_length):
                item = state.voices[i][j]
                if isinstance(item, Note):
                    # One pitch per voice
                    pitch = item.written_pitch
                    index = state.composition_parameters.pitch_indices[i][pitch]
                    features[position + index] = 1
                else:
                    index = self.options_per_voice[i] - 1
                    features[position + index] = 1
                position += self.options_per_voice[i]

        for i in range(0, self.num_voices):
            item = action.notes_per_voice[i]
            if isinstance(item, Note):
                # One pitch per voice
                pitch = item.written_pitch
                index = state.composition_parameters.pitch_indices[i][pitch]
                features[position + index] = 1
            position += self.options_per_voice[i]

        if not self.position_invariant:
            beat = int(float(state.preceding_duration) / 1.00)
            features[position + beat] = 1
        return features

    def num_features(self) -> int:
        if self.position_invariant:
            num = sum(self.options_per_voice) * (self.history_length + 1)
        else:
            num = sum(self.options_per_voice) * (self.history_length + 1) + self.max_beats
        #
        if num == 0:
            return 1
        return num


text:
package org.hisp.dhis.webapi.service;

import static org.hisp.dhis.utils.Assertions.assertEquivalentRelativeUrls;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.when;

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

import org.hisp.dhis.common.Pager;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.schema.SchemaService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;

/**
 * Unit tests for {@link DefaultLinkService}.
 *
 * @author Volker Schmidt
 */
@ExtendWith( MockitoExtension.class )
class DefaultLinkServiceTest
{
    @Mock
    private SchemaService schemaService;

    @Mock
    private ContextService contextService;

    @InjectMocks
    private DefaultLinkService service;

    private final MockHttpServletRequest request = new MockHttpServletRequest();

    @Test
    void noLinks()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        final Pager pager = new Pager();
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertNull( pager.getPrevPage() );
        assertNull( pager.getNextPage() );
    }

    @Test
    void nextLinkDefaultParameters()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setRelativeApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        request.setRequestURI( "/organizationUnits" );
        when( contextService.getRequest() ).thenReturn( request );

        when( contextService.getApiPath() ).thenReturn( "/demo/api/456" );

        when( contextService.getParameterValuesMap() ).thenAnswer( invocation -> Map.of(
            "page", List.of( "1" ),
            "pageSize", List.of( "55" ) ) );

        final Pager pager = new Pager( 1, 1000 );
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertNull( pager.getPrevPage() );
        assertEquals( "/demo/api/456/organizationUnits?page=2", pager.getNextPage() );
    }

    @Test
    void nextLinkParameters()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setRelativeApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        request.setRequestURI( "/organizationUnits.json" );
        when( contextService.getRequest() ).thenReturn( request );

        when( contextService.getApiPath() ).thenReturn( "/demo/api/456" );

        when( contextService.getParameterValuesMap() ).thenAnswer( invocation -> Map.of(
            "page", List.of( "1" ),
            "pageSize", List.of( "55" ),
            "fields", List.of( "id,name,value[id,text]" ),
            "value[x]", List.of( "test1", "test2\u00D8" ) ) );

        final Pager pager = new Pager( 1, 1000 );
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertNull( pager.getPrevPage() );
        assertEquivalentRelativeUrls(
            "/demo/api/456/organizationUnits.json?page=2&fields=id%2Cname%2Cvalue%5Bid%2Ctext%5D&value%5Bx%5D=test1&value%5Bx%5D=test2%C3%98",
            pager.getNextPage() );
    }

    @Test
    void prevLinkDefaultParameters()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setRelativeApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        request.setRequestURI( "/organizationUnits.xml" );
        when( contextService.getRequest() ).thenReturn( request );

        when( contextService.getApiPath() ).thenReturn( "/demo/api/456" );

        when( contextService.getParameterValuesMap() ).thenAnswer( invocation -> Map.of(
            "page", List.of( "1" ),
            "pageSize", List.of( "55" ) ) );

        final Pager pager = new Pager( 2, 60 );
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertEquals( "/demo/api/456/organizationUnits.xml", pager.getPrevPage() );
        assertNull( pager.getNextPage() );
    }

    @Test
    void nextLink()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setRelativeApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        request.setRequestURI( "/organizationUnits.xml.gz" );
        when( contextService.getRequest() ).thenReturn( request );

        when( contextService.getApiPath() ).thenReturn( "/demo/api/456" );

        when( contextService.getParameterValuesMap() ).thenAnswer( invocation -> Map.of(
            "page", List.of( "1" ),
            "pageSize", List.of( "55" ) ) );

        final Pager pager = new Pager( 2, 60 );
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertEquals( "/demo/api/456/organizationUnits.xml.gz", pager.getPrevPage() );
        assertNull( pager.getNextPage() );
    }

    @Test
    void nextLinkWithDotsInPath()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setRelativeApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        request.setRequestURI( "https://play.dhis2.org/2.30/api/30/organizationUnits.xml.gz" );
        when( contextService.getRequest() ).thenReturn( request );

        when( contextService.getApiPath() ).thenReturn( "/2.30/api/30" );

        when( contextService.getParameterValuesMap() ).thenAnswer( invocation -> Map.of(
            "page", List.of( "1" ),
            "pageSize", List.of( "55" ) ) );

        final Pager pager = new Pager( 2, 60 );
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertEquals( "/2.30/api/30/organizationUnits.xml.gz", pager.getPrevPage() );
        assertNull( pager.getNextPage() );
    }

    @Test
    void prevLinkParameters()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setRelativeApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        when( contextService.getRequest() ).thenReturn( request );

        when( contextService.getApiPath() ).thenReturn( "/demo/api/456" );

        when( contextService.getParameterValuesMap() ).thenAnswer( invocation -> Map.of(
            "page", List.of( "1" ),
            "pageSize", List.of( "55" ),
            "fields", List.of( "id,name,value[id,text]" ),
            "value[x]", List.of( "test1", "test2\u00D8" ) ) );

        final Pager pager = new Pager( 3, 110 );
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertNull( pager.getNextPage() );
        assertEquivalentRelativeUrls(
            "/demo/api/456/organizationUnits?page=2&fields=id%2Cname%2Cvalue%5Bid%2Ctext%5D&value%5Bx%5D=test1&value%5Bx%5D=test2%C3%98",
            pager.getPrevPage() );
    }

    @Test
    void prevLinkParametersPage1()
    {
        when( schemaService.getDynamicSchema( OrganisationUnit.class ) )
            .thenAnswer( invocation -> {
                Schema schema = new Schema( OrganisationUnit.class, "organisationUnit", "organisationUnits" );
                schema.setRelativeApiEndpoint( "/organizationUnits" );
                return schema;
            } );

        when( contextService.getRequest() ).thenReturn( request );

        when( contextService.getApiPath() ).thenReturn( "/demo/api/456" );

        when( contextService.getParameterValuesMap() ).thenAnswer( invocation -> Map.of(
            "page", List.of( "1" ),
            "pageSize", List.of( "55" ),
            "fields", List.of( "id,name,value[id,text]" ),
            "value[x]", List.of( "test1", "test2\u00D8" ) ) );

        final Pager pager = new Pager( 2, 90 );
        service.generatePagerLinks( pager, OrganisationUnit.class );
        assertNull( pager.getNextPage() );
        assertEquivalentRelativeUrls(
            "/demo/api/456/organizationUnits?fields=id%2Cname%2Cvalue%5Bid%2Ctext%5D&value%5Bx%5D=test1&value%5Bx%5D=test2%C3%98",
            pager.getPrevPage() );
    }
}


text:
<?php

/**
 * Socket-based HTTP future, for making HTTP requests using future semantics.
 * This is an alternative to @{class:CURLFuture} which has better resolution
 * behavior (select()-based wait instead of busy wait) but fewer features. You
 * should prefer this class to @{class:CURLFuture} unless you need its advanced
 * features (like HTTP/1.1, chunked transfer encoding, gzip, etc.).
 *
 * Example Usage
 *
 *    $future = new HTTPFuture('http://www.example.com/');
 *    list($response_body, $headers) = $future->resolvex();
 *
 * Or
 *
 *    $future = new HTTPFuture('http://www.example.com/');
 *    list($http_response_status_object,
 *         $response_body,
 *         $headers) = $future->resolve();
 *
 * Prefer @{method:resolvex} to @{method:resolve} as the former throws
 * @{class:HTTPFutureHTTPResponseStatus} on failures, which includes an
 * informative exception message.
 */
final class HTTPFuture extends BaseHTTPFuture {

  private $host;
  private $port = 80;
  private $fullRequestPath;

  private $socket;
  private $writeBuffer;
  private $response;

  private $stateConnected     = false;
  private $stateWriteComplete = false;
  private $stateReady         = false;
  private $stateStartTime;

  private $profilerCallID;

  public function setURI($uri) {
    $parts = parse_url($uri);
    if (!$parts) {
      throw new Exception(pht("Could not parse URI '%s'.", $uri));
    }

    if (empty($parts['scheme']) || $parts['scheme'] !== 'http') {
      throw new Exception(
        pht(
          "URI '%s' must be fully qualified with '%s' scheme.",
          $uri,
          'http://'));
    }

    if (!isset($parts['host'])) {
      throw new Exception(
        pht("URI '%s' must be fully qualified and include host name.", $uri));
    }

    $this->host = $parts['host'];

    if (!empty($parts['port'])) {
      $this->port = $parts['port'];
    }

    if (isset($parts['user']) || isset($parts['pass'])) {
      throw new Exception(
        pht('HTTP Basic Auth is not supported by %s.', __CLASS__));
    }

    if (isset($parts['path'])) {
      $this->fullRequestPath = $parts['path'];
    } else {
      $this->fullRequestPath = '/';
    }

    if (isset($parts['query'])) {
      $this->fullRequestPath .= '?'.$parts['query'];
    }

    return parent::setURI($uri);
  }

  public function __destruct() {
    if ($this->socket) {
      @fclose($this->socket);
      $this->socket = null;
    }
  }

  public function getReadSockets() {
    if ($this->socket) {
      return array($this->socket);
    }
    return array();
  }

  public function getWriteSockets() {
    if (strlen($this->writeBuffer)) {
      return array($this->socket);
    }
    return array();
  }

  public function isWriteComplete() {
    return $this->stateWriteComplete;
  }

  private function getDefaultUserAgent() {
    return __CLASS__.'/1.0';
  }

  public function isReady() {
    if ($this->stateReady) {
      return true;
    }

    if (!$this->socket) {
      $this->stateStartTime = microtime(true);
      $this->socket = $this->buildSocket();
      if (!$this->socket) {
        return $this->stateReady;
      }
    }

    if (!$this->stateConnected) {
      $read   = array();
      $write  = array($this->socket);
      $except = array();
      $select = stream_select($read, $write, $except, $tv_sec = 0);
      if ($write) {
        $this->stateConnected = true;
      }
    }

    if ($this->stateConnected) {
      if (strlen($this->writeBuffer)) {
        $bytes = @fwrite($this->socket, $this->writeBuffer);
        if ($bytes === false) {
          throw new Exception(pht('Failed to write to buffer.'));
        } else if ($bytes) {
          $this->writeBuffer = substr($this->writeBuffer, $bytes);
        }
      }

      if (!strlen($this->writeBuffer)) {
        $this->stateWriteComplete = true;
      }

      while (($data = fread($this->socket, 32768)) || strlen($data)) {
        $this->response .= $data;
      }

      if ($data === false) {
        throw new Exception(pht('Failed to read socket.'));
      }
    }

    return $this->checkSocket();
  }

  private function buildSocket() {
    $errno = null;
    $errstr = null;
    $socket = @stream_socket_client(
      'tcp://'.$this->host.':'.$this->port,
      $errno,
      $errstr,
      $ignored_connection_timeout = 1.0,
      STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT);

    if (!$socket) {
      $this->stateReady = true;
      $this->setResult(
        $this->buildErrorResult(
          HTTPFutureTransportResponseStatus::ERROR_CONNECTION_FAILED));
      return null;
    }

    $ok = stream_set_blocking($socket, 0);
    if (!$ok) {
      throw new Exception(pht('Failed to set stream nonblocking.'));
    }

    $this->writeBuffer = $this->buildHTTPRequest();

    return $socket;
  }

  private function checkSocket() {
    $timeout = false;
    $now = microtime(true);
    if (($now - $this->stateStartTime) > $this->getTimeout()) {
      $timeout = true;
    }

    if (!feof($this->socket) && !$timeout) {
      return false;
    }

    $this->stateReady = true;

    if ($timeout) {
      $this->setResult(
        $this->buildErrorResult(
          HTTPFutureTransportResponseStatus::ERROR_TIMEOUT));
    } else if (!$this->stateConnected) {
      $this->setResult(
        $this->buildErrorResult(
          HTTPFutureTransportResponseStatus::ERROR_CONNECTION_REFUSED));
    } else if (!$this->stateWriteComplete) {
      $this->setResult(
        $this->buildErrorResult(
          HTTPFutureTransportResponseStatus::ERROR_CONNECTION_FAILED));
    } else {
      $this->setResult($this->parseRawHTTPResponse($this->response));
    }

    return true;
  }

  private function buildErrorResult($error) {
    return array(
      $status = new HTTPFutureTransportResponseStatus($error, $this->getURI()),
      $body = null,
      $headers = array(),
    );
  }

  private function buildHTTPRequest() {
    $data = $this->getData();
    $method = $this->getMethod();
    $uri = $this->fullRequestPath;

    $add_headers = array();

    if ($this->getMethod() == 'GET') {
      if (is_array($data)) {
        $data = phutil_build_http_querystring($data);
        if (strpos($uri, '?') !== false) {
          $uri .= '&'.$data;
        } else {
          $uri .= '?'.$data;
        }
        $data = '';
      }
    } else {
      if (is_array($data)) {
        $data = phutil_build_http_querystring($data)."\r\n";
        $add_headers[] = array(
          'Content-Type',
          'application/x-www-form-urlencoded',
        );
      }
    }

    $length = strlen($data);

    $add_headers[] = array(
      'Content-Length',
      $length,
    );

    if (!$this->getHeaders('User-Agent')) {
      $add_headers[] = array(
        'User-Agent',
        $this->getDefaultUserAgent(),
      );
    }

    if (!$this->getHeaders('Host')) {
      $add_headers[] = array(
        'Host',
        $this->host,
      );
    }

    $headers = array_merge($this->getHeaders(), $add_headers);
    foreach ($headers as $key => $header) {
      list($name, $value) = $header;
      if (strlen($value)) {
        $value = ': '.$value;
      }
      $headers[$key] = $name.$value."\r\n";
    }

    return
      "{$method} {$uri} HTTP/1.0\r\n".
      implode('', $headers).
      "\r\n".
      $data;
  }

  protected function getServiceProfilerStartParameters() {
    return array(
      'type' => 'http',
      'uri' => phutil_string_cast($this->getURI()),
    );
  }

}


text:
#pragma once

#ifdef USE_DRIVE_NOTIFICATIONS

// Include "mega/drivenotify.h" where needed.
// This header cannot be used by itself.

#include <map>
#include <thread>
#include <atomic>

namespace mega {

// Windows: Platform specific definition
//
// Uses WMI. Use 'wbemtest' tool to run WQL queries, for testing and comparison.
class DriveNotifyWin final : public DriveNotify
{
public:
    ~DriveNotifyWin() override { stopNotifier(); }

protected:
    void doInThread() override;

    enum EventType
    {
        UNKNOWN_EVENT,
        DRIVE_CONNECTED_EVENT,
        DRIVE_DISCONNECTED_EVENT
    };
};

} // namespace

#endif // USE_DRIVE_NOTIFICATIONS


text:
<?php
/*
Holy Child Montessori
2017

Notification

General Template:
$notif_title = ;
$notif_content = ;
$notif_photo_url = ;
$notif_url = ;
$notif_icon = ;
$notif_user_id = ;
$notif_sender_alternative = ;
$notif_sender_id = ;

// Send Notification
include("../_require/notif.php");

*/

// Generate a Notification ID
$notif_id = uniqid();

// Get Current Date and Time
$notif_create_month = date("M");
$notif_create_day = date("d");
$notif_create_year = date("Y");
$notif_create_time = date("h:i a");

// Handle empty vars
if(!@$notif_title) $notif_title = "Untitled Notification";
if(!@$notif_content) $notif_content = "";
if(!@$notif_photo_url) $notif_photo_url = "";
if(!@$notif_url) $notif_url = "";
if(!@$notif_icon) $notif_icon = "";
if(!@$notif_user_id) $notif_user_id = "";
if(!@$notif_sender_alternative) $notif_sender_alternative = "";
if(!@$notif_sender_id) $notif_sender_id = "";

// Prepare Array
$notif_array = array(
    "notification_id" => "$notif_id",
	"notification_title" => "$notif_title",
	"notification_content" => "$notif_content",
	"photo_url" => "$notif_photo_url",
	"notification_url" => "$notif_url",
	"notification_icon" => "$notif_icon",
	"user_id" => "$notif_user_id",
	"sender_alternative" => "$notif_sender_alternative",
	"sender_id" => "$notif_sender_id",
	"create_month" => "$notif_create_month",
	"create_day" => "$notif_create_day",
	"create_year" => "$notif_create_year",
	"create_time" => "$notif_create_time"
);

// Add to Database
$db_notification->add($notif_array);
?>


text:
package rest.web;

import org.json.JSONArray;
import rest.dao.ISecurityDao;
import rest.dao.SecurityDao;
import rest.service.ISecurityService;
import rest.service.SecurityService;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * Created by b4ut4
 */
@Path("services/{token: [A-Z0-9]*}")
public class Services {

    ISecurityDao securityDao = new SecurityDao();
    ISecurityService securityService = new SecurityService(securityDao);
    @PathParam("token") String token;

    @Path("user")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUser() throws Exception {
        return Response.ok(securityService.getUser(token, "users").toString(), MediaType.APPLICATION_JSON_TYPE).build();
    }

    @Path("modules/{id:\\d+}/{parent:\\d+}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getModules(@PathParam("id") Long id, @PathParam("parent") Long parent) throws Exception {
        return Response.ok(securityService.getModulesByUser(token, "users", id.intValue(), parent.intValue()).toString(), MediaType.APPLICATION_JSON_TYPE).build();
    }

    @Path("apps")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getApps() throws Exception {
        return Response.ok(securityService.getAppsByUser(token, "users").toString(), MediaType.APPLICATION_JSON_TYPE).build();
    }

    @Path("operations/{id:\\d+}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOperations(@PathParam("id") Long id) throws Exception {
        return Response.ok(securityService.getOperationsByUser(token, "users", id.intValue()).toString(), MediaType.APPLICATION_JSON_TYPE).build();
    }

}


text:
require 'spec_helper'

describe ActivitiesController do
  describe "show" do
    it "should redirecto to activity object" do
      id = 3
      activity = double("activity")
      post = Factory(:post)

      activity.should_receive(:direct_object) { post }

      Activity.should_receive(:find).with(id.to_s) { activity }

      get :show, id: id
    end
  end
end


text:
package com.coolweather.android.gson;

/**
 * Created by zhengw on 2017.3.2.
 */

public class AQI {

    public AQICity city;

    public class AQICity{

        public String  aqi;
        public String pm25;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.whitelist">
    <module_version install_time="1370464852443" last="true" origin="installer" specification_version="1.11.1">
        <file crc="1351095255" name="config/Modules/org-netbeans-modules-whitelist.xml"/>
        <file crc="3807311618" name="modules/locale/org-netbeans-modules-whitelist_ja.jar"/>
        <file crc="3589125461" name="modules/locale/org-netbeans-modules-whitelist_pt_BR.jar"/>
        <file crc="2149602626" name="modules/locale/org-netbeans-modules-whitelist_ru.jar"/>
        <file crc="2286118053" name="modules/locale/org-netbeans-modules-whitelist_zh_CN.jar"/>
        <file crc="3579069065" name="modules/org-netbeans-modules-whitelist.jar"/>
    </module_version>
</module>


text:
<!doctype html>

  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="WZyOKgG2FCszEk1sz_fP543_B8lAVLJEWLEjQoeIEzc" />

  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>

  <link href="//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">

<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />

  <meta name="keywords" content="phimor, program" />

  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.5.0" />

<meta name="description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
Quick">
<meta property="og:type" content="article">
<meta property="og:title" content="hello-world">
<meta property="og:url" content="http://yoursite.com/2016/02/26/hello-world/index.html">
<meta property="og:site_name" content="Phimor">
<meta property="og:description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
Quick">
<meta property="og:updated_time" content="2016-02-26T06:08:55.178Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="hello-world">
<meta name="twitter:description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
Quick">

  <title> hello-world | Phimor </title>

      Phimor

  <button>

  </button>

            首页

            分类

            归档

            标签

            搜索

  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

                hello-world

            发表于
            <time itemprop="dateCreated" datetime="2016-02-26T14:08:25+08:00" content="2016-02-26">
              2016-02-26
            </time>

                  |

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1

$ hexo new "My New Post"

More info: Writing

Run server

1

$ hexo server

More info: Server

Generate static files

1

$ hexo generate

More info: Generating

Deploy to remote sites

1

$ hexo deploy

More info: Deployment

                 hello-markdown

分享到:

微博

QQ空间

腾讯微博

微信

            文章目录

            站点概览

Phimor

看吧,那个整天在烈日中赤着身子游玩的,喜欢玩泥巴的,满嘴脏话的小毛孩又出现了

              2
              日志

                1
                分类

                1
                标签

1. Quick Start

1.1. Create a new post

1.2. Run server

1.3. Generate static files

1.4. Deploy to remote sites

  ©
  2016

  Phimor

  由 Hexo 强力驱动

  主题 -

    NexT.Pisces


text:
import { inject, computedFrom, bindable } from 'aurelia-framework';
import { Router, RouteConfig } from 'aurelia-router';

import { DaaSAPI, DatabaseServer, ProvisioningAction } from '../api/daas-api';
import { ConfirmDialog } from '../dialogs/confirm';
import { sortByName } from '../../utilities/sorting';

@inject(DaaSAPI, Router)
export class ServerList {
    private routeConfig: RouteConfig;
    private pollHandle: number = 0;

    @bindable public servers: DatabaseServer[] = [];
    @bindable public errorMessage: string | null = null;
    @bindable public isLoading: boolean = false;

    @bindable private confirmDialog: ConfirmDialog

    constructor(private api: DaaSAPI, private router: Router) { }

    /**
     * Are there no servers defined in the system?
     */
    @computedFrom('isLoading', 'servers')
    public get hasNoServers(): boolean {
        return !this.isLoading && this.servers.length == 0;
    }

    /**
     * Has an error occurred?
     */
    @computedFrom('errorMessage')
    public get hasError(): boolean {
        return this.errorMessage !== null;
    }

    /**
     * Refresh the server list.
     */
    public async refreshServerList(): Promise<void> {
        this.clearError();

        try {
            this.servers = await this.api.getServers();
        } catch (error) {
            this.showError(error as Error);
        }
    }

    /**
     * Called when the component is activated.
     *
     * @param params Route parameters.
     * @param routeConfig The configuration for the currently-active route.
     */
    public activate(params: any, routeConfig: RouteConfig): void {
        this.routeConfig = routeConfig;

        this.load(false);
    }

    /**
     * Called when the component is deactivated.
     */
    public deactivate(): void {
        if (this.pollHandle) {
            window.clearTimeout(this.pollHandle);
            this.pollHandle = 0;
        }
    }

    /**
     * Load tenant details.
     *
     * @param isReload False if this is the initial load.
     */
    private async load(isReload: boolean): Promise<void> {
        if (!isReload)
            this.isLoading = true;

        try
        {
            this.servers = sortByName(
                await this.api.getServers()
            );

            if (this.servers && this.servers.find(server => server.action != ProvisioningAction.None)) {
                this.pollHandle = window.setTimeout(() => this.load(true), 2000);
            } else {
                this.pollHandle = 0;
            }
        }
        catch (error) {
            this.showError(error as Error)
        }
        finally {
            if (!isReload)
                this.isLoading = false;
        }
    }

    /**
     * Show a server's databases.
     *
     * @param server The target server.
     */
    public showDatabases(server: DatabaseServer): void {
        this.router.navigateToRoute('serverDatabases', {
            serverId: server.id
        });
    }

    /**
     * Show a server's events.
     *
     * @param server The target server.
     */
    public showEvents(server: DatabaseServer): void {
        this.router.navigateToRoute('serverEvents', {
            serverId: server.id
        });
    }

    /**
     * Repair a server.
     *
     * @param server The server to repair.
     */
    public async repairServer(server: DatabaseServer): Promise<void> {
        this.clearError();

        try {
            const confirm = await this.confirmDialog.show('Repair Server',
                `Repair server "${server.name}"?`
            );
            if (!confirm)
                return;

            await this.api.reconfigureServer(server.id);
        }
        catch (error) {
            this.showError(error as Error);

            return;
        }

        await this.load(true);
    }

    /**
     * Destroy a server.
     *
     * @param server The server to destroy.
     */
    public async destroyServer(server: DatabaseServer): Promise<void> {
        this.clearError();

        try {
            const confirm = await this.confirmDialog.show('Destroy Server',
                `Destroy server "${server.name}"?`
            );
            if (!confirm)
                return;

            await this.api.destroyServer(server.id);
        }
        catch (error) {
            this.showError(error as Error);

            return;
        }

        await this.load(true);
    }

    /**
     * Clear the current error message (if any).
     */
    private clearError(): void {
        this.errorMessage = null;
    }

    /**
     * Show an error message.
     *
     * @param error The error to show.
     */
    private showError(error: Error): void {
        console.log(error);

        this.errorMessage = (error.message as string || 'Unknown error.').split('\n').join('<br/>');
    }
}


text:
REPORTER = dot

build: blob.js

blob.js:
	@./node_modules/.bin/browserify --standalone blob index.js > blob.js

test:
	@./node_modules/.bin/zuul -- test/index.js

clean:
	rm blob.js

.PHONY: test blob.js


text:
[![GoDoc](https://img.shields.io/badge/api-reference-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/tidwall/pretty)

Pretty is a Go package that provides [fast](#performance) methods for formatting JSON for human readability, or to compact JSON for smaller payloads.

Getting Started
===============

## Installing

To start using Pretty, install Go and run `go get`:

```sh
$ go get -u github.com/tidwall/pretty
```

This will retrieve the library.

## Pretty

Using this example:

```json
{"name":  {"first":"Tom","last":"Anderson"},  "age":37,
"children": ["Sara","Alex","Jack"],
"fav.movie": "Deer Hunter", "friends": [
    {"first": "Janet", "last": "Murphy", "age": 44}
  ]}
```

The following code:
```go
result = pretty.Pretty(example)
```

Will format the json to:

```json
{
  "name": {
    "first": "Tom",
    "last": "Anderson"
  },
  "age": 37,
  "children": ["Sara", "Alex", "Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {
      "first": "Janet",
      "last": "Murphy",
      "age": 44
    }
  ]
}
```

## Color

Color will colorize the json for outputing to the screen.

```json
result = pretty.Color(json, nil)
```

Will add color to the result for printing to the terminal.
The second param is used for a customizing the style, and passing nil will use the default `pretty.TerminalStyle`.

## Ugly

The following code:
```go
result = pretty.Ugly(example)
```

Will format the json to:

```json
{"name":{"first":"Tom","last":"Anderson"},"age":37,"children":["Sara","Alex","Jack"],"fav.movie":"Deer Hunter","friends":[{"first":"Janet","last":"Murphy","age":44}]}```
```

## Customized output

There's a `PrettyOptions(json, opts)` function which allows for customizing the output with the following options:

```go
type Options struct {
	// Width is an max column width for single line arrays
	// Default is 80
	Width int
	// Prefix is a prefix for all lines
	// Default is an empty string
	Prefix string
	// Indent is the nested indentation
	// Default is two spaces
	Indent string
	// SortKeys will sort the keys alphabetically
	// Default is false
	SortKeys bool
}
```
## Performance

Benchmarks of Pretty alongside the builtin `encoding/json` Indent/Compact methods.
```
BenchmarkPretty-16           1000000    1034 ns/op    720 B/op     2 allocs/op
BenchmarkPrettySortKeys-16    586797    1983 ns/op   2848 B/op    14 allocs/op
BenchmarkUgly-16             4652365     254 ns/op    240 B/op     1 allocs/op
BenchmarkUglyInPlace-16      6481233     183 ns/op      0 B/op     0 allocs/op
BenchmarkJSONIndent-16        450654    2687 ns/op   1221 B/op     0 allocs/op
BenchmarkJSONCompact-16       685111    1699 ns/op    442 B/op     0 allocs/op
```

*These benchmarks were run on a MacBook Pro 2.4 GHz 8-Core Intel Core i9.*

## Contact
Josh Baker [@tidwall](http://twitter.com/tidwall)

## License

Pretty source code is available under the MIT [License](/LICENSE).


text:
/// Copyright 2017 Troy Lewis. All Rights Reserved
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace NFOGenerator.Util
{
    /// <summary>
    /// Utilities about Class
    /// Reference: http://javaextjs.iteye.com/blog/364624
    /// </summary>
    public class ClassUtil
    {
        #region Class Members
        #region Private
        /// <summary>
        /// Get properties by reflection
        /// </summary>
        /// <param name="o">Object class</param>
        /// <returns>properties</returns>
        private static PropertyInfo[] GetProperties(object o)
        {
            return o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        }
        /// <summary>
        /// Get description by reflection
        /// </summary>
        /// <param name="a">member info</param>
        /// <returns>description of member</returns>
        private static string GetDescription(MemberInfo a)
        {
            DescriptionAttribute attr = Attribute.GetCustomAttribute(a,
                    typeof(DescriptionAttribute)) as DescriptionAttribute;
            return (attr == null) ? "Unknown" : attr.Description;
        }
        #endregion

        #region Public
        /// <summary>
        /// Map properties which have specific description to a dictionary
        /// </summary>
        /// <param name="o">Object class</param>
        /// <param name="description">specific description</param>
        /// <returns>properties info</returns>
        public static Dictionary<string, string> ToStringMap(Object o, string description)
        {
            PropertyInfo[] pi = GetProperties(o);
            Dictionary<string, string> map = new Dictionary<string, string>();
            MethodInfo mi;

            foreach (PropertyInfo p in pi)
            {
                mi = p.GetGetMethod();
                if (mi != null && mi.IsPublic && GetDescription(p) == description)
                {
                    map.Add(p.Name.Replace('_', ' '), mi.Invoke(o, new Object[] { }).ToString());
                }
            }

            return map;
        }
        #endregion
        #endregion
    }
}


text:
SYNONYM

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

#### Published in
Michelia 1(no. 5): 504 (1879)

#### Original name
Fusidium ranunculi Bonord., 1851

### Remarks
null


text:
namespace Game.Components
{
    public enum Direction : int
    {
        Undefined,
        Up,
        Down,
        Left,
        Right
    }

    [Game]
    public class SnakeDirection : Entitas.IComponent
    {
        public Direction currentDirection;
        public Direction currentWantedDirection;
    }
}


text:
namespace CS_OOP_Advanced_Exam_Prep_July_2016.Interfaces
{
    public interface IProduct
    {
        int Size { get; set; }
        string Name { get; set; }
        int Id { get; }
    }
}


text:
require 'spec_helper'

describe 'User' do
  context "valid params" do
    it 'build an user' do
      user = build(:user)
      expect(user).to be_valid
    end
  end

  context "invalid params" do
    it "without a password" do
      user = build(:user, password: '')
      expect(user).to_not be_valid
    end

    it "without a password confirmation" do
      user = build(:user, password_confirmation: '')
      expect(user).to_not be_valid
    end

    it "with different password and password confirmation" do
      user = build(:user, password: 'password', password_confirmation: 'wrong-password')
      expect(user).to_not be_valid
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus oinodes Berk. & M.A. Curtis

### Remarks
null