text:
<?xml version="1.0" standalone="no"?>

<!DOCTYPE caldavtest SYSTEM "caldavtest.dtd">

<!--
 Copyright (c) 2006-2015 Apple Inc. 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.
 -->

<caldavtest>
	<require-feature>
		<feature>caldav</feature>
	</require-feature>

	<start/>

	<test-suite name='prop patches'>
		<test name='1'>
			<description>PROPPATCH of details: good</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarpath1:/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/1.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details</value>
						<value>{DAV:}details2</value>
					</arg>
				</verify>
			</request>
			<request>
				<method>PROPFIND</method>
				<ruri>$calendarpath1:/</ruri>
				<header>
					<name>Depth</name>
					<value>0</value>
				</header>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/2.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details$My Name</value>
						<value>{DAV:}details2$My Name 2</value>
					</arg>
				</verify>
			</request>
		</test>
		<test name='2'>
			<description>PROPPATCH of details: remove it</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarpath1:/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/3.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details</value>
					</arg>
				</verify>
			</request>
			<request>
				<method>PROPFIND</method>
				<ruri>$calendarpath1:/</ruri>
				<header>
					<name>Depth</name>
					<value>0</value>
				</header>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/2.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details2$My Name 2</value>
					</arg>
					<arg>
						<name>badprops</name>
						<value>{DAV:}details</value>
					</arg>
				</verify>
			</request>
		</test>
		<test name='3'>
			<description>PROPPATCH remove non-existant</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarpath1:/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/4.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}missing</value>
					</arg>
				</verify>
			</request>
		</test>
		<test name='4'>
			<description>PROPPATCH of resourcetype: fails</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarpath1:/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/5.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>badprops</name>
						<value>{DAV:}details</value>
						<value>{DAV:}details2</value>
						<value>{DAV:}resourcetype</value>
					</arg>
				</verify>
			</request>
			<request>
				<method>PROPFIND</method>
				<ruri>$calendarpath1:/</ruri>
				<header>
					<name>Depth</name>
					<value>0</value>
				</header>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/2.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details2$My Name 2</value>
					</arg>
					<arg>
						<name>badprops</name>
						<value>{DAV:}details</value>
					</arg>
				</verify>
			</request>
		</test>
		<test name='5'>
			<description>PROPPATCH of encoded value</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarpath1:/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/8.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}displayname</value>
					</arg>
				</verify>
			</request>
			<request>
				<method>PROPFIND</method>
				<ruri>$calendarpath1:/</ruri>
				<header>
					<name>Depth</name>
					<value>0</value>
				</header>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/9.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}displayname$calendar <- & ]]></value>
					</arg>
				</verify>
			</request>
		</test>
		<test name='6'>
			<description>PROPPATCH non-existent calendar</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarhome1:/bogus-calendar/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/3.xml</filepath>
				</data>
				<verify>
					<callback>statusCode</callback>
					<arg>
						<name>status</name>
						<value>404</value>
					</arg>
				</verify>
			</request>
		</test>
	</test-suite>

	<test-suite name='prop patch property attributes'>
		<test name='1'>
			<description>PROPPATCH with property XML attribute</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarpath1:/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/6.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details</value>
					</arg>
				</verify>
			</request>
			<request>
				<method>PROPFIND</method>
				<ruri>$calendarpath1:/</ruri>
				<header>
					<name>Depth</name>
					<value>0</value>
				</header>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/7.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details$My Name</value>
					</arg>
				</verify>
				<verify>
					<callback>dataString</callback>
					<arg>
						<name>contains</name>
						<value>details xml:lang='en'</value>
					</arg>
				</verify>
			</request>
		</test>
		<test name='2'>
			<description>PROPPATCH of details: remove it</description>
			<request>
				<method>PROPPATCH</method>
				<ruri>$calendarpath1:/</ruri>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/3.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details</value>
					</arg>
				</verify>
			</request>
			<request>
				<method>PROPFIND</method>
				<ruri>$calendarpath1:/</ruri>
				<header>
					<name>Depth</name>
					<value>0</value>
				</header>
				<data>
					<content-type>text/xml; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/proppatches/2.xml</filepath>
				</data>
				<verify>
					<callback>propfindItems</callback>
					<arg>
						<name>okprops</name>
						<value>{DAV:}details2$My Name 2</value>
					</arg>
					<arg>
						<name>badprops</name>
						<value>{DAV:}details</value>
					</arg>
				</verify>
			</request>
		</test>
	</test-suite>

	<end/>

</caldavtest>


text:
package org.datacommons.tool;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.google.common.truth.Expect;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.datacommons.util.LogWrapper;
import org.datacommons.util.SummaryReportGenerator;
import org.datacommons.util.TmcfCsvParser;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import picocli.CommandLine;

// To add a new test case, add a new directory in resources/org/datacommons/tool/lint. In that new
// directory, add an input directory and an output directory. In the input directory, put the test
// files you want to run the lint tool against. In the output directory, put a report.json file with
// the expected report output. Optionally, you may put a text file in the input directory named
// "args.txt"
// that contains one command line arguments (e.g. -s=true) per line.
//
// These tests can be run in a mode to produce golden files, as below:
//    mvn -DgoldenFilesPrefix=$PWD/tool/src/test/resources/org/datacommons/tool test
//
public class GenMcfTest {
  @Rule public TemporaryFolder testFolder = new TemporaryFolder();
  @Rule public final Expect expect = Expect.create();
  // To ensure we test the right number of files for every test, when you add a file, add the
  // count here.
  private static Map<String, Integer> EXPECTED_FILES_TO_CHECK =
      Map.of(
          "fataltmcf", 2,
          "resolution", 5,
          "statchecks", 3,
          "successtmcf", 3,
          "measurementresult", 4,
          "localidresolution", 5,
          "manyinconsistent", 4);

  private static final String ARGS_TXT_FNAME = "args.txt";

  @Test
  public void GenMcfTest() throws IOException {
    // Set this so that the generated node IDs are deterministic
    TmcfCsvParser.TEST_mode = true;
    SummaryReportGenerator.TEST_mode = true;
    LogWrapper.TEST_MODE = true;

    String goldenFilesPrefix = System.getProperty("goldenFilesPrefix");
    Main app = new Main();
    CommandLine cmd = new CommandLine(app);
    File[] testDirectories = new File(resourceFile("genmcf")).listFiles(File::isDirectory);
    for (File directory : testDirectories) {
      String testName = directory.getName();
      System.err.println(testName + ": BEGIN");
      assertTrue(EXPECTED_FILES_TO_CHECK.containsKey(testName));
      List<String> argsList = new ArrayList<>();
      argsList.add("genmcf");
      File[] inputFiles = new File(Path.of(directory.getPath(), "input").toString()).listFiles();
      List<String> expectedOutputFiles =
          new ArrayList<>(
              List.of(
                  "report.json",
                  "instance_mcf_nodes.mcf",
                  "failed_instance_mcf_nodes.mcf",
                  "summary_report.html"));
      for (File inputFile : inputFiles) {
        String fName = inputFile.getName();

        if (fName.equals(ARGS_TXT_FNAME)) {
          List<String> argsFromFile = TestUtil.readLinesFromFile(inputFile);
          argsList.addAll(argsFromFile);
        } else {
          argsList.add(inputFile.getPath());
          if (fName.endsWith(".csv") || fName.endsWith(".tsv")) {
            expectedOutputFiles.add(
                "table_mcf_nodes_" + FilenameUtils.removeExtension(fName) + ".mcf");
            expectedOutputFiles.add(
                "failed_table_mcf_nodes_" + FilenameUtils.removeExtension(fName) + ".mcf");
          }
        }
      }

      argsList.add("--resolution=FULL");
      argsList.add("--output-dir=" + Paths.get(testFolder.getRoot().getPath(), testName));
      String[] args = argsList.toArray(new String[argsList.size()]);
      cmd.execute(args);

      Integer numChecked = 0;
      if (goldenFilesPrefix != null && !goldenFilesPrefix.isEmpty()) {
        for (var f : expectedOutputFiles) {
          Path actual = TestUtil.getTestFilePath(testFolder, testName, f);
          if (!f.equals("report.json") && !new File(actual.toString()).exists()) continue;

          Path golden = Path.of(goldenFilesPrefix, "genmcf", testName, "output", f);
          Files.copy(actual, golden, REPLACE_EXISTING);
          numChecked++;
        }
      } else {
        for (var f : expectedOutputFiles) {
          Path actual = TestUtil.getTestFilePath(testFolder, testName, f);
          if (!f.equals("report.json") && !new File(actual.toString()).exists()) continue;

          Path expected = TestUtil.getOutputFilePath(directory.getPath(), f);
          if (f.equals("report.json")) {
            TestUtil.assertReportFilesAreSimilar(
                expect, TestUtil.readStringFromPath(expected), TestUtil.readStringFromPath(actual));
          } else if (f.equals("summary_report.html")) {
            TestUtil.assertHtmlFilesAreSimilar(
                TestUtil.readStringFromPath(expected), TestUtil.readStringFromPath(actual));
          } else {
            assertEquals(
                org.datacommons.util.TestUtil.mcfFromFile(expected.toString()),
                org.datacommons.util.TestUtil.mcfFromFile(actual.toString()));
          }
          numChecked++;
        }
      }
      assertEquals(numChecked, EXPECTED_FILES_TO_CHECK.get(testName));
      System.err.println(testName + ": PASSED");
    }
  }

  private String resourceFile(String resource) {
    return this.getClass().getResource(resource).getPath();
  }
}

redpajama_set_name: RedPajamaGithub


text:
---
layout: post
title: Okinawa (CZ)
description: První zkušenost s Japonskem se nesla v americkém duchu. Že tohle není klasické Japonsko člověk pozná po několika hodinách strávených na tomto ostrově, který jedna americká civilistka popsala jako "ostrov hledajicí svoji osobnost" a jeden americký voják jako "Havaj Japonska".
author: Petr Lorenc
comments: true
---

První zkušenost s Japonskem se nesla v americkém duchu. Že tohle není klasické Japonsko člověk pozná po několika hodinách strávených na tomto ostrově, který jedna americká civilistka popsala jako "ostrov hledajicí svoji osobnost" a jeden americký voják jako "Havaj Japonska".

{% include menu_taiwan.html %}

## My si to tady radši pohlídáme

To je frajer

O výhodné strategické pozici ostrova není třeba pochybovat. Už letmý pohled na mapu prozradí, že po Taiwanu je to další strategický bod pro snadnou kontrolu čínských lodí a jejich manévrů. Po pohledu na ostrov pochopíte, že američané nechtějí nic nechat náhodě a zasadili do krajiny ostrova několik svých vojenských základen. Kultuře ostrova to dodává zajímavý smíšený ráz japonské přesnosti a úcty k tradici a amerického užívání si života. Přítomnost američanů je důvod, proč většina barů ve větších městech může vůbec existovat. Další výhodu to přináší v podobě snazší komunikace, protože angličtinou se s američany překvapivě domluvíte. A s Japonci zvyklými na Američany zrovna tak.

Foceno americkýmn vojákem

## Japonské památky bych spočítal na prstech jedné ruky

Vzhledem k vzdálenosti od Japonska a faktu, že tu velkou část historie vládl samostatný kmen Ryukyuan, se moc památek nezachovalo. Mezi hlavní, které jsem navštívil, patří hrad Šuri. Musím říct, že by bylo lepší, kdyby zrovna nebyl v rekonstrukci. Tento fakt se snažili zamaskovat obarveným plátnem, takže to vypadalo jako Národní divadlo na Václaváku. Potom se ztrácí rozdíl mezi prohlížením fotek a díváním se na plátno.

Pěkné plátno, že? To prostě musíte vidět

## Přeci jenom to ale je japonská kultura

Představení národních tanců

Co jim na památkach chybí se snaží dohnat na důkladném chování. Zde to jsou Japonci, jak si je představuji. Při příletu na letiště mě vítalo asi 6 Japonců, kteří se mi klaněli / vítali mě a dalších 6 mi ukazovalo cestu v uličce bez možnosti odbočit. Poté mi provedli důkladnou prohlídku, jestli náhodou nepašuju zlato - koukali se mi i do ovesných vloček (a ano, vzal jsem si s sebou vločky - prosím nesmějte se). Trochu rozdíl oproti Taiwanskému letišti, kde mě nechali pronést i lahev s vodou. To samé mě čekalo při odletu z Okinawy, kdy po mě navíc chtěli vidět letenku z Taiwanu. Moje poznámky, že to není přeci jejich starost a že by to mělo zajímat spíše Taiwance prostě ignorovali. Na pořádek si zkrátka potrpí.

Kdo z vás to má? Nebo spíš chce? Já ne.

 Myslím, že k turistům jsou Japonci více odměření a méně přátelští než Taiwanci (přitom sdíli část historie). Připadali mi více namyšlení a konzervativní. Samozřejmě v rámci dobrého vychování a nemůžu si stěžovat na nic konkrétního - je to jenom pocit.

Kdyby vám vaše uši nestačili

## Doprava a nový kamarádi

Nápisům na dopravních prostředcích většina turistů nerozumí, tak se musíte orientovat podle něčeho jiného. Pro tyto účely skvěle poslouží kombinace Google Maps a japonské dochvilnosti. Pokud Mapy řeknou, že odjezd autobusu je v 16:00 z určitého místa, tak pokud budete v 16:00 na určitém místě, nemusíte se bát, že nastoupíte na jinou linku.

Tímto bych se daleko nedostal

Cestování v Asii má pro neasiata také jednu nespornou výhodu v tom, že ostatní neasiaty snadno pozná a může je obtěžovat pokusy o seznámení. To se stalo osudné mladému páru, který jsem poznal při čekání na autobus do Akvária. Slovo dalo slovo a my jsme spolu s Ilyou a Arisou strávili parádní den v Akváriu. Mladý pár byl z Krymu a oba momentálně žijí v Tokiu. Možná to bylo tím, že nám všem koluje v žilách slovanská krev, ale opravdu jsme si rozuměli, a proto jsem byl smutný, když jsme se pak loučili. Naštestí jsme se domluvili na tom, že se potkáme při mém výletu do Tokia.

Nový kamarádi

## Okinawa Churaumi Aquarium

A zlatý hřeb mého výletu byla návštěva Okinawa Churaumi Aquarium. Velmi se mi zde líbilo a také jsem měl možnost navštívit zdejší muzeum původních obyvatel, historickou vesničku a botanickou zahradu. Lepší bude podívat se na fotky.

Okinawa Churaumi Aquarium

Okinawa Churaumi Aquarium

 Návštěvu Akvária jsem zakončil 7km během/chůzí při zapadajícím slunci, směr moje ubytování.

## Pláže

Malou zmínku také věnuji zdejších plážím. Ty a čistá voda přímo vybízí ke koupání. Neodolal jsem - po 8km běhu na pláž, ležící na malém ostrůvku Sesoko spojeným s Okinawou mostem, jsem si vychutnal koupaní v Východočínském moři.

Láká ke koupání. Ani já neodolal.

A to by bylo prozatím vše. Děkuji


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using PowerLib.System;
using PowerLib.System.IO.Streamed.Typed;

namespace PowerLib.System.Data.SqlTypes.Collections
{
  [SqlUserDefinedType(Format.UserDefined, Name = "DateTimeArray", IsByteOrdered = true, IsFixedLength = false, MaxByteSize = -1)]
  public sealed class SqlDateTimeArray : INullable, IBinarySerialize
  {
    private DateTime?[] _array;

    #region Contructors

    public SqlDateTimeArray()
    {
      _array = null;
    }

    public SqlDateTimeArray(int length)
    {
      if (length < 0)
        throw new ArgumentOutOfRangeException("length");

      _array = new DateTime?[length];
    }

    public SqlDateTimeArray(IEnumerable<DateTime?> coll)
    {
      _array = coll != null ? coll.ToArray() : null;
    }

    private SqlDateTimeArray(DateTime?[] array)
    {
      _array = array;
    }

    #endregion
    #region Properties

    public DateTime?[] Array
    {
      get { return _array; }
      set { _array = value; }
    }

    public static SqlDateTimeArray Null
    {
      get { return new SqlDateTimeArray(); }
    }

    public bool IsNull
    {
      get { return _array == null; }
    }

    public SqlInt32 Length
    {
      get { return _array != null ? _array.Length : SqlInt32.Null; }
    }

    #endregion
    #region Methods

    public static SqlDateTimeArray Parse(SqlString s)
    {
      if (s.IsNull)
        return Null;

      return new SqlDateTimeArray(SqlFormatting.ParseArray<DateTime?>(s.Value,
        t => !t.Equals(SqlFormatting.NullText, StringComparison.InvariantCultureIgnoreCase) ? SqlDateTime.Parse(t).Value : default(DateTime?)));
    }

    public override String ToString()
    {
      return SqlFormatting.Format(_array, t => (t.HasValue ? new SqlDateTime(t.Value) : SqlDateTime.Null).ToString());
    }

    [SqlMethod]
    public SqlDateTime GetItem(SqlInt32 index)
    {
      return !index.IsNull && _array[index.Value].HasValue ? _array[index.Value].Value : SqlDateTime.Null;
    }

    [SqlMethod(IsMutator = true)]
    public void SetItem(SqlDateTime value, SqlInt32 index)
    {
      if (!index.IsNull)
        _array[index.Value] = !value.IsNull ? value.Value : default(DateTime?);
    }

    [SqlMethod]
    public SqlDateTimeArray GetRange(SqlInt32 index, SqlInt32 count)
    {
      int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _array.Length - count.Value;
      int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _array.Length - index.Value;
      return new SqlDateTimeArray(_array.Range(indexValue, countValue));
    }

    [SqlMethod(IsMutator = true)]
    public void SetRange(SqlDateTimeArray array, SqlInt32 index)
    {
      if (array.IsNull)
        return;

      int indexValue = index.IsNull ? _array.Length - Comparable.Min(_array.Length, array._array.Length) : index.Value;
      _array.Fill(i => array._array[i - indexValue]);
    }

    [SqlMethod(IsMutator = true)]
    public void FillRange(SqlDateTime value, SqlInt32 index, SqlInt32 count)
    {
      int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _array.Length - count.Value;
      int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _array.Length - index.Value;
      _array.Fill(!value.IsNull ? value.Value : default(DateTime?), indexValue, countValue);
    }

    [SqlMethod]
    public SqlDateTimeCollection ToCollection()
    {
      return new SqlDateTimeCollection(_array);
    }

    #endregion
    #region Operators

    public static implicit operator byte[] (SqlDateTimeArray array)
    {
      using (var ms = new MemoryStream())
      using (new NulDateTimeStreamedArray(ms, SizeEncoding.B4, true, array._array, true, false))
        return ms.ToArray();
    }

    public static explicit operator SqlDateTimeArray(byte[] buffer)
    {
      using (var ms = new MemoryStream(buffer))
      using (var sa = new NulDateTimeStreamedArray(ms, true, false))
        return new SqlDateTimeArray(sa.ToArray());
    }

    #endregion
    #region IBinarySerialize implementation

    public void Read(BinaryReader rd)
    {
      using (var sa = new NulDateTimeStreamedArray(rd.BaseStream, true, false))
        _array = sa.ToArray();
    }

    public void Write(BinaryWriter wr)
    {
      using (var ms = new MemoryStream())
      using (var sa = new NulDateTimeStreamedArray(ms, SizeEncoding.B4, true, _array, true, false))
        wr.Write(ms.GetBuffer(), 0, (int)ms.Length);
    }

    #endregion
  }
}


text:
package com.android.test.hwui;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;

@SuppressWarnings({"UnusedDeclaration"})
public class MoreNinePatchesActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FrameLayout layout = new FrameLayout(this);
        PatchView b = new PatchView (this);
        b.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER));
        layout.addView(b);
        layout.setBackgroundColor(0xffffffff);

        setContentView(layout);
    }

    private class PatchView extends View {
        private final Drawable mDrawable1;
        private final Drawable mDrawable2;
        private final Drawable mDrawable3;

        private PatchView(Context context) {
            super(context);
            Resources res = context.getResources();
            mDrawable1 = res.getDrawable(R.drawable.progress_vertical_holo_dark);
            mDrawable2 = res.getDrawable(R.drawable.scrubber_progress_vertical_holo_dark);
            mDrawable3 = res.getDrawable(R.drawable.scrubber_vertical_primary_holo);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            canvas.translate(100, 100);
            mDrawable1.setBounds(0, 0, 33, 120);
            mDrawable1.setLevel(5000);
            mDrawable1.draw(canvas);

            canvas.translate(20, 0);
            mDrawable2.setBounds(0, 0, 33, 120);
            mDrawable2.setLevel(5000);
            mDrawable2.draw(canvas);

            canvas.translate(20, 0);
            mDrawable3.setBounds(0, 0, 33, 120);
            mDrawable3.draw(canvas);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>FTP Upload Example</title>

FTP Upload Example

    <form action="upload.php" method="post" enctype="multipart/form-data">
        Please choose file:
        <input type="file" name="pf" />
        <input type="submit" value="upload">
    </form>


text:
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C

import ctypes
_EXTENSION_NAME = 'GL_ARB_instanced_arrays'
def _f( function ):
    return _p.createFunction( function,_p.PLATFORM.GL,'GL_ARB_instanced_arrays',error_checker=_errors._error_checker)
GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB=_C('GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB',0x88FE)
@_f
@_p.types(None,_cs.GLuint,_cs.GLuint)
def glVertexAttribDivisorARB(index,divisor):pass


text:
Sample app for the [React MVA](https://mva.microsoft.com/en-US/training-courses/react-the-definitive-beginners-guide-16547)

## Dependencies:
* [React](https://facebook.github.io/react/)
* [Babel](https://babeljs.io/)
* [Webpack](https://webpack.github.io/)

## How to Run Debug Server

Make sure you have the Webpack dev server installed:

```
npm install -g webpack webpack-dev-server
```

## To Add Visual Studio Code Intellisense

Run typings to install the React/JSX typings.

```
npm install -g typings
typings install --ambient react-global
```


text:
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import typescript2 from 'rollup-plugin-typescript2';
import uglify from 'rollup-plugin-uglify';

export default {
  input: `src/index.ts`,
  output: {
    name: 'hw',
    file: `dist/bundle.js`,
    format: 'iife',
    sourcemap: false
  },
  plugins: [
    typescript2({
      typescript: require('typescript'),
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true
    }),
    replace({
      delimiters: ['', ''],
      values: {
        '/** @class */': '/** @__PURE__ */'
      }
    }),
    nodeResolve({jsnext: true, module: true}),
    commonjs({
      include: 'node_modules/rxjs/**',
    }),
    uglify({
      mangle: true,
      compress: {
        global_defs: {
          'ngDevMode': false,
        }
      }
    })
  ],
  external: []
}


text:
package org.apache.hadoop.util;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;

/**
 * A class that provides a line reader from an input stream.
 * Depending on the constructor used, lines will either be terminated by:
 *

 *
one of the following: '\n' (LF) , '\r' (CR),
 * or '\r\n' (CR+LF).

 *
or, a custom byte sequence delimiter

 *

 * In both cases, EOF also terminates an otherwise unterminated
 * line.
 */
@InterfaceAudience.LimitedPrivate({"MapReduce"})
@InterfaceStability.Unstable
public class LineReader implements Closeable {
  private static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
  private int bufferSize = DEFAULT_BUFFER_SIZE;
  private InputStream in;
  private byte[] buffer;
  // the number of bytes of real data in the buffer
  private int bufferLength = 0;
  // the current position in the buffer
  private int bufferPosn = 0;

  private static final byte CR = '\r';
  private static final byte LF = '\n';

  // The line delimiter
  private final byte[] recordDelimiterBytes;

  /**
   * Create a line reader that reads from the given stream using the
   * default buffer-size (64k).
   * @param in The input stream
   * @throws IOException
   */
  public LineReader(InputStream in) {
    this(in, DEFAULT_BUFFER_SIZE);
  }

  /**
   * Create a line reader that reads from the given stream using the
   * given buffer-size.
   * @param in The input stream
   * @param bufferSize Size of the read buffer
   * @throws IOException
   */
  public LineReader(InputStream in, int bufferSize) {
    this.in = in;
    this.bufferSize = bufferSize;
    this.buffer = new byte[this.bufferSize];
    this.recordDelimiterBytes = null;
  }

  /**
   * Create a line reader that reads from the given stream using the
   * io.file.buffer.size specified in the given
   * Configuration.
   * @param in input stream
   * @param conf configuration
   * @throws IOException
   */
  public LineReader(InputStream in, Configuration conf) throws IOException {
    this(in, conf.getInt("io.file.buffer.size", DEFAULT_BUFFER_SIZE));
  }

  /**
   * Create a line reader that reads from the given stream using the
   * default buffer-size, and using a custom delimiter of array of
   * bytes.
   * @param in The input stream
   * @param recordDelimiterBytes The delimiter
   */
  public LineReader(InputStream in, byte[] recordDelimiterBytes) {
    this.in = in;
    this.bufferSize = DEFAULT_BUFFER_SIZE;
    this.buffer = new byte[this.bufferSize];
    this.recordDelimiterBytes = recordDelimiterBytes;
  }

  /**
   * Create a line reader that reads from the given stream using the
   * given buffer-size, and using a custom delimiter of array of
   * bytes.
   * @param in The input stream
   * @param bufferSize Size of the read buffer
   * @param recordDelimiterBytes The delimiter
   * @throws IOException
   */
  public LineReader(InputStream in, int bufferSize,
      byte[] recordDelimiterBytes) {
    this.in = in;
    this.bufferSize = bufferSize;
    this.buffer = new byte[this.bufferSize];
    this.recordDelimiterBytes = recordDelimiterBytes;
  }

  /**
   * Create a line reader that reads from the given stream using the
   * io.file.buffer.size specified in the given
   * Configuration, and using a custom delimiter of array of
   * bytes.
   * @param in input stream
   * @param conf configuration
   * @param recordDelimiterBytes The delimiter
   * @throws IOException
   */
  public LineReader(InputStream in, Configuration conf,
      byte[] recordDelimiterBytes) throws IOException {
    this.in = in;
    this.bufferSize = conf.getInt("io.file.buffer.size", DEFAULT_BUFFER_SIZE);
    this.buffer = new byte[this.bufferSize];
    this.recordDelimiterBytes = recordDelimiterBytes;
  }

  /**
   * Close the underlying stream.
   * @throws IOException
   */
  public void close() throws IOException {
    in.close();
  }

  /**
   * Read one line from the InputStream into the given Text.
   *
   * @param str the object to store the given line (without newline)
   * @param maxLineLength the maximum number of bytes to store into str;
   *  the rest of the line is silently discarded.
   * @param maxBytesToConsume the maximum number of bytes to consume
   *  in this call.  This is only a hint, because if the line cross
   *  this threshold, we allow it to happen.  It can overshoot
   *  potentially by as much as one buffer length.
   *
   * @return the number of bytes read including the (longest) newline
   * found.
   *
   * @throws IOException if the underlying stream throws
   */
  public int readLine(Text str, int maxLineLength,
                      int maxBytesToConsume) throws IOException {
    if (this.recordDelimiterBytes != null) {
      return readCustomLine(str, maxLineLength, maxBytesToConsume);
    } else {
      return readDefaultLine(str, maxLineLength, maxBytesToConsume);
    }
  }

  protected int fillBuffer(InputStream in, byte[] buffer, boolean inDelimiter)
      throws IOException {
    return in.read(buffer);
  }

  /**
   * Read a line terminated by one of CR, LF, or CRLF.
   */
  private int readDefaultLine(Text str, int maxLineLength, int maxBytesToConsume)
  throws IOException {
    /* We're reading data from in, but the head of the stream may be
     * already buffered in buffer, so we have several cases:
     * 1. No newline characters are in the buffer, so we need to copy
     *    everything and read another buffer from the stream.
     * 2. An unambiguously terminated line is in buffer, so we just
     *    copy to str.
     * 3. Ambiguously terminated line is in buffer, i.e. buffer ends
     *    in CR.  In this case we copy everything up to CR to str, but
     *    we also need to see what follows CR: if it's LF, then we
     *    need consume LF as well, so next call to readLine will read
     *    from after that.
     * We use a flag prevCharCR to signal if previous character was CR
     * and, if it happens to be at the end of the buffer, delay
     * consuming it until we have a chance to look at the char that
     * follows.
     */
    str.clear();
    int txtLength = 0; //tracks str.getLength(), as an optimization
    int newlineLength = 0; //length of terminating newline
    boolean prevCharCR = false; //true of prev char was CR
    long bytesConsumed = 0;
    do {
      int startPosn = bufferPosn; //starting from where we left off the last time
      if (bufferPosn >= bufferLength) {
        startPosn = bufferPosn = 0;
        if (prevCharCR) {
          ++bytesConsumed; //account for CR from previous read
        }
        bufferLength = fillBuffer(in, buffer, prevCharCR);
        if (bufferLength <= 0) {
          break; // EOF
        }
      }
      for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline
        if (buffer[bufferPosn] == LF) {
          newlineLength = (prevCharCR) ? 2 : 1;
          ++bufferPosn; // at next invocation proceed from following byte
          break;
        }
        if (prevCharCR) { //CR + notLF, we are at notLF
          newlineLength = 1;
          break;
        }
        prevCharCR = (buffer[bufferPosn] == CR);
      }
      int readLength = bufferPosn - startPosn;
      if (prevCharCR && newlineLength == 0) {
        --readLength; //CR at the end of the buffer
      }
      bytesConsumed += readLength;
      int appendLength = readLength - newlineLength;
      if (appendLength > maxLineLength - txtLength) {
        appendLength = maxLineLength - txtLength;
      }
      if (appendLength > 0) {
        str.append(buffer, startPosn, appendLength);
        txtLength += appendLength;
      }
    } while (newlineLength == 0 && bytesConsumed < maxBytesToConsume);

    if (bytesConsumed > Integer.MAX_VALUE) {
      throw new IOException("Too many bytes before newline: " + bytesConsumed);
    }
    return (int)bytesConsumed;
  }

  /**
   * Read a line terminated by a custom delimiter.
   */
  private int readCustomLine(Text str, int maxLineLength, int maxBytesToConsume)
      throws IOException {
   /* We're reading data from inputStream, but the head of the stream may be
    *  already captured in the previous buffer, so we have several cases:
    *
    * 1. The buffer tail does not contain any character sequence which
    *    matches with the head of delimiter. We count it as a
    *    ambiguous byte count = 0
    *
    * 2. The buffer tail contains a X number of characters,
    *    that forms a sequence, which matches with the
    *    head of delimiter. We count ambiguous byte count = X
    *
    *    // ***  eg: A segment of input file is as follows
    *
    *    " record 1792: I found this bug very interesting and
    *     I have completely read about it. record 1793: This bug
    *     can be solved easily record 1794: This ."
    *
    *    delimiter = "record";
    *
    *    supposing:- String at the end of buffer =
    *    "I found this bug very interesting and I have completely re"
    *    There for next buffer = "ad about it. record 179       ...."
    *
    *     The matching characters in the input
    *     buffer tail and delimiter head = "re"
    *     Therefore, ambiguous byte count = 2 ****   //
    *
    *     2.1 If the following bytes are the remaining characters of
    *         the delimiter, then we have to capture only up to the starting
    *         position of delimiter. That means, we need not include the
    *         ambiguous characters in str.
    *
    *     2.2 If the following bytes are not the remaining characters of
    *         the delimiter ( as mentioned in the example ),
    *         then we have to include the ambiguous characters in str.
    */
    str.clear();
    int txtLength = 0; // tracks str.getLength(), as an optimization
    long bytesConsumed = 0;
    int delPosn = 0;
    int ambiguousByteCount=0; // To capture the ambiguous characters count
    do {
      int startPosn = bufferPosn; // Start from previous end position
      if (bufferPosn >= bufferLength) {
        startPosn = bufferPosn = 0;
        bufferLength = fillBuffer(in, buffer, ambiguousByteCount > 0);
        if (bufferLength <= 0) {
          if (ambiguousByteCount > 0) {
            str.append(recordDelimiterBytes, 0, ambiguousByteCount);
            bytesConsumed += ambiguousByteCount;
          }
          break; // EOF
        }
      }
      for (; bufferPosn < bufferLength; ++bufferPosn) {
        if (buffer[bufferPosn] == recordDelimiterBytes[delPosn]) {
          delPosn++;
          if (delPosn >= recordDelimiterBytes.length) {
            bufferPosn++;
            break;
          }
        } else if (delPosn != 0) {
          bufferPosn--;
          delPosn = 0;
        }
      }
      int readLength = bufferPosn - startPosn;
      bytesConsumed += readLength;
      int appendLength = readLength - delPosn;
      if (appendLength > maxLineLength - txtLength) {
        appendLength = maxLineLength - txtLength;
      }
      bytesConsumed += ambiguousByteCount;
      if (appendLength >= 0 && ambiguousByteCount > 0) {
        //appending the ambiguous characters (refer case 2.2)
        str.append(recordDelimiterBytes, 0, ambiguousByteCount);
        ambiguousByteCount = 0;
        // since it is now certain that the split did not split a delimiter we
        // should not read the next record: clear the flag otherwise duplicate
        // records could be generated
        unsetNeedAdditionalRecordAfterSplit();
      }
      if (appendLength > 0) {
        str.append(buffer, startPosn, appendLength);
        txtLength += appendLength;
      }
      if (bufferPosn >= bufferLength) {
        if (delPosn > 0 && delPosn < recordDelimiterBytes.length) {
          ambiguousByteCount = delPosn;
          bytesConsumed -= ambiguousByteCount; //to be consumed in next
        }
      }
    } while (delPosn < recordDelimiterBytes.length
        && bytesConsumed < maxBytesToConsume);
    if (bytesConsumed > Integer.MAX_VALUE) {
      throw new IOException("Too many bytes before delimiter: " + bytesConsumed);
    }
    return (int) bytesConsumed;
  }

  /**
   * Read from the InputStream into the given Text.
   * @param str the object to store the given line
   * @param maxLineLength the maximum number of bytes to store into str.
   * @return the number of bytes read including the newline
   * @throws IOException if the underlying stream throws
   */
  public int readLine(Text str, int maxLineLength) throws IOException {
    return readLine(str, maxLineLength, Integer.MAX_VALUE);
  }

  /**
   * Read from the InputStream into the given Text.
   * @param str the object to store the given line
   * @return the number of bytes read including the newline
   * @throws IOException if the underlying stream throws
   */
  public int readLine(Text str) throws IOException {
    return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE);
  }

  protected int getBufferPosn() {
    return bufferPosn;
  }

  protected int getBufferSize() {
    return bufferSize;
  }

  protected void unsetNeedAdditionalRecordAfterSplit() {
    // needed for custom multi byte line delimiters only
    // see MAPREDUCE-6549 for details
  }
}


text:
package org.gluu.oxauth.client;

import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.gluu.oxauth.model.common.AuthorizationMethod;
import org.gluu.oxauth.model.crypto.OxAuthCryptoProvider;
import org.gluu.oxauth.model.jwe.Jwe;
import org.gluu.oxauth.model.jwt.Jwt;
import org.gluu.oxauth.model.userinfo.UserInfoErrorResponseType;
import org.gluu.oxauth.model.util.JwtUtil;
import org.gluu.oxauth.model.util.Util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Encapsulates functionality to make user info request calls to an authorization server via REST Services.
 *
 * @author Javier Rojas Blum
 * @version December 26, 2016
 */
public class UserInfoClient extends BaseClient<UserInfoRequest, UserInfoResponse> {

    private String sharedKey;
    private PrivateKey privateKey;
    private String jwksUri;

    /**
     * Constructs an User Info client by providing a REST url where the service is located.
     *
     * @param url The REST Service location.
     */
    public UserInfoClient(String url) {
        super(url);
    }

    @Override
    public String getHttpMethod() {
        if (request.getAuthorizationMethod() == null
                || request.getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD
                || request.getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
            return HttpMethod.GET;
        } else /*if (request.getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER)*/ {
            return HttpMethod.POST;
        }
    }

    /**
     * Executes the call to the REST Service and processes the response.
     *
     * @param accessToken The access token obtained from the oxAuth authorization request.
     * @return The service response.
     */
    public UserInfoResponse execUserInfo(String accessToken) {
        setRequest(new UserInfoRequest(accessToken));

        return exec();
    }

    /**
     * Executes the call to the REST Service and processes the response.
     *
     * @return The service response.
     */
    public UserInfoResponse exec() {
        // Prepare request parameters
        initClientRequest();

        Builder clientRequest = null;
        if (getRequest().getAuthorizationMethod() == null
                || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD) {
            if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            	clientRequest = webTarget.request();
                clientRequest.header("Authorization", "Bearer " + getRequest().getAccessToken());
            }
        } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
            if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
                requestForm.param("access_token", getRequest().getAccessToken());
            }
        } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
            if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            	addReqParam("access_token", getRequest().getAccessToken().toString());
            }
        }

        if (clientRequest == null) {
        	clientRequest = webTarget.request();
        }

        clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
//      clientRequest.setHttpMethod(getHttpMethod());

        // Call REST Service and handle response
        try {
            if (getRequest().getAuthorizationMethod() == null
                    || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD
                    || getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
                clientResponse = clientRequest.buildGet().invoke();
            } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
                clientResponse = clientRequest.buildPost(Entity.form(requestForm)).invoke();
            }

            int status = clientResponse.getStatus();

            setResponse(new UserInfoResponse(status));

            String entity = clientResponse.readEntity(String.class);
            getResponse().setEntity(entity);
            getResponse().setHeaders(clientResponse.getMetadata());
            if (StringUtils.isNotBlank(entity)) {
                List<Object> contentType = clientResponse.getHeaders().get("Content-Type");
                if (contentType != null && contentType.contains("application/jwt")) {
                    String[] jwtParts = entity.split("\\.");
                    if (jwtParts.length == 5) {
                        byte[] sharedSymmetricKey = sharedKey != null ? sharedKey.getBytes(Util.UTF8_STRING_ENCODING) : null;
                        Jwe jwe = Jwe.parse(entity, privateKey, sharedSymmetricKey);
                        getResponse().setClaims(jwe.getClaims().toMap());
                    } else {
                        Jwt jwt = Jwt.parse(entity);

                        OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
                        boolean signatureVerified = cryptoProvider.verifySignature(
                                jwt.getSigningInput(),
                                jwt.getEncodedSignature(),
                                jwt.getHeader().getKeyId(),
                                JwtUtil.getJSONWebKeys(jwksUri),
                                sharedKey,
                                jwt.getHeader().getSignatureAlgorithm());

                        if (signatureVerified) {
                            getResponse().setClaims(jwt.getClaims().toMap());
                        }
                    }
                } else {
                    try {
                        JSONObject jsonObj = new JSONObject(entity);

                        if (jsonObj.has("error")) {
                            getResponse().setErrorType(UserInfoErrorResponseType.fromString(jsonObj.getString("error")));
                            jsonObj.remove("error");
                        }
                        if (jsonObj.has("error_description")) {
                            getResponse().setErrorDescription(jsonObj.getString("error_description"));
                            jsonObj.remove("error_description");
                        }
                        if (jsonObj.has("error_uri")) {
                            getResponse().setErrorUri(jsonObj.getString("error_uri"));
                            jsonObj.remove("error_uri");
                        }

                        for (Iterator<String> iterator = jsonObj.keys(); iterator.hasNext(); ) {
                            String key = iterator.next();
                            List<String> values = new ArrayList<String>();

                            JSONArray jsonArray = jsonObj.optJSONArray(key);
                            if (jsonArray != null) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    String value = jsonArray.optString(i);
                                    if (value != null) {
                                        values.add(value);
                                    }
                                }
                            } else {
                                String value = jsonObj.optString(key);
                                if (value != null) {
                                    values.add(value);
                                }
                            }

                            getResponse().getClaims().put(key, values);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConnection();
        }

        return getResponse();
    }

    public void setSharedKey(String sharedKey) {
        this.sharedKey = sharedKey;
    }

    public void setPrivateKey(PrivateKey privateKey) {
        this.privateKey = privateKey;
    }

    public String getJwksUri() {
        return jwksUri;
    }

    public void setJwksUri(String jwksUri) {
        this.jwksUri = jwksUri;
    }
}


text:
package test.listeners.github2385;

import org.testng.annotations.Test;

public class TestMultiInheritSample implements ITestClassInterface, ITestInterface {

  @Test
  public void testMultiInherit() {}
}


text:
<!-- Start www/bootstrap.jsx -->

# [bootstrap.jsx](bootstrap.jsx)

This file initializes zland and launches the app on cordova deviceready event
(or immediately if its build for browser)

<!-- End www/bootstrap.jsx -->


text:
chronos-collectd-plugin
=======================

A [collectd](http://collectd.org) plugin for [Chronos](https://github.com/mesos/chronos) running on
[Apache Mesos](http://mesos.apache.org) using collectd's
[Python plugin](http://collectd.org/documentation/manpages/collectd-python.5.shtml).

This plugin is inspired by the [Mesos Python plugin](https://github.com/rayrod2030/collectd-mesos).

It collects data from Chronos's `/metrics` API endpoint.

Install
-------
 1. Place `chronos.py` in /opt/collectd/lib/collectd/plugins/python (assuming you have collectd installed to /opt/collectd).
 2. Configure the plugin (see below).
 3. Restart collectd.

Configuration
-------------
 * See `chronos.conf`

Requirements
------------
 * collectd 4.9+
 * Chronos 2.1.0 or greater

License
-------
This software is released under the Apache License


text:
import oauth2 as oauth
import simplejson as json
import urllib2
import urllib

class YelpApi:
  token = ""
  consumer = ""
  search_url =  "http://api.yelp.com/v2/search"
  biz_url = "http://api.yelp.com/v2/business/"
  request_url = ""
  oauth_request =""

  def  __init__(self, consumer_key, consumer_secret, token_key, token_secret):
    self.consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
    self.token = oauth.Token(key=token_key, secret=token_secret)

  def biz_search(self, biz_name):
    self.request_url = "%s%s" % (self.biz_url, biz_name)
    self.init_request()
    return self.send_request()

  def search(self, params):
    if not params:
	  raise Exception('No params specified - search halted')

    encoded_params = urllib.urlencode(params)
    self.request_url = "%s?%s" % (self.search_url, encoded_params)
    self.init_request()
    return self.send_request()

  def init_request(self):
    self.oauth_request = oauth.Request('GET', self.request_url, {})
    self.oauth_request.update({'oauth_nonce': oauth.generate_nonce(),
                       'oauth_timestamp': oauth.generate_timestamp(),
                       'oauth_token': self.token.key,
                       'oauth_consumer_key': self.consumer.key})
    self.oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), self.consumer, self.token)
    self.request_url = self.oauth_request.to_url()

  def send_request(self):
    try:
      conn = urllib2.urlopen(self.request_url, None)
      try:
        response = json.loads(conn.read())
      finally:
        conn.close()
    except urllib2.HTTPError, error:
        raise Exception('Yo dawg, you got mad HTTP problems up in yo grill : %s' % error)

    return response


text:
<?php

use Symfony\Bundle\FrameworkBundle\Console\Application as BaseApplication;
use Composer\{Composer, Factory};
use Composer\IO\{ConsoleIO, IOInterface};
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Application extends BaseApplication
{
    /** @var IOInterface */
    protected $io;

    /** @var Composer */
    protected $composer;

    /**
     * {@inheritdoc}
     */
    public function doRun(InputInterface $input, OutputInterface $output)
    {
        $this->io = new ConsoleIO($input, $output, $this->getHelperSet());

        return parent::doRun($input, $output);
    }

    /**
     * @param bool $required
     * @param null $config
     * @return Composer
     */
    public function getComposer($required = true, $config = null)
    {
        if (null === $this->composer) {
            try {
                $this->composer = Factory::create($this->io, $config);
            } catch (\InvalidArgumentException $e) {
                echo $e;
                exit(1);
            }
        }

        return $this->composer;
    }
}


text:
"""
test_cellulist
----------------------------------

Tests for `cellulist` module.
"""

import unittest
from cellulist import cell_list

class TestCellulist(unittest.TestCase):

    def setUp(self):
        pass

    def test_cellulist(self):
        pass

    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main()


text:
class CreateCrawlerLogs < ActiveRecord::Migration
  def change
    create_table :crawler_logs do |t|
      t.references :crawler, index: true, foreign_key: true
      t.string :message, default: ""
      t.integer :processed, default: 0
      t.integer :orders_count, default: 0

      t.timestamps null: false
    end
  end
end


text:
  View source  Improve this doc
$rootScopeProvider

service in module ng

Description

Provider for the $rootScope service.

Methods

digestTtl(limit)

Sets the number of $digest iterations the scope should attempt to execute before giving up and assuming that the model is unstable.

The current default is 10 iterations.

In complex applications it's possible that the dependencies between $watchs will result in several digest iterations.
However if an application needs more than the default 10 digest iterations for its model to stabilize then you should investigate what is causing the model to continuously change during the digest.

Increasing the TTL could have performance implications, so you should not change it without proper justification.

Parameters

Param	Type	Details

limit	number

The number of digest iterations.


text:
package com.github.perf.http.jetty;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class JettyHttpHandler extends AbstractHandler {

	public void handle(String target, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		baseRequest.setHandled(true);
		if (!dispatch(request.getRequestURI(), request, response)) {
			if (request.getMethod().equals("POST"))
				response.getWriter().print(request.getParameter("param"));
			else
				response.getWriter().print("Test");
		}
	}

	private boolean dispatch(String requestURI,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if ("/login".equals(requestURI)) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			if ("test".equals(username) && "pass".equals(password)) {
				response.getWriter().print("Session created " + request.getSession(true).getId());
			} else {
				response.getWriter().print("Wrong user name or password");
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			}
			return true;
		}
		return false;
	}

}


text:
using System;
using System.Text.RegularExpressions;
using System.Text;

namespace _04_CubicMessages
{
    public class CubicMessages
    {
        public static void Main()
        {
            //string pattern = @"^(\d+)([A-Za-z]+)([^A-Za-z]*)$";

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "Over!")
                {
                    break;
                }

                int n = int.Parse(Console.ReadLine());
                string pattern =  @"^(\d+)([A-Za-z]{"+n+"})([^A-Za-z]*)$" ;

                Match match = Regex.Match(input, pattern);

                if (match.Success)
                {
                    string message = match.Groups[2].Value;
                    string indexesString = match.Groups[1].Value + match.Groups[3].Value;

                    Console.WriteLine("{0} == {1}", message, StringFromIndexNums(message, indexesString));
                }
            }
        }

        private static string StringFromIndexNums(string s, string indexesString)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char symbol in indexesString)
            {
                if (char.IsDigit(symbol))
                {
                    int currentIndex = int.Parse(symbol.ToString());
                    if (currentIndex >= 0 && currentIndex < s.Length)
                    {
                        sb.Append(s[currentIndex]);
                    }
                    else
                    {
                        sb.Append(' ');
                    }
                }
            }

            return sb.ToString();
        }
    }
}


text:
//===-- HexagonRegisterInfo.cpp - Hexagon Register Information ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the Hexagon implementation of the TargetRegisterInfo
// class.
//
//===----------------------------------------------------------------------===//

#include "HexagonRegisterInfo.h"
#include "Hexagon.h"
#include "HexagonMachineFunctionInfo.h"
#include "HexagonSubtarget.h"
#include "HexagonTargetMachine.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"

using namespace llvm;

HexagonRegisterInfo::HexagonRegisterInfo()
    : HexagonGenRegisterInfo(Hexagon::R31) {}

bool HexagonRegisterInfo::isEHReturnCalleeSaveReg(unsigned R) const {
  return R == Hexagon::R0 || R == Hexagon::R1 || R == Hexagon::R2 ||
         R == Hexagon::R3 || R == Hexagon::D0 || R == Hexagon::D1;
}

bool HexagonRegisterInfo::isCalleeSaveReg(unsigned Reg) const {
  return Hexagon::R16 <= Reg && Reg <= Hexagon::R27;
}

const MCPhysReg *
HexagonRegisterInfo::getCallerSavedRegs(const MachineFunction *MF) const {
  static const MCPhysReg CallerSavedRegsV4[] = {
    Hexagon::R0, Hexagon::R1, Hexagon::R2, Hexagon::R3, Hexagon::R4,
    Hexagon::R5, Hexagon::R6, Hexagon::R7, Hexagon::R8, Hexagon::R9,
    Hexagon::R10, Hexagon::R11, Hexagon::R12, Hexagon::R13, Hexagon::R14,
    Hexagon::R15, 0
  };

  auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
  switch (HST.getHexagonArchVersion()) {
  case HexagonSubtarget::V4:
  case HexagonSubtarget::V5:
    return CallerSavedRegsV4;
  }
  llvm_unreachable(
    "Callee saved registers requested for unknown archtecture version");
}

const MCPhysReg *
HexagonRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
  static const MCPhysReg CalleeSavedRegsV3[] = {
    Hexagon::R16,   Hexagon::R17,   Hexagon::R18,   Hexagon::R19,
    Hexagon::R20,   Hexagon::R21,   Hexagon::R22,   Hexagon::R23,
    Hexagon::R24,   Hexagon::R25,   Hexagon::R26,   Hexagon::R27, 0
  };

  switch (MF->getSubtarget<HexagonSubtarget>().getHexagonArchVersion()) {
  case HexagonSubtarget::V4:
  case HexagonSubtarget::V5:
    return CalleeSavedRegsV3;
  }
  llvm_unreachable("Callee saved registers requested for unknown architecture "
                   "version");
}

BitVector HexagonRegisterInfo::getReservedRegs(const MachineFunction &MF)
  const {
  BitVector Reserved(getNumRegs());
  Reserved.set(HEXAGON_RESERVED_REG_1);
  Reserved.set(HEXAGON_RESERVED_REG_2);
  Reserved.set(Hexagon::R29);
  Reserved.set(Hexagon::R30);
  Reserved.set(Hexagon::R31);
  Reserved.set(Hexagon::D14);
  Reserved.set(Hexagon::D15);
  Reserved.set(Hexagon::LC0);
  Reserved.set(Hexagon::LC1);
  Reserved.set(Hexagon::SA0);
  Reserved.set(Hexagon::SA1);
  return Reserved;
}

void HexagonRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
                                              int SPAdj, unsigned FIOp,
                                              RegScavenger *RS) const {
  //
  // Hexagon_TODO: Do we need to enforce this for Hexagon?
  assert(SPAdj == 0 && "Unexpected");

  MachineInstr &MI = *II;

  MachineBasicBlock &MB = *MI.getParent();
  MachineFunction &MF = *MB.getParent();
  MachineFrameInfo &MFI = *MF.getFrameInfo();
  auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
  auto &HII = *HST.getInstrInfo();
  auto &HFI = *HST.getFrameLowering();

  int FI = MI.getOperand(FIOp).getIndex();
  int Offset = MFI.getObjectOffset(FI) + MI.getOperand(FIOp+1).getImm();
  bool HasAlloca = MFI.hasVarSizedObjects();
  bool HasAlign = needsStackRealignment(MF);

  // XXX: Fixed objects cannot be accessed through SP if there are aligned
  // objects in the local frame, or if there are dynamically allocated objects.
  // In such cases, there has to be FP available.
  if (!HFI.hasFP(MF)) {
    assert(!HasAlloca && !HasAlign && "This function must have frame pointer");
    // We will not reserve space on the stack for the lr and fp registers.
    Offset -= 8;
  }

  unsigned SP = getStackRegister(), FP = getFrameRegister();
  unsigned AP = 0;
  if (MachineInstr *AI = HFI.getAlignaInstr(MF))
    AP = AI->getOperand(0).getReg();
  unsigned FrameSize = MFI.getStackSize();

  // Special handling of dbg_value instructions and INLINEASM.
  if (MI.isDebugValue() || MI.isInlineAsm()) {
    MI.getOperand(FIOp).ChangeToRegister(SP, false /*isDef*/);
    MI.getOperand(FIOp+1).ChangeToImmediate(Offset+FrameSize);
    return;
  }

  bool UseFP = false, UseAP = false;  // Default: use SP.
  if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
    UseFP = HasAlloca || HasAlign;
  } else {
    if (HasAlloca) {
      if (HasAlign)
        UseAP = true;
      else
        UseFP = true;
    }
  }

  unsigned Opc = MI.getOpcode();
  bool ValidSP = HII.isValidOffset(Opc, FrameSize+Offset);
  bool ValidFP = HII.isValidOffset(Opc, Offset);

  // Calculate the actual offset in the instruction.
  int64_t RealOffset = Offset;
  if (!UseFP && !UseAP)
    RealOffset = FrameSize+Offset;

  switch (Opc) {
    case Hexagon::TFR_FIA:
      MI.setDesc(HII.get(Hexagon::A2_addi));
      MI.getOperand(FIOp).ChangeToImmediate(RealOffset);
      MI.RemoveOperand(FIOp+1);
      return;
    case Hexagon::TFR_FI:
      // Set up the instruction for updating below.
      MI.setDesc(HII.get(Hexagon::A2_addi));
      break;
  }

  unsigned BP = 0;
  bool Valid = false;
  if (UseFP) {
    BP = FP;
    Valid = ValidFP;
  } else if (UseAP) {
    BP = AP;
    Valid = ValidFP;
  } else {
    BP = SP;
    Valid = ValidSP;
  }

  if (Valid) {
    MI.getOperand(FIOp).ChangeToRegister(BP, false);
    MI.getOperand(FIOp+1).ChangeToImmediate(RealOffset);
    return;
  }

#ifndef NDEBUG
  const Function *F = MF.getFunction();
  dbgs() << "In function ";
  if (F) dbgs() << F->getName();
  else   dbgs() << "<?>";
  dbgs() << ", BB#" << MB.getNumber() << "\n" << MI;
#endif
  llvm_unreachable("Unhandled instruction");
}

unsigned HexagonRegisterInfo::getRARegister() const {
  return Hexagon::R31;
}

unsigned HexagonRegisterInfo::getFrameRegister(const MachineFunction
                                               &MF) const {
  const HexagonFrameLowering *TFI = getFrameLowering(MF);
  if (TFI->hasFP(MF))
    return Hexagon::R30;
  return Hexagon::R29;
}

unsigned HexagonRegisterInfo::getFrameRegister() const {
  return Hexagon::R30;
}

unsigned HexagonRegisterInfo::getStackRegister() const {
  return Hexagon::R29;
}

bool
HexagonRegisterInfo::useFPForScavengingIndex(const MachineFunction &MF) const {
  const HexagonFrameLowering *TFI = getFrameLowering(MF);
  return TFI->hasFP(MF);
}

bool
HexagonRegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
  const MachineFrameInfo *MFI = MF.getFrameInfo();
  return MFI->getMaxAlignment() > 8;
}

unsigned HexagonRegisterInfo::getFirstCallerSavedNonParamReg() const {
  return Hexagon::R6;
}

#define GET_REGINFO_TARGET_DESC
#include "HexagonGenRegisterInfo.inc"


text:
using System;

namespace Xwt
{
	public class KeyEventArgs: EventArgs
	{
		public KeyEventArgs (Key key, ModifierKeys modifiers, bool isRepeat, long timestamp)
		{
			this.Key = key;
			this.Modifiers = modifiers;
			this.IsRepeat = isRepeat;
			this.Timestamp = timestamp;
		}

		public Key Key { get; private set; }

		public ModifierKeys Modifiers { get; private set; }

		public bool IsRepeat { get; private set; }

		public long Timestamp { get; private set; }

		public bool Handled { get; set; }
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>MysoreScript: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

MysoreScript

AST

NewExpr

AST::NewExpr Member List

This is the complete list of members for AST::NewExpr, including all inherited members.

cache	AST::Expression	protected

compile(Compiler::Context &c) override final	AST::Expression	inlinevirtual

evaluate(Interpreter::Context &c)	AST::Expression

interpret(Interpreter::Context &c) override final	AST::Expression	inlinevirtual

isConstantExpression()	AST::Expression	inlinevirtual

<address class="footer">
Generated on Thu Jun 1 2017 18:33:56 for MysoreScript by

 1.8.12
</address>


text:
from django.db import models

class Statement(models.Model):
    """
    A short (<255) chat message, tweet, forum post, etc.
    """

    text = models.CharField(
        unique=True,
        blank=False,
        null=False,
        max_length=255
    )

    extra_data = models.CharField(max_length=500)

    def __str__(self):
        if len(self.text.strip()) > 60:
            return '{}...'.format(self.text[:57])
        elif len(self.text.strip()) > 0:
            return self.text
        return '<empty>'

class Response(models.Model):
    """
    Connection between a response and the statement that triggered it.

    Comparble to a ManyToMany "through" table, but without the M2M indexing/relations.

    Only the text and number of times it has occurred are currently stored.
    Might be useful to store additional features like language, location(s)/region(s),
    first created datetime(s), username, user full name, user gender, etc.
    A the very least occurrences should be an FK to a meta-data table with this info.
    """

    statement = models.ForeignKey(
        'Statement',
        related_name='in_response_to'
    )

    response = models.ForeignKey(
        'Statement',
        related_name='+'
    )

    unique_together = (('statement', 'response'),)

    occurrence = models.PositiveIntegerField(default=0)

    def __str__(self):
        s = self.statement.text if len(self.statement.text) <= 20 else self.statement.text[:17] + '...'
        s += ' => '
        s += self.response.text if len(self.response.text) <= 40 else self.response.text[:37] + '...'
        return s


text:
/*
 * Encoders/Decoders for the various AMP Types that we support.
 *
 */

/* For INFINITY macro, etc */
#define _ISOC99_SOURCE

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <math.h>
#include <ctype.h>

#include "amp.h"
#include "amp_internal.h"
#include "buftoll.h"

/* AMP Type: Bytes (known as String in Twisted) */

/* Store an array of bytes into an AMP_Box. */
int amp_put_bytes(AMP_Box_T *box, const char *key,
                  const unsigned char *buf, int buf_size)
{
    return _amp_put_buf(box, key, buf, buf_size);
}

/* Retrieve an array of bytes from an AMP_Box. */
int amp_get_bytes(AMP_Box_T *box, const char *key,
                  unsigned char **buf, int *size)
{
    return _amp_get_buf(box, key, buf, size);
}

/* Encode and store an array of bytes given as a NULL-terminated
 * C string. Does not store the extra NULL byte.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_put_cstring(AMP_Box_T *box, const char *key, const char *value)
{
    return _amp_put_buf(box, key, (unsigned char*)value, strlen(value));
}

/* AMP Type: Boolean */

/* Encode and store a boolean value into an AMP_Box.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_put_bool(AMP_Box_T *box, const char *key, int value)
{
    const char *buf;
    if (value)
        buf = "True";
    else
        buf = "False";

    return _amp_put_buf(box, key, (unsigned char *)buf, strlen(buf));
}

/* Retrieve and decode a boolean value from an AMP_Box.
 * If the boolean is true `value' is set to 1, otherwise it is set to 0.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_get_bool(AMP_Box_T *box, const char *key, int *value)
{
    int err;
    unsigned char *buf;
    int buf_size;

    if ( (err = _amp_get_buf(box, key, &buf, &buf_size)) != 0)
        return err;

    if (buf_size == 4 && memcmp(buf, "True", buf_size) == 0)
        *value = 1;
    else if (buf_size == 5 && memcmp(buf, "False", buf_size) == 0)
        *value = 0;
    else
        return AMP_DECODE_ERROR;

    return 0;
}

/* Encode and store a `long long' into an AMP_Box.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_put_long_long(AMP_Box_T *box, const char *key,
                      long long value)
{
    /* A ludicrous way to determine the maximum number of base-10 digits
     * required to represent any `long long' on this system.
     *
     * add 3 because:
     *         1) round up because casting to `int' truncates the `double'
     *         2) need extra byte to hold possible "-" sign char
     *         3) extra byte to hold NUL-terminator
     *
     * Any sane person would have just done char buf[100];
     */
    int bufLen = ((int)(log10(pow(2, sizeof(long long)*CHAR_BIT)))) + 3;
    char buf[bufLen];

    snprintf(buf, bufLen, "%lld", value);
    return _amp_put_buf(box, key, (unsigned char *)buf, strlen(buf));
}

/* Retrieve and decode a `long long' from an AMP_Box.
 * Stores the decoded integer in to the `long long' pointed to by `value'.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_get_long_long(AMP_Box_T *box, const char *key,
                      long long *value)
{
    int err;
    unsigned char *buf;
    int buf_size;

    if ( (err = _amp_get_buf(box, key, &buf, &buf_size)) != 0)
        return err;

    *value = buftoll(buf, buf_size, &err);

    /* `err' will have been set to 0 if conversion was successful.
     * Otherwise it will be an AMP_* error code. */
    return err;
}

/* AMP Type: Integer (C type `int') */

/* Encode and store a `int' into an AMP_Box.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_put_int(AMP_Box_T *box, const char *key, int value)
{
    /* A ludicrous way to determine the maximum number of base-10 digits
     * required to represent any `int' on this system. */
    /* add 3 because:
     *         1) round up because casting to `int' truncates the `double'
     *         2) need extra byte to hold possible "-" sign char
     *         3) extra byte to hold NUL-terminator
     *
     * Any sane person would have just done char buf[100];
     */
    int bufLen = ((int)(log10(pow(2, sizeof(int)*CHAR_BIT)))) + 3;
    char buf[bufLen];

    snprintf(buf, bufLen, "%d", value);
    return _amp_put_buf(box, key, (unsigned char *)buf, strlen(buf));
}

/* Retrieve and decode a `int' from an AMP_Box.
 * Stores the decoded integer in to the `int' pointed to by `value'.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_get_int(AMP_Box_T *box, const char *key, int *value)
{
    int err;
    unsigned char *buf;
    int buf_size;
    long long tmp = 0;

    if ( (err = _amp_get_buf(box, key, &buf, &buf_size)) != 0)
        return err;

    tmp = buftoll(buf, buf_size, &err);
    if (err == 0)
    {
        if (tmp >= INT_MIN && tmp <= INT_MAX)
        {
            *value = (int)tmp;
            return 0;
        }
        else
        {
            return AMP_OUT_OF_RANGE;
        }
    }
    else
    {
        /* `err' will have been set to 0 if conversion was successful.
         * Otherwise it will be an AMP_* error code. */
        return err;
    }
}

/* Encode and store an `unsigned int' into an AMP_Box.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_put_uint(AMP_Box_T *box, const char *key, unsigned int value)
{
    /* calculate maximum number of base-10 digits required to represent
     * any `unsigned int' on this system. same as for amp_put_int(), minus
     * one character since we won't need a '-' sign. */
    int bufLen = ((int)(log10(pow(2, sizeof(unsigned int)*8)))) + 2;
    char buf[bufLen];

    snprintf(buf, bufLen, "%u", value);
    return _amp_put_buf(box, key, (unsigned char *)buf, strlen(buf));
}

/* Retrieve and decode an `unsigned int' from an AMP_Box.
 * Stores the decoded integer in to the `unsigned int' pointed to by `value'.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_get_uint(AMP_Box_T *box, const char *key, unsigned int *value)
{
    int err;
    unsigned char *buf;
    int buf_size;
    long long tmp = 0;

    if ( (err = _amp_get_buf(box, key, &buf, &buf_size)) != 0)
        return err;

    tmp = buftoll(buf, buf_size, &err);
    if (err == 0)
    {
        if (tmp >= 0 && tmp <= UINT_MAX)
        {
            *value = (unsigned int)tmp;
            return 0;
        }
        else
        {
            return AMP_OUT_OF_RANGE;
        }
    }
    else
    {
        /* `err' will have been set to 0 if conversion was successful.
         * Otherwise it will be an AMP_* error code. */
        return err;
    }
}

/* AMP Type: Float (C `double') */

/* Encode and store a `double' in to an AMP_Box.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_put_double(AMP_Box_T *box, const char *key, double value)
{
    unsigned char buf[100];
    int buf_size;

    if (isnan(value))
    {
        buf_size = 3;
        strncpy((char *)buf, "nan", buf_size);
    }
    else if (isinf(value))
    {
        if (signbit(value) == 0)
        {
            /* positive */
            buf_size = 3;
            strncpy((char *)buf, "inf", buf_size);
        }
        else
        {
            /* negative */
            buf_size = 4;
            strncpy((char *)buf, "-inf", buf_size);
        }
    }
    else
    {
        /* not Infinity or NaN so assume a normal float */
        buf_size = snprintf((char *)buf, 100, "%.17f", value);
    }

    return _amp_put_buf(box, key, buf, buf_size);
}

/* Retrieve and decode a `double' from an AMP_Box.
 * Stores the decoded floating-point number in to the `double'
 * pointed to by `value'.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_get_double(AMP_Box_T *box, const char *key, double *value)
{
    unsigned char *buf;
    int buf_size;
    int ret;
    int base = 10;    /* we only parse base-10 numbers */
    int any = 0;      /* have we parsed any digits at all? */
    int neg = 0;      /* have parsed a negative sign? */
    int gotDot = 0;   /* have we parsed a dot ('.'), yet? */
    double acc = 0.0; /* accumulator */
    double fractionFactor = 0.1;

    int size;         /* copy of buf_size that we decrement in the loop below */
    int c;            /* the character being parsed */
    unsigned char *s; /* pointer in to input buffer */

    if ( (ret = _amp_get_buf(box, key, &buf, &buf_size)) != 0)
        return ret;

    s = buf;
    size = buf_size;

    if (size < 1)
        return AMP_DECODE_ERROR;

    /* Got at least one char */

    /* check for special values */
    if (size == 3)
    {
        if (strncmp((char *)buf, "inf", 3) == 0)
        {
            /* Return Positive Infinity */
            *value = INFINITY;
            return 0;
        }
        else if (strncmp((char *)buf, "nan", 3) == 0)
        {
            /* Return Not-a-number */
            *value = NAN;
            return 0;
        }
    }
    else if (size == 4 && strncmp((char *)buf, "-inf", 4) == 0)
    {
            /* Return Negative Infinity */
            *value = INFINITY * -1;
            return 0;
    }

    /* Not a recognized special value */

    /* Try to parse it as decimal digits with an optional leading sign
     * character (+ or -). */

    c = *s; /* grab first char - guaranteed to have at least one char in buf at this point */

    if (c == '+')
    {
        /* skip to next char - neg already 0 */
        s++;
        size--;
    }
    else if (c == '-')
    {
        /* skip to next char - set neg = 1 */
        s++;
        size--;
        neg = 1;
    }

    while (size-- > 0)
    {
        c = *s++;

        if (isdigit(c))
        {
            c -= '0';
        }
        else
        {
            if (c == '.' && !gotDot && any)
            {
                /* 1) found a decimal point
                 * 2) haven't found one before
                 * 3) have parsed at least one digit before now */

                gotDot = 1;
                continue;
            }
            else
            {
                return AMP_DECODE_ERROR;
            }
        }

        any = 1; /* have seen at least one digit now */

        if (!gotDot)
        {
            /* parsing integer portion */

            if (neg)
            {
                /* building a negative value... */
                acc *= base;
                acc -= c;
            }
            else
            {
                /* building a positive value... */
                acc *= base;
                acc += c;
            }
        }
        else
        {
            /* parsing fractional portion */

            if (neg)
            {
                /* building a negative value... */
                acc -= c * fractionFactor;
            }
            else
            {
                /* building a positive value... */
                acc += c * fractionFactor;
            }
            fractionFactor /= 10;
        }
    }

    if (!any) /* never parsed a digit */
        return AMP_DECODE_ERROR;

    *value = acc;
    return 0;
}

/* AMP Type: DateTime (C type `AMP_DateTime_T *') */

/* An AMP DateTime representation is always 32 bytes. */
#define AMP_DT_SIZE 32

/* Encode and store an `AMP_DateTime' in to an AMP_Box.
 * Returns 0 on success, or an AMP_* error code on failure. */
int amp_put_datetime(AMP_Box_T *box, const char *key, AMP_DateTime_T *value)
{
    /* snprintf() needs space for an extra \0 even though we don't need it. */
    static uint8_t buf[AMP_DT_SIZE+1];
    char sign;
    int offset_hour, offset_min;

    /* assert values are within valid ranges */
    if (value->year < 1  || value->year > 9999   ||
        value->month < 1 || value->month > 12    ||
        value->day < 1   || value->day > 31      ||
        value->hour < 0  || value->hour > 23     ||
        value->min < 0   || value->min > 59      ||
        value->sec < 0   || value->sec > 59      ||
        value->msec < 0  || value->msec > 999999 ||
        value->utc_offset < -1439 ||
        value->utc_offset > 1439)
    {
        return AMP_ENCODE_ERROR;
    }

    offset_hour = value->utc_offset / 60;
    offset_min  = value->utc_offset % 60;

    if (value->utc_offset >= 0)
        sign = '+';
    else
    {
        sign = '-';
        /* If utc_offset is negative, then these two should be negative too -
         * but we need them to be positive */
        offset_hour = -offset_hour;
        offset_min = -offset_min;
    }

    snprintf((char *)buf, AMP_DT_SIZE+1,
             "%04d-%02d-%02dT%02d:%02d:%02d.%06ld%c%02d:%02d",
             value->year,
             value->month,
             value->day,
             value->hour,
             value->min,
             value->sec,
             value->msec,
             sign,
             offset_hour,
             offset_min);

    return amp_put_bytes(box, key, buf, AMP_DT_SIZE);
}

/* Retrieve and decode an `AMP_DateTime' from an AMP_Box.
 * Stores the decoded data in to the `AMP_DateTime' pointed to by `value'.
 * Returns 0 on success, or an AMP_* error code on failure. On error,
 * `value' may have been partially filled in before the error was detected. */
int amp_get_datetime(AMP_Box_T *box, const char *key, AMP_DateTime_T *value)
{
    int ret;
    uint8_t *buf;
    int buf_size;
    int err;

    int offset_hour, offset_min;

    if ( (ret = amp_get_bytes(box, key, &buf, &buf_size)) != 0)
        return ret;

    if (buf_size != 32)
        return AMP_DECODE_ERROR;

    /* TODO - as a minor optimization write an integer parsing function that
     * works on `int's instead of `long long's */

    value->year = buftoll_range(buf, 4, 1, 9999, &err);
    if (err)
        return err;

    value->month = buftoll_range(buf+5, 2, 1, 12, &err);
    if (err)
        return err;

    value->day = buftoll_range(buf+8, 2, 1, 31, &err);
    if (err)
        return err;

    value->hour = buftoll_range(buf+11, 2, 0, 23, &err);
    if (err)
        return err;

    value->min = buftoll_range(buf+14, 2, 0, 59, &err);
    if (err)
        return err;

    value->sec = buftoll_range(buf+17, 2, 0, 59, &err);
    if (err)
        return err;

    value->msec = buftoll_range(buf+20, 6, 0, 999999, &err);
    if (err)
        return err;

    offset_hour = buftoll_range(buf+27, 2, 0, 23, &err);
    if (err)
        return err;

    offset_min = buftoll_range(buf+30, 2, 0, 59, &err);
    if (err)
        return err;

    if (buf[26] == '+')
    {
        value->utc_offset = offset_hour * 60 + offset_min;
    }
    else if (buf[26] == '-')
    {
        value->utc_offset = offset_hour * -60 - offset_min;
    }
    else
        return AMP_DECODE_ERROR;

    return 0;
}