text:
package status

import (
	"encoding/json"
	"time"

	"github.com/operator-framework/operator-sdk/pkg/ansible/runner/eventapi"

	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
)

var log = logf.Log.WithName("controller.status")

const (
	host = "localhost"
)

// AnsibleResult - encapsulation of the ansible result.
type AnsibleResult struct {
	Ok               int                `json:"ok"`
	Changed          int                `json:"changed"`
	Skipped          int                `json:"skipped"`
	Failures         int                `json:"failures"`
	TimeOfCompletion eventapi.EventTime `json:"completion"`
}

// NewAnsibleResultFromStatusJobEvent - creates a Ansible status from job event.
func NewAnsibleResultFromStatusJobEvent(je eventapi.StatusJobEvent) *AnsibleResult {
	// ok events.
	a := &AnsibleResult{TimeOfCompletion: je.Created}
	if v, ok := je.EventData.Changed[host]; ok {
		a.Changed = v
	}
	if v, ok := je.EventData.Ok[host]; ok {
		a.Ok = v
	}
	if v, ok := je.EventData.Skipped[host]; ok {
		a.Skipped = v
	}
	if v, ok := je.EventData.Failures[host]; ok {
		a.Failures = v
	}
	return a
}

// NewAnsibleResultFromMap - creates a Ansible status from a job event.
func NewAnsibleResultFromMap(sm map[string]interface{}) *AnsibleResult {
	//Create Old top level status
	// ok events.
	a := &AnsibleResult{}
	if v, ok := sm["changed"]; ok {
		a.Changed = int(v.(int64))
	}
	if v, ok := sm["ok"]; ok {
		a.Ok = int(v.(int64))
	}
	if v, ok := sm["skipped"]; ok {
		a.Skipped = int(v.(int64))
	}
	if v, ok := sm["failures"]; ok {
		a.Failures = int(v.(int64))
	}
	if v, ok := sm["completion"]; ok {
		s := v.(string)
		if err := a.TimeOfCompletion.UnmarshalJSON([]byte(s)); err != nil {
			log.Error(err, "Failed to unmarshal time of completion for ansible result")
		}
	}
	return a
}

// ConditionType - type of condition
type ConditionType string

const (
	// RunningConditionType - condition type of running.
	RunningConditionType ConditionType = "Running"
	// FailureConditionType - condition type of failure.
	FailureConditionType ConditionType = "Failure"
)

// Condition - the condition for the ansible operator.
type Condition struct {
	Type               ConditionType      `json:"type"`
	Status             v1.ConditionStatus `json:"status"`
	LastTransitionTime metav1.Time        `json:"lastTransitionTime"`
	AnsibleResult      *AnsibleResult     `json:"ansibleResult,omitempty"`
	Reason             string             `json:"reason"`
	Message            string             `json:"message"`
}

func createConditionFromMap(cm map[string]interface{}) Condition {
	ct, ok := cm["type"].(string)
	if !ok {
		//If we do not find the string we are defaulting
		// to make sure we can at least update the status.
		ct = string(RunningConditionType)
	}
	status, ok := cm["status"].(string)
	if !ok {
		status = string(v1.ConditionTrue)
	}
	reason, ok := cm["reason"].(string)
	if !ok {
		reason = RunningReason
	}
	message, ok := cm["message"].(string)
	if !ok {
		message = RunningMessage
	}
	asm, ok := cm["ansibleResult"].(map[string]interface{})
	var ansibleResult *AnsibleResult
	if ok {
		ansibleResult = NewAnsibleResultFromMap(asm)
	}
	ltts, ok := cm["lastTransitionTime"].(string)
	ltt := metav1.Now()
	if ok {
		t, err := time.Parse("2006-01-02T15:04:05Z", ltts)
		if err != nil {
			log.Info("Unable to parse time for status condition", "Time", ltts)
		} else {
			ltt = metav1.NewTime(t)
		}
	}
	return Condition{
		Type:               ConditionType(ct),
		Status:             v1.ConditionStatus(status),
		LastTransitionTime: ltt,
		Reason:             reason,
		Message:            message,
		AnsibleResult:      ansibleResult,
	}
}

// Status - The status for custom resources managed by the operator-sdk.
type Status struct {
	Conditions   []Condition            `json:"conditions"`
	CustomStatus map[string]interface{} `json:"-"`
}

// CreateFromMap - create a status from the map
func CreateFromMap(statusMap map[string]interface{}) Status {
	customStatus := make(map[string]interface{})
	for key, value := range statusMap {
		if key != "conditions" {
			customStatus[key] = value
		}
	}
	conditionsInterface, ok := statusMap["conditions"].([]interface{})
	if !ok {
		return Status{Conditions: []Condition{}, CustomStatus: customStatus}
	}
	conditions := []Condition{}
	for _, ci := range conditionsInterface {
		cm, ok := ci.(map[string]interface{})
		if !ok {
			log.Info("Unknown condition, removing condition", "ConditionInterface", ci)
			continue
		}
		conditions = append(conditions, createConditionFromMap(cm))
	}
	return Status{Conditions: conditions, CustomStatus: customStatus}
}

// GetJSONMap - gets the map value for the status object.
// This is used to set the status on the CR.
// This is needed because the unstructured type has special rules around DeepCopy.
// If you do not convert the status to the map, then DeepCopy for the
// unstructured will fail and throw runtime exceptions.
// Please note that this will return an empty map on error.
func (status *Status) GetJSONMap() map[string]interface{} {
	b, err := json.Marshal(status)
	if err != nil {
		log.Error(err, "Unable to marshal json")
		return status.CustomStatus
	}
	if err := json.Unmarshal(b, &status.CustomStatus); err != nil {
		log.Error(err, "Unable to unmarshal json")
	}
	return status.CustomStatus
}


text:
package org.springframework.social.facebook.api;

import java.io.Serializable;

/**
 * Domain type representing a taggable friend.
 * @author Craig Walls
 */
@SuppressWarnings("serial")
public class UserTaggableFriend extends FacebookObject implements Serializable {

	private final String id;

	private final String name;

	private final String firstName;

	private final String middleName;

	private final String lastName;

	private ProfilePictureSource picture;

	public UserTaggableFriend(String id, String name, String firstName, String middleName, String lastName, ProfilePictureSource picture) {
		this.id = id;
		this.name = name;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.picture = picture;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getMiddleName() {
		return middleName;
	}

	public String getLastName() {
		return lastName;
	}

	public ProfilePictureSource getPicture() {
		return picture;
	}

}

redpajama_set_name: RedPajamaGithub


text:
import { div, VNode } from "@cycle/dom";
import { ComponentSources, ComponentSinks, StyleAndContentArgs, ContentObj, DOMContent, isDOMContent } from "../../types";
import { renderPropsAndContent, runPropsAndContent, makeIsArgs, addClassName } from "../../common";
import { TextAlignment, VerticalAlignment} from "../../enums";
import { numToText, getScope } from "../../utils";

export namespace Row {
  export interface Props {
    width: number;
    doubling: boolean;
    centered: boolean;
    stretched: boolean;
    mobileOnly: boolean;
    tabletOnly: boolean;
    computerOnly: boolean;
    largescreenOnly: boolean;
    equalWidth: boolean;
    alignment: VerticalAlignment | string;
    textAlignment: TextAlignment | string;
  }

  export type RowArgs = StyleAndContentArgs<Props, DOMContent, ContentObj<DOMContent>>;
  export type RowSources = ComponentSources<Props, DOMContent, ContentObj<DOMContent>>;

  export function render(arg1?: Partial<Props>|DOMContent|RowArgs, arg2?: DOMContent) : VNode {
    return renderPropsAndContent(row, makeIsArgs(isDOMContent), isDOMContent, arg1, arg2);
  }
  export function run(sources: RowSources, scope: string = getScope()) : ComponentSinks {
    return runPropsAndContent(sources, row, ".row", scope);
  }
  export function from(node: VNode, props: Partial<Props> = {}): VNode {
    return addClassName(node, getClassname(props));
  }
  export function row(args): VNode {
    let props = args.props ? args.props : {};
    let content = args.content ? isDOMContent(args.content) ? args.content : args.content.main: [];
    return div({ props: { className: getClassname(props) } }, content);
  }
  function getClassname(props: Partial<Props>): string {
    let className = "ui";
    if (props.doubling) {
      className += " doubling";
    }
    if (props.centered) {
      className += " centered";
    }
    if (props.stretched) {
      className += " stretched";
    }
    if (props.mobileOnly) {
      className += " mobile only";
    }
    if (props.tabletOnly) {
      className += " tablet only";
    }
    if (props.computerOnly) {
      className += " computer only";
    }
    if (props.largescreenOnly) {
      className += " large screen only";
    }
    if (props.equalWidth) {
      className += " equal width";
    }
    if (props.width) {
      className += numToText(props.width) + " column";
    }
    if (typeof(props.textAlignment) !== "undefined") {
      className += TextAlignment.ToClassname(props.textAlignment);
    }
    if (typeof(props.alignment) !== "undefined") {
      className += VerticalAlignment.ToClassname(props.alignment);
    }
    className += " row";
    return className;
  }
}


text:
package com.facebook.buck.cxx;

import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.Arg;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;

/**
 * Defines the factory interface to create linking strategy. Used by {@link CxxLinkableEnhancer} to
 * create the {@link CxxConditionalLinkStrategy} that will be used to perform linking.
 */
public interface CxxConditionalLinkStrategyFactory {

  /**
   * Creates a strategy that will be used by {@link CxxLink} for linking.
   *
   * @param ldArgs The list of arguments given to the linker.
   * @param outputPath The path to the linked executable.
   */
  CxxConditionalLinkStrategy createStrategy(
      ActionGraphBuilder graphBuilder,
      ProjectFilesystem projectFilesystem,
      BuildRuleResolver ruleResolver,
      BuildTarget target,
      ImmutableList<Arg> ldArgs,
      Linker linker,
      Path outputPath);
}


text:
<?php

namespace backend\modules\seller;

/**
 * seller module definition class
 */
class seller extends \yii\base\Module
{
    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'backend\modules\seller\controllers';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // custom initialization code goes here
        $this->modules = [
            'catalog' => [
                'class' => 'backend\modules\seller\modules\catalog\catalog',
                'viewPath' => '@app/themes/adminlte/modules/catalog/views',
            ],
            'orders' => [
                'class' => 'backend\modules\seller\modules\orders\orders',
                'viewPath' => '@app/themes/adminlte/modules/orders/views',
            ],
            'managers' => [
                'class' => 'backend\modules\seller\modules\managers\managers',
                'viewPath' => '@app/themes/adminlte/modules/managers/views',
            ],
            'customers' => [
                'class' => 'backend\modules\seller\modules\customers\customers',
                'viewPath' => '@app/themes/adminlte/modules/customers/views',
            ],
            'shipping' => [
                'class' => 'backend\modules\seller\modules\shipping\shipping',
                'viewPath' => '@app/themes/adminlte/modules/shipping/views',
            ],
        ];

    }
}


text:
function getBodyElement() {
    return document.getElementsByTagName('body')[0];
}

function englishDimensions() {
    generateDimensions(" inches", " lbs");
}

function metricDimensions() {
    generateDimensions(" mm", " kg");
}

function generateDimensions(dimensionlbl, weightlbl) {

    var div = document.getElementById("dimensionsForm");

    var fieldSet = document.createElement("fieldset");
    fieldSet.setAttribute("id", "dimensionsFieldset");
    div.appendChild(fieldSet);

    var legend = document.createElement("legend");
    legend.innerHTML = "Package Dimensions/Weight";
    fieldSet.appendChild(legend);

    var table = document.createElement("table");
    table.setAttribute("class", "table-format");
    fieldSet.appendChild(table);

    var tbody = document.createElement("tbody");
    table.appendChild(tbody);

    var tr = document.createElement("tr");
    tbody.appendChild(tr);

    var td = document.createElement("td");
    td.setAttribute("class", "textbox");
    tr.appendChild(td);

    var lengthLabel = document.createElement("label");
    lengthLabel.setAttribute("for", "LengthLabel");
    lengthLabel.innerHTML = "Length ";
    td.appendChild(lengthLabel);

    var lengthInput = document.createElement("input");
    lengthInput.setAttribute("type", "text");
    lengthInput.setAttribute("name", "length");
    lengthInput.setAttribute("id", "length");
    lengthInput.setAttribute("value", "");
    td.appendChild(lengthInput);

    var widthLabel = document.createElement("label");
    widthLabel.setAttribute("for", "widthLabel");
    widthLabel.innerHTML = " Width ";
    td.appendChild(widthLabel);

    var widthInput = document.createElement("input");
    widthInput.setAttribute("type", "text");
    widthInput.setAttribute("name", "width");
    widthInput.setAttribute("id", "width");
    widthInput.setAttribute("value", "");
    td.appendChild(widthInput);

    var heightLabel = document.createElement("label");
    heightLabel.setAttribute("for", "heightLabel");
    heightLabel.innerHTML = " Height ";
    td.appendChild(heightLabel);

    var heightInput = document.createElement("input");
    heightInput.setAttribute("type", "text");
    heightInput.setAttribute("name", "height");
    heightInput.setAttribute("id", "height");
    heightInput.setAttribute("value", "");
    td.appendChild(heightInput);

    var dimensionsLabel = document.createElement("label");
    dimensionsLabel.setAttribute("id", "dimensions");
    dimensionsLabel.innerHTML = dimensionlbl;
    td.appendChild(dimensionsLabel);

    var tr2 = document.createElement("tr");
    tbody.appendChild(tr2);

    var td2 = document.createElement("td");
    td.setAttribute("class", "textbox");
    tr2.appendChild(td2);

    var weightLabel = document.createElement("label");
    weightLabel.setAttribute("for", "weightLabel");
    weightLabel.innerHTML = "Weight ";
    td2.appendChild(weightLabel);

    var weightInput = document.createElement("input");
    weightInput.setAttribute("type", "text");
    weightInput.setAttribute("name", "weight");
    weightInput.setAttribute("id", "weight");
    weightInput.setAttribute("value", "");
    td2.appendChild(weightInput);

    var pckgWeightLabel = document.createElement("label");
    pckgWeightLabel.setAttribute("id", "pckgWeight");
    pckgWeightLabel.innerHTML = weightlbl;
    td2.appendChild(pckgWeightLabel);

    document.getElementById("metrics").disabled = true;
    document.getElementById("english").disabled = true;
    document.getElementById("start-over").disabled = false;
}

function startOver() {
    var div = document.getElementById("dimensionsForm");
    var olddiv = document.getElementById("dimensionsFieldset");
    div.removeChild(olddiv);

    document.getElementById("metrics").disabled = false;
    document.getElementById("english").disabled = false;
    document.getElementById("start-over").disabled = true;
}

function goBack() {
    history.go(-1);
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using CalbucciLib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Net.Mail;

namespace CalbucciLib.Tests
{
    [TestClass()]
	public class LoggerTests
    {
        [TestMethod()]
        public void LogErrorTest()
        {
            bool calledAppend = false;
            var logEvent = Logger.LogError(le =>
            {
                calledAppend = true;
            }, "This is an error {0}", "abc");

            Assert.IsTrue(calledAppend, "Didn't call appendData");
            Assert.AreEqual(logEvent.Type, "Error");
            Assert.AreEqual(logEvent.Message, "This is an error abc");
            Assert.IsNotNull(logEvent.StackSignature);
        }

        [TestMethod()]
        public void LogExceptionTest()
        {
            var exception = new ArgumentNullException("argument");
            bool calledAppend = false;
            var logEvent = Logger.LogException(le =>
            {
                calledAppend = true;
            }, exception, "abc");

            Assert.IsTrue(calledAppend, "Didn't call appendData");
            Assert.AreEqual(logEvent.Type, "Exception");
            Assert.IsNotNull(logEvent.StackSignature);
            Assert.AreEqual(logEvent.Get("Exception", "Type"), "System.ArgumentNullException");

        }

        [TestMethod()]
        public void LogExceptionTest_NoLambda()
        {
            var exception = new ArgumentNullException("argument");
            var logEvent = Logger.LogException(exception, null);

            Assert.AreEqual(logEvent.Type, "Exception");
            Assert.IsNotNull(logEvent.StackSignature);
            Assert.AreEqual(logEvent.Get("Exception", "Type"), "System.ArgumentNullException");

        }

		[TestMethod()]
		public void LogWarningTest()
		{
			HttpContext.Current = new HttpContext(new HttpRequest("", "http://tempuri.org", ""),
					new HttpResponse(new StringWriter()));

			string userName = "John Doe";
			var context = new HttpContext(new HttpRequest(null, "http://blog.calbucci.com", null), new HttpResponse(null));
			context.User = Mock.Of<ClaimsPrincipal>(cp =>
				cp.Identity.IsAuthenticated == true &&
				cp.Identity.Name == userName
				);

			HttpContext.Current = context;

			var logEvent = Logger.LogWarning("Warning 1", "abc");

			Assert.AreEqual(logEvent.Get("HttpUser", "Name"), userName);
		}

		[TestMethod()]
		public void AddExtensionTest()
		{
			// TODO
		}

		[TestMethod()]
	    public void ShouldLogCallbackTest()
	    {
		    // TODO
	    }

	    [TestMethod]
	    public void SendEmailTest()
	    {
            Logger.Default.SendToEmailAddressFatal = "username@gmail.com";
            SmtpClient outlookserver = new SmtpClient("smtp.live.com")
            {
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential("username", "password"),
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Port = 587,
                EnableSsl = true,
            };

            Logger.Default.SmtpClient = outlookserver;

            var LogEvent = Logger.LogFatal("Fatal error test with email", "abc");

            Assert.AreEqual(Logger.Default.ConfirmEmailSent, true);

        }
    }
}


text:
import { gl, createProgram, interleave, sendAttibutes } from './lib/gl.js'
import { random, flatten } from './lib/util.js'

import icosphere from 'icosphere'

import vertex from './vert.glsl'
import fragment from './frag.glsl'

gl.enable(gl.DEPTH_TEST)

const program = createProgram(vertex, fragment)

const mesh = icosphere(2)

const n = mesh.positions.length

const data = new Float32Array(n * 8)

interleave(data, 8, (chunk, i) => {

  chunk[0] = mesh.positions[i][0] * 0.6
  chunk[1] = mesh.positions[i][1] * 0.6
  chunk[2] = mesh.positions[i][2] * 0.6

  // movement offset/phase
  chunk[3] = random(0, Math.PI*2)
  chunk[4] = random(0, Math.PI*2)

  // color
  chunk[5] = random(0.5, 1)
  chunk[6] = random(0.5, 1)
  chunk[7] = random(0.5, 1)

})

const indices = flatten(mesh.cells)

sendAttibutes(
  program, data,
  [
    ['aPosition', 3],
    ['aPhase', 2],
    ['aColor', 3]
  ],
  indices
)

const uTime = gl.getUniformLocation(program, 'uTime')

function render(t) {
  requestAnimationFrame(render)
  gl.uniform1f(uTime, t / 10000)
  gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0)
}

requestAnimationFrame(render)


text:
/* $OpenBSD: xcbc_enc.c,v 1.9 2015/02/07 13:19:15 doug Exp $ */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 *
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 *
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 *
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include "des_locl.h"

/* RSA's DESX */

void DES_xcbc_encrypt(const unsigned char *in, unsigned char *out,
		      long length, DES_key_schedule *schedule,
		      DES_cblock *ivec, const_DES_cblock *inw,
		      const_DES_cblock *outw, int enc)
	{
	DES_LONG tin0,tin1;
	DES_LONG tout0,tout1,xor0,xor1;
	DES_LONG inW0,inW1,outW0,outW1;
	const unsigned char *in2;
	long l=length;
	DES_LONG tin[2];
	unsigned char *iv;

	in2 = &(*inw)[0];
	c2l(in2,inW0);
	c2l(in2,inW1);
	in2 = &(*outw)[0];
	c2l(in2,outW0);
	c2l(in2,outW1);

	iv = &(*ivec)[0];

	if (enc)
		{
		c2l(iv,tout0);
		c2l(iv,tout1);
		for (l-=8; l>=0; l-=8)
			{
			c2l(in,tin0);
			c2l(in,tin1);
			tin0^=tout0^inW0; tin[0]=tin0;
			tin1^=tout1^inW1; tin[1]=tin1;
			DES_encrypt1(tin,schedule,DES_ENCRYPT);
			tout0=tin[0]^outW0; l2c(tout0,out);
			tout1=tin[1]^outW1; l2c(tout1,out);
			}
		if (l != -8)
			{
			c2ln(in,tin0,tin1,l+8);
			tin0^=tout0^inW0; tin[0]=tin0;
			tin1^=tout1^inW1; tin[1]=tin1;
			DES_encrypt1(tin,schedule,DES_ENCRYPT);
			tout0=tin[0]^outW0; l2c(tout0,out);
			tout1=tin[1]^outW1; l2c(tout1,out);
			}
		iv = &(*ivec)[0];
		l2c(tout0,iv);
		l2c(tout1,iv);
		}
	else
		{
		c2l(iv,xor0);
		c2l(iv,xor1);
		for (l-=8; l>0; l-=8)
			{
			c2l(in,tin0); tin[0]=tin0^outW0;
			c2l(in,tin1); tin[1]=tin1^outW1;
			DES_encrypt1(tin,schedule,DES_DECRYPT);
			tout0=tin[0]^xor0^inW0;
			tout1=tin[1]^xor1^inW1;
			l2c(tout0,out);
			l2c(tout1,out);
			xor0=tin0;
			xor1=tin1;
			}
		if (l != -8)
			{
			c2l(in,tin0); tin[0]=tin0^outW0;
			c2l(in,tin1); tin[1]=tin1^outW1;
			DES_encrypt1(tin,schedule,DES_DECRYPT);
			tout0=tin[0]^xor0^inW0;
			tout1=tin[1]^xor1^inW1;
			l2cn(tout0,tout1,out,l+8);
			xor0=tin0;
			xor1=tin1;
			}

		iv = &(*ivec)[0];
		l2c(xor0,iv);
		l2c(xor1,iv);
		}
	tin0=tin1=tout0=tout1=xor0=xor1=0;
	inW0=inW1=outW0=outW1=0;
	tin[0]=tin[1]=0;
	}


text:
"""Constants for the Huisbaasje integration."""
from huisbaasje.const import (
    SOURCE_TYPE_ELECTRICITY,
    SOURCE_TYPE_ELECTRICITY_IN,
    SOURCE_TYPE_ELECTRICITY_IN_LOW,
    SOURCE_TYPE_ELECTRICITY_OUT,
    SOURCE_TYPE_ELECTRICITY_OUT_LOW,
    SOURCE_TYPE_GAS,
)

from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass
from homeassistant.const import ENERGY_KILO_WATT_HOUR, TIME_HOURS, VOLUME_CUBIC_METERS

DATA_COORDINATOR = "coordinator"

DOMAIN = "huisbaasje"

FLOW_CUBIC_METERS_PER_HOUR = f"{VOLUME_CUBIC_METERS}/{TIME_HOURS}"

"""Interval in seconds between polls to huisbaasje."""
POLLING_INTERVAL = 20

"""Timeout for fetching sensor data"""
FETCH_TIMEOUT = 10

SENSOR_TYPE_RATE = "rate"
SENSOR_TYPE_THIS_DAY = "thisDay"
SENSOR_TYPE_THIS_WEEK = "thisWeek"
SENSOR_TYPE_THIS_MONTH = "thisMonth"
SENSOR_TYPE_THIS_YEAR = "thisYear"

SOURCE_TYPES = [
    SOURCE_TYPE_ELECTRICITY,
    SOURCE_TYPE_ELECTRICITY_IN,
    SOURCE_TYPE_ELECTRICITY_IN_LOW,
    SOURCE_TYPE_ELECTRICITY_OUT,
    SOURCE_TYPE_ELECTRICITY_OUT_LOW,
    SOURCE_TYPE_GAS,
]

SENSORS_INFO = [
    {
        "name": "Huisbaasje Current Power",
        "device_class": SensorDeviceClass.POWER,
        "source_type": SOURCE_TYPE_ELECTRICITY,
    },
    {
        "name": "Huisbaasje Current Power In Peak",
        "device_class": SensorDeviceClass.POWER,
        "source_type": SOURCE_TYPE_ELECTRICITY_IN,
    },
    {
        "name": "Huisbaasje Current Power In Off Peak",
        "device_class": SensorDeviceClass.POWER,
        "source_type": SOURCE_TYPE_ELECTRICITY_IN_LOW,
    },
    {
        "name": "Huisbaasje Current Power Out Peak",
        "device_class": SensorDeviceClass.POWER,
        "source_type": SOURCE_TYPE_ELECTRICITY_OUT,
    },
    {
        "name": "Huisbaasje Current Power Out Off Peak",
        "device_class": SensorDeviceClass.POWER,
        "source_type": SOURCE_TYPE_ELECTRICITY_OUT_LOW,
    },
    {
        "name": "Huisbaasje Energy Consumption Peak Today",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY_IN,
        "sensor_type": SENSOR_TYPE_THIS_DAY,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "precision": 3,
    },
    {
        "name": "Huisbaasje Energy Consumption Off Peak Today",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY_IN_LOW,
        "sensor_type": SENSOR_TYPE_THIS_DAY,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "precision": 3,
    },
    {
        "name": "Huisbaasje Energy Production Peak Today",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY_OUT,
        "sensor_type": SENSOR_TYPE_THIS_DAY,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "precision": 3,
    },
    {
        "name": "Huisbaasje Energy Production Off Peak Today",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY_OUT_LOW,
        "sensor_type": SENSOR_TYPE_THIS_DAY,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "precision": 3,
    },
    {
        "name": "Huisbaasje Energy Today",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY,
        "sensor_type": SENSOR_TYPE_THIS_DAY,
        "precision": 1,
    },
    {
        "name": "Huisbaasje Energy This Week",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY,
        "sensor_type": SENSOR_TYPE_THIS_WEEK,
        "precision": 1,
    },
    {
        "name": "Huisbaasje Energy This Month",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY,
        "sensor_type": SENSOR_TYPE_THIS_MONTH,
        "precision": 1,
    },
    {
        "name": "Huisbaasje Energy This Year",
        "device_class": SensorDeviceClass.ENERGY,
        "unit_of_measurement": ENERGY_KILO_WATT_HOUR,
        "source_type": SOURCE_TYPE_ELECTRICITY,
        "sensor_type": SENSOR_TYPE_THIS_YEAR,
        "precision": 1,
    },
    {
        "name": "Huisbaasje Current Gas",
        "unit_of_measurement": FLOW_CUBIC_METERS_PER_HOUR,
        "source_type": SOURCE_TYPE_GAS,
        "icon": "mdi:fire",
        "precision": 1,
    },
    {
        "name": "Huisbaasje Gas Today",
        "device_class": SensorDeviceClass.GAS,
        "unit_of_measurement": VOLUME_CUBIC_METERS,
        "source_type": SOURCE_TYPE_GAS,
        "sensor_type": SENSOR_TYPE_THIS_DAY,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "icon": "mdi:counter",
        "precision": 1,
    },
    {
        "name": "Huisbaasje Gas This Week",
        "device_class": SensorDeviceClass.GAS,
        "unit_of_measurement": VOLUME_CUBIC_METERS,
        "source_type": SOURCE_TYPE_GAS,
        "sensor_type": SENSOR_TYPE_THIS_WEEK,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "icon": "mdi:counter",
        "precision": 1,
    },
    {
        "name": "Huisbaasje Gas This Month",
        "device_class": SensorDeviceClass.GAS,
        "unit_of_measurement": VOLUME_CUBIC_METERS,
        "source_type": SOURCE_TYPE_GAS,
        "sensor_type": SENSOR_TYPE_THIS_MONTH,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "icon": "mdi:counter",
        "precision": 1,
    },
    {
        "name": "Huisbaasje Gas This Year",
        "device_class": SensorDeviceClass.GAS,
        "unit_of_measurement": VOLUME_CUBIC_METERS,
        "source_type": SOURCE_TYPE_GAS,
        "sensor_type": SENSOR_TYPE_THIS_YEAR,
        "state_class": SensorStateClass.TOTAL_INCREASING,
        "icon": "mdi:counter",
        "precision": 1,
    },
]


text:
{% extends "basic/layout.html" %}

{% block extrahead %}

<link rel="stylesheet" href="{{ pathto('_static/featured.css', 1) }}">

{% if theme_favicon %}
<link rel="shortcut icon" href="{{ pathto('_static/'+theme_favicon, 1) }}" />
{% endif %}
{% endblock %}

{# can use fenics_logo as alternative relbar figure #}
{% block relbar1 %}

{% endblock %}

{# do not display sidebars #}
{% block sidebar1 %}{% endblock %}
{% block sidebar2 %}{% endblock %}


text:
/*
	libGUI dinamic library
	(c) andrew_programmer 2009
 */

/*
 * vkos (21.10.2009):
 * Replaced "meneger" (& others so) with "manager"
 */

//service libGUI types of data,functions and constants
#include "types.h"
#include "libGUI.h"
#include "kolibri_system.h"
#include "draw_controls.h"
#include "fonts_manager.h"
#include "keys.h"

//controls
#include "control_button.h"
#include "control_image.h"
#include "control_progress_bar.h"
#include "control_scroll_bar.h"
#include "control_scrolled_window.h"
#include "control_text.h"

//some libC functions
#include "stdarg.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"

//code parts
#include "stdio.inc"
#include "string.inc"
#include "malloc.inc"
#include "stdlib.inc"
#include "kolibri_system.inc"
#include "draw_controls.inc"
#include "fonts_manager.inc"
#include "libGUI_management.inc"
#include "parent_window.inc"
#include "main_libGUI.inc"
#include "control_text.inc"
#include "control_image.inc"
#include "control_button.inc"
#include "control_progress_bar.inc"
#include "control_scroll_bar.inc"
#include "control_scrolled_window.inc"

typedef struct
{
	char *name;
	void *function;
}export_t;

//char szSTART[]                                           = "START";
char szLibGUIversion[]                                   = "LibGUIversion";
char szInitLibGUI[]                                      = "InitLibGUI";
char szLibGUImain[]                                      = "LibGUImain";
char szQuitLibGUI[]                                      = "QuitLibGUI";

char szCreateWindow[]                                    = "CreateWindow";
char szSetWindowSizeRequest[]                            = "SetWindowSizeRequest";

char szPackControls[]                                    = "PackControls";
char szDestroyControl[]                                  = "DestroyControl";
char szSetControlSizeRequest[]                           = "SetControlSizeRequest";
char szGetControlSizeX[]                                 = "GetControlSizeX";
char szGetControlSizeY[]                                 = "GetControlSizeY";
char szSetControlNewPosition[]                           = "SetControlNewPosition";
char szGetControlPositionX[]                             = "GetControlPositionX";
char szGetControlPositionY[]                             = "GetControlPositionY";
char szSetFocuse[]                                       = "SetFocuse";
char szRedrawControl[]                                   = "RedrawControl";
char szSpecialRedrawControl[]                            = "SpecialRedrawControl";

char szSetCallbackFunction[]                             = "SetCallbackFunction";
char szBlockCallbackFunction[]                           = "BlockCallbackFunction";
char szUnblockCallbackFunction[]                         = "UnblockCallbackFunction";

char szSetIDL_Function[]                                 = "SetIDL_Function";
char szDestroyIDL_Function[]                             = "DestroyIDL_Function";

char szSetTimerCallbackForFunction[]                     = "SetTimerCallbackForFunction";
char szDestroyTimerCallbackForFunction[]                 = "DestroyTimerCallbackForFunction";

char szSetCallbackFunctionForEvent[]                     = "SetCallbackFunctionForEvent";
char szDestroyCallbackFunctionForEvent[]                 = "DestroyCallbackFunctionForEvent";

char szCreateButton[]                                    = "CreateButton";
char szCreateButtonWithText[]                            = "CreateButtonWithText";

char szCreateProgressBar[]                               = "CreateProgressBar";
char szSetProgressBarPulse[]                             = "SetProgressBarPulse";
char szProgressBarSetText[]                              = "ProgressBarSetText";
char szProgressBarGetText[]                              = "ProgressBarGetText";

char szCreateHorizontalScrollBar[]                       = "CreateHorizontalScrollBar";
char szCreateVerticalScrollBar[]                         = "CreateVerticalScrollBar";

char szCreateScrolledWindow[]                            = "CreateScrolledWindow";
char szScrolledWindowPackControls[]                      = "ScrolledWindowPackControls";

char szCreateImage[]                                     = "CreateImage";

char szCreateText[]                                      = "CreateText";
char szTextBackgroundOn[]                                = "TextBackgroundOn";
char szTextBackgroundOff[]                               = "TextBackgroundOff";

char szLoadFont[]                                        = "LoadFont";
char szFreeFont[]                                        = "FreeFont";

export_t	EXPORTS[]__asm__("EXPORTS") =
	{
		{szLibGUIversion,                         LibGUIversion                        },
		{szInitLibGUI,                            InitLibGUI                           },
		{szLibGUImain,                            LibGUImain                           },
		{szQuitLibGUI,                            QuitLibGUI                           },

		{szCreateWindow,                          CreateWindow                         },
		{szSetWindowSizeRequest,                  SetWindowSizeRequest                 },

		{szPackControls,                          PackControls                         },
		{szDestroyControl,                        DestroyControl                       },
		{szSetControlSizeRequest,                 SetControlSizeRequest                },
		{szGetControlSizeX,                       GetControlSizeX                      },
		{szGetControlSizeY,                       GetControlSizeY                      },
		{szSetControlNewPosition,                 SetControlNewPosition                },
		{szGetControlPositionX,                   GetControlPositionX                  },
		{szGetControlPositionY,                   GetControlPositionY                  },
		{szSetFocuse,                             SetFocuse                            },
		{szRedrawControl,                         RedrawControl                        },
		{szSpecialRedrawControl,                  SpecialRedrawControl                 },

		{szSetCallbackFunction,                   SetCallbackFunction                  },
		{szBlockCallbackFunction,                 BlockCallbackFunction                },
		{szUnblockCallbackFunction,               UnblockCallbackFunction              },

		{szSetIDL_Function,                       SetIDL_Function                      },
		{szDestroyIDL_Function,                   DestroyIDL_Function                  },

		{szSetTimerCallbackForFunction,           SetTimerCallbackForFunction          },
		{szDestroyTimerCallbackForFunction,       DestroyTimerCallbackForFunction      },

		{szSetCallbackFunctionForEvent,           SetCallbackFunctionForEvent          },
		{szDestroyCallbackFunctionForEvent,       DestroyCallbackFunctionForEvent      },

		{szCreateButton,                          CreateButton                         },
		{szCreateButtonWithText,                  CreateButtonWithText                 },

		{szCreateProgressBar,                     CreateProgressBar                    },
		{szSetProgressBarPulse,                   SetProgressBarPulse                  },
		{szProgressBarSetText,                    ProgressBarSetText                   },
		{szProgressBarGetText,                    ProgressBarGetText                   },

		{szCreateHorizontalScrollBar,             CreateHorizontalScrollBar            },
		{szCreateVerticalScrollBar,               CreateVerticalScrollBar              },

		{szCreateScrolledWindow,                  CreateScrolledWindow                 },
		{szScrolledWindowPackControls,            ScrolledWindowPackControls           },

		{szCreateImage,                           CreateImage                          },

		{szCreateText,                            CreateText                           },
		{szTextBackgroundOn,                      TextBackgroundOn                     },
		{szTextBackgroundOff,                     TextBackgroundOff                    },

		{szLoadFont,                              LoadFont                             },
		{szFreeFont,                              FreeFont                             },

		{NULL,NULL},
	};


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

/*  Monkey HTTP Server
 *  ==================
 *  Copyright 2001-2015 Monkey Software LLC <eduardo@monkey.io>
 *
 *  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.
 */

#include <monkey/mk_api.h>

#include "fastcgi.h"
#include "fcgi_handler.h"

#define FCGI_BUF(h)           (char *) h->buf_data + h->buf_len
#define FCGI_PARAM_DYN(str)   str, strlen(str), MK_FALSE
#define FCGI_PARAM_CONST(str) str, sizeof(str) -1, MK_FALSE
#define FCGI_PARAM_PTR(ptr)   ptr.data, ptr.len, MK_FALSE
#define FCGI_PARAM_DUP(str)   strdup(str), strlen(str), MK_TRUE

static inline void fcgi_build_header(struct fcgi_record_header *rec,
                                     uint8_t type, uint16_t request_id,
                                     uint16_t content_length)
{
    rec->version         = FCGI_VERSION_1;
    rec->type            = type;
    fcgi_encode16(&rec->request_id, request_id);
    fcgi_encode16(&rec->content_length, content_length);
    rec->padding_length  = 0;
    rec->reserved        = 0;
}

static inline void fcgi_build_request_body(struct fcgi_begin_request_body *body)
{
    fcgi_encode16(&body->role, FCGI_RESPONDER);
    body->flags       = 0;
    memset(body->reserved, '\0', sizeof(body->reserved));
}

static inline size_t fcgi_write_length(char *p, size_t len)
{
    if (len < 127) {
		*p++ = len;
		return 1;
    }
    else{
		*p++  = (len >> 24) | 0x80;
		*p++  = (len >> 16) & 0xff;
		*p++  = (len >>  8) & 0xff;
		*p++  = (len)       & 0xff;
		return 4;
	}
}

static inline int fcgi_add_param_empty(struct fcgi_handler *handler)
{
    char *p;

    p = FCGI_BUF(handler);
    fcgi_build_header((struct fcgi_record_header *) p, FCGI_PARAMS, 1, 0);
    mk_api->iov_add(handler->iov, p,
                    sizeof(struct fcgi_record_header), MK_FALSE);
    handler->buf_len += sizeof(struct fcgi_record_header);
    return 0;
}

static inline int fcgi_add_param(struct fcgi_handler *handler,
                                 char *key, int key_len, int key_free,
                                 char *val, int val_len, int val_free)
{
    int len;
    int diff;
    char *p;
    char *buf;

    buf = p = (char * ) handler->buf_data + handler->buf_len;

	len  = key_len + val_len;
	len += key_len > 127 ? 4 : 1;
	len += val_len > 127 ? 4 : 1;

    fcgi_build_header((struct fcgi_record_header *) p, FCGI_PARAMS, 1, len);
    p += sizeof(struct fcgi_record_header);

    p += fcgi_write_length(p, key_len);
    p += fcgi_write_length(p, val_len);

    diff = (p - buf);
    handler->buf_len += diff;
    mk_api->iov_add(handler->iov, buf, diff, MK_FALSE);
    mk_api->iov_add(handler->iov, key, key_len, key_free);
    mk_api->iov_add(handler->iov, val, val_len, val_free);

    return 0;
}

static inline int fcgi_add_param_http_header(struct fcgi_handler *handler,
                                             struct mk_http_header *header)
{
    unsigned int i;
    int avail;
    int req;
    int diff;
    char *p;
    char *buf;

    avail = (sizeof(handler->buf_data) - handler->buf_len);
    req   = sizeof(struct fcgi_record_header) + 8;
    req  += header->key.len + 5;

    if (avail < req) {
        return -1;
    }

    buf = p = (handler->buf_data + handler->buf_len);
    *p++ = 'H';
    *p++ = 'T';
    *p++ = 'T';
    *p++ = 'P';
    *p++ = '_';

    for (i = 0; i < header->key.len; i++) {
        if (header->key.data[i] == '-') {
            *p++ = '_';
        }
        else {
            *p++ = toupper(header->key.data[i]);
        }
    }

    diff = (p - buf);
    handler->buf_len += diff;
    fcgi_add_param(handler,
                   buf, diff, MK_FALSE,
                   header->val.data, header->val.len, MK_FALSE);

    return 0;
}

static inline int fcgi_add_param_net(struct fcgi_handler *handler)
{
    int ret;
    const char *p;
    char buffer[256];
	struct sockaddr_in addr;
	socklen_t addr_len = sizeof(struct sockaddr_in);

    ret = getsockname(handler->cs->socket, (struct sockaddr *)&addr, &addr_len);
    if (ret == -1) {
#ifdef TRACE
        perror("getsockname");
#endif
        if (errno == EBADF) {
            MK_TRACE("[fastcgi=%i] network connection broken",
                     handler->cs->socket);
        }
        return -1;
    }

    p = inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(buffer));
    if (!p) {
        perror("inet_ntop");
        return -1;
    }

    /* Server Address */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("SERVER_ADDR"),
                   FCGI_PARAM_DUP(buffer));

    /* Server Port */
    snprintf(buffer, 256, "%d", ntohs(addr.sin_port));
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("SERVER_PORT"),
                   FCGI_PARAM_DUP(buffer));

    ret = getpeername(handler->cs->socket, (struct sockaddr *)&addr, &addr_len);
    if (ret == -1) {
        perror("getpeername");
        return -1;
    }

    p = inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(buffer));
    if (!p) {
        perror("inet_ntop");
        return -1;
    }

    /* Remote Addr */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("REMOTE_ADDR"),
                   FCGI_PARAM_DUP(buffer));

    /* Remote Port */
    snprintf(buffer, 256, "%d", ntohs(addr.sin_port));
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("REMOTE_PORT"),
                   FCGI_PARAM_DUP(buffer));

    return 0;
}

static inline int fcgi_add_stdin(struct fcgi_handler *handler)
{
    char *p;

    p = FCGI_BUF(handler);
    fcgi_build_header((struct fcgi_record_header *) p, FCGI_STDIN, 1,
                      handler->sr->data.len);
    mk_api->iov_add(handler->iov, p, FCGI_RECORD_HEADER_SIZE, MK_FALSE);
    handler->buf_len += FCGI_RECORD_HEADER_SIZE;

    if (handler->sr->data.len > 0) {
        mk_api->iov_add(handler->iov,
                        handler->sr->data.data,
                        handler->sr->data.len,
                        MK_FALSE);
    }

    return 0;
}

static int fcgi_encode_request(struct fcgi_handler *handler)
{
    int ret;
    struct fcgi_begin_request_record *request;

    request = &handler->header_request;
    fcgi_build_header(&request->header, FCGI_BEGIN_REQUEST, 1,
                      FCGI_BEGIN_REQUEST_BODY_SIZE);

    fcgi_build_request_body(&request->body);

    /* BEGIN_REQUEST */
    mk_api->iov_add(handler->iov,
                    &handler->header_request,
                    sizeof(handler->header_request),
                    MK_FALSE);

    /* Server Software */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("SERVER_SOFTWARE"),
                   FCGI_PARAM_DYN(mk_api->config->server_signature));

    /* Server Name */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("SERVER_NAME"),
                   handler->sr->host_alias->name,
                   handler->sr->host_alias->len,
                   MK_FALSE);

    /* Document Root */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("DOCUMENT_ROOT"),
                   FCGI_PARAM_PTR(handler->sr->host_conf->documentroot));

    /* Network params: SERVER_ADDR, SERVER_PORT, REMOTE_ADDR & REMOTE_PORT */
    ret = fcgi_add_param_net(handler);
    if (ret == -1) {
        return -1;
    }

    /* Script Filename */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("SCRIPT_FILENAME"),
                   FCGI_PARAM_PTR(handler->sr->real_path));

    /* Script Filename */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("SCRIPT_NAME"),
                   FCGI_PARAM_PTR(handler->sr->uri_processed));

    /* Request Method */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("REQUEST_METHOD"),
                   FCGI_PARAM_PTR(handler->sr->method_p));

    /* Request URI */
    fcgi_add_param(handler,
                   FCGI_PARAM_CONST("REQUEST_URI"),
                   FCGI_PARAM_PTR(handler->sr->uri));

    /* Query String */
    if (handler->sr->query_string.len > 0) {
        fcgi_add_param(handler,
                       FCGI_PARAM_CONST("QUERY_STRING"),
                       FCGI_PARAM_PTR(handler->sr->query_string));
    }

    /* HTTPS */
    if (MK_SCHED_CONN_CAP(handler->cs->conn) & MK_CAP_SOCK_SSL) {
        fcgi_add_param(handler,
                       FCGI_PARAM_CONST("HTTPS"),
                       FCGI_PARAM_CONST("on"));
    }

    /* Append HTTP request headers */
    struct mk_list *head;
    struct mk_http_header *http_header;
    mk_list_foreach(head, &handler->cs->parser.header_list) {
        http_header = mk_list_entry(head, struct mk_http_header, _head);
        fcgi_add_param_http_header(handler, http_header);
    }

    /* Append the empty params record */
    fcgi_add_param_empty(handler);

    /* Data for FCGI_STDIN */
    fcgi_add_stdin(handler);

    return 0;
}

size_t fcgi_read_header(void *p, struct fcgi_record_header *h)
{
    memcpy(h, p, sizeof(struct fcgi_record_header));
    h->request_id     = htons(h->request_id);
    h->content_length = htons(h->content_length);

	return sizeof(*h);
}

static inline int fcgi_buffer_consume(struct fcgi_handler *handler, size_t bytes)
{
    if (bytes >= handler->buf_len) {
        handler->buf_len = 0;
        return 0;
    }

    memmove(handler->buf_data, handler->buf_data + bytes,
            handler->buf_len - bytes);
    handler->buf_len -= bytes;
    return 0;
}

static char *getearliestbreak(const char buf[], const unsigned bufsize,
                              unsigned char * const advance)
{
    char *crend;
    char *lfend;

    crend = memmem(buf, bufsize, "\r\n\r\n", 4);
    lfend = memmem(buf, bufsize, "\n\n", 2);

    if (!crend && !lfend)
        return NULL;

    /* If only one found, return that one */
    if (!crend) {
        *advance = 2;
        return lfend;
    }
    if (!lfend)
        return crend;

    /* Both found, return the earlier one - the latter one is part of content */
    if (lfend < crend) {
        *advance = 2;
        return lfend;
    }
    return crend;
}

static int fcgi_write(struct fcgi_handler *handler, char *buf, size_t len)
{
    mk_stream_set(NULL,
                  MK_STREAM_COPYBUF,
                  handler->cs->channel,
                  buf, len,
                  NULL, NULL, NULL, NULL);

    if (handler->headers_set == MK_TRUE) {
        mk_stream_set(NULL,
                      MK_STREAM_COPYBUF,
                      handler->cs->channel,
                      "\r\n", 2,
                      NULL, NULL, NULL, NULL);
    }
    return 0;
}

int fcgi_exit(struct fcgi_handler *handler)
{
    if (handler->iov) {
        if (handler->server_fd > 0) {
            mk_api->ev_del(mk_api->sched_loop(), &handler->event);
            close(handler->server_fd);
            handler->server_fd = -1;
        }

        mk_api->iov_free(handler->iov);
        mk_api->sched_event_free((struct mk_event *) handler);
        handler->iov = NULL;
    }

    if (handler->active == MK_TRUE) {
        mk_api->http_request_end(handler->cs, handler->hangup);
    }

    return 0;
}

int fcgi_error(struct fcgi_handler *handler)
{
    fcgi_exit(handler);
    mk_api->http_request_error(500, handler->cs, handler->sr);
    return 0;
}

static int fcgi_response(struct fcgi_handler *handler, char *buf, size_t len)
{
    int status;
    int diff;
    int xlen;
    char tmp[16];
    char *p;
    char *end;
    size_t p_len;
    unsigned char advance;

    MK_TRACE("[fastcgi=%i] process response len=%lu",
             handler->server_fd, len);

    p = buf;
    p_len = len;

    if (len == 0 && handler->chunked && handler->headers_set == MK_TRUE) {
        MK_TRACE("[fastcgi=%i] sending EOF", handler->server_fd);
        mk_stream_set(NULL,
                      MK_STREAM_COPYBUF,
                      handler->cs->channel,
                      "0\r\n\r\n", 5,
                      handler,
                      NULL /*cb_fcgi_eof*/, NULL, NULL);
        mk_api->channel_flush(handler->cs->channel);
        return 0;
    }

    if (handler->headers_set == MK_FALSE) {
        advance = 4;
        end = getearliestbreak(buf, len, &advance);
        if (!end) {
            /* we need more data */
            return -1;
        }

        handler->sr->headers.cgi = MK_TRUE;
        if (strncasecmp(buf, "Status: ", 8) == 0) {
            sscanf(buf + 8, "%d", &status);
            mk_api->header_set_http_status(handler->sr, status);
        }
        else {
            mk_api->header_set_http_status(handler->sr, 200);
        }

        /* Set transfer encoding */
        if (handler->sr->protocol >= MK_HTTP_PROTOCOL_11 &&
            (handler->sr->headers.status < MK_REDIR_MULTIPLE ||
             handler->sr->headers.status > MK_REDIR_USE_PROXY)) {
            handler->sr->headers.transfer_encoding = MK_HEADER_TE_TYPE_CHUNKED;
            handler->chunked = MK_TRUE;
        }

        mk_api->header_prepare(handler->cs, handler->sr);

        diff = (end - buf) + advance;
        fcgi_write(handler, buf, diff);

        p = buf + diff;
        p_len -= diff;
        handler->write_rounds++;
        handler->headers_set = MK_TRUE;
    }

    if (p_len > 0) {
        xlen = snprintf(tmp, 16, "%x\r\n", (unsigned int) p_len);
        mk_stream_set(NULL,
                      MK_STREAM_COPYBUF,
                      handler->cs->channel,
                      tmp, xlen,
                      NULL, NULL, NULL, NULL);
        fcgi_write(handler, p, p_len);
    }

    return 0;
}

int cb_fastcgi_on_read(void *data)
{
    int n;
    int ret = 0;
    int avail;
    char *body;
    size_t offset;
    struct fcgi_handler *handler = data;
    struct fcgi_record_header header;

    if (handler->active == MK_FALSE) {
        fcgi_exit(handler);
        return -1;
    }

    avail = FCGI_BUF_SIZE - handler->buf_len;
    n = read(handler->server_fd, handler->buf_data + handler->buf_len, avail);
    MK_TRACE("[fastcgi=%i] read=%i", handler->server_fd, n);
    if (n <= 0) {
        fcgi_exit(handler);
        return -1;
    }
    else {
        handler->buf_len += n;
    }

    if ((unsigned) handler->buf_len < FCGI_RECORD_HEADER_SIZE) {
        /* wait for more data */
        return n;
    }

    while (1) {
        /* decode the header */
        fcgi_read_header(&handler->buf_data, &header);

        if (header.type != FCGI_STDOUT && header.type != FCGI_STDERR &&
            header.type != FCGI_END_REQUEST) {
            fcgi_exit(handler);
            return -1;
        }

        /* Check if the package is complete */
        if (handler->buf_len < (FCGI_RECORD_HEADER_SIZE + header.content_length)) {
            /* we need more data */
            return n;
        }

        body = handler->buf_data + FCGI_RECORD_HEADER_SIZE;
        switch (header.type) {
        case FCGI_STDOUT:
            MK_TRACE("[fastcgi=%i] FCGI_STDOUT content_length=%i",
                     handler->server_fd, header.content_length);
            ret = fcgi_response(handler, body, header.content_length);
            break;
        case FCGI_STDERR:
            MK_TRACE("[fastcgi=%i] FCGI_STDERR content_length=%i",
                     handler->server_fd, header.content_length);
            break;
        case FCGI_END_REQUEST:
            MK_TRACE("[fastcgi=%i] FCGI_END_REQUEST content_length=%i",
                     handler->server_fd, header.content_length);
            ret = fcgi_response(handler, NULL, 0);
        default:
            //fcgi_exit(handler);
            return -1;
        }

        if (ret == -1) {
            /* Missing header breaklines ? */
            return n;
        }

        mk_api->channel_flush(handler->cs->channel);

        /* adjust buffer content */
        offset = FCGI_RECORD_HEADER_SIZE +
            header.content_length + header.padding_length;

        fcgi_buffer_consume(handler, offset);
    }
    return n;
}

void cb_fastcgi_request_flush(void *data)
{
    int ret;
    size_t count = 0;
    struct fcgi_handler *handler = data;

    ret = mk_channel_write(&handler->fcgi_channel, &count);

    MK_TRACE("[fastcgi=%i] %lu bytes, ret=%i",
                 handler->server_fd, count, ret);

    if (ret == MK_CHANNEL_DONE || ret == MK_CHANNEL_EMPTY) {
        /* Request done, switch the event side to receive the FCGI response */
        handler->buf_len = 0;
        handler->event.handler = cb_fastcgi_on_read;
        ret = mk_api->ev_add(mk_sched_loop(),
                             handler->server_fd,
                             MK_EVENT_CUSTOM, MK_EVENT_READ, handler);
        if (ret == -1) {
            goto error;
        }
    }
    else if (ret == MK_CHANNEL_ERROR) {
        fcgi_exit(handler);
    }

 error:
    return;
}

/* Callback: on connect to the backend server */
int cb_fastcgi_on_connect(void *data)
{
    int ret;
    int s_err;
    size_t count;
    socklen_t s_len = sizeof(s_err);
    struct fcgi_handler *handler = data;
    struct mk_channel *channel;

    if (handler->active == MK_FALSE) {
        printf("disabled???\n");
        return -1;
    }

    /* We connect in async mode, we need to check if the connection was OK */
    ret = getsockopt(handler->server_fd, SOL_SOCKET, SO_ERROR, &s_err, &s_len);
    if (ret == -1) {
        goto error;
    }

    if (s_err) {
        /* FastCGI server unavailable */
        goto error;
    }

    /* Convert the original request to FCGI format */
    ret = fcgi_encode_request(handler);
    if (ret == -1) {
        goto error;
    }

    /* Prepare the channel */
    channel = &handler->fcgi_channel;
    channel->type = MK_CHANNEL_SOCKET;
    channel->fd   = handler->server_fd;

    /* FIXME: Need to specify the channel type, raw ? */
    channel->io   = handler->cs->conn->net;
    mk_list_init(&channel->streams);

    mk_api->stream_set(&handler->fcgi_stream,
                       MK_STREAM_IOV,
                       &handler->fcgi_channel,
                       handler->iov,
                       -1,
                       handler,
                       NULL, NULL, NULL);

    cb_fastcgi_request_flush(handler);
    return 0;

 error:
    fcgi_error(handler);
    mk_channel_write(handler->cs->channel, &count);
    return 0;
}

struct fcgi_handler *fcgi_handler_new(struct mk_http_session *cs,
                                      struct mk_http_request *sr)
{
    int ret;
    int entries;
    struct fcgi_handler *h;

    /* Allocate handler instance and set fields */
    h = mk_api->mem_alloc_z(sizeof(struct fcgi_handler));
    if (!h) {
        return NULL;
    }
    h->cs = cs;
    h->sr = sr;
    h->write_rounds = 0;
    h->active = MK_TRUE;
    h->server_fd = -1;

    /* Allocate enough space for our data */
    entries =  40 + (cs->parser.header_count * 3);
    h->iov = mk_api->iov_create(entries, 0);

    /* Associate the handler with the Session Request */
    sr->handler_data = h;

    if (sr->protocol >= MK_HTTP_PROTOCOL_11) {
        h->hangup = MK_FALSE;
    }
    else {
        h->hangup = MK_TRUE;
    }

    /* Params buffer set an offset to include the header */
    h->buf_len = FCGI_RECORD_HEADER_SIZE;

    /* Request and async connection to the server */
    if (fcgi_conf.server_addr) {
        h->server_fd = mk_api->socket_connect(fcgi_conf.server_addr,
                                              atoi(fcgi_conf.server_port),
                                              MK_TRUE);
    }
    else if (fcgi_conf.server_path) {
        h->server_fd = mk_api->socket_open(fcgi_conf.server_path, MK_TRUE);
    }

    if (h->server_fd == -1) {
        goto error;
    }

    /* Prepare the built-in event structure */
    MK_EVENT_INIT(&h->event, h->server_fd, h, cb_fastcgi_on_connect);

    /*
     * Let the event loop notify us when we can flush data to
     * the FastCGI server.
     */
    ret = mk_api->ev_add(mk_sched_loop(),
                         h->server_fd,
                         MK_EVENT_CUSTOM, MK_EVENT_WRITE, h);
    if (ret == -1) {
        close(h->server_fd);
        goto error;
    }

    return h;

 error:
    mk_api->iov_free(h->iov);
    mk_api->mem_free(h);
    mk_api->http_request_error(500, cs, sr);
    return NULL;
}


text:
package club.baidu.hust.edu.cn.csapp.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

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

import club.baidu.hust.edu.cn.csapp.R;
import club.baidu.hust.edu.cn.csapp.model.BaseActionBarActivity;
import club.baidu.hust.edu.cn.csapp.model.News;
import club.baidu.hust.edu.cn.csapp.util.DialogUtil;
import club.baidu.hust.edu.cn.csapp.util.GetJson;
import club.baidu.hust.edu.cn.csapp.util.LogUtil;
import club.baidu.hust.edu.cn.csapp.util.ParseJson;

/**
 * Created by jiadong on 2015/7/9.
 */
public class NewsActivity extends BaseActionBarActivity implements SwipeRefreshLayout.OnRefreshListener {
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private String[] title;
    private int[] newsId;
    private SimpleAdapter simpleAdapter;
    private GridView gridView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Boolean exception = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);

        //set toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        pref = PreferenceManager.getDefaultSharedPreferences(this);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.color_bule2,
                R.color.color_bule,
                R.color.color_bule2,
                R.color.color_bule3);
        swipeRefreshLayout.post(new Thread(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        }));
        onRefresh();

        //set gridView and clickListener
        gridView = (GridView) findViewById(R.id.grid_view);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                for (int i = 0; i < title.length; i++) {
                    if (position == i) {
                        editor = pref.edit();
                        editor.putInt("newsId", newsId[i]);
                        editor.commit();
                        NewsContentActivity.actionStart(NewsActivity.this, title[i], newsId[i]);
                    }
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                new Thread() {
                    public void run() {
                        new GetNews().execute("JSON");
                    }
                }.start();
            }
        }, 500);
    }

    /**
     * set adapter for gridView
     *
     * @param gridView
     */
    private void initGridView(GridView gridView) {
        List<Map<String, Object>> listItems = new ArrayList<>();
        for (int i = 0; i < title.length; i++) {
            Map<String, Object> listItem = new HashMap<>();
            listItem.put("title", title[i]);
            listItems.add(listItem);
        }
        simpleAdapter = new SimpleAdapter(this, listItems, R.layout.item_news,
                new String[]{"title"},
                new int[]{R.id.news_text_title});
        gridView.setAdapter(simpleAdapter);
    }

    /**
     * get news by asyncTask
     */
    private class GetNews extends AsyncTask<String, Void, String> {
        @Override
        protected void onPostExecute(String result) {
            swipeRefreshLayout.setRefreshing(false);
            if (exception) {
                //deal exception
                exception = false;
                finish();
                Toast.makeText(getApplicationContext(), R.string.refresh_exception, Toast.LENGTH_SHORT).show();
            } else {
                // refresh UI
                initGridView(gridView);
            }
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                GetJson getJson = new GetJson();
                String url = "http://45.62.117.228:8000/news/";
                String newList_json = getJson.run(url);
                List<News> newsList = ParseJson.fromJsontoNewsList(newList_json);
                title = new String[newsList.size()];
                newsId = new int[newsList.size()];
                for (int i = 0; i < newsList.size(); i++) {
                    News news = newsList.get(i);
                    title[i] = news.getTitle();
                    newsId[i] = news.getId();
                    LogUtil.i("MainActivity", "id is " + news.getId());
                }
            } catch (java.net.ConnectException e) {
                e.printStackTrace();
                LogUtil.i("Connect Error", "can't connect to the server!");
                exception = true;
            } catch (java.io.IOException e) {
                LogUtil.i("IO Error", e.getMessage());
                exception = true;
            } catch (Exception e) {
                e.printStackTrace();
                exception = true;
            }
            return params[0];
        }
    }

    /**
     * show menu
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean login = pref.getBoolean("login_state", false);
        if (login) {
            getMenuInflater().inflate(R.menu.menu_main, menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_hiding, menu);
        }
        return true;
    }

    /**
     * set menu's click event
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_person) {
            Intent intent = new Intent(getApplicationContext(), UserInfoActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_leave) {
            editor = pref.edit();
            editor.putBoolean("login_state", false);
            editor.commit();
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
        } else if (id == R.id.action_login) {
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
        } else if (id == R.id.action_exit) {
            DialogUtil.showDialog(this, "确定要退出程序吗?");
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
package org.apache.flink.table.runtime.typeutils;

import org.apache.flink.table.types.logical.BooleanType;
import org.apache.flink.table.types.logical.IntType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.VarCharType;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

/**
 * Test for {@link RowDataTypeInfo}.
 */
public class RowDataTypeInfoTest {
	private static LogicalType[] typeList = new LogicalType[]{
			new IntType(),
			new VarCharType(VarCharType.MAX_LENGTH)
	};

	@Test(expected = IllegalArgumentException.class)
	public void testWrongNumberOfFieldNames() {
		new RowDataTypeInfo(typeList, new String[]{"int", "string", "int"});
		// number of field names should be equal to number of types, go fail
	}

	@Test(expected = IllegalArgumentException.class)
	public void testDuplicateCustomFieldNames() {
		new RowDataTypeInfo(typeList, new String[]{"int", "int"});
		// field names should not be the same, go fail
	}

	@Test
	public void testBinaryRowTypeInfoEquality() {
		RowDataTypeInfo typeInfo1 = new RowDataTypeInfo(
				new IntType(),
				new VarCharType(VarCharType.MAX_LENGTH));

		RowDataTypeInfo typeInfo2 = new RowDataTypeInfo(
				new IntType(),
				new VarCharType(VarCharType.MAX_LENGTH));

		assertEquals(typeInfo1, typeInfo2);
		assertEquals(typeInfo1.hashCode(), typeInfo2.hashCode());
	}

	@Test
	public void testBinaryRowTypeInfoInequality() {
		RowDataTypeInfo typeInfo1 = new RowDataTypeInfo(
				new IntType(),
				new VarCharType(VarCharType.MAX_LENGTH));

		RowDataTypeInfo typeInfo2 = new RowDataTypeInfo(
				new IntType(),
				new BooleanType());

		assertNotEquals(typeInfo1, typeInfo2);
		assertNotEquals(typeInfo1.hashCode(), typeInfo2.hashCode());
	}
}


text:
package org.apache.derby.impl.store.raw.data;

import org.apache.derby.iapi.reference.SQLState;

import org.apache.derby.impl.store.raw.data.BasePage;

import org.apache.derby.iapi.services.sanity.SanityManager;

import org.apache.derby.iapi.services.io.FormatIdUtil;
import org.apache.derby.iapi.services.io.StoredFormatIds;

import org.apache.derby.iapi.error.StandardException;

import org.apache.derby.iapi.store.raw.Page;
import org.apache.derby.iapi.store.raw.RecordHandle;
import org.apache.derby.iapi.store.raw.Transaction;

import org.apache.derby.iapi.store.raw.log.LogInstant;
import org.apache.derby.iapi.store.raw.xact.RawTransaction;

import org.apache.derby.iapi.types.DataValueDescriptor;

import org.apache.derby.iapi.services.io.FormatableBitSet;
import org.apache.derby.iapi.util.ByteArray;
import org.apache.derby.iapi.services.io.CompressedNumber;
import org.apache.derby.iapi.services.io.DynamicByteArrayOutputStream;
import org.apache.derby.iapi.services.io.DynamicByteArrayOutputStream;

import java.io.OutputStream;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
import org.apache.derby.iapi.services.io.LimitObjectInput;

/**
	Represents the update of a particular row on a page.

	<PRE>
	@format_id	LOGOP_UPDATE
		the formatId is written by FormatIdOutputStream when this object is
		written out by writeObject
	@purpose	update a record on the page
	@upgrade
	@disk_layout
		PhysicalPageOperation	the super class
		doMeSlot(CompressedInt)	the slot the updated record is in
		recordId(CompressedInt) the recordId of the updated record

		OptionalData	The new image of the record (length included),
						follow by the old image of the record (length included)
	@end_format
	</PRE>
*/

public final class UpdateOperation extends PhysicalPageOperation {

	protected int			doMeSlot;	// record slot - only valid during a doMe() operation
	protected int			recordId;	// record id
	transient protected int nextColumn;	// next column that needs to be updated in a row.

	transient protected ByteArray preparedLog;

	public UpdateOperation(
    RawTransaction              t,
    BasePage                    page,
    int                         slot,
    int                         recordId,
    Object[]       row,
    FormatableBitSet                     validColumns,
    int                         realStartColumn,
    DynamicByteArrayOutputStream      logBuffer,
    int                         realSpaceOnPage,
    RecordHandle                headRowHandle)
		throws StandardException
	{
		super(page);

		this.doMeSlot = slot;
		this.recordId = recordId;
		this.nextColumn = -1;

		// RESOLVE SRW-DJD/YYZ
		try {
			writeOptionalDataToBuffer(t, (DynamicByteArrayOutputStream) logBuffer,
				row, validColumns, realStartColumn,
				realSpaceOnPage, headRowHandle);
		} catch (IOException ioe) {
			throw StandardException.newException(
                    SQLState.DATA_UNEXPECTED_EXCEPTION, ioe);
		}

	}

	/*
	 * Formatable methods
	 */

	// no-arg constructor, required by Formatable
	public UpdateOperation() { super(); }

	public void writeExternal(ObjectOutput out) throws IOException
	{
		super.writeExternal(out);
		CompressedNumber.writeInt(out, doMeSlot);
		CompressedNumber.writeInt(out, recordId);
	}

	/**
		Read this in
		@exception IOException error reading from log stream
		@exception ClassNotFoundException log stream corrupted
	*/
	public void readExternal(ObjectInput in)
		 throws IOException, ClassNotFoundException
	{
		super.readExternal(in);
		doMeSlot = CompressedNumber.readInt(in);
		recordId = CompressedNumber.readInt(in);
	}

	/**
		Return my format identifier.
	*/
	public int getTypeFormatId() {
		return StoredFormatIds.LOGOP_UPDATE;
	}

	/**
		Return the last column of the row this operation logged
	*/
	public int getNextStartColumn() {
		return nextColumn;
	}

	/*
	 * Loggable methods
	 */
	/**
		Store the new record directly over the old record, the implementation
		of storeRecord is responsible for removing any old data.

		@exception StandardException Thrown by methods I call
		@exception IOException Thrown by methods I call

		@see BasePage#storeRecord
		@see org.apache.derby.iapi.store.raw.Loggable#doMe
	*/
	public void doMe(Transaction xact, LogInstant instant, LimitObjectInput in)
		 throws StandardException, IOException
	{
		this.page.storeRecord(instant, doMeSlot, false, in);
	}

	/*
	 * PhysicalPageOperation methods
	 */

	/**
		Store the old record directly over the new record, the implementation
		of storeRecord is responsible for removing any new data.

		@exception StandardException Thrown by methods I call
		@exception IOException Thrown by methods I call

		@see BasePage#storeRecord
		@see PhysicalPageOperation#undoMe
	*/
	public void undoMe(Transaction xact, BasePage undoPage,
					   LogInstant CLRInstant, LimitObjectInput in)
		 throws StandardException, IOException
	{

		int slot = undoPage.findRecordById(recordId, Page.FIRST_SLOT_NUMBER);

		// skip the after image of the record
		undoPage.skipRecord(in);

		undoPage.storeRecord(CLRInstant, slot, false, in);
		undoPage.setAuxObject(null);
	}

	/*
		methods to support prepared log

		the following two methods should not be called during recover
	*/

	public ByteArray getPreparedLog()
	{
		return (this.preparedLog);
	}

	/**
		Write out the changed colums of new record (from the row) followed by
        changed columns of the old record (from the page).

		@exception StandardException Thrown by methods I call
		@exception IOException Thrown by methods I call
	*/
	private void writeOptionalDataToBuffer(
    RawTransaction                  t,
    DynamicByteArrayOutputStream    logBuffer,
    Object[]           row,
    FormatableBitSet                         validColumns,
    int                             realStartColumn,
    int                             realSpaceOnPage,
    RecordHandle                    headRowHandle)
		throws StandardException, IOException
	{

		if (SanityManager.DEBUG)
        {
			SanityManager.ASSERT(this.page != null);
		}

		if (realStartColumn == (-1))
        {
			logBuffer = t.getLogBuffer();
		}

		int optionalDataStart = logBuffer.getPosition();

		if (SanityManager.DEBUG)
        {

            SanityManager.ASSERT(
                (realStartColumn != -1 || optionalDataStart == 0),
                "Buffer for writing optional data should start at position 0");
        }

		this.nextColumn =
            this.page.logRow(
                doMeSlot, false, recordId, row, validColumns,
                logBuffer, 0, Page.INSERT_OVERFLOW, realStartColumn,
                realSpaceOnPage, 100);

		FormatableBitSet loggedColumns = validColumns;

        // If this update results in moving columns off the current page to
        // another page, then we must log the before image values of the columns
        // being moved (deleted from this page) in addition to logging the
        // columns actually being changed as part of the update.

        if ((nextColumn != -1) && (validColumns != null))
        {
            // if nextColumn is not -1, then this must be an update which moves
            // columns off of the current page.  If validColumns == null then
            // we are logging all of the before image columns anyway.

            // get total number of fields of the old record.
			int numberFields = page.getHeaderAtSlot(doMeSlot).getNumberFields();

            // create new bit map, copying all bits that were set in original
			loggedColumns = new FormatableBitSet(validColumns);

            // make sure there is room in the bit map to add the columns being
            // deleted from the end of the row.
            // The important thing is that endField must be at least as big as
            // the number of columns in the entire record (including previous
            // pages of a long row) up to the end of this page.
            int endField = nextColumn + numberFields;
            loggedColumns.grow(endField);
            // now include all columns being deleted.
            // This actually sets too many bits in this bit set but
            // logRecord will just ignore the extra bits.
			for (int i = nextColumn; i < endField; i++)
            {
				loggedColumns.set(i);
			}
        }

		// log the old version of the changed data
		this.page.logRecord(
            doMeSlot, BasePage.LOG_RECORD_FOR_UPDATE,
            recordId, loggedColumns, logBuffer, headRowHandle);

        // get length of all the optional data.
		optionalDataStart = logBuffer.getBeginPosition();
		int optionalDataLength = logBuffer.getPosition() - optionalDataStart;

		// set the position to the beginning of the buffer
		logBuffer.setPosition(optionalDataStart);

		this.preparedLog = new ByteArray(
            logBuffer.getByteArray(), optionalDataStart, optionalDataLength);
	}

	/*
	 * PageBasicOperation
	 */

	/**
	 * restore the before image of the page
	 *
	 * @exception StandardException Standard Derby Error Policy
	 * @exception IOException problem reading the complete log record from the
	 * input stream
	 */
	public void restoreMe(Transaction xact, BasePage undoPage,
					   LogInstant CLRInstant, LimitObjectInput in)
		 throws StandardException, IOException
	{
		undoMe(xact, undoPage, CLRInstant, in);
	}

	public String toString()
	{
		if (SanityManager.DEBUG)
		{
			return super.toString() +
			"Update " +
			" Slot=" + doMeSlot +
			" recordId=" + recordId;
		}
		else
			return null;
	}
}