text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{pageTitle}}</title>
</head>
<body>
    <pre>
/**
 * @description {{pageName}}
 * @author {{author}}
 * @time {{create_time}}
 */
    </pre>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
namespace Google.Cloud.Logging.V2.Snippets
{
    // [START logging_v2_generated_ConfigServiceV2_UpdateExclusion_sync]
    using Google.Cloud.Logging.V2;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedConfigServiceV2ClientSnippets
    {
        /// <summary>Snippet for UpdateExclusion</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void UpdateExclusionRequestObject()
        {
            // Create client
            ConfigServiceV2Client configServiceV2Client = ConfigServiceV2Client.Create();
            // Initialize request argument(s)
            UpdateExclusionRequest request = new UpdateExclusionRequest
            {
                LogExclusionName = LogExclusionName.FromProjectExclusion("[PROJECT]", "[EXCLUSION]"),
                Exclusion = new LogExclusion(),
                UpdateMask = new FieldMask(),
            };
            // Make the request
            LogExclusion response = configServiceV2Client.UpdateExclusion(request);
        }
    }
    // [END logging_v2_generated_ConfigServiceV2_UpdateExclusion_sync]
}


text:
package lib

import (
	"encoding/json"
	"fmt"
	"strconv"

	"k8s.io/klog/v2"
)

func (e *Exporter) collectV1(stats Stats, exposedHttpStatusCodes []string, collectorConfig CollectorConfig) error {
	e.databasesTotal.Set(float64(stats.DatabasesTotal))

	for name, nodeStats := range stats.StatsByNodeName {
		//fmt.Printf("%s -> %v\n", name, stats)
		//klog.Info(fmt.Sprintf("name: %s -> stats: %v\n", name, stats))
		e.nodeUp.WithLabelValues(name).Set(nodeStats.Up)
		e.nodeInfo.WithLabelValues(name, nodeStats.NodeInfo.Version, nodeStats.NodeInfo.Vendor.Name).Set(1)

		e.authCacheHits.WithLabelValues(name).Set(nodeStats.Couchdb.AuthCacheHits.Current)
		e.authCacheMisses.WithLabelValues(name).Set(nodeStats.Couchdb.AuthCacheMisses.Current)
		e.databaseReads.WithLabelValues(name).Set(nodeStats.Couchdb.DatabaseReads.Current)
		e.databaseWrites.WithLabelValues(name).Set(nodeStats.Couchdb.DatabaseWrites.Current)
		e.openDatabases.WithLabelValues(name).Set(nodeStats.Couchdb.OpenDatabases.Current)
		e.openOsFiles.WithLabelValues(name).Set(nodeStats.Couchdb.OpenOsFiles.Current)
		e.requestTime.WithLabelValues(name, "Current").Set(nodeStats.Couchdb.RequestTime.Current)

		for _, code := range exposedHttpStatusCodes {
			if _, ok := nodeStats.HttpdStatusCodes[code]; ok {
				e.httpdStatusCodes.WithLabelValues(code, name).Set(nodeStats.HttpdStatusCodes[code].Current)
			}
		}

		e.httpdRequestMethods.WithLabelValues("COPY", name).Set(nodeStats.HttpdRequestMethods.COPY.Current)
		e.httpdRequestMethods.WithLabelValues("DELETE", name).Set(nodeStats.HttpdRequestMethods.DELETE.Current)
		e.httpdRequestMethods.WithLabelValues("GET", name).Set(nodeStats.HttpdRequestMethods.GET.Current)
		e.httpdRequestMethods.WithLabelValues("HEAD", name).Set(nodeStats.HttpdRequestMethods.HEAD.Current)
		e.httpdRequestMethods.WithLabelValues("POST", name).Set(nodeStats.HttpdRequestMethods.POST.Current)
		e.httpdRequestMethods.WithLabelValues("PUT", name).Set(nodeStats.HttpdRequestMethods.PUT.Current)

		e.bulkRequests.WithLabelValues(name).Set(nodeStats.Httpd.BulkRequests.Current)
		e.clientsRequestingChanges.WithLabelValues(name).Set(nodeStats.Httpd.ClientsRequestingChanges.Current)
		e.requests.WithLabelValues(name).Set(nodeStats.Httpd.Requests.Current)
		e.temporaryViewReads.WithLabelValues(name).Set(nodeStats.Httpd.TemporaryViewReads.Current)
		e.viewReads.WithLabelValues(name).Set(nodeStats.Httpd.ViewReads.Current)
	}

	for _, dbName := range collectorConfig.ObservedDatabases {
		e.dbInfo.WithLabelValues(
			dbName,
			strconv.FormatFloat(stats.DatabaseStatsByDbName[dbName].DiskFormatVersion, 'G', -1, 32),
			strconv.FormatBool(stats.DatabaseStatsByDbName[dbName].Props.Partitioned),
		).Set(1)
		e.diskSize.WithLabelValues(dbName).Set(stats.DatabaseStatsByDbName[dbName].DiskSize)
		e.dataSize.WithLabelValues(dbName).Set(stats.DatabaseStatsByDbName[dbName].DataSize)
		e.docCount.WithLabelValues(dbName).Set(stats.DatabaseStatsByDbName[dbName].DocCount)
		e.docDelCount.WithLabelValues(dbName).Set(stats.DatabaseStatsByDbName[dbName].DocDelCount)
		e.compactRunning.WithLabelValues(dbName).Set(stats.DatabaseStatsByDbName[dbName].CompactRunning)
		e.diskSizeOverhead.WithLabelValues(dbName).Set(stats.DatabaseStatsByDbName[dbName].DiskSizeOverhead)

		for designDoc, view := range stats.DatabaseStatsByDbName[dbName].Views {
			for viewName, updateSeq := range view {
				var intSeq int64
				err := json.Unmarshal(stats.DatabaseStatsByDbName[dbName].UpdateSeq, &intSeq)
				if err != nil {
					klog.Warningf("%v", err)
					continue
				}
				dbUpdateSeq := intSeq
				viewUpdateSeq, _ := strconv.ParseInt(updateSeq, 10, 64)
				age := dbUpdateSeq - viewUpdateSeq
				e.viewStaleness.WithLabelValues(dbName, designDoc, viewName, "0", "1").Set(float64(age))
			}
		}
	}

	activeTasksByNode := make(map[string]ActiveTaskTypes)
	for _, task := range stats.ActiveTasksResponse {
		if task.Type == "replication" {
			e.activeTasksReplicationLastUpdate.WithLabelValues(
				task.Node,
				task.DocId,
				strconv.FormatBool(task.Continuous),
				task.Source,
				task.Target).Set(task.UpdatedOn)
			e.activeTasksReplicationChangesPending.WithLabelValues(
				task.Node,
				task.DocId,
				strconv.FormatBool(task.Continuous),
				task.Source,
				task.Target).Set(float64(task.ChangesPending))
		}

		if _, ok := activeTasksByNode[task.Node]; !ok {
			activeTasksByNode[task.Node] = ActiveTaskTypes{}
		}
		types := activeTasksByNode[task.Node]

		switch taskType := task.Type; taskType {
		case "database_compaction":
			types.DatabaseCompaction++
			types.Sum++
		case "view_compaction":
			types.ViewCompaction++
			types.Sum++
		case "indexer":
			types.Indexer++
			types.Sum++
		case "replication":
			types.Replication++
			types.Sum++
		default:
			fmt.Printf("unknown task type %s.", taskType)
			types.Sum++
		}
		activeTasksByNode[task.Node] = types
	}
	for nodeName, tasks := range activeTasksByNode {
		e.activeTasks.WithLabelValues(nodeName).Set(tasks.Sum)
		e.activeTasksDatabaseCompaction.WithLabelValues(nodeName).Set(tasks.DatabaseCompaction)
		e.activeTasksViewCompaction.WithLabelValues(nodeName).Set(tasks.ViewCompaction)
		e.activeTasksIndexer.WithLabelValues(nodeName).Set(tasks.Indexer)
		e.activeTasksReplication.WithLabelValues(nodeName).Set(tasks.Replication)
	}

	return nil
}


text:
<!DOCTYPE html>

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

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Carousel Template for Bootstrap</title>

    <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="../css/carousel.css" rel="stylesheet">
    <link href="../css/homepage.css" rel="stylesheet">

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

              </button>
              Project name

Home

About

Contact

                  Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

        Previous

        Next

一风之音《饿了就搞》

琅琊榜续集:梅长苏死亡真相

一风之音《饿了就搞》

琅琊榜续集:梅长苏死亡真相

一风之音《饿了就搞》

琅琊榜续集:梅长苏死亡真相

一风之音《饿了就搞》

琅琊榜续集:梅长苏死亡真相

一风之音《饿了就搞》

琅琊榜续集:梅长苏死亡真相

一风之音《饿了就搞》

琅琊榜续集:梅长苏死亡真相

First featurette heading. It'll blow your mind.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

Oh yeah, it's that good. See for yourself.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

And lastly, this one. Checkmate.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

Back to top

© 2014 Company, Inc. · Privacy · Terms


text:
package net.fortytwo.ripple;

/**
 * A single, custom Exception used for many purposes in Ripple
 *
 * @author Joshua Shinavier (http://fortytwo.net)
 */
public class RippleException extends Exception {
    private static final long serialVersionUID = 2498405641024203574L;

    public RippleException() {
        super();
    }

    public RippleException(final Throwable cause) {
        super(cause);
    }

    public RippleException(final String msg) {
        super(msg);
    }

    public RippleException(final String message, final Throwable cause) {
        super(message, cause);
    }
}


text:
Bem vindos ao nosso repositorio de Exercicios de JAVA
========================================================

Aqui cada pasta representa uma aula, è necessario Seguir o padrão Aula1 , Aula2 ,Aula3, AulaY....

Caso exista algum exercicio em especial (um exercicio que não envolva exatament uma aula)

você pode criar uma pasta com um nome (um nome que lembre ou explique o exercicio ), por exemplo

Projeto_Game_RPG

dentro dessa pasta, deve ter um arquivo README.md contendo uma explicação do projeto ou programa, por exemplo

Projeto_Game_RPG : README.md "Projeto para simular uma batalha RPG em JAVA"


text:
local VolumetricMaxPooling, parent = torch.class('nn.VolumetricMaxPooling', 'nn.Module')

VolumetricMaxPooling.__version = 2

function VolumetricMaxPooling:__init(kT, kW, kH, dT, dW, dH, padT, padW, padH)
   parent.__init(self)

   dT = dT or kT
   dW = dW or kW
   dH = dH or kH

   self.kT = kT
   self.kH = kH
   self.kW = kW
   self.dT = dT
   self.dW = dW
   self.dH = dH

   self.padT = padT or 0
   self.padW = padW or 0
   self.padH = padH or 0

   self.ceil_mode = false
   self.indices = torch.Tensor()
end

function VolumetricMaxPooling:ceil()
    self.ceil_mode = true
    return self
end

function VolumetricMaxPooling:floor()
    self.ceil_mode = false
    return self
end

function VolumetricMaxPooling:updateOutput(input)
   self.indices = self.indices or input.new()
   input.THNN.VolumetricMaxPooling_updateOutput(
      input:cdata(),
      self.output:cdata(),
      self.indices:cdata(),
      self.kT, self.kW, self.kH,
      self.dT, self.dW, self.dH,
      self.padT, self.padW, self.padH,
      self.ceil_mode
   )
   return self.output
end

function VolumetricMaxPooling:updateGradInput(input, gradOutput)
   input.THNN.VolumetricMaxPooling_updateGradInput(
      input:cdata(),
      gradOutput:cdata(),
      self.gradInput:cdata(),
      self.indices:cdata(),
      self.dT, self.dW, self.dH,
      self.padT, self.padW, self.padH
   )
   return self.gradInput
end

function VolumetricMaxPooling:empty()
   self:clearState()
end

function VolumetricMaxPooling:clearState()
   if self.indices then self.indices:set() end
   return parent.clearState(self)
end

function VolumetricMaxPooling:read(file, version)
   parent.read(self, file)
   if version < 2 then
      self.ceil_mode = false
   end
end


text:
package okio;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import static okio.TestUtil.repeat;
import static okio.Util.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public final class OkioTest {
  @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();

  @Test public void readWriteFile() throws Exception {
    File file = temporaryFolder.newFile();

    BufferedSink sink = Okio.buffer(Okio.sink(file));
    sink.writeUtf8("Hello, java.io file!");
    sink.close();
    assertTrue(file.exists());
    assertEquals(20, file.length());

    BufferedSource source = Okio.buffer(Okio.source(file));
    assertEquals("Hello, java.io file!", source.readUtf8());
    source.close();
  }

  @Test public void appendFile() throws Exception {
    File file = temporaryFolder.newFile();

    BufferedSink sink = Okio.buffer(Okio.appendingSink(file));
    sink.writeUtf8("Hello, ");
    sink.close();
    assertTrue(file.exists());
    assertEquals(7, file.length());

    sink = Okio.buffer(Okio.appendingSink(file));
    sink.writeUtf8("java.io file!");
    sink.close();
    assertEquals(20, file.length());

    BufferedSource source = Okio.buffer(Okio.source(file));
    assertEquals("Hello, java.io file!", source.readUtf8());
    source.close();
  }

  @Test public void readWritePath() throws Exception {
    Path path = temporaryFolder.newFile().toPath();

    BufferedSink sink = Okio.buffer(Okio.sink(path));
    sink.writeUtf8("Hello, java.nio file!");
    sink.close();
    assertTrue(Files.exists(path));
    assertEquals(21, Files.size(path));

    BufferedSource source = Okio.buffer(Okio.source(path));
    assertEquals("Hello, java.nio file!", source.readUtf8());
    source.close();
  }

  @Test public void sinkFromOutputStream() throws Exception {
    Buffer data = new Buffer();
    data.writeUtf8("a");
    data.writeUtf8(repeat('b', 9998));
    data.writeUtf8("c");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Sink sink = Okio.sink(out);
    sink.write(data, 3);
    assertEquals("abb", out.toString("UTF-8"));
    sink.write(data, data.size());
    assertEquals("a" + repeat('b', 9998) + "c", out.toString("UTF-8"));
  }

  @Test public void sourceFromInputStream() throws Exception {
    InputStream in = new ByteArrayInputStream(
        ("a" + repeat('b', Segment.SIZE * 2) + "c").getBytes(UTF_8));

    // Source: ab...bc
    Source source = Okio.source(in);
    Buffer sink = new Buffer();

    // Source: b...bc. Sink: abb.
    assertEquals(3, source.read(sink, 3));
    assertEquals("abb", sink.readUtf8(3));

    // Source: b...bc. Sink: b...b.
    assertEquals(Segment.SIZE, source.read(sink, 20000));
    assertEquals(repeat('b', Segment.SIZE), sink.readUtf8());

    // Source: b...bc. Sink: b...bc.
    assertEquals(Segment.SIZE - 1, source.read(sink, 20000));
    assertEquals(repeat('b', Segment.SIZE - 2) + "c", sink.readUtf8());

    // Source and sink are empty.
    assertEquals(-1, source.read(sink, 1));
  }

  @Test public void sourceFromInputStreamBounds() throws Exception {
    Source source = Okio.source(new ByteArrayInputStream(new byte[100]));
    try {
      source.read(new Buffer(), -1);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  @Test public void bufferSinkThrowsOnNull() {
    try {
      Okio.buffer((Sink) null);
      fail();
    } catch (NullPointerException expected) {
      assertEquals("sink == null", expected.getMessage());
    }
  }

  @Test public void bufferSourceThrowsOnNull() {
    try {
      Okio.buffer((Source) null);
      fail();
    } catch (NullPointerException expected) {
      assertEquals("source == null", expected.getMessage());
    }
  }

  @Test public void blackhole() throws Exception {
    Buffer data = new Buffer();
    data.writeUtf8("blackhole");

    Sink blackhole = Okio.blackhole();
    blackhole.write(data, 5);

    assertEquals("hole", data.readUtf8());
  }
}


text:
namespace jqGrid04.Models
{
    public class Product
    {
        public int Id { set; get; }
        public string Name { set; get; }
        public decimal Price { set; get; }
        public Supplier Supplier { set; get; }
        public Category Category { set; get; }
    }

    public class Category
    {
        public int Id { set; get; }
        public string Name { set; get; }
    }

    public class Supplier
    {
        public int Id { set; get; }
        public string CompanyName { set; get; }
        public string Address { set; get; }
        public string PostalCode { set; get; }
        public string City { set; get; }
        public string Country { set; get; }
        public string Phone { set; get; }
        public string HomePage { set; get; }
    }
}


text:
package brotli

import "encoding/binary"

/* Function for fast encoding of an input fragment, independently from the input
   history. This function uses one-pass processing: when we find a backward
   match, we immediately emit the corresponding command and literal codes to
   the bit stream.

   Adapted from the CompressFragment() function in
   https://github.com/google/snappy/blob/master/snappy.cc */

const maxDistance_compress_fragment = 262128

func hash5(p []byte, shift uint) uint32 {
	var h uint64 = (binary.LittleEndian.Uint64(p) << 24) * uint64(kHashMul32)
	return uint32(h >> shift)
}

func hashBytesAtOffset5(v uint64, offset int, shift uint) uint32 {
	assert(offset >= 0)
	assert(offset <= 3)
	{
		var h uint64 = ((v >> uint(8*offset)) << 24) * uint64(kHashMul32)
		return uint32(h >> shift)
	}
}

func isMatch5(p1 []byte, p2 []byte) bool {
	return binary.LittleEndian.Uint32(p1) == binary.LittleEndian.Uint32(p2) &&
		p1[4] == p2[4]
}

/* Builds a literal prefix code into "depths" and "bits" based on the statistics
   of the "input" string and stores it into the bit stream.
   Note that the prefix code here is built from the pre-LZ77 input, therefore
   we can only approximate the statistics of the actual literal stream.
   Moreover, for long inputs we build a histogram from a sample of the input
   and thus have to assign a non-zero depth for each literal.
   Returns estimated compression ratio millibytes/char for encoding given input
   with generated code. */
func buildAndStoreLiteralPrefixCode(input []byte, input_size uint, depths []byte, bits []uint16, storage_ix *uint, storage []byte) uint {
	var histogram = [256]uint32{0}
	var histogram_total uint
	var i uint
	if input_size < 1<<15 {
		for i = 0; i < input_size; i++ {
			histogram[input[i]]++
		}

		histogram_total = input_size
		for i = 0; i < 256; i++ {
			/* We weigh the first 11 samples with weight 3 to account for the
			   balancing effect of the LZ77 phase on the histogram. */
			var adjust uint32 = 2 * brotli_min_uint32_t(histogram[i], 11)
			histogram[i] += adjust
			histogram_total += uint(adjust)
		}
	} else {
		const kSampleRate uint = 29
		for i = 0; i < input_size; i += kSampleRate {
			histogram[input[i]]++
		}

		histogram_total = (input_size + kSampleRate - 1) / kSampleRate
		for i = 0; i < 256; i++ {
			/* We add 1 to each population count to avoid 0 bit depths (since this is
			   only a sample and we don't know if the symbol appears or not), and we
			   weigh the first 11 samples with weight 3 to account for the balancing
			   effect of the LZ77 phase on the histogram (more frequent symbols are
			   more likely to be in backward references instead as literals). */
			var adjust uint32 = 1 + 2*brotli_min_uint32_t(histogram[i], 11)
			histogram[i] += adjust
			histogram_total += uint(adjust)
		}
	}

	buildAndStoreHuffmanTreeFast(histogram[:], histogram_total, /* max_bits = */
		8, depths, bits, storage_ix, storage)
	{
		var literal_ratio uint = 0
		for i = 0; i < 256; i++ {
			if histogram[i] != 0 {
				literal_ratio += uint(histogram[i] * uint32(depths[i]))
			}
		}

		/* Estimated encoding ratio, millibytes per symbol. */
		return (literal_ratio * 125) / histogram_total
	}
}

/* Builds a command and distance prefix code (each 64 symbols) into "depth" and
   "bits" based on "histogram" and stores it into the bit stream. */
func buildAndStoreCommandPrefixCode1(histogram []uint32, depth []byte, bits []uint16, storage_ix *uint, storage []byte) {
	var tree [129]huffmanTree
	var cmd_depth = [numCommandSymbols]byte{0}
	/* Tree size for building a tree over 64 symbols is 2 * 64 + 1. */

	var cmd_bits [64]uint16

	createHuffmanTree(histogram, 64, 15, tree[:], depth)
	createHuffmanTree(histogram[64:], 64, 14, tree[:], depth[64:])

	/* We have to jump through a few hoops here in order to compute
	   the command bits because the symbols are in a different order than in
	   the full alphabet. This looks complicated, but having the symbols
	   in this order in the command bits saves a few branches in the Emit*
	   functions. */
	copy(cmd_depth[:], depth[:24])

	copy(cmd_depth[24:][:], depth[40:][:8])
	copy(cmd_depth[32:][:], depth[24:][:8])
	copy(cmd_depth[40:][:], depth[48:][:8])
	copy(cmd_depth[48:][:], depth[32:][:8])
	copy(cmd_depth[56:][:], depth[56:][:8])
	convertBitDepthsToSymbols(cmd_depth[:], 64, cmd_bits[:])
	copy(bits, cmd_bits[:24])
	copy(bits[24:], cmd_bits[32:][:8])
	copy(bits[32:], cmd_bits[48:][:8])
	copy(bits[40:], cmd_bits[24:][:8])
	copy(bits[48:], cmd_bits[40:][:8])
	copy(bits[56:], cmd_bits[56:][:8])
	convertBitDepthsToSymbols(depth[64:], 64, bits[64:])
	{
		/* Create the bit length array for the full command alphabet. */
		var i uint
		for i := 0; i < int(64); i++ {
			cmd_depth[i] = 0
		} /* only 64 first values were used */
		copy(cmd_depth[:], depth[:8])
		copy(cmd_depth[64:][:], depth[8:][:8])
		copy(cmd_depth[128:][:], depth[16:][:8])
		copy(cmd_depth[192:][:], depth[24:][:8])
		copy(cmd_depth[384:][:], depth[32:][:8])
		for i = 0; i < 8; i++ {
			cmd_depth[128+8*i] = depth[40+i]
			cmd_depth[256+8*i] = depth[48+i]
			cmd_depth[448+8*i] = depth[56+i]
		}

		storeHuffmanTree(cmd_depth[:], numCommandSymbols, tree[:], storage_ix, storage)
	}

	storeHuffmanTree(depth[64:], 64, tree[:], storage_ix, storage)
}

/* REQUIRES: insertlen < 6210 */
func emitInsertLen1(insertlen uint, depth []byte, bits []uint16, histo []uint32, storage_ix *uint, storage []byte) {
	if insertlen < 6 {
		var code uint = insertlen + 40
		writeBits(uint(depth[code]), uint64(bits[code]), storage_ix, storage)
		histo[code]++
	} else if insertlen < 130 {
		var tail uint = insertlen - 2
		var nbits uint32 = log2FloorNonZero(tail) - 1
		var prefix uint = tail >> nbits
		var inscode uint = uint((nbits << 1) + uint32(prefix) + 42)
		writeBits(uint(depth[inscode]), uint64(bits[inscode]), storage_ix, storage)
		writeBits(uint(nbits), uint64(tail)-(uint64(prefix)<<nbits), storage_ix, storage)
		histo[inscode]++
	} else if insertlen < 2114 {
		var tail uint = insertlen - 66
		var nbits uint32 = log2FloorNonZero(tail)
		var code uint = uint(nbits + 50)
		writeBits(uint(depth[code]), uint64(bits[code]), storage_ix, storage)
		writeBits(uint(nbits), uint64(tail)-(uint64(uint(1))<<nbits), storage_ix, storage)
		histo[code]++
	} else {
		writeBits(uint(depth[61]), uint64(bits[61]), storage_ix, storage)
		writeBits(12, uint64(insertlen)-2114, storage_ix, storage)
		histo[61]++
	}
}

func emitLongInsertLen(insertlen uint, depth []byte, bits []uint16, histo []uint32, storage_ix *uint, storage []byte) {
	if insertlen < 22594 {
		writeBits(uint(depth[62]), uint64(bits[62]), storage_ix, storage)
		writeBits(14, uint64(insertlen)-6210, storage_ix, storage)
		histo[62]++
	} else {
		writeBits(uint(depth[63]), uint64(bits[63]), storage_ix, storage)
		writeBits(24, uint64(insertlen)-22594, storage_ix, storage)
		histo[63]++
	}
}

func emitCopyLen1(copylen uint, depth []byte, bits []uint16, histo []uint32, storage_ix *uint, storage []byte) {
	if copylen < 10 {
		writeBits(uint(depth[copylen+14]), uint64(bits[copylen+14]), storage_ix, storage)
		histo[copylen+14]++
	} else if copylen < 134 {
		var tail uint = copylen - 6
		var nbits uint32 = log2FloorNonZero(tail) - 1
		var prefix uint = tail >> nbits
		var code uint = uint((nbits << 1) + uint32(prefix) + 20)
		writeBits(uint(depth[code]), uint64(bits[code]), storage_ix, storage)
		writeBits(uint(nbits), uint64(tail)-(uint64(prefix)<<nbits), storage_ix, storage)
		histo[code]++
	} else if copylen < 2118 {
		var tail uint = copylen - 70
		var nbits uint32 = log2FloorNonZero(tail)
		var code uint = uint(nbits + 28)
		writeBits(uint(depth[code]), uint64(bits[code]), storage_ix, storage)
		writeBits(uint(nbits), uint64(tail)-(uint64(uint(1))<<nbits), storage_ix, storage)
		histo[code]++
	} else {
		writeBits(uint(depth[39]), uint64(bits[39]), storage_ix, storage)
		writeBits(24, uint64(copylen)-2118, storage_ix, storage)
		histo[39]++
	}
}

func emitCopyLenLastDistance1(copylen uint, depth []byte, bits []uint16, histo []uint32, storage_ix *uint, storage []byte) {
	if copylen < 12 {
		writeBits(uint(depth[copylen-4]), uint64(bits[copylen-4]), storage_ix, storage)
		histo[copylen-4]++
	} else if copylen < 72 {
		var tail uint = copylen - 8
		var nbits uint32 = log2FloorNonZero(tail) - 1
		var prefix uint = tail >> nbits
		var code uint = uint((nbits << 1) + uint32(prefix) + 4)
		writeBits(uint(depth[code]), uint64(bits[code]), storage_ix, storage)
		writeBits(uint(nbits), uint64(tail)-(uint64(prefix)<<nbits), storage_ix, storage)
		histo[code]++
	} else if copylen < 136 {
		var tail uint = copylen - 8
		var code uint = (tail >> 5) + 30
		writeBits(uint(depth[code]), uint64(bits[code]), storage_ix, storage)
		writeBits(5, uint64(tail)&31, storage_ix, storage)
		writeBits(uint(depth[64]), uint64(bits[64]), storage_ix, storage)
		histo[code]++
		histo[64]++
	} else if copylen < 2120 {
		var tail uint = copylen - 72
		var nbits uint32 = log2FloorNonZero(tail)
		var code uint = uint(nbits + 28)
		writeBits(uint(depth[code]), uint64(bits[code]), storage_ix, storage)
		writeBits(uint(nbits), uint64(tail)-(uint64(uint(1))<<nbits), storage_ix, storage)
		writeBits(uint(depth[64]), uint64(bits[64]), storage_ix, storage)
		histo[code]++
		histo[64]++
	} else {
		writeBits(uint(depth[39]), uint64(bits[39]), storage_ix, storage)
		writeBits(24, uint64(copylen)-2120, storage_ix, storage)
		writeBits(uint(depth[64]), uint64(bits[64]), storage_ix, storage)
		histo[39]++
		histo[64]++
	}
}

func emitDistance1(distance uint, depth []byte, bits []uint16, histo []uint32, storage_ix *uint, storage []byte) {
	var d uint = distance + 3
	var nbits uint32 = log2FloorNonZero(d) - 1
	var prefix uint = (d >> nbits) & 1
	var offset uint = (2 + prefix) << nbits
	var distcode uint = uint(2*(nbits-1) + uint32(prefix) + 80)
	writeBits(uint(depth[distcode]), uint64(bits[distcode]), storage_ix, storage)
	writeBits(uint(nbits), uint64(d)-uint64(offset), storage_ix, storage)
	histo[distcode]++
}

func emitLiterals(input []byte, len uint, depth []byte, bits []uint16, storage_ix *uint, storage []byte) {
	var j uint
	for j = 0; j < len; j++ {
		var lit byte = input[j]
		writeBits(uint(depth[lit]), uint64(bits[lit]), storage_ix, storage)
	}
}

/* REQUIRES: len <= 1 << 24. */
func storeMetaBlockHeader1(len uint, is_uncompressed bool, storage_ix *uint, storage []byte) {
	var nibbles uint = 6

	/* ISLAST */
	writeBits(1, 0, storage_ix, storage)

	if len <= 1<<16 {
		nibbles = 4
	} else if len <= 1<<20 {
		nibbles = 5
	}

	writeBits(2, uint64(nibbles)-4, storage_ix, storage)
	writeBits(nibbles*4, uint64(len)-1, storage_ix, storage)

	/* ISUNCOMPRESSED */
	writeSingleBit(is_uncompressed, storage_ix, storage)
}

func updateBits(n_bits uint, bits uint32, pos uint, array []byte) {
	for n_bits > 0 {
		var byte_pos uint = pos >> 3
		var n_unchanged_bits uint = pos & 7
		var n_changed_bits uint = brotli_min_size_t(n_bits, 8-n_unchanged_bits)
		var total_bits uint = n_unchanged_bits + n_changed_bits
		var mask uint32 = (^((1 << total_bits) - 1)) | ((1 << n_unchanged_bits) - 1)
		var unchanged_bits uint32 = uint32(array[byte_pos]) & mask
		var changed_bits uint32 = bits & ((1 << n_changed_bits) - 1)
		array[byte_pos] = byte(changed_bits<<n_unchanged_bits | unchanged_bits)
		n_bits -= n_changed_bits
		bits >>= n_changed_bits
		pos += n_changed_bits
	}
}

func rewindBitPosition1(new_storage_ix uint, storage_ix *uint, storage []byte) {
	var bitpos uint = new_storage_ix & 7
	var mask uint = (1 << bitpos) - 1
	storage[new_storage_ix>>3] &= byte(mask)
	*storage_ix = new_storage_ix
}

var shouldMergeBlock_kSampleRate uint = 43

func shouldMergeBlock(data []byte, len uint, depths []byte) bool {
	var histo = [256]uint{0}
	var i uint
	for i = 0; i < len; i += shouldMergeBlock_kSampleRate {
		histo[data[i]]++
	}
	{
		var total uint = (len + shouldMergeBlock_kSampleRate - 1) / shouldMergeBlock_kSampleRate
		var r float64 = (fastLog2(total)+0.5)*float64(total) + 200
		for i = 0; i < 256; i++ {
			r -= float64(histo[i]) * (float64(depths[i]) + fastLog2(histo[i]))
		}

		return r >= 0.0
	}
}

func shouldUseUncompressedMode(metablock_start []byte, next_emit []byte, insertlen uint, literal_ratio uint) bool {
	var compressed uint = uint(-cap(next_emit) + cap(metablock_start))
	if compressed*50 > insertlen {
		return false
	} else {
		return literal_ratio > 980
	}
}

func emitUncompressedMetaBlock1(begin []byte, end []byte, storage_ix_start uint, storage_ix *uint, storage []byte) {
	var len uint = uint(-cap(end) + cap(begin))
	rewindBitPosition1(storage_ix_start, storage_ix, storage)
	storeMetaBlockHeader1(uint(len), true, storage_ix, storage)
	*storage_ix = (*storage_ix + 7) &^ 7
	copy(storage[*storage_ix>>3:], begin[:len])
	*storage_ix += uint(len << 3)
	storage[*storage_ix>>3] = 0
}

var kCmdHistoSeed = [128]uint32{
	0,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	0,
	0,
	0,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	0,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	1,
	0,
	0,
	0,
	0,
}

var compressFragmentFastImpl_kFirstBlockSize uint = 3 << 15
var compressFragmentFastImpl_kMergeBlockSize uint = 1 << 16

func compressFragmentFastImpl(in []byte, input_size uint, is_last bool, table []int, table_bits uint, cmd_depth []byte, cmd_bits []uint16, cmd_code_numbits *uint, cmd_code []byte, storage_ix *uint, storage []byte) {
	var cmd_histo [128]uint32
	var ip_end int
	var next_emit int = 0
	var base_ip int = 0
	var input int = 0
	const kInputMarginBytes uint = windowGap
	const kMinMatchLen uint = 5
	var metablock_start int = input
	var block_size uint = brotli_min_size_t(input_size, compressFragmentFastImpl_kFirstBlockSize)
	var total_block_size uint = block_size
	var mlen_storage_ix uint = *storage_ix + 3
	var lit_depth [256]byte
	var lit_bits [256]uint16
	var literal_ratio uint
	var ip int
	var last_distance int
	var shift uint = 64 - table_bits

	/* "next_emit" is a pointer to the first byte that is not covered by a
	   previous copy. Bytes between "next_emit" and the start of the next copy or
	   the end of the input will be emitted as literal bytes. */

	/* Save the start of the first block for position and distance computations.
	 */

	/* Save the bit position of the MLEN field of the meta-block header, so that
	   we can update it later if we decide to extend this meta-block. */
	storeMetaBlockHeader1(block_size, false, storage_ix, storage)

	/* No block splits, no contexts. */
	writeBits(13, 0, storage_ix, storage)

	literal_ratio = buildAndStoreLiteralPrefixCode(in[input:], block_size, lit_depth[:], lit_bits[:], storage_ix, storage)
	{
		/* Store the pre-compressed command and distance prefix codes. */
		var i uint
		for i = 0; i+7 < *cmd_code_numbits; i += 8 {
			writeBits(8, uint64(cmd_code[i>>3]), storage_ix, storage)
		}
	}

	writeBits(*cmd_code_numbits&7, uint64(cmd_code[*cmd_code_numbits>>3]), storage_ix, storage)

	/* Initialize the command and distance histograms. We will gather
	   statistics of command and distance codes during the processing
	   of this block and use it to update the command and distance
	   prefix codes for the next block. */
emit_commands:
	copy(cmd_histo[:], kCmdHistoSeed[:])

	/* "ip" is the input pointer. */
	ip = input

	last_distance = -1
	ip_end = int(uint(input) + block_size)

	if block_size >= kInputMarginBytes {
		var len_limit uint = brotli_min_size_t(block_size-kMinMatchLen, input_size-kInputMarginBytes)
		var ip_limit int = int(uint(input) + len_limit)
		/* For the last block, we need to keep a 16 bytes margin so that we can be
		   sure that all distances are at most window size - 16.
		   For all other blocks, we only need to keep a margin of 5 bytes so that
		   we don't go over the block size with a copy. */

		var next_hash uint32
		ip++
		for next_hash = hash5(in[ip:], shift); ; {
			var skip uint32 = 32
			var next_ip int = ip
			/* Step 1: Scan forward in the input looking for a 5-byte-long match.
			   If we get close to exhausting the input then goto emit_remainder.

			   Heuristic match skipping: If 32 bytes are scanned with no matches
			   found, start looking only at every other byte. If 32 more bytes are
			   scanned, look at every third byte, etc.. When a match is found,
			   immediately go back to looking at every byte. This is a small loss
			   (~5% performance, ~0.1% density) for compressible data due to more
			   bookkeeping, but for non-compressible data (such as JPEG) it's a huge
			   win since the compressor quickly "realizes" the data is incompressible
			   and doesn't bother looking for matches everywhere.

			   The "skip" variable keeps track of how many bytes there are since the
			   last match; dividing it by 32 (i.e. right-shifting by five) gives the
			   number of bytes to move ahead for each iteration. */

			var candidate int
			assert(next_emit < ip)

		trawl:
			for {
				var hash uint32 = next_hash
				var bytes_between_hash_lookups uint32 = skip >> 5
				skip++
				assert(hash == hash5(in[next_ip:], shift))
				ip = next_ip
				next_ip = int(uint32(ip) + bytes_between_hash_lookups)
				if next_ip > ip_limit {
					goto emit_remainder
				}

				next_hash = hash5(in[next_ip:], shift)
				candidate = ip - last_distance
				if isMatch5(in[ip:], in[candidate:]) {
					if candidate < ip {
						table[hash] = int(ip - base_ip)
						break
					}
				}

				candidate = base_ip + table[hash]
				assert(candidate >= base_ip)
				assert(candidate < ip)

				table[hash] = int(ip - base_ip)
				if !(!isMatch5(in[ip:], in[candidate:])) {
					break
				}
			}

			/* Check copy distance. If candidate is not feasible, continue search.
			   Checking is done outside of hot loop to reduce overhead. */
			if ip-candidate > maxDistance_compress_fragment {
				goto trawl
			}

			/* Step 2: Emit the found match together with the literal bytes from
			   "next_emit" to the bit stream, and then see if we can find a next match
			   immediately afterwards. Repeat until we find no match for the input
			   without emitting some literal bytes. */
			{
				var base int = ip
				/* > 0 */
				var matched uint = 5 + findMatchLengthWithLimit(in[candidate+5:], in[ip+5:], uint(ip_end-ip)-5)
				var distance int = int(base - candidate)
				/* We have a 5-byte match at ip, and we need to emit bytes in
				   [next_emit, ip). */

				var insert uint = uint(base - next_emit)
				ip += int(matched)
				if insert < 6210 {
					emitInsertLen1(insert, cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)
				} else if shouldUseUncompressedMode(in[metablock_start:], in[next_emit:], insert, literal_ratio) {
					emitUncompressedMetaBlock1(in[metablock_start:], in[base:], mlen_storage_ix-3, storage_ix, storage)
					input_size -= uint(base - input)
					input = base
					next_emit = input
					goto next_block
				} else {
					emitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)
				}

				emitLiterals(in[next_emit:], insert, lit_depth[:], lit_bits[:], storage_ix, storage)
				if distance == last_distance {
					writeBits(uint(cmd_depth[64]), uint64(cmd_bits[64]), storage_ix, storage)
					cmd_histo[64]++
				} else {
					emitDistance1(uint(distance), cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)
					last_distance = distance
				}

				emitCopyLenLastDistance1(matched, cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)

				next_emit = ip
				if ip >= ip_limit {
					goto emit_remainder
				}

				/* We could immediately start working at ip now, but to improve
				   compression we first update "table" with the hashes of some positions
				   within the last copy. */
				{
					var input_bytes uint64 = binary.LittleEndian.Uint64(in[ip-3:])
					var prev_hash uint32 = hashBytesAtOffset5(input_bytes, 0, shift)
					var cur_hash uint32 = hashBytesAtOffset5(input_bytes, 3, shift)
					table[prev_hash] = int(ip - base_ip - 3)
					prev_hash = hashBytesAtOffset5(input_bytes, 1, shift)
					table[prev_hash] = int(ip - base_ip - 2)
					prev_hash = hashBytesAtOffset5(input_bytes, 2, shift)
					table[prev_hash] = int(ip - base_ip - 1)

					candidate = base_ip + table[cur_hash]
					table[cur_hash] = int(ip - base_ip)
				}
			}

			for isMatch5(in[ip:], in[candidate:]) {
				var base int = ip
				/* We have a 5-byte match at ip, and no need to emit any literal bytes
				   prior to ip. */

				var matched uint = 5 + findMatchLengthWithLimit(in[candidate+5:], in[ip+5:], uint(ip_end-ip)-5)
				if ip-candidate > maxDistance_compress_fragment {
					break
				}
				ip += int(matched)
				last_distance = int(base - candidate) /* > 0 */
				emitCopyLen1(matched, cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)
				emitDistance1(uint(last_distance), cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)

				next_emit = ip
				if ip >= ip_limit {
					goto emit_remainder
				}

				/* We could immediately start working at ip now, but to improve
				   compression we first update "table" with the hashes of some positions
				   within the last copy. */
				{
					var input_bytes uint64 = binary.LittleEndian.Uint64(in[ip-3:])
					var prev_hash uint32 = hashBytesAtOffset5(input_bytes, 0, shift)
					var cur_hash uint32 = hashBytesAtOffset5(input_bytes, 3, shift)
					table[prev_hash] = int(ip - base_ip - 3)
					prev_hash = hashBytesAtOffset5(input_bytes, 1, shift)
					table[prev_hash] = int(ip - base_ip - 2)
					prev_hash = hashBytesAtOffset5(input_bytes, 2, shift)
					table[prev_hash] = int(ip - base_ip - 1)

					candidate = base_ip + table[cur_hash]
					table[cur_hash] = int(ip - base_ip)
				}
			}

			ip++
			next_hash = hash5(in[ip:], shift)
		}
	}

emit_remainder:
	assert(next_emit <= ip_end)
	input += int(block_size)
	input_size -= block_size
	block_size = brotli_min_size_t(input_size, compressFragmentFastImpl_kMergeBlockSize)

	/* Decide if we want to continue this meta-block instead of emitting the
	   last insert-only command. */
	if input_size > 0 && total_block_size+block_size <= 1<<20 && shouldMergeBlock(in[input:], block_size, lit_depth[:]) {
		assert(total_block_size > 1<<16)

		/* Update the size of the current meta-block and continue emitting commands.
		   We can do this because the current size and the new size both have 5
		   nibbles. */
		total_block_size += block_size

		updateBits(20, uint32(total_block_size-1), mlen_storage_ix, storage)
		goto emit_commands
	}

	/* Emit the remaining bytes as literals. */
	if next_emit < ip_end {
		var insert uint = uint(ip_end - next_emit)
		if insert < 6210 {
			emitInsertLen1(insert, cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)
			emitLiterals(in[next_emit:], insert, lit_depth[:], lit_bits[:], storage_ix, storage)
		} else if shouldUseUncompressedMode(in[metablock_start:], in[next_emit:], insert, literal_ratio) {
			emitUncompressedMetaBlock1(in[metablock_start:], in[ip_end:], mlen_storage_ix-3, storage_ix, storage)
		} else {
			emitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo[:], storage_ix, storage)
			emitLiterals(in[next_emit:], insert, lit_depth[:], lit_bits[:], storage_ix, storage)
		}
	}

	next_emit = ip_end

	/* If we have more data, write a new meta-block header and prefix codes and
	   then continue emitting commands. */
next_block:
	if input_size > 0 {
		metablock_start = input
		block_size = brotli_min_size_t(input_size, compressFragmentFastImpl_kFirstBlockSize)
		total_block_size = block_size

		/* Save the bit position of the MLEN field of the meta-block header, so that
		   we can update it later if we decide to extend this meta-block. */
		mlen_storage_ix = *storage_ix + 3

		storeMetaBlockHeader1(block_size, false, storage_ix, storage)

		/* No block splits, no contexts. */
		writeBits(13, 0, storage_ix, storage)

		literal_ratio = buildAndStoreLiteralPrefixCode(in[input:], block_size, lit_depth[:], lit_bits[:], storage_ix, storage)
		buildAndStoreCommandPrefixCode1(cmd_histo[:], cmd_depth, cmd_bits, storage_ix, storage)
		goto emit_commands
	}

	if !is_last {
		/* If this is not the last block, update the command and distance prefix
		   codes for the next block and store the compressed forms. */
		cmd_code[0] = 0

		*cmd_code_numbits = 0
		buildAndStoreCommandPrefixCode1(cmd_histo[:], cmd_depth, cmd_bits, cmd_code_numbits, cmd_code)
	}
}

/* Compresses "input" string to the "*storage" buffer as one or more complete
   meta-blocks, and updates the "*storage_ix" bit position.

   If "is_last" is 1, emits an additional empty last meta-block.

   "cmd_depth" and "cmd_bits" contain the command and distance prefix codes
   (see comment in encode.h) used for the encoding of this input fragment.
   If "is_last" is 0, they are updated to reflect the statistics
   of this input fragment, to be used for the encoding of the next fragment.

   "*cmd_code_numbits" is the number of bits of the compressed representation
   of the command and distance prefix codes, and "cmd_code" is an array of
   at least "(*cmd_code_numbits + 7) >> 3" size that contains the compressed
   command and distance prefix codes. If "is_last" is 0, these are also
   updated to represent the updated "cmd_depth" and "cmd_bits".

   REQUIRES: "input_size" is greater than zero, or "is_last" is 1.
   REQUIRES: "input_size" is less or equal to maximal metablock size (1 << 24).
   REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
   REQUIRES: "table_size" is an odd (9, 11, 13, 15) power of two
   OUTPUT: maximal copy distance <= |input_size|
   OUTPUT: maximal copy distance <= BROTLI_MAX_BACKWARD_LIMIT(18) */
func compressFragmentFast(input []byte, input_size uint, is_last bool, table []int, table_size uint, cmd_depth []byte, cmd_bits []uint16, cmd_code_numbits *uint, cmd_code []byte, storage_ix *uint, storage []byte) {
	var initial_storage_ix uint = *storage_ix
	var table_bits uint = uint(log2FloorNonZero(table_size))

	if input_size == 0 {
		assert(is_last)
		writeBits(1, 1, storage_ix, storage) /* islast */
		writeBits(1, 1, storage_ix, storage) /* isempty */
		*storage_ix = (*storage_ix + 7) &^ 7
		return
	}

	compressFragmentFastImpl(input, input_size, is_last, table, table_bits, cmd_depth, cmd_bits, cmd_code_numbits, cmd_code, storage_ix, storage)

	/* If output is larger than single uncompressed block, rewrite it. */
	if *storage_ix-initial_storage_ix > 31+(input_size<<3) {
		emitUncompressedMetaBlock1(input, input[input_size:], initial_storage_ix, storage_ix, storage)
	}

	if is_last {
		writeBits(1, 1, storage_ix, storage) /* islast */
		writeBits(1, 1, storage_ix, storage) /* isempty */
		*storage_ix = (*storage_ix + 7) &^ 7
	}
}


text:
#define HARNESS_DEFAULT_MIN_THREADS 4
#define HARNESS_DEFAULT_MAX_THREADS 8

#include "harness_defs.h"
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <utility>
#include "tbb/task.h"
#include "tbb/task_scheduler_init.h"
#include "tbb/tick_count.h"
#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"
#include "tbb/mutex.h"
#include "tbb/spin_mutex.h"
#include "tbb/queuing_mutex.h"
#include "harness.h"

using namespace std;
using namespace tbb;

///////////////////// Parallel methods ////////////////////////

// *** Serial shared by mutexes *** //
int SharedI = 1, SharedN;
template<typename M>
class SharedSerialFibBody: NoAssign {
    M &mutex;
public:
    SharedSerialFibBody( M &m ) : mutex( m ) {}
    //! main loop
    void operator()( const blocked_range<int>& /*range*/ ) const {
        for(;;) {
            typename M::scoped_lock lock( mutex );
            if(SharedI >= SharedN) break;
            volatile double sum = 7.3;
            sum *= 11.17;
            ++SharedI;
        }
    }
};

//! Root function
template<class M>
void SharedSerialFib(int n)
{
    SharedI = 1;
    SharedN = n;
    M mutex;
    parallel_for( blocked_range<int>(0,4,1), SharedSerialFibBody<M>( mutex ) );
}

/////////////////////////// Main ////////////////////////////////////////////////////

double Tsum = 0; int Tnum = 0;

typedef void (*MeasureFunc)(int);
//! Measure ticks count in loop [2..n]
void Measure(const char *name, MeasureFunc func, int n)
{
    tick_count t0;
    tick_count::interval_t T;
    REMARK("%s",name);
    t0 = tick_count::now();
    for(int number = 2; number <= n; number++)
        func(number);
    T = tick_count::now() - t0;
    double avg = Tnum? Tsum/Tnum : 1;
    if (avg == 0.0) avg = 1;
    if(avg * 100 < T.seconds()) {
        REPORT("Warning: halting detected (%g sec, av: %g)\n", T.seconds(), avg);
        ASSERT(avg * 1000 > T.seconds(), "Too long halting period");
    } else {
        Tsum += T.seconds(); Tnum++;
    }
    REMARK("\t- in %f msec\n", T.seconds()*1000);
}

int TestMain () {
    MinThread = max(2, MinThread);
    int NumbersCount = 100;
    short recycle = 100;
    do {
        for(int threads = MinThread; threads <= MaxThread; threads++) {
            task_scheduler_init scheduler_init(threads);
            REMARK("Threads number is %d\t", threads);
            Measure("Shared serial (wrapper mutex)\t", SharedSerialFib<mutex>, NumbersCount);
            //sum = Measure("Shared serial (spin_mutex)", SharedSerialFib<tbb::spin_mutex>, NumbersCount);
            //sum = Measure("Shared serial (queuing_mutex)", SharedSerialFib<tbb::queuing_mutex>, NumbersCount);
        }
    } while(--recycle);
    return Harness::Done;
}


text:
import { NotificationHandler, RequestHandler, ProgressType, ProgressToken } from 'vscode-jsonrpc';
import { uinteger } from 'vscode-languageserver-types';

import { MessageDirection, ProtocolRequestType, ProtocolNotificationType } from './messages';

export interface WorkDoneProgressBegin {

	kind: 'begin';

	/**
	 * Mandatory title of the progress operation. Used to briefly inform about
	 * the kind of operation being performed.
	 *
	 * Examples: "Indexing" or "Linking dependencies".
	 */
	title: string;

	/**
	 * Controls if a cancel button should show to allow the user to cancel the
	 * long running operation. Clients that don't support cancellation are allowed
	 * to ignore the setting.
	 */
	cancellable?: boolean;

	/**
	 * Optional, more detailed associated progress message. Contains
	 * complementary information to the `title`.
	 *
	 * Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
	 * If unset, the previous progress message (if any) is still valid.
	 */
	message?: string;

	/**
	 * Optional progress percentage to display (value 100 is considered 100%).
	 * If not provided infinite progress is assumed and clients are allowed
	 * to ignore the `percentage` value in subsequent in report notifications.
	 *
	 * The value should be steadily rising. Clients are free to ignore values
	 * that are not following this rule. The value range is [0, 100].
	 */
	percentage?: uinteger;
}

export interface WorkDoneProgressReport {

	kind: 'report';

	/**
	 * Controls enablement state of a cancel button.
	 *
	 * Clients that don't support cancellation or don't support controlling the button's
	 * enablement state are allowed to ignore the property.
	 */
	cancellable?: boolean;

	/**
	 * Optional, more detailed associated progress message. Contains
	 * complementary information to the `title`.
	 *
	 * Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
	 * If unset, the previous progress message (if any) is still valid.
	 */
	message?: string;

	/**
	 * Optional progress percentage to display (value 100 is considered 100%).
	 * If not provided infinite progress is assumed and clients are allowed
	 * to ignore the `percentage` value in subsequent in report notifications.
	 *
	 * The value should be steadily rising. Clients are free to ignore values
	 * that are not following this rule. The value range is [0, 100]
	 */
	percentage?: uinteger;
}

export interface WorkDoneProgressEnd {

	kind: 'end';

	/**
	 * Optional, a final message indicating to for example indicate the outcome
	 * of the operation.
	 */
	message?: string;
}

export namespace WorkDoneProgress {
	export const type = new ProgressType<WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd>();

	export function is(value: ProgressType<any>): value is typeof type {
		return value === type;
	}
}

export interface WorkDoneProgressCreateParams  {
	/**
	 * The token to be used to report progress.
	 */
	token: ProgressToken;
}

/**
 * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
 * reporting from the server.
 */
export namespace WorkDoneProgressCreateRequest {
	export const method: 'window/workDoneProgress/create' = 'window/workDoneProgress/create';
	export const messageDirection: MessageDirection = MessageDirection.serverToClient;
	export const type = new ProtocolRequestType<WorkDoneProgressCreateParams, void, never, void, void>(method);
	export type HandlerSignature = RequestHandler<WorkDoneProgressCreateParams, void, void>;
}

export interface WorkDoneProgressCancelParams {
	/**
	 * The token to be used to report progress.
	 */
	token: ProgressToken;
}

/**
 * The `window/workDoneProgress/cancel` notification is sent from  the client to the server to cancel a progress
 * initiated on the server side.
 */
export namespace WorkDoneProgressCancelNotification {
	export const method: 'window/workDoneProgress/cancel' = 'window/workDoneProgress/cancel';
	export const messageDirection: MessageDirection = MessageDirection.clientToServer;
	export const type = new ProtocolNotificationType<WorkDoneProgressCancelParams, void>(method);
	export type HandlerSignature = NotificationHandler<WorkDoneProgressCancelParams>;
}


text:
package com.pmstation.shared.soap.client;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for userSetting complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="userSetting">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="editable" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="possibleValues" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="title" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "userSetting", propOrder = {
    "editable",
    "id",
    "name",
    "possibleValues",
    "title",
    "type",
    "value"
})
public class UserSetting {

    protected boolean editable;
    protected int id;
    protected String name;
    @XmlElement(nillable = true)
    protected List<String> possibleValues;
    protected String title;
    protected String type;
    protected String value;

    /**
     * Gets the value of the editable property.
     *
     */
    public boolean isEditable() {
        return editable;
    }

    /**
     * Sets the value of the editable property.
     *
     */
    public void setEditable(boolean value) {
        this.editable = value;
    }

    /**
     * Gets the value of the id property.
     *
     */
    public int getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     */
    public void setId(int value) {
        this.id = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the possibleValues property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the possibleValues property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getPossibleValues().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link String }
     *
     *
     */
    public List<String> getPossibleValues() {
        if (possibleValues == null) {
            possibleValues = new ArrayList<String>();
        }
        return this.possibleValues;
    }

    /**
     * Gets the value of the title property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTitle() {
        return title;
    }

    /**
     * Sets the value of the title property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTitle(String value) {
        this.title = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

}


text:
#ifndef DocumentInit_h
#define DocumentInit_h

#include "core/dom/CustomElementRegistrationContext.h"
#include "core/dom/SecurityContext.h"
#include "weborigin/KURL.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"

namespace WebCore {

class Document;
class Frame;
class HTMLImport;
class Settings;

class DocumentInit {
public:
    explicit DocumentInit(const KURL& url = KURL(), Frame* frame = 0, HTMLImport* import = 0)
        : m_url(url)
        , m_frame(frame)
        , m_import(import)
    { }

    const KURL& url() const { return m_url; }
    Frame* frame() const { return m_frame; }
    HTMLImport* import() const { return m_import; }

    bool hasSecurityContext() const { return frameForSecurityContext(); }
    bool shouldTreatURLAsSrcdocDocument() const;
    bool shouldSetURL() const;
    SandboxFlags sandboxFlags() const;

    Frame* ownerFrame() const;
    Settings* settings() const;

    DocumentInit& withRegistrationContext(CustomElementRegistrationContext*);
    PassRefPtr<CustomElementRegistrationContext> registrationContext(Document*) const;

private:
    Frame* frameForSecurityContext() const;

    KURL m_url;
    Frame* m_frame;
    HTMLImport* m_import;
    RefPtr<CustomElementRegistrationContext> m_registrationContext;
};

} // namespace WebCore

#endif // DocumentInit_h


text:
package com.webianks.popupbubble;

/**
 * Created by R Ankit on 29-05-2016.
 */
public class DataClass {

    String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}


text:
package org.kie.workbench.common.stunner.core.definition.adapter.binding;

import java.util.Collection;
import java.util.LinkedList;

import org.kie.workbench.common.stunner.core.api.DefinitionManager;
import org.kie.workbench.common.stunner.core.definition.adapter.DefinitionId;
import org.kie.workbench.common.stunner.core.registry.definition.AdapterRegistry;

public class BindableAdapterUtils {

    public static String getDefinitionId(final Class<?> type) {
        return getDefinitionId(type,
                               null);
    }

    public static String getDefinitionId(final Class<?> type,
                                         final AdapterRegistry registry) {
        return getGenericClassName(type);
    }

    public static String getDynamicDefinitionId(final Class<?> type,
                                                final String suffix) {
        return getDynamicDefinitionId(getDefinitionId(type),
                                      suffix);
    }

    public static String getDynamicDefinitionId(final String typeId,
                                                final String suffix) {
        return null != suffix ?
                DefinitionId.generateId(typeId, suffix) :
                typeId;
    }

    public static String getDynamicId(final Class<?> type,
                                      final String definitionId) {
        final String gcn = getGenericClassName(type);
        final int gcnl = gcn.length();
        final int dl = definitionId.length();
        return dl > (gcnl + 1) ?
                definitionId.substring(gcnl + 1, dl) :
                null;
    }

    public static String getDefinitionSetId(final Class<?> type) {
        return getDefinitionSetId(type,
                                  null);
    }

    public static String getDefinitionSetDomain(final Class<?> type) {
        final String n = type.getName();
        return n.substring(0,
                           n.lastIndexOf("."));
    }

    public static String getDefinitionSetId(final Class<?> type,
                                            final AdapterRegistry registry) {
        return getGenericClassName(type);
    }

    public static String getPropertySetId(final Class<?> type) {
        return getPropertySetId(type,
                                null);
    }

    public static String getPropertySetId(final Class<?> type,
                                          final DefinitionManager definitionManager) {
        return getGenericClassName(type);
    }

    public static String getPropertyId(final Class<?> type,
                                       final DefinitionManager definitionManager) {
        return getGenericClassName(type);
    }

    public static String getPropertyId(final Class<?> type) {
        return getPropertyId(type,
                             null);
    }

    public static String getShapeSetId(final Class<?> shapeSetClass) {
        return getGenericClassName(shapeSetClass);
    }

    public static String getGenericClassName(final Class<?> type) {
        return type.getName();
    }

    private static String getGenericClassId(final Class<?> type) {
        return type.getSimpleName();
    }

    public static String toSimpleName(final Object o) {
        final String definitionId = getDefinitionId(o.getClass());
        return definitionId.substring(definitionId.lastIndexOf(".") + 1,
                                      definitionId.length());
    }

    public static <T> Collection<Class<?>> toClassCollection(final Iterable<T> source) {
        if (null != source && source.iterator().hasNext()) {
            final LinkedList<Class<?>> result = new LinkedList<>();
            for (final Object sourceObject : source) {
                result.add(sourceObject.getClass());
            }
            return result;
        }
        return null;
    }
}


text:
require 'strumbar/version'
require 'strumbar/configuration'
require 'strumbar/client'
require 'strumbar/instrumentation'

require 'active_support'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/module/delegation'

module Strumbar
  class << self
    def configure
      @configuration = Configuration.new
      yield @configuration
      Instrumentation.load
    end

    def client
      @client ||= Client.new host, port
    end

    def configuration
      @configuration ||= Configuration.new
    end

    delegate :host, :port, :instruments, :application, :default_rate, to: :configuration

    def subscribe identifier
      ActiveSupport::Notifications.subscribe identifier do |*args|
        event = ActiveSupport::Notifications::Event.new(*args)
        yield client, event
      end
    end

    def strum event, payload, &block
      ActiveSupport::Notifications.instrument event, payload, &block
    end
  end
end


text:
<?php

namespace yiingine\base;

use \Yii;
use \yii\imagine\Image;

/**
 * A component wrapper over the yii2-imagine library to move converted images
 * to the a web accessible folder when they have been modified.
 *
 * @author Antoine Mercier-Linteau <antoine.mercier-linteau@arza-studio.com>
 * */
class Imagine extends \yii\base\Component
{
    /** @var string the name of the folder that contains the modified images. */
    public $folderName = 'imagineImages';

    /** @var string the web accessible path where converted images will reside.
     * when they have been modified. If not specified, a folder will be created in
     * the asset manager's folder.*/
    public $basePath;

    /** @var string the url through which images will be accessible. */
    public $baseUrl;

    /**
     * @inheritdoc
     * */
    public function init()
    {
        if(!isset($this->basePath)) // If no path has been specified during initialization.
        {
            $this->basePath = Yii::$app->assetManager->basePath;

            if(!is_dir($this->basePath.DIRECTORY_SEPARATOR.$this->folderName))
            {
                // Create the folder where the modified images will be stored.
                mkdir($this->basePath.DIRECTORY_SEPARATOR.$this->folderName);
            }
        }

        if(!isset($this->baseUrl)) // If no url has been specified during initialization.
        {
             $this->baseUrl = Yii::$app->assetManager->baseUrl;
        }
    }

    /**
     * Creates a thumbnail image. The function differs from `\Imagine\Image\ImageInterface::thumbnail()` function that
     * it keeps the aspect ratio of the image.
     * @param string $fileName the image file path or path alias.
     * @param integer $height the height in pixels to create the thumbnail.
     * @return string the url to the thumbnail.
     */
    public function getThumbnail($fileName, $height)
    {
        $fileModificationTime = filemtime($fileName);
        $extension = pathinfo($fileName, PATHINFO_EXTENSION);

        $thumbnail = $this->basePath.DIRECTORY_SEPARATOR.$this->folderName.DIRECTORY_SEPARATOR.md5($fileName.$height.'thumbnail').$fileModificationTime.'.'.$extension;

        if(is_file($thumbnail)) // If a previously thumbnailed file exists.
        {
            // Reuse the existing thumbnail.
            return str_replace($this->basePath, $this->baseUrl, $thumbnail);
        }
        else // The file has changed.
        {
            // Check all files in the folder for ones matching the old thumbnailed file.
            foreach(glob($this->basePath.DIRECTORY_SEPARATOR.$this->folderName.DIRECTORY_SEPARATOR.md5($fileName.$height.'thumbnail').'*') as $file)
            {
                if(is_file($thumbnail))
                {
                    unlink($thumbnail); // The file has been modified so delete the old one.
                }
            }
        }

        $size = getimagesize($fileName); // Get image size.
        $ratio = $size[0] / $size[1]; // Get image size ratio.

        // A new thumbnail must be created.
        Image::thumbnail($fileName, ceil($height * $ratio), $height)->save($thumbnail, ['quality' => 100]);

        // Return the url to the new thumnail.
        return str_replace($this->basePath, $this->baseUrl, $thumbnail);
    }

    /**
     * Flushes all the images contained in $path.
     * */
    public function flush()
    {
        if(!$this->basePath) // If no base path has been specified (the component was not initialized).
        {
            throw new \yii\base\Exception('Base path not specified.');
        }

        \yii\helpers\FileHelper::removeDirectory($this->basePath.DIRECTORY_SEPARATOR.$this->folderName);
    }
}


text:
package org.apache.hadoop.hdfs;

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

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.LocatedStripedBlock;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManagerTestUtil;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.namenode.ErasureCodingPolicyManager;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
import org.apache.hadoop.hdfs.server.protocol.BlockECRecoveryCommand.BlockECRecoveryInfo;
import org.apache.hadoop.hdfs.util.StripedBlockUtil;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class TestRecoverStripedFile {
  public static final Log LOG = LogFactory.getLog(TestRecoverStripedFile.class);

  private static final int dataBlkNum = StripedFileTestUtil.NUM_DATA_BLOCKS;
  private static final int parityBlkNum = StripedFileTestUtil.NUM_PARITY_BLOCKS;
  private static final int cellSize = StripedFileTestUtil.BLOCK_STRIPED_CELL_SIZE;
  private static final int blockSize = cellSize * 3;
  private static final int groupSize = dataBlkNum + parityBlkNum;
  private static final int dnNum = groupSize + parityBlkNum;

  static {
    GenericTestUtils.setLogLevel(DFSClient.LOG, Level.ALL);
  }

  private MiniDFSCluster cluster;
  private Configuration conf;
  private DistributedFileSystem fs;
  // Map: DatanodeID -> datanode index in cluster
  private Map<DatanodeID, Integer> dnMap = new HashMap<DatanodeID, Integer>();

  @Before
  public void setup() throws IOException {
    conf = new Configuration();
    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
    conf.setInt(DFSConfigKeys.DFS_DATANODE_STRIPED_READ_BUFFER_SIZE_KEY,
        cellSize - 1);
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 1);
    conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY,
        false);
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(dnNum).build();
    cluster.waitActive();

    fs = cluster.getFileSystem();
    fs.getClient().setErasureCodingPolicy("/", null);

    List<DataNode> datanodes = cluster.getDataNodes();
    for (int i = 0; i < dnNum; i++) {
      dnMap.put(datanodes.get(i).getDatanodeId(), i);
    }
  }

  @After
  public void tearDown() {
    if (cluster != null) {
      cluster.shutdown();
      cluster = null;
    }
  }

  @Test(timeout = 120000)
  public void testRecoverOneParityBlock() throws Exception {
    int fileLen = 10 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverOneParityBlock", fileLen, 0, 1);
  }

  @Test(timeout = 120000)
  public void testRecoverOneParityBlock1() throws Exception {
    int fileLen = cellSize + cellSize/10;
    assertFileBlocksRecovery("/testRecoverOneParityBlock1", fileLen, 0, 1);
  }

  @Test(timeout = 120000)
  public void testRecoverOneParityBlock2() throws Exception {
    int fileLen = 1;
    assertFileBlocksRecovery("/testRecoverOneParityBlock2", fileLen, 0, 1);
  }

  @Test(timeout = 120000)
  public void testRecoverOneParityBlock3() throws Exception {
    int fileLen = 3 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverOneParityBlock3", fileLen, 0, 1);
  }

  @Test(timeout = 120000)
  public void testRecoverThreeParityBlocks() throws Exception {
    int fileLen = 10 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverThreeParityBlocks", fileLen, 0, 3);
  }

  @Test(timeout = 120000)
  public void testRecoverThreeDataBlocks() throws Exception {
    int fileLen = 10 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverThreeDataBlocks", fileLen, 1, 3);
  }

  @Test(timeout = 120000)
  public void testRecoverThreeDataBlocks1() throws Exception {
    int fileLen = 3 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverThreeDataBlocks1", fileLen, 1, 3);
  }

  @Test(timeout = 120000)
  public void testRecoverOneDataBlock() throws Exception {
    int fileLen = 10 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverOneDataBlock", fileLen, 1, 1);
  }

  @Test(timeout = 120000)
  public void testRecoverOneDataBlock1() throws Exception {
    int fileLen = cellSize + cellSize/10;
    assertFileBlocksRecovery("/testRecoverOneDataBlock1", fileLen, 1, 1);
  }

  @Test(timeout = 120000)
  public void testRecoverOneDataBlock2() throws Exception {
    int fileLen = 1;
    assertFileBlocksRecovery("/testRecoverOneDataBlock2", fileLen, 1, 1);
  }

  @Test(timeout = 120000)
  public void testRecoverAnyBlocks() throws Exception {
    int fileLen = 3 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverAnyBlocks", fileLen, 2, 2);
  }

  @Test(timeout = 120000)
  public void testRecoverAnyBlocks1() throws Exception {
    int fileLen = 10 * blockSize + blockSize/10;
    assertFileBlocksRecovery("/testRecoverAnyBlocks1", fileLen, 2, 3);
  }

  /**
   * Test the file blocks recovery.
   * 1. Check the replica is recovered in the target datanode,
   *    and verify the block replica length, generationStamp and content.
   * 2. Read the file and verify content.
   */
  private void assertFileBlocksRecovery(String fileName, int fileLen,
      int recovery, int toRecoverBlockNum) throws Exception {
    if (recovery != 0 && recovery != 1 && recovery != 2) {
      Assert.fail("Invalid recovery: 0 is to recovery parity blocks,"
          + "1 is to recovery data blocks, 2 is any.");
    }
    if (toRecoverBlockNum < 1 || toRecoverBlockNum > parityBlkNum) {
      Assert.fail("toRecoverBlockNum should be between 1 ~ " + parityBlkNum);
    }

    Path file = new Path(fileName);

    final byte[] data = new byte[fileLen];
    ThreadLocalRandom.current().nextBytes(data);
    DFSTestUtil.writeFile(fs, file, data);
    StripedFileTestUtil.waitBlockGroupsReported(fs, fileName);

    LocatedBlocks locatedBlocks = getLocatedBlocks(file);
    assertEquals(locatedBlocks.getFileLength(), fileLen);

    LocatedStripedBlock lastBlock =
        (LocatedStripedBlock)locatedBlocks.getLastLocatedBlock();

    DatanodeInfo[] storageInfos = lastBlock.getLocations();
    byte[] indices = lastBlock.getBlockIndices();

    BitSet bitset = new BitSet(dnNum);
    for (DatanodeInfo storageInfo : storageInfos) {
      bitset.set(dnMap.get(storageInfo));
    }

    int[] toDead = new int[toRecoverBlockNum];
    int n = 0;
    for (int i = 0; i < indices.length; i++) {
      if (n < toRecoverBlockNum) {
        if (recovery == 0) {
          if (indices[i] >= dataBlkNum) {
            toDead[n++] = i;
          }
        } else if (recovery == 1) {
          if (indices[i] < dataBlkNum) {
            toDead[n++] = i;
          }
        } else {
          toDead[n++] = i;
        }
      } else {
        break;
      }
    }

    DatanodeInfo[] dataDNs = new DatanodeInfo[toRecoverBlockNum];
    int[] deadDnIndices = new int[toRecoverBlockNum];
    ExtendedBlock[] blocks = new ExtendedBlock[toRecoverBlockNum];
    File[] replicas = new File[toRecoverBlockNum];
    File[] metadatas = new File[toRecoverBlockNum];
    byte[][] replicaContents = new byte[toRecoverBlockNum][];
    for (int i = 0; i < toRecoverBlockNum; i++) {
      dataDNs[i] = storageInfos[toDead[i]];
      deadDnIndices[i] = dnMap.get(dataDNs[i]);

      // Check the block replica file on deadDn before it dead.
      blocks[i] = StripedBlockUtil.constructInternalBlock(
          lastBlock.getBlock(), cellSize, dataBlkNum, indices[toDead[i]]);
      replicas[i] = cluster.getBlockFile(deadDnIndices[i], blocks[i]);
      metadatas[i] = cluster.getBlockMetadataFile(deadDnIndices[i], blocks[i]);
      // the block replica on the datanode should be the same as expected
      assertEquals(replicas[i].length(),
          StripedBlockUtil.getInternalBlockLength(
          lastBlock.getBlockSize(), cellSize, dataBlkNum, indices[toDead[i]]));
      assertTrue(metadatas[i].getName().
          endsWith(blocks[i].getGenerationStamp() + ".meta"));
      replicaContents[i] = DFSTestUtil.readFileAsBytes(replicas[i]);
    }

    int cellsNum = (fileLen - 1) / cellSize + 1;
    int groupSize = Math.min(cellsNum, dataBlkNum) + parityBlkNum;

    for (int i = 0; i < toRecoverBlockNum; i++) {
      /*
       * Kill the datanode which contains one replica
       * We need to make sure it dead in namenode: clear its update time and
       * trigger NN to check heartbeat.
       */
      DataNode dn = cluster.getDataNodes().get(deadDnIndices[i]);
      dn.shutdown();
      cluster.setDataNodeDead(dn.getDatanodeId());
    }

    // Check the locatedBlocks of the file again
    locatedBlocks = getLocatedBlocks(file);
    lastBlock = (LocatedStripedBlock)locatedBlocks.getLastLocatedBlock();
    storageInfos = lastBlock.getLocations();
    assertEquals(storageInfos.length, groupSize - toRecoverBlockNum);

    int[] targetDNs = new int[dnNum - groupSize];
    n = 0;
    for (int i = 0; i < dnNum; i++) {
      if (!bitset.get(i)) { // not contain replica of the block.
        targetDNs[n++] = i;
      }
    }

    waitForRecoveryFinished(file, groupSize);

    targetDNs = sortTargetsByReplicas(blocks, targetDNs);

    // Check the replica on the new target node.
    for (int i = 0; i < toRecoverBlockNum; i++) {
      File replicaAfterRecovery = cluster.getBlockFile(targetDNs[i], blocks[i]);
      File metadataAfterRecovery =
          cluster.getBlockMetadataFile(targetDNs[i], blocks[i]);
      assertEquals(replicaAfterRecovery.length(), replicas[i].length());
      assertTrue(metadataAfterRecovery.getName().
          endsWith(blocks[i].getGenerationStamp() + ".meta"));
      byte[] replicaContentAfterRecovery =
          DFSTestUtil.readFileAsBytes(replicaAfterRecovery);

      Assert.assertArrayEquals(replicaContents[i], replicaContentAfterRecovery);
    }
  }

  private int[] sortTargetsByReplicas(ExtendedBlock[] blocks, int[] targetDNs) {
    int[] result = new int[blocks.length];
    for (int i = 0; i < blocks.length; i++) {
      result[i] = -1;
      for (int j = 0; j < targetDNs.length; j++) {
        if (targetDNs[j] != -1) {
          File replica = cluster.getBlockFile(targetDNs[j], blocks[i]);
          if (replica != null) {
            result[i] = targetDNs[j];
            targetDNs[j] = -1;
            break;
          }
        }
      }
      if (result[i] == -1) {
        Assert.fail("Failed to recover striped block: " + blocks[i].getBlockId());
      }
    }
    return result;
  }

  private LocatedBlocks waitForRecoveryFinished(Path file, int groupSize)
      throws Exception {
    final int ATTEMPTS = 60;
    for (int i = 0; i < ATTEMPTS; i++) {
      LocatedBlocks locatedBlocks = getLocatedBlocks(file);
      LocatedStripedBlock lastBlock =
          (LocatedStripedBlock)locatedBlocks.getLastLocatedBlock();
      DatanodeInfo[] storageInfos = lastBlock.getLocations();
      if (storageInfos.length >= groupSize) {
        return locatedBlocks;
      }
      Thread.sleep(1000);
    }
    throw new IOException ("Time out waiting for EC block recovery.");
  }

  private LocatedBlocks getLocatedBlocks(Path file) throws IOException {
    return fs.getClient().getLocatedBlocks(file.toString(), 0, Long.MAX_VALUE);
  }

  /*
   * Tests that processErasureCodingTasks should not throw exceptions out due to
   * invalid ECTask submission.
   */
  @Test
  public void testProcessErasureCodingTasksSubmitionShouldSucceed()
      throws Exception {
    DataNode dataNode = cluster.dataNodes.get(0).datanode;

    // Pack invalid(dummy) parameters in ecTasks. Irrespective of parameters, each task
    // thread pool submission should succeed, so that it will not prevent
    // processing other tasks in the list if any exceptions.
    int size = cluster.dataNodes.size();
    byte[] liveIndices = new byte[size];
    DatanodeInfo[] dataDNs = new DatanodeInfo[size + 1];
    DatanodeStorageInfo targetDnInfos_1 = BlockManagerTestUtil
        .newDatanodeStorageInfo(DFSTestUtil.getLocalDatanodeDescriptor(),
            new DatanodeStorage("s01"));
    DatanodeStorageInfo[] dnStorageInfo = new DatanodeStorageInfo[] {
        targetDnInfos_1 };

    BlockECRecoveryInfo invalidECInfo = new BlockECRecoveryInfo(
        new ExtendedBlock("bp-id", 123456), dataDNs, dnStorageInfo, liveIndices,
        ErasureCodingPolicyManager.getSystemDefaultPolicy());
    List<BlockECRecoveryInfo> ecTasks = new ArrayList<BlockECRecoveryInfo>();
    ecTasks.add(invalidECInfo);
    dataNode.getErasureCodingWorker().processErasureCodingTasks(ecTasks);
  }
}


text:
#include <aws/organizations/model/CreateAccountFailureReason.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace Organizations
  {
    namespace Model
    {
      namespace CreateAccountFailureReasonMapper
      {

        static const int ACCOUNT_LIMIT_EXCEEDED_HASH = HashingUtils::HashString("ACCOUNT_LIMIT_EXCEEDED");
        static const int EMAIL_ALREADY_EXISTS_HASH = HashingUtils::HashString("EMAIL_ALREADY_EXISTS");
        static const int INVALID_ADDRESS_HASH = HashingUtils::HashString("INVALID_ADDRESS");
        static const int INVALID_EMAIL_HASH = HashingUtils::HashString("INVALID_EMAIL");
        static const int CONCURRENT_ACCOUNT_MODIFICATION_HASH = HashingUtils::HashString("CONCURRENT_ACCOUNT_MODIFICATION");
        static const int INTERNAL_FAILURE_HASH = HashingUtils::HashString("INTERNAL_FAILURE");
        static const int GOVCLOUD_ACCOUNT_ALREADY_EXISTS_HASH = HashingUtils::HashString("GOVCLOUD_ACCOUNT_ALREADY_EXISTS");
        static const int MISSING_BUSINESS_VALIDATION_HASH = HashingUtils::HashString("MISSING_BUSINESS_VALIDATION");
        static const int FAILED_BUSINESS_VALIDATION_HASH = HashingUtils::HashString("FAILED_BUSINESS_VALIDATION");
        static const int PENDING_BUSINESS_VALIDATION_HASH = HashingUtils::HashString("PENDING_BUSINESS_VALIDATION");
        static const int INVALID_IDENTITY_FOR_BUSINESS_VALIDATION_HASH = HashingUtils::HashString("INVALID_IDENTITY_FOR_BUSINESS_VALIDATION");
        static const int UNKNOWN_BUSINESS_VALIDATION_HASH = HashingUtils::HashString("UNKNOWN_BUSINESS_VALIDATION");
        static const int MISSING_PAYMENT_INSTRUMENT_HASH = HashingUtils::HashString("MISSING_PAYMENT_INSTRUMENT");
        static const int INVALID_PAYMENT_INSTRUMENT_HASH = HashingUtils::HashString("INVALID_PAYMENT_INSTRUMENT");

        CreateAccountFailureReason GetCreateAccountFailureReasonForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == ACCOUNT_LIMIT_EXCEEDED_HASH)
          {
            return CreateAccountFailureReason::ACCOUNT_LIMIT_EXCEEDED;
          }
          else if (hashCode == EMAIL_ALREADY_EXISTS_HASH)
          {
            return CreateAccountFailureReason::EMAIL_ALREADY_EXISTS;
          }
          else if (hashCode == INVALID_ADDRESS_HASH)
          {
            return CreateAccountFailureReason::INVALID_ADDRESS;
          }
          else if (hashCode == INVALID_EMAIL_HASH)
          {
            return CreateAccountFailureReason::INVALID_EMAIL;
          }
          else if (hashCode == CONCURRENT_ACCOUNT_MODIFICATION_HASH)
          {
            return CreateAccountFailureReason::CONCURRENT_ACCOUNT_MODIFICATION;
          }
          else if (hashCode == INTERNAL_FAILURE_HASH)
          {
            return CreateAccountFailureReason::INTERNAL_FAILURE;
          }
          else if (hashCode == GOVCLOUD_ACCOUNT_ALREADY_EXISTS_HASH)
          {
            return CreateAccountFailureReason::GOVCLOUD_ACCOUNT_ALREADY_EXISTS;
          }
          else if (hashCode == MISSING_BUSINESS_VALIDATION_HASH)
          {
            return CreateAccountFailureReason::MISSING_BUSINESS_VALIDATION;
          }
          else if (hashCode == FAILED_BUSINESS_VALIDATION_HASH)
          {
            return CreateAccountFailureReason::FAILED_BUSINESS_VALIDATION;
          }
          else if (hashCode == PENDING_BUSINESS_VALIDATION_HASH)
          {
            return CreateAccountFailureReason::PENDING_BUSINESS_VALIDATION;
          }
          else if (hashCode == INVALID_IDENTITY_FOR_BUSINESS_VALIDATION_HASH)
          {
            return CreateAccountFailureReason::INVALID_IDENTITY_FOR_BUSINESS_VALIDATION;
          }
          else if (hashCode == UNKNOWN_BUSINESS_VALIDATION_HASH)
          {
            return CreateAccountFailureReason::UNKNOWN_BUSINESS_VALIDATION;
          }
          else if (hashCode == MISSING_PAYMENT_INSTRUMENT_HASH)
          {
            return CreateAccountFailureReason::MISSING_PAYMENT_INSTRUMENT;
          }
          else if (hashCode == INVALID_PAYMENT_INSTRUMENT_HASH)
          {
            return CreateAccountFailureReason::INVALID_PAYMENT_INSTRUMENT;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<CreateAccountFailureReason>(hashCode);
          }

          return CreateAccountFailureReason::NOT_SET;
        }

        Aws::String GetNameForCreateAccountFailureReason(CreateAccountFailureReason enumValue)
        {
          switch(enumValue)
          {
          case CreateAccountFailureReason::ACCOUNT_LIMIT_EXCEEDED:
            return "ACCOUNT_LIMIT_EXCEEDED";
          case CreateAccountFailureReason::EMAIL_ALREADY_EXISTS:
            return "EMAIL_ALREADY_EXISTS";
          case CreateAccountFailureReason::INVALID_ADDRESS:
            return "INVALID_ADDRESS";
          case CreateAccountFailureReason::INVALID_EMAIL:
            return "INVALID_EMAIL";
          case CreateAccountFailureReason::CONCURRENT_ACCOUNT_MODIFICATION:
            return "CONCURRENT_ACCOUNT_MODIFICATION";
          case CreateAccountFailureReason::INTERNAL_FAILURE:
            return "INTERNAL_FAILURE";
          case CreateAccountFailureReason::GOVCLOUD_ACCOUNT_ALREADY_EXISTS:
            return "GOVCLOUD_ACCOUNT_ALREADY_EXISTS";
          case CreateAccountFailureReason::MISSING_BUSINESS_VALIDATION:
            return "MISSING_BUSINESS_VALIDATION";
          case CreateAccountFailureReason::FAILED_BUSINESS_VALIDATION:
            return "FAILED_BUSINESS_VALIDATION";
          case CreateAccountFailureReason::PENDING_BUSINESS_VALIDATION:
            return "PENDING_BUSINESS_VALIDATION";
          case CreateAccountFailureReason::INVALID_IDENTITY_FOR_BUSINESS_VALIDATION:
            return "INVALID_IDENTITY_FOR_BUSINESS_VALIDATION";
          case CreateAccountFailureReason::UNKNOWN_BUSINESS_VALIDATION:
            return "UNKNOWN_BUSINESS_VALIDATION";
          case CreateAccountFailureReason::MISSING_PAYMENT_INSTRUMENT:
            return "MISSING_PAYMENT_INSTRUMENT";
          case CreateAccountFailureReason::INVALID_PAYMENT_INSTRUMENT:
            return "INVALID_PAYMENT_INSTRUMENT";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace CreateAccountFailureReasonMapper
    } // namespace Model
  } // namespace Organizations
} // namespace Aws


text:
package org.deeplearning4j.optimize.listeners;

import lombok.Builder;
import org.deeplearning4j.nn.api.Model;
import org.deeplearning4j.optimize.api.IterationListener;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.ops.transforms.Transforms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Map;

/**
 * An iteration listener that provides details on parameters and gradients at each iteration during traning.
 * Attempts to provide much of the same information as the UI histogram iteration listener, but in a text-based
 * format (for example, when learning on a system accessed via SSH etc).
 * i.e., is intended to aid network tuning and debugging

 * This iteration listener is set up to calculate mean, min, max, and mean absolute value
 * of each type of parameter and gradient in the network at each iteration.

 * These
 *
 *
 * @author Alex Black
 */
public class ParamAndGradientIterationListener implements IterationListener {
    private static final int MAX_WRITE_FAILURE_MESSAGES = 10;
    private static final Logger logger = LoggerFactory.getLogger(ParamAndGradientIterationListener.class);

    private boolean invoked = false;

    private int iterations;
    private long totalIterationCount = 0;
    private boolean printMean = true;
    private boolean printHeader = true;
    private boolean printMinMax = true;
    private boolean printMeanAbsValue = true;
    private File file;
    private Path filePath;
    private boolean outputToConsole;
    private boolean outputToFile;
    private boolean outputToLogger;
    private String delimiter = "\t";

    private int writeFailureCount = 0;

    /** Default constructor for output to console only every iteration, tab delimited */
    public ParamAndGradientIterationListener() {
        this(1, true, true, true, true, true, false, false, null, "\t");
    }

    /**Full constructor with all options.
     * Note also: ParamAndGradientIterationListener.builder() can be used instead of this constructor.
     * @param iterations calculate and report values every 'iterations' iterations
     * @param printHeader Whether to output a header row (i.e., names for each column)
     * @param printMean Calculate and display the mean of parameters and gradients
     * @param printMinMax Calculate and display the min/max of the parameters and gradients
     * @param printMeanAbsValue Calculate and display the mean absolute value
     * @param outputToConsole If true, display the values to the console (System.out.println())
     * @param outputToFile If true, write the values to a file, one per line
     * @param outputToLogger If true, log the values
     * @param file File to write values to. May be null, not used if outputToFile == false
     * @param delimiter delimiter (for example, "\t" or "," etc)
     */
    @Builder
    public ParamAndGradientIterationListener(int iterations, boolean printHeader, boolean printMean,
                    boolean printMinMax, boolean printMeanAbsValue, boolean outputToConsole, boolean outputToFile,
                    boolean outputToLogger, File file, String delimiter) {
        this.printHeader = printHeader;
        this.printMean = printMean;
        this.printMinMax = printMinMax;
        this.printMeanAbsValue = printMeanAbsValue;
        this.iterations = iterations;
        this.file = file;
        if (this.file != null) {
            this.filePath = file.toPath();
        }
        this.outputToConsole = outputToConsole;
        this.outputToFile = outputToFile;
        this.outputToLogger = outputToLogger;
        this.delimiter = delimiter;
    }

    @Override
    public boolean invoked() {
        return invoked;
    }

    @Override
    public void invoke() {
        invoked = true;
    }

    @Override
    public void iterationDone(Model model, int iteration) {
        totalIterationCount++;

        if (totalIterationCount == 1 && printHeader) {
            Map<String, INDArray> params = model.paramTable();
            model.conf().getVariables();

            StringBuilder sb = new StringBuilder();

            sb.append("n");
            sb.append(delimiter);
            sb.append("score");

            for (String s : params.keySet()) {
                //Parameters:
                if (printMean)
                    sb.append(delimiter).append(s).append("_mean");
                //Min, max
                if (printMinMax) {
                    sb.append(delimiter).append(s).append("_min").append(delimiter).append(s).append("_max");
                }
                if (printMeanAbsValue)
                    sb.append(delimiter).append(s).append("_meanAbsValue");

                //Gradients:
                if (printMean)
                    sb.append(delimiter).append(s).append("_meanG");
                //Min, max
                if (printMinMax) {
                    sb.append(delimiter).append(s).append("_minG").append(delimiter).append(s).append("_maxG");
                }
                if (printMeanAbsValue)
                    sb.append(delimiter).append(s).append("_meanAbsValueG");
            }
            sb.append("\n");

            if (outputToFile) {
                try {
                    Files.write(filePath, sb.toString().getBytes(), StandardOpenOption.CREATE,
                                    StandardOpenOption.TRUNCATE_EXISTING);
                } catch (IOException e) {
                    if (writeFailureCount++ < MAX_WRITE_FAILURE_MESSAGES) {
                        //Print error message
                        logger.warn("Error writing to file: {}", e);
                    }
                    if (writeFailureCount == MAX_WRITE_FAILURE_MESSAGES) {
                        logger.warn("Max file write messages displayed. No more failure messages will be printed");
                    }
                }
            }

            if (outputToLogger)
                logger.info(sb.toString());
            if (outputToConsole)
                System.out.println(sb.toString());
        }

        if (totalIterationCount % iterations != 0)
            return; //No op this iteration

        Map<String, INDArray> params = model.paramTable();
        Map<String, INDArray> grads = model.gradient().gradientForVariable();

        StringBuilder sb = new StringBuilder();
        sb.append(totalIterationCount);
        sb.append(delimiter);
        sb.append(model.score());

        //Calculate actual values for parameters and gradients
        for (Map.Entry<String, INDArray> entry : params.entrySet()) {
            INDArray currParams = entry.getValue();
            INDArray currGrad = grads.get(entry.getKey());

            //Parameters:
            if (printMean) {
                sb.append(delimiter);
                sb.append(currParams.meanNumber().doubleValue());
            }
            if (printMinMax) {
                sb.append(delimiter);
                sb.append(currParams.minNumber().doubleValue());
                sb.append(delimiter);
                sb.append(currParams.maxNumber().doubleValue());
            }
            if (printMeanAbsValue) {
                sb.append(delimiter);
                INDArray abs = Transforms.abs(currParams.dup());
                sb.append(abs.meanNumber().doubleValue());
            }

            //Gradients:
            if (printMean) {
                sb.append(delimiter);
                sb.append(currGrad.meanNumber().doubleValue());
            }
            if (printMinMax) {
                sb.append(delimiter);
                sb.append(currGrad.minNumber().doubleValue());
                sb.append(delimiter);
                sb.append(currGrad.maxNumber().doubleValue());
            }
            if (printMeanAbsValue) {
                sb.append(delimiter);
                INDArray abs = Transforms.abs(currGrad.dup());
                sb.append(abs.meanNumber().doubleValue());
            }
        }
        sb.append("\n");

        String out = sb.toString();
        if (outputToLogger)
            logger.info(out);
        if (outputToConsole)
            System.out.print(out);

        if (outputToFile) {
            try {
                Files.write(filePath, out.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            } catch (IOException e) {
                if (writeFailureCount++ < MAX_WRITE_FAILURE_MESSAGES) {
                    //Print error message
                    logger.warn("Error writing to file: {}", e);
                }
                if (writeFailureCount == MAX_WRITE_FAILURE_MESSAGES) {
                    logger.warn("Max file write messages displayed. No more failure messages will be printed");
                }
            }
        }

    }
}


text:
require 'spec_helper'
require File.expand_path('lib/haystack/instrumentations/net_http')

describe "Net::HTTP instrumentation" do
  let(:events) { [] }
  before do
    ActiveSupport::Notifications.subscribe(/^[^!]/) do |*args|
      events << ActiveSupport::Notifications::Event.new(*args)
    end
  end

  it "should instrument request" do
    stub_request(:any, 'www.google.com')

    Net::HTTP.get_response(URI.parse('http://www.google.com'))

    event = events.last
    event.name.should == 'request.net_http'
    event.payload[:host].should == 'www.google.com'
    event.payload[:scheme].should == 'http'
    event.payload[:path].should == '/'
    event.payload[:method].should == 'GET'
  end
end


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

class My404 extends CI_Controller {
	public function __construct()
	{

		parent::__construct();
	}
    public function index(){

    	$this->load->view('partials/404');

    }
}


text:
(function() {
  var HarResult, Statistic;

  HarResult = require('./harResult');

  Statistic = (function() {
    function Statistic(results) {
      var res, _i, _len;
      if (results == null) {
        results = [];
      }
      this.results = [];
      for (_i = 0, _len = results.length; _i < _len; _i++) {
        res = results[_i];
        this.addResult(res);
      }
    }

    Statistic.prototype.addResult = function(result) {
      return this.results.push(result);
    };

    Statistic.prototype.average = function() {
      var r, result, _i, _len, _ref;
      result = new HarResult();
      if (this.results.length) {
        _ref = this.results;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          r = _ref[_i];
          result = HarResult.add(result, r);
        }
        result = HarResult.divideBy(result, this.results.length);
      }
      return result;
    };

    Statistic.prototype.deviation = function() {
      var average, r, result, tmp, _i, _len, _ref;
      result = new HarResult();
      average = this.average();
      _ref = this.results;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        r = _ref[_i];
        tmp = HarResult.substract(average, r);
        tmp = HarResult.pow(tmp, 2);
        result = HarResult.add(result, tmp);
      }
      result = HarResult.divideBy(result, this.results.length);
      return HarResult.sqrt(result);
    };

    return Statistic;

  })();

  module.exports = Statistic;

}).call(this);


text:
#include "network/parameter_collection.h"

#include <google/protobuf/descriptor.h>
#include <iosfwd>
#include <iostream>
#include <ostream>

#include "google/protobuf/message.h"

namespace bigbrain {

ParameterCollection::ParameterCollection() {
}

ParameterCollection::~ParameterCollection() {
  for (auto paramset : param_list_) {
    delete paramset;
  }
}

google::protobuf::Message* ParameterCollection::Insert(
    google::protobuf::Message* input_param_set) {
  std::string input;
  std::string saved;

  std::string input_description =
      input_param_set->GetDescriptor()->DebugString();

  for (auto paramset : param_list_) {
    std::string paramset_description = paramset->GetDescriptor()->DebugString();

    if (paramset_description != input_description) {
      continue;
    }
    if (input_param_set->SerializeAsString() == paramset->SerializeAsString()) {
      delete input_param_set;
      return paramset;
    }
  }
  printf("[PC] Adding new parameter set\n");
  param_list_.push_back(input_param_set);
  return input_param_set;
}

void ParameterCollection::Collapse() {
  for (auto p : param_list_) {
    delete p;
  }
  param_list_.clear();
}

}  // namespace bigbrain