text:
#ifndef _EXCEPTION_H_
#define _EXCEPTION_H_

#ifdef __ASSEMBLER__
#define	Const_(x)	$##x
#else
#define	Const_(x)	x
#endif

#ifndef SW_C1
#include "fpu_emu.h"
#endif SW_C1

#define FPU_BUSY        Const_(0x8000)   /* FPU busy bit (8087 compatibility) */
#define EX_ErrorSummary Const_(0x0080)   /* Error summary status */
/* Special exceptions: */
#define	EX_INTERNAL	Const_(0x8000)	/* Internal error in wm-FPU-emu */
#define EX_StackOver	Const_(0x0041|SW_C1)	/* stack overflow */
#define EX_StackUnder	Const_(0x0041)	/* stack underflow */
/* Exception flags: */
#define EX_Precision	Const_(0x0020)	/* loss of precision */
#define EX_Underflow	Const_(0x0010)	/* underflow */
#define EX_Overflow	Const_(0x0008)	/* overflow */
#define EX_ZeroDiv	Const_(0x0004)	/* divide by zero */
#define EX_Denormal	Const_(0x0002)	/* denormalized operand */
#define EX_Invalid	Const_(0x0001)	/* invalid operation */

#define PRECISION_LOST_UP    Const_((EX_Precision | SW_C1))
#define PRECISION_LOST_DOWN  Const_(EX_Precision)

#ifndef __ASSEMBLER__

#ifdef DEBUG
#define	EXCEPTION(x)	{ printk("exception in %s at line %d\n", \
	__FILE__, __LINE__); exception(x); }
#else
#define	EXCEPTION(x)	exception(x)
#endif

#endif __ASSEMBLER__

#endif _EXCEPTION_H_


text:
class AddArea < ActiveRecord::Migration
  def self.up

    create_table(:areas) do |t|
      t.column 'title', :string
      t.column 'title_dashed', :string
    end

    add_column 'users', 'level', :integer
    add_column 'users', 'area_id', :integer
    add_column 'categories', 'area_id', :integer
    add_column 'posts', 'area_id', :integer
  end

  def self.down

    drop_table(:areas)

    remove_column 'users', 'level'
    remove_column 'users', 'area_id'
    remove_column 'categories', 'area_id'
    remove_column 'posts', 'area_id'
  end
end

redpajama_set_name: RedPajamaGithub


text:
import { test } from 'substance-test'
import { DefaultDOMElement } from 'substance'
import { FnGroupConverter } from 'substance-texture'
import readFixture from '../fixture/readFixture'

const fixture = readFixture('fn-group.xml')
const noFnGroupFixture = readFixture('empty-back.xml')

test('FnGroupConverter: Import document without fn-group', function (t) {
  let dom = DefaultDOMElement.parseXML(noFnGroupFixture)
  let converter = new FnGroupConverter()
  converter.import(dom)

  let fnGroup = dom.find('fn-group')
  t.ok(fnGroup, 'should be one fn-group')
  t.equal(fnGroup.children.length, 0, 'fn-group should be empty')

  t.end()
})

test('FnGroupConverter: Import document with fn-group', function (t) {
  let dom = DefaultDOMElement.parseXML(fixture)
  let converter = new FnGroupConverter()
  converter.import(dom)

  let fnGroup = dom.find('fn-group')
  t.ok(fnGroup, 'should be one fn-group')
  t.ok(fnGroup.children.length > 0, 'fn-group should be non empty')

  let xTags = fnGroup.find('x')
  t.notOk(xTags, 'should be no x tags inside fn-group')

  t.end()
})

test('FnGroupConverter: Export empty fn-group', function (t) {
  let dom = DefaultDOMElement.parseXML(noFnGroupFixture)
  let converter = new FnGroupConverter()
  converter.import(dom)
  converter.export(dom)

  let fnGroup = dom.find('fn-group')
  t.notOk(fnGroup, 'should be no fn-group')

  t.end()
})

test('FnGroupConverter: Export not empty fn-group', function (t) {
  let dom = DefaultDOMElement.parseXML(fixture)
  let converter = new FnGroupConverter()
  converter.import(dom)
  converter.export(dom)

  let fnGroup = dom.find('fn-group')
  t.ok(fnGroup, 'should be fn-group')

  t.end()
})


text:
All errors in Elixir implement the _Exception Behaviour_. Just like the _Access Behaviour_, the _Exception Behaviour_ defines callback functions that a module must implement to fulfill the software contract of the behaviour. Once an error is defined, it has the following properties:

- The module's name defines the error's name.
- The module defines an error-struct.
- The struct will have a `:message` field.
- The module can be be used with `raise/1` and `raise/2` to raise the intended error

The _Exception Behaviour_ also specifies two callbacks: `message/1` and `exception/1`. If unimplemented, default implementations will be used. `message/1` transforms the error-struct to a readable message when called with `raise`. `exception/1` allows additional context to be added to the message when it is called with `raise/2`

### Defining an exception

To define an exception from an error module, we use the `defexception` macro:

```elixir
# Defines a minimal error, with the name `MyError`
defmodule MyError do
  defexception message: "error"
end

# Defines an error with a customized exception/1 function
defmodule MyCustomizedError do
  defexception message: "custom error"

  @impl true
  def exception(value) do
    case value do
      [] ->
        %MyCustomizedError{}
      _ ->
        %MyCustomizedError{message: "Alert: " <> value}
    end
  end
end
```

### Using exceptions

Defined errors may be used like a built in error using either `raise/1` or `raise/2`.

- `raise/1` raises a specific error by its module name, or, if the argument is a string, it will raise a `RuntimeError` with the string as the message.
- `raise/2` raises a specific error by its module name, and accepts an attributes argument which is used to obtain the error with the appropriate message.


text:
package com.celeral.netlet.util;

import java.io.Closeable;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.celeral.utils.Attribute;

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.context.propagation.TextMapSetter;

public abstract class Telemetry {
  static OpenTelemetry instance;
  public static Tracer tracer;

  static {
    setTelemetryInstance(GlobalOpenTelemetry.get());
  }

  public static void setTelemetryInstance(OpenTelemetry telemetry) {
    tracer = telemetry.getTracer("netlet", "2.0.0");
    instance = telemetry;
  }

  public static final Attribute<Map<String, String>> CONTEXT = new Attribute<>(null);

  public static Closeable getCloseable(Span span) {
    return span::end;
  }

  public static Map<String, String> getInjectableContext() {
    HashMap<String, String> map = new HashMap<>();
    populateInjectableContext(map);
    return map;
  }

  static class MapTextMapSetter implements TextMapSetter<Map<String, String>> {
    @Override
    public void set(Map<String, String> carrier, String key, String value) {
      carrier.put(key, value);
    }

    static final MapTextMapSetter INSTANCE = new MapTextMapSetter();
  }

  static void populateInjectableContext(Map<String, String> map) {
    ContextPropagators propagators = instance.getPropagators();
    TextMapPropagator textMapPropagator = propagators.getTextMapPropagator();
    textMapPropagator.inject(Context.current(), map, MapTextMapSetter.INSTANCE);
  }

  static class MapTextMapGetter implements TextMapGetter<Map<String, String>> {
    @Override
    public Iterable<String> keys(Map<String, String> carrier) {
      return carrier.keySet();
    }

    @Override
    public String get(Map<String, String> carrier, String key) {
      return carrier.get(key);
    }

    static final MapTextMapGetter INSTANCE = new MapTextMapGetter();
  }

  public static Context getExtractedContext(Map<String, String> map) {
    if (map == null) {
      return Context.current();
    }

    ContextPropagators propagators = instance.getPropagators();
    TextMapPropagator textMapPropagator = propagators.getTextMapPropagator();
    return textMapPropagator.extract(Context.current(), map, MapTextMapGetter.INSTANCE);
  }

  private static final long serialVersionUID =
      Attribute.AttributeMap.AttributeInitializer.initialize(Telemetry.class);
  private static final Logger logger = LogManager.getLogger(Telemetry.class);
}


text:
{-# LANGUAGE BangPatterns, RankNTypes, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module ECC.Code.LDPC.Reference.Min where

-- Reference implementation of LDPC with tanh/atanh replaced with the min
-- approach.

-- TODO: Make sure this is correct

import ECC.Code.LDPC.Utils
import ECC.Types
import ECC.Puncture
import Data.Char (isDigit)
import Data.Matrix
import Data.Bit
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import Debug.Trace

type M a = Matrix a
type V a = U.Vector a

code :: Code
code = mkLDPC_Code "min" encoder decoder

---------------------------------------------------------------------

encoder :: M Bool -> Rate -> U.Vector Bool -> U.Vector Bool
encoder g _ v = U.map toBool $ U.convert (getRow 1 (multStd (rowVector $ U.convert (U.map fromBool v)) ((fmap fromBool g))))

---------------------------------------------------------------------

decoder :: M Bool -> Rate -> Int -> U.Vector Double -> Maybe (U.Vector Bool)
decoder a rate maxIterations orig_lam = Just $ U.convert (ldpc a maxIterations (U.convert orig_lam))

toBit :: Num a => Bool -> a
toBit False = 0
toBit True  = 1

fromBit :: (Num a, Eq a, Show a) => a -> Bool
fromBit 0 = False
fromBit 1 = True
fromBit n = error $ "fromBit: " ++ show n

multStd' :: M Bool -> M Bool -> M Bool
multStd' a b = fmap fromBit $ multStd (fmap toBit a) (fmap toBit b)

toBits :: M Bool -> M Bit
toBits = fmap toBit

fromBits :: M Bit -> M Bool
fromBits = fmap fromBit

ldpc :: M Bool -> Int -> V Double -> V Bool
ldpc a0 maxIterations orig_lam = U.map hard $ loop 0 orig_ne orig_lam
  where
    a :: M Bit
    a = toBits a0

    orig_ne :: M Double
    orig_ne = fmap (const 0) a

    loop :: Int -> M Double -> V Double -> V Double
    loop !n ne lam
        | U.all (== False) ans     = lam
        | n >= maxIterations       = orig_lam
        | otherwise                = loop (n+1) ne' lam'
      where
        c_hat :: V Bit
        c_hat = U.map (toBit . hard) lam

        ans :: V Bool
        ans = U.convert $ fmap fromBit $ getCol 1 (a `multStd` colVector (U.convert c_hat))

        ne' :: M Double
        ne' = matrix (nrows orig_ne) (ncols orig_ne) $ \ (m,n) ->
                if a ! (m,n) == 1
                then
                  (-3/4) * foldr1 min'
                        [ - (lam U.! (j-1) - ne ! (m,j))
                        | j <- [1 .. U.length orig_lam]
                        , j /= n
                        , a ! (m,j) == 1
                        ]
                else 0

        min' x y = signum x * signum y * min (abs x) (abs y)

        -- ne' :: M Double
        -- ne' = matrix (nrows orig_ne) (ncols orig_ne) $ \ (m,n) ->
        --         if a ! (m,n) == 1
        --         then
        --             -2 * atanh' (product
        --                 [ tanh (- ((lam U.! (j-1) - ne ! (m,j)) / 2))
        --                 | j <- [1 .. U.length orig_lam]
        --                 , j /= n
        --                 , a ! (m,j) == 1
        --                 ])
        --         else 0

        lam' :: V Double
        lam' = U.fromList [ U.foldr (+) (orig_lam U.! (j - 1)) (U.convert (getCol j ne'))
                          | j <- [1 .. U.length lam]
                          ]


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import com.google.protobuf.Descriptors.FieldDescriptor;
import map_test.MapForProto2TestProto.BizarroTestMap;
import map_test.MapForProto2TestProto.ReservedAsMapField;
import map_test.MapForProto2TestProto.ReservedAsMapFieldWithEnumValue;
import map_test.MapForProto2TestProto.TestMap;
import map_test.MapForProto2TestProto.TestMap.MessageValue;
import map_test.MapForProto2TestProto.TestMap.MessageWithRequiredFields;
import map_test.MapForProto2TestProto.TestMapOrBuilder;
import map_test.MapForProto2TestProto.TestRecursiveMap;
import map_test.MapForProto2TestProto.TestUnknownEnumValue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;

/**
 * Unit tests for map fields in proto2 protos.
 */
public class MapForProto2Test extends TestCase {

  private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);
  //
    builder.getMutableInt32ToStringField().put(1, "11");
    builder.getMutableInt32ToStringField().put(2, "22");
    builder.getMutableInt32ToStringField().put(3, "33");
  //
    builder.getMutableInt32ToBytesField().put(1, TestUtil.toBytes("11"));
    builder.getMutableInt32ToBytesField().put(2, TestUtil.toBytes("22"));
    builder.getMutableInt32ToBytesField().put(3, TestUtil.toBytes("33"));
  //
    builder.getMutableInt32ToEnumField().put(1, TestMap.EnumValue.FOO);
    builder.getMutableInt32ToEnumField().put(2, TestMap.EnumValue.BAR);
    builder.getMutableInt32ToEnumField().put(3, TestMap.EnumValue.BAZ);
  //
    builder.getMutableInt32ToMessageField().put(
        1, MessageValue.newBuilder().setValue(11).build());
    builder.getMutableInt32ToMessageField().put(
        2, MessageValue.newBuilder().setValue(22).build());
    builder.getMutableInt32ToMessageField().put(
        3, MessageValue.newBuilder().setValue(33).build());
  //
    builder.getMutableStringToInt32Field().put("1", 11);
    builder.getMutableStringToInt32Field().put("2", 22);
    builder.getMutableStringToInt32Field().put("3", 33);
  }

  private void setMapValuesUsingAccessors(TestMap.Builder builder) {
    builder
        .putInt32ToInt32Field(1, 11)
        .putInt32ToInt32Field(2, 22)
        .putInt32ToInt32Field(3, 33)

        .putInt32ToStringField(1, "11")
        .putInt32ToStringField(2, "22")
        .putInt32ToStringField(3, "33")

        .putInt32ToBytesField(1, TestUtil.toBytes("11"))
        .putInt32ToBytesField(2, TestUtil.toBytes("22"))
        .putInt32ToBytesField(3, TestUtil.toBytes("33"))

        .putInt32ToEnumField(1, TestMap.EnumValue.FOO)
        .putInt32ToEnumField(2, TestMap.EnumValue.BAR)
        .putInt32ToEnumField(3, TestMap.EnumValue.BAZ)

        .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build())
        .putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build())
        .putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build())

        .putStringToInt32Field("1", 11)
        .putStringToInt32Field("2", 22)
        .putStringToInt32Field("3", 33);
  }

  public void testSetMapValues() {
    TestMap.Builder usingMutableMapBuilder = TestMap.newBuilder();
    setMapValuesUsingMutableMap(usingMutableMapBuilder);
    TestMap usingMutableMap = usingMutableMapBuilder.build();
    assertMapValuesSet(usingMutableMap);

    TestMap.Builder usingAccessorsBuilder = TestMap.newBuilder();
    setMapValuesUsingAccessors(usingAccessorsBuilder);
    TestMap usingAccessors = usingAccessorsBuilder.build();
    assertMapValuesSet(usingAccessors);

    assertEquals(usingAccessors, usingMutableMap);
  }

  private void copyMapValues(TestMap source, TestMap.Builder destination) {
    destination
        .putAllInt32ToInt32Field(source.getInt32ToInt32Field())
        .putAllInt32ToStringField(source.getInt32ToStringField())
        .putAllInt32ToBytesField(source.getInt32ToBytesField())
        .putAllInt32ToEnumField(source.getInt32ToEnumField())
        .putAllInt32ToMessageField(source.getInt32ToMessageField())
        .putAllStringToInt32Field(source.getStringToInt32Field());
  }

  private void assertMapValuesSet(TestMapOrBuilder message) {
    assertEquals(3, message.getInt32ToInt32Field().size());
    assertEquals(11, message.getInt32ToInt32Field().get(1).intValue());
    assertEquals(22, message.getInt32ToInt32Field().get(2).intValue());
    assertEquals(33, message.getInt32ToInt32Field().get(3).intValue());

    assertEquals(3, message.getInt32ToStringField().size());
    assertEquals("11", message.getInt32ToStringField().get(1));
    assertEquals("22", message.getInt32ToStringField().get(2));
    assertEquals("33", message.getInt32ToStringField().get(3));

    assertEquals(3, message.getInt32ToBytesField().size());
    assertEquals(TestUtil.toBytes("11"), message.getInt32ToBytesField().get(1));
    assertEquals(TestUtil.toBytes("22"), message.getInt32ToBytesField().get(2));
    assertEquals(TestUtil.toBytes("33"), message.getInt32ToBytesField().get(3));

    assertEquals(3, message.getInt32ToEnumField().size());
    assertEquals(TestMap.EnumValue.FOO, message.getInt32ToEnumField().get(1));
    assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(2));
    assertEquals(TestMap.EnumValue.BAZ, message.getInt32ToEnumField().get(3));

    assertEquals(3, message.getInt32ToMessageField().size());
    assertEquals(11, message.getInt32ToMessageField().get(1).getValue());
    assertEquals(22, message.getInt32ToMessageField().get(2).getValue());
    assertEquals(33, message.getInt32ToMessageField().get(3).getValue());

    assertEquals(3, message.getStringToInt32Field().size());
    assertEquals(11, message.getStringToInt32Field().get("1").intValue());
    assertEquals(22, message.getStringToInt32Field().get("2").intValue());
    assertEquals(33, message.getStringToInt32Field().get("3").intValue());
  }

  private void updateMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 111);
    builder.getMutableInt32ToInt32Field().remove(2);
    builder.getMutableInt32ToInt32Field().put(4, 44);
  //
    builder.getMutableInt32ToStringField().put(1, "111");
    builder.getMutableInt32ToStringField().remove(2);
    builder.getMutableInt32ToStringField().put(4, "44");
  //
    builder.getMutableInt32ToBytesField().put(1, TestUtil.toBytes("111"));
    builder.getMutableInt32ToBytesField().remove(2);
    builder.getMutableInt32ToBytesField().put(4, TestUtil.toBytes("44"));
  //
    builder.getMutableInt32ToEnumField().put(1, TestMap.EnumValue.BAR);
    builder.getMutableInt32ToEnumField().remove(2);
    builder.getMutableInt32ToEnumField().put(4, TestMap.EnumValue.QUX);
  //
    builder.getMutableInt32ToMessageField().put(
        1, MessageValue.newBuilder().setValue(111).build());
    builder.getMutableInt32ToMessageField().remove(2);
    builder.getMutableInt32ToMessageField().put(
        4, MessageValue.newBuilder().setValue(44).build());
  //
    builder.getMutableStringToInt32Field().put("1", 111);
    builder.getMutableStringToInt32Field().remove("2");
    builder.getMutableStringToInt32Field().put("4", 44);
  }

  private void updateMapValuesUsingAccessors(TestMap.Builder builder) {
    builder
        .putInt32ToInt32Field(1, 111)
        .removeInt32ToInt32Field(2)
        .putInt32ToInt32Field(4, 44)

        .putInt32ToStringField(1, "111")
        .removeInt32ToStringField(2)
        .putInt32ToStringField(4, "44")

        .putInt32ToBytesField(1, TestUtil.toBytes("111"))
        .removeInt32ToBytesField(2)
        .putInt32ToBytesField(4, TestUtil.toBytes("44"))

        .putInt32ToEnumField(1, TestMap.EnumValue.BAR)
        .removeInt32ToEnumField(2)
        .putInt32ToEnumField(4, TestMap.EnumValue.QUX)

        .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build())
        .removeInt32ToMessageField(2)
        .putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build())

        .putStringToInt32Field("1", 111)
        .removeStringToInt32Field("2")
        .putStringToInt32Field("4", 44);
  }

  public void testUpdateMapValues() {
    TestMap.Builder usingMutableMapBuilder = TestMap.newBuilder();
    setMapValuesUsingMutableMap(usingMutableMapBuilder);
    TestMap usingMutableMap = usingMutableMapBuilder.build();
    assertMapValuesSet(usingMutableMap);

    TestMap.Builder usingAccessorsBuilder = TestMap.newBuilder();
    setMapValuesUsingAccessors(usingAccessorsBuilder);
    TestMap usingAccessors = usingAccessorsBuilder.build();
    assertMapValuesSet(usingAccessors);

    assertEquals(usingAccessors, usingMutableMap);
    //
    usingMutableMapBuilder = usingMutableMap.toBuilder();
    updateMapValuesUsingMutableMap(usingMutableMapBuilder);
    usingMutableMap = usingMutableMapBuilder.build();
    assertMapValuesUpdated(usingMutableMap);

    usingAccessorsBuilder = usingAccessors.toBuilder();
    updateMapValuesUsingAccessors(usingAccessorsBuilder);
    usingAccessors = usingAccessorsBuilder.build();
    assertMapValuesUpdated(usingAccessors);

    assertEquals(usingAccessors, usingMutableMap);
  }

  private void assertMapValuesUpdated(TestMap message) {
    assertEquals(3, message.getInt32ToInt32Field().size());
    assertEquals(111, message.getInt32ToInt32Field().get(1).intValue());
    assertEquals(33, message.getInt32ToInt32Field().get(3).intValue());
    assertEquals(44, message.getInt32ToInt32Field().get(4).intValue());

    assertEquals(3, message.getInt32ToStringField().size());
    assertEquals("111", message.getInt32ToStringField().get(1));
    assertEquals("33", message.getInt32ToStringField().get(3));
    assertEquals("44", message.getInt32ToStringField().get(4));

    assertEquals(3, message.getInt32ToBytesField().size());
    assertEquals(TestUtil.toBytes("111"), message.getInt32ToBytesField().get(1));
    assertEquals(TestUtil.toBytes("33"), message.getInt32ToBytesField().get(3));
    assertEquals(TestUtil.toBytes("44"), message.getInt32ToBytesField().get(4));

    assertEquals(3, message.getInt32ToEnumField().size());
    assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1));
    assertEquals(TestMap.EnumValue.BAZ, message.getInt32ToEnumField().get(3));
    assertEquals(TestMap.EnumValue.QUX, message.getInt32ToEnumField().get(4));

    assertEquals(3, message.getInt32ToMessageField().size());
    assertEquals(111, message.getInt32ToMessageField().get(1).getValue());
    assertEquals(33, message.getInt32ToMessageField().get(3).getValue());
    assertEquals(44, message.getInt32ToMessageField().get(4).getValue());

    assertEquals(3, message.getStringToInt32Field().size());
    assertEquals(111, message.getStringToInt32Field().get("1").intValue());
    assertEquals(33, message.getStringToInt32Field().get("3").intValue());
    assertEquals(44, message.getStringToInt32Field().get("4").intValue());
  }

  private void assertMapValuesCleared(TestMapOrBuilder testMapOrBuilder) {
    assertEquals(0, testMapOrBuilder.getInt32ToInt32Field().size());
    assertEquals(0, testMapOrBuilder.getInt32ToInt32FieldCount());
    assertEquals(0, testMapOrBuilder.getInt32ToStringField().size());
    assertEquals(0, testMapOrBuilder.getInt32ToStringFieldCount());
    assertEquals(0, testMapOrBuilder.getInt32ToBytesField().size());
    assertEquals(0, testMapOrBuilder.getInt32ToBytesFieldCount());
    assertEquals(0, testMapOrBuilder.getInt32ToEnumField().size());
    assertEquals(0, testMapOrBuilder.getInt32ToEnumFieldCount());
    assertEquals(0, testMapOrBuilder.getInt32ToMessageField().size());
    assertEquals(0, testMapOrBuilder.getInt32ToMessageFieldCount());
    assertEquals(0, testMapOrBuilder.getStringToInt32Field().size());
    assertEquals(0, testMapOrBuilder.getStringToInt32FieldCount());
  }

  public void testGetMapIsImmutable() {
    TestMap.Builder builder = TestMap.newBuilder();
    assertMapsAreImmutable(builder);
    assertMapsAreImmutable(builder.build());

    setMapValuesUsingAccessors(builder);
    assertMapsAreImmutable(builder);
    assertMapsAreImmutable(builder.build());
  }

  private void assertMapsAreImmutable(TestMapOrBuilder testMapOrBuilder) {
    assertImmutable(testMapOrBuilder.getInt32ToInt32Field(), 1, 2);
    assertImmutable(testMapOrBuilder.getInt32ToStringField(), 1, "2");
    assertImmutable(testMapOrBuilder.getInt32ToBytesField(), 1, TestUtil.toBytes("2"));
    assertImmutable(testMapOrBuilder.getInt32ToEnumField(), 1, TestMap.EnumValue.FOO);
    assertImmutable(
        testMapOrBuilder.getInt32ToMessageField(), 1, MessageValue.getDefaultInstance());
    assertImmutable(testMapOrBuilder.getStringToInt32Field(), "1", 2);
  }

  private <K, V> void assertImmutable(Map<K, V> map, K key, V value) {
    try {
      map.put(key, value);
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
  }

  public void testMutableMapLifecycle() {
    TestMap.Builder builder = TestMap.newBuilder();
    Map<Integer, Integer> intMap = builder.getMutableInt32ToInt32Field();
    intMap.put(1, 2);
    assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field());
    try {
      intMap.put(2, 3);
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    assertEquals(newMap(1, 2), builder.getInt32ToInt32Field());
    builder.getMutableInt32ToInt32Field().put(2, 3);
    assertEquals(newMap(1, 2, 2, 3), builder.getInt32ToInt32Field());
 //
    Map<Integer, TestMap.EnumValue> enumMap = builder.getMutableInt32ToEnumField();
    enumMap.put(1, TestMap.EnumValue.BAR);
    assertEquals(newMap(1, TestMap.EnumValue.BAR), builder.build().getInt32ToEnumField());
    try {
      enumMap.put(2, TestMap.EnumValue.FOO);
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    assertEquals(newMap(1, TestMap.EnumValue.BAR), builder.getInt32ToEnumField());
    builder.getMutableInt32ToEnumField().put(2, TestMap.EnumValue.FOO);
    assertEquals(
        newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO),
        builder.getInt32ToEnumField());
  //
    Map<Integer, String> stringMap = builder.getMutableInt32ToStringField();
    stringMap.put(1, "1");
    assertEquals(newMap(1, "1"), builder.build().getInt32ToStringField());
    try {
      stringMap.put(2, "2");
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    assertEquals(newMap(1, "1"), builder.getInt32ToStringField());
    builder.getMutableInt32ToStringField().put(2, "2");
    assertEquals(
        newMap(1, "1", 2, "2"),
        builder.getInt32ToStringField());
  //
    Map<Integer, TestMap.MessageValue> messageMap = builder.getMutableInt32ToMessageField();
    messageMap.put(1, TestMap.MessageValue.getDefaultInstance());
    assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()),
        builder.build().getInt32ToMessageField());
    try {
      messageMap.put(2, TestMap.MessageValue.getDefaultInstance());
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()),
        builder.getInt32ToMessageField());
    builder.getMutableInt32ToMessageField().put(2, TestMap.MessageValue.getDefaultInstance());
    assertEquals(
        newMap(1, TestMap.MessageValue.getDefaultInstance(),
            2, TestMap.MessageValue.getDefaultInstance()),
        builder.getInt32ToMessageField());
  }
  //
  public void testMutableMapLifecycle_collections() {
    TestMap.Builder builder = TestMap.newBuilder();
    Map<Integer, Integer> intMap = builder.getMutableInt32ToInt32Field();
    intMap.put(1, 2);
    assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field());
    try {
      intMap.remove(2);
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    try {
      intMap.entrySet().remove(new Object());
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    try {
      intMap.entrySet().iterator().remove();
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    try {
      intMap.keySet().remove(new Object());
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    try {
      intMap.values().remove(new Object());
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    try {
      intMap.values().iterator().remove();
      fail();
    } catch (UnsupportedOperationException e) {
      // expected
    }
    assertEquals(newMap(1, 2), intMap);
    assertEquals(newMap(1, 2), builder.getInt32ToInt32Field());
    assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field());
  }

  public void testGettersAndSetters() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();
    TestMap message = builder.build();
    assertMapValuesCleared(message);

    builder = message.toBuilder();
    setMapValuesUsingAccessors(builder);
    message = builder.build();
    assertMapValuesSet(message);

    builder = message.toBuilder();
    updateMapValuesUsingAccessors(builder);
    message = builder.build();
    assertMapValuesUpdated(message);

    builder = message.toBuilder();
    builder.clear();
    assertMapValuesCleared(builder);
    message = builder.build();
    assertMapValuesCleared(message);
  }

  public void testPutAll() throws Exception {
    TestMap.Builder sourceBuilder = TestMap.newBuilder();
    setMapValuesUsingAccessors(sourceBuilder);
    TestMap source = sourceBuilder.build();
    assertMapValuesSet(source);

    TestMap.Builder destination = TestMap.newBuilder();
    copyMapValues(source, destination);
    assertMapValuesSet(destination.build());

    assertEquals(3, destination.getInt32ToEnumFieldCount());
  }

  public void testPutChecksNullKeysAndValues() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();

    try {
      builder.putInt32ToStringField(1, null);
      fail();
    } catch (NullPointerException e) {
      // expected.
    }

    try {
      builder.putInt32ToBytesField(1, null);
      fail();
    } catch (NullPointerException e) {
      // expected.
    }

    try {
      builder.putInt32ToEnumField(1, null);
      fail();
    } catch (NullPointerException e) {
      // expected.
    }

    try {
      builder.putInt32ToMessageField(1, null);
      fail();
    } catch (NullPointerException e) {
      // expected.
    }

    try {
      builder.putStringToInt32Field(null, 1);
      fail();
    } catch (NullPointerException e) {
      // expected.
    }
  }

  public void testSerializeAndParse() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    TestMap message = builder.build();
    assertEquals(message.getSerializedSize(), message.toByteString().size());
    message = TestMap.parser().parseFrom(message.toByteString());
    assertMapValuesSet(message);

    builder = message.toBuilder();
    updateMapValuesUsingAccessors(builder);
    message = builder.build();
    assertEquals(message.getSerializedSize(), message.toByteString().size());
    message = TestMap.parser().parseFrom(message.toByteString());
    assertMapValuesUpdated(message);

    builder = message.toBuilder();
    builder.clear();
    message = builder.build();
    assertEquals(message.getSerializedSize(), message.toByteString().size());
    message = TestMap.parser().parseFrom(message.toByteString());
    assertMapValuesCleared(message);
  }

  private TestMap tryParseTestMap(BizarroTestMap bizarroMap) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CodedOutputStream output = CodedOutputStream.newInstance(byteArrayOutputStream);
    bizarroMap.writeTo(output);
    output.flush();
    return TestMap.parser().parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray()));
  }

  public void testParseError() throws Exception {
    ByteString bytes = TestUtil.toBytes("SOME BYTES");
    String stringKey = "a string key";

    TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
        .putInt32ToInt32Field(5, bytes)
        .build());
    assertEquals(map.getInt32ToInt32FieldOrDefault(5, -1), 0);

    map = tryParseTestMap(BizarroTestMap.newBuilder()
        .putInt32ToStringField(stringKey, 5)
        .build());
    assertEquals(map.getInt32ToStringFieldOrDefault(0, null), "");

    map = tryParseTestMap(BizarroTestMap.newBuilder()
        .putInt32ToBytesField(stringKey, 5)
        .build());
    assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY);

    map = tryParseTestMap(BizarroTestMap.newBuilder()
        .putInt32ToEnumField(stringKey, bytes)
        .build());
    assertEquals(map.getInt32ToEnumFieldOrDefault(0, null), TestMap.EnumValue.FOO);

    try {
      tryParseTestMap(BizarroTestMap.newBuilder()
          .putInt32ToMessageField(stringKey, bytes)
          .build());
      fail();
    } catch (InvalidProtocolBufferException expected) {
      assertTrue(expected.getUnfinishedMessage() instanceof TestMap);
      map = (TestMap) expected.getUnfinishedMessage();
      assertTrue(map.getInt32ToMessageField().isEmpty());
    }

    map = tryParseTestMap(BizarroTestMap.newBuilder()
        .putStringToInt32Field(stringKey, bytes)
        .build());
    assertEquals(map.getStringToInt32FieldOrDefault(stringKey, -1), 0);
  }

  public void testMergeFrom() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    TestMap message = builder.build();

    TestMap.Builder other = TestMap.newBuilder();
    other.mergeFrom(message);
    assertMapValuesSet(other.build());
  }

  public void testEqualsAndHashCode() throws Exception {
    // Test that generated equals() and hashCode() will disregard the order
    // of map entries when comparing/hashing map fields.

    // We can't control the order of elements in a HashMap. The best we can do
    // here is to add elements in different order.
    TestMap.Builder b1 = TestMap.newBuilder();
    b1.putInt32ToInt32Field(1, 2);
    b1.putInt32ToInt32Field(3, 4);
    b1.putInt32ToInt32Field(5, 6);
    TestMap m1 = b1.build();

    TestMap.Builder b2 = TestMap.newBuilder();
    b2.putInt32ToInt32Field(5, 6);
    b2.putInt32ToInt32Field(1, 2);
    b2.putInt32ToInt32Field(3, 4);
    TestMap m2 = b2.build();

    assertEquals(m1, m2);
    assertEquals(m1.hashCode(), m2.hashCode());

    // Make sure we did compare map fields.
    b2.putInt32ToInt32Field(1, 0);
    m2 = b2.build();
    assertFalse(m1.equals(m2));
    // Don't check m1.hashCode() != m2.hashCode() because it's not guaranteed
    // to be different.
  }

  // The following methods are used to test reflection API.

  private static FieldDescriptor f(String name) {
    return TestMap.getDescriptor().findFieldByName(name);
  }

  private static Object getFieldValue(Message mapEntry, String name) {
    FieldDescriptor field = mapEntry.getDescriptorForType().findFieldByName(name);
    return mapEntry.getField(field);
  }

  private static Message.Builder setFieldValue(
      Message.Builder mapEntry, String name, Object value) {
    FieldDescriptor field = mapEntry.getDescriptorForType().findFieldByName(name);
    mapEntry.setField(field, value);
    return mapEntry;
  }

  private static void assertHasMapValues(Message message, String name, Map<?, ?> values) {
    FieldDescriptor field = f(name);
    for (Object entry : (List<?>) message.getField(field)) {
      Message mapEntry = (Message) entry;
      Object key = getFieldValue(mapEntry, "key");
      Object value = getFieldValue(mapEntry, "value");
      assertTrue(values.containsKey(key));
      assertEquals(value, values.get(key));
    }
    assertEquals(values.size(), message.getRepeatedFieldCount(field));
    for (int i = 0; i < message.getRepeatedFieldCount(field); i++) {
      Message mapEntry = (Message) message.getRepeatedField(field, i);
      Object key = getFieldValue(mapEntry, "key");
      Object value = getFieldValue(mapEntry, "value");
      assertTrue(values.containsKey(key));
      assertEquals(value, values.get(key));
    }
  }

  private static <KeyType, ValueType>
  Message newMapEntry(Message.Builder builder, String name, KeyType key, ValueType value) {
    FieldDescriptor field = builder.getDescriptorForType().findFieldByName(name);
    Message.Builder entryBuilder = builder.newBuilderForField(field);
    FieldDescriptor keyField = entryBuilder.getDescriptorForType().findFieldByName("key");
    FieldDescriptor valueField = entryBuilder.getDescriptorForType().findFieldByName("value");
    entryBuilder.setField(keyField, key);
    entryBuilder.setField(valueField, value);
    return entryBuilder.build();
  }

  private static void setMapValues(Message.Builder builder, String name, Map<?, ?> values) {
    List<Message> entryList = new ArrayList<Message>();
    for (Map.Entry<?, ?> entry : values.entrySet()) {
      entryList.add(newMapEntry(builder, name, entry.getKey(), entry.getValue()));
    }
    FieldDescriptor field = builder.getDescriptorForType().findFieldByName(name);
    builder.setField(field, entryList);
  }

  private static <KeyType, ValueType> Map<KeyType, ValueType> mapForValues(
      KeyType key1, ValueType value1, KeyType key2, ValueType value2) {
    Map<KeyType, ValueType> map = new HashMap<KeyType, ValueType>();
    map.put(key1, value1);
    map.put(key2, value2);
    return map;
  }

  public void testReflectionApi() throws Exception {
    // In reflection API, map fields are just repeated message fields.
    TestMap.Builder builder = TestMap.newBuilder()
        .putInt32ToInt32Field(1, 2)
        .putInt32ToInt32Field(3, 4)
        .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build())
        .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build());
    TestMap message = builder.build();

    // Test getField(), getRepeatedFieldCount(), getRepeatedField().
    assertHasMapValues(message, "int32_to_int32_field",
        mapForValues(1, 2, 3, 4));
    assertHasMapValues(message, "int32_to_message_field",
        mapForValues(
            11, MessageValue.newBuilder().setValue(22).build(),
            33, MessageValue.newBuilder().setValue(44).build()));

    // Test clearField()
    builder.clearField(f("int32_to_int32_field"));
    builder.clearField(f("int32_to_message_field"));
    message = builder.build();
    assertEquals(0, message.getInt32ToInt32Field().size());
    assertEquals(0, message.getInt32ToMessageField().size());

    // Test setField()
    setMapValues(builder, "int32_to_int32_field",
        mapForValues(11, 22, 33, 44));
    setMapValues(builder, "int32_to_message_field",
        mapForValues(
            111, MessageValue.newBuilder().setValue(222).build(),
            333, MessageValue.newBuilder().setValue(444).build()));
    message = builder.build();
    assertEquals(22, message.getInt32ToInt32Field().get(11).intValue());
    assertEquals(44, message.getInt32ToInt32Field().get(33).intValue());
    assertEquals(222, message.getInt32ToMessageField().get(111).getValue());
    assertEquals(444, message.getInt32ToMessageField().get(333).getValue());

    // Test addRepeatedField
    builder.addRepeatedField(f("int32_to_int32_field"),
        newMapEntry(builder, "int32_to_int32_field", 55, 66));
    builder.addRepeatedField(f("int32_to_message_field"),
        newMapEntry(builder, "int32_to_message_field", 555,
            MessageValue.newBuilder().setValue(666).build()));
    message = builder.build();
    assertEquals(66, message.getInt32ToInt32Field().get(55).intValue());
    assertEquals(666, message.getInt32ToMessageField().get(555).getValue());

    // Test addRepeatedField (overriding existing values)
    builder.addRepeatedField(f("int32_to_int32_field"),
        newMapEntry(builder, "int32_to_int32_field", 55, 55));
    builder.addRepeatedField(f("int32_to_message_field"),
        newMapEntry(builder, "int32_to_message_field", 555,
            MessageValue.newBuilder().setValue(555).build()));
    message = builder.build();
    assertEquals(55, message.getInt32ToInt32Field().get(55).intValue());
    assertEquals(555, message.getInt32ToMessageField().get(555).getValue());

    // Test setRepeatedField
    for (int i = 0; i < builder.getRepeatedFieldCount(f("int32_to_int32_field")); i++) {
      Message mapEntry = (Message) builder.getRepeatedField(f("int32_to_int32_field"), i);
      int oldKey = ((Integer) getFieldValue(mapEntry, "key")).intValue();
      int oldValue = ((Integer) getFieldValue(mapEntry, "value")).intValue();
      // Swap key with value for each entry.
      Message.Builder mapEntryBuilder = mapEntry.toBuilder();
      setFieldValue(mapEntryBuilder, "key", oldValue);
      setFieldValue(mapEntryBuilder, "value", oldKey);
      builder.setRepeatedField(f("int32_to_int32_field"), i, mapEntryBuilder.build());
    }
    message = builder.build();
    assertEquals(11, message.getInt32ToInt32Field().get(22).intValue());
    assertEquals(33, message.getInt32ToInt32Field().get(44).intValue());
    assertEquals(55, message.getInt32ToInt32Field().get(55).intValue());
  }

  // See additional coverage in TextFormatTest.java.
  public void testTextFormat() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    TestMap message = builder.build();

    String textData = TextFormat.printToString(message);

    builder = TestMap.newBuilder();
    TextFormat.merge(textData, builder);
    message = builder.build();

    assertMapValuesSet(message);
  }

  public void testDynamicMessage() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    TestMap message = builder.build();

    Message dynamicDefaultInstance =
        DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
    Message dynamicMessage = dynamicDefaultInstance
        .newBuilderForType().mergeFrom(message.toByteString()).build();

    assertEquals(message, dynamicMessage);
    assertEquals(message.hashCode(), dynamicMessage.hashCode());
  }

  public void testReflectionEqualsAndHashCode() throws Exception {
    // Test that generated equals() and hashCode() will disregard the order
    // of map entries when comparing/hashing map fields.

    // We use DynamicMessage to test reflection based equals()/hashCode().
    Message dynamicDefaultInstance =
        DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
    FieldDescriptor field = f("int32_to_int32_field");

    Message.Builder b1 = dynamicDefaultInstance.newBuilderForType();
    b1.addRepeatedField(field, newMapEntry(b1, "int32_to_int32_field", 1, 2));
    b1.addRepeatedField(field, newMapEntry(b1, "int32_to_int32_field", 3, 4));
    b1.addRepeatedField(field, newMapEntry(b1, "int32_to_int32_field", 5, 6));
    Message m1 = b1.build();

    Message.Builder b2 = dynamicDefaultInstance.newBuilderForType();
    b2.addRepeatedField(field, newMapEntry(b2, "int32_to_int32_field", 5, 6));
    b2.addRepeatedField(field, newMapEntry(b2, "int32_to_int32_field", 1, 2));
    b2.addRepeatedField(field, newMapEntry(b2, "int32_to_int32_field", 3, 4));
    Message m2 = b2.build();

    assertEquals(m1, m2);
    assertEquals(m1.hashCode(), m2.hashCode());

    // Make sure we did compare map fields.
    b2.setRepeatedField(field, 0, newMapEntry(b1, "int32_to_int32_field", 0, 0));
    m2 = b2.build();
    assertFalse(m1.equals(m2));
    // Don't check m1.hashCode() != m2.hashCode() because it's not guaranteed
    // to be different.
  }

  public void testUnknownEnumValues() throws Exception {
    TestUnknownEnumValue.Builder builder = TestUnknownEnumValue.newBuilder()
        .putInt32ToInt32Field(1, 1)
        .putInt32ToInt32Field(2, 54321);
    ByteString data = builder.build().toByteString();

    TestMap message = TestMap.parseFrom(data);
    // Entries with unknown enum values will be stored into UnknownFieldSet so
    // there is only one entry in the map.
    assertEquals(1, message.getInt32ToEnumField().size());
    assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1));
    // UnknownFieldSet should not be empty.
    assertFalse(message.getUnknownFields().asMap().isEmpty());
    // Serializing and parsing should preserve the unknown entry.
    data = message.toByteString();
    TestUnknownEnumValue messageWithUnknownEnums =
        TestUnknownEnumValue.parseFrom(data);
    assertEquals(2, messageWithUnknownEnums.getInt32ToInt32Field().size());
    assertEquals(1, messageWithUnknownEnums.getInt32ToInt32Field().get(1).intValue());
    assertEquals(54321, messageWithUnknownEnums.getInt32ToInt32Field().get(2).intValue());
  }

  public void testRequiredMessage() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();
    builder.putRequiredMessageMap(0, MessageWithRequiredFields.newBuilder().buildPartial());
    TestMap message = builder.buildPartial();
    assertFalse(message.isInitialized());

    builder.putRequiredMessageMap(0, MessageWithRequiredFields.newBuilder().setValue(1).build());
    message = builder.build();
    assertTrue(message.isInitialized());
  }

  public void testRecursiveMap() throws Exception {
    TestRecursiveMap.Builder builder = TestRecursiveMap.newBuilder();
    builder.putRecursiveMapField(1, TestRecursiveMap.newBuilder().setValue(2).build());
    builder.putRecursiveMapField(3, TestRecursiveMap.newBuilder().setValue(4).build());
    ByteString data = builder.build().toByteString();

    TestRecursiveMap message = TestRecursiveMap.parseFrom(data);
    assertEquals(2, message.getRecursiveMapField().get(1).getValue());
    assertEquals(4, message.getRecursiveMapField().get(3).getValue());
  }

  public void testIterationOrder() throws Exception {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    TestMap message = builder.build();

    assertEquals(Arrays.asList("1", "2", "3"),
        new ArrayList<String>(message.getStringToInt32Field().keySet()));
  }

  public void testContains() {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    assertMapContainsSetValues(builder);
    assertMapContainsSetValues(builder.build());
  }

  private void assertMapContainsSetValues(TestMapOrBuilder testMapOrBuilder) {
    assertTrue(testMapOrBuilder.containsInt32ToInt32Field(1));
    assertTrue(testMapOrBuilder.containsInt32ToInt32Field(2));
    assertTrue(testMapOrBuilder.containsInt32ToInt32Field(3));
    assertFalse(testMapOrBuilder.containsInt32ToInt32Field(-1));

    assertTrue(testMapOrBuilder.containsInt32ToStringField(1));
    assertTrue(testMapOrBuilder.containsInt32ToStringField(2));
    assertTrue(testMapOrBuilder.containsInt32ToStringField(3));
    assertFalse(testMapOrBuilder.containsInt32ToStringField(-1));

    assertTrue(testMapOrBuilder.containsInt32ToBytesField(1));
    assertTrue(testMapOrBuilder.containsInt32ToBytesField(2));
    assertTrue(testMapOrBuilder.containsInt32ToBytesField(3));
    assertFalse(testMapOrBuilder.containsInt32ToBytesField(-1));

    assertTrue(testMapOrBuilder.containsInt32ToEnumField(1));
    assertTrue(testMapOrBuilder.containsInt32ToEnumField(2));
    assertTrue(testMapOrBuilder.containsInt32ToEnumField(3));
    assertFalse(testMapOrBuilder.containsInt32ToEnumField(-1));

    assertTrue(testMapOrBuilder.containsInt32ToMessageField(1));
    assertTrue(testMapOrBuilder.containsInt32ToMessageField(2));
    assertTrue(testMapOrBuilder.containsInt32ToMessageField(3));
    assertFalse(testMapOrBuilder.containsInt32ToMessageField(-1));

    assertTrue(testMapOrBuilder.containsStringToInt32Field("1"));
    assertTrue(testMapOrBuilder.containsStringToInt32Field("2"));
    assertTrue(testMapOrBuilder.containsStringToInt32Field("3"));
    assertFalse(testMapOrBuilder.containsStringToInt32Field("-1"));
  }

  public void testCount() {
    TestMap.Builder builder = TestMap.newBuilder();
    assertMapCounts(0, builder);

    setMapValuesUsingAccessors(builder);
    assertMapCounts(3, builder);

    TestMap message = builder.build();
    assertMapCounts(3, message);

    builder = message.toBuilder().putInt32ToInt32Field(4, 44);
    assertEquals(4, builder.getInt32ToInt32FieldCount());
    assertEquals(4, builder.build().getInt32ToInt32FieldCount());

    // already present - should be unchanged
    builder.putInt32ToInt32Field(4, 44);
    assertEquals(4, builder.getInt32ToInt32FieldCount());
  }

  private void assertMapCounts(int expectedCount, TestMapOrBuilder testMapOrBuilder) {
    assertEquals(expectedCount, testMapOrBuilder.getInt32ToInt32FieldCount());
    assertEquals(expectedCount, testMapOrBuilder.getInt32ToStringFieldCount());
    assertEquals(expectedCount, testMapOrBuilder.getInt32ToBytesFieldCount());
    assertEquals(expectedCount, testMapOrBuilder.getInt32ToEnumFieldCount());
    assertEquals(expectedCount, testMapOrBuilder.getInt32ToMessageFieldCount());
    assertEquals(expectedCount, testMapOrBuilder.getStringToInt32FieldCount());
  }

  public void testGetOrDefault() {
    TestMap.Builder builder = TestMap.newBuilder();
    assertMapCounts(0, builder);
    setMapValuesUsingAccessors(builder);
    doTestGetOrDefault(builder);
    doTestGetOrDefault(builder.build());
  }

  public void doTestGetOrDefault(TestMapOrBuilder testMapOrBuilder) {
    assertEquals(11, testMapOrBuilder.getInt32ToInt32FieldOrDefault(1, -11));
    assertEquals(-11, testMapOrBuilder.getInt32ToInt32FieldOrDefault(-1, -11));

    assertEquals("11", testMapOrBuilder.getInt32ToStringFieldOrDefault(1, "-11"));
    assertNull("-11", testMapOrBuilder.getInt32ToStringFieldOrDefault(-1, null));

    assertEquals(TestUtil.toBytes("11"), testMapOrBuilder.getInt32ToBytesFieldOrDefault(1, null));
    assertNull(testMapOrBuilder.getInt32ToBytesFieldOrDefault(-1, null));

    assertEquals(TestMap.EnumValue.FOO, testMapOrBuilder.getInt32ToEnumFieldOrDefault(1, null));
    assertNull(testMapOrBuilder.getInt32ToEnumFieldOrDefault(-1, null));

    assertEquals(MessageValue.newBuilder().setValue(11).build(),
        testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null));
    assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null));

    assertEquals(11, testMapOrBuilder.getStringToInt32FieldOrDefault("1", -11));
    assertEquals(-11, testMapOrBuilder.getStringToInt32FieldOrDefault("-1", -11));

    try {
      testMapOrBuilder.getStringToInt32FieldOrDefault(null, -11);
      fail();
    } catch (NullPointerException e) {
      // expected
    }
  }

  public void testGetOrThrow() {
    TestMap.Builder builder = TestMap.newBuilder();
    assertMapCounts(0, builder);
    setMapValuesUsingAccessors(builder);
    doTestGetOrDefault(builder);
    doTestGetOrDefault(builder.build());
  }

  public void doTestGetOrThrow(TestMapOrBuilder testMapOrBuilder) {
    assertEquals(11, testMapOrBuilder.getInt32ToInt32FieldOrThrow(1));
    try {
      testMapOrBuilder.getInt32ToInt32FieldOrThrow(-1);
      fail();
    } catch (IllegalArgumentException e) {
      // expected
    }

    assertEquals("11", testMapOrBuilder.getInt32ToStringFieldOrThrow(1));

    try {
      testMapOrBuilder.getInt32ToStringFieldOrThrow(-1);
      fail();
    } catch (IllegalArgumentException e) {
      // expected
    }

    assertEquals(TestUtil.toBytes("11"), testMapOrBuilder.getInt32ToBytesFieldOrThrow(1));

    try {
      testMapOrBuilder.getInt32ToBytesFieldOrThrow(-1);
      fail();
    } catch (IllegalArgumentException e) {
      // expected
    }

    assertEquals(TestMap.EnumValue.FOO, testMapOrBuilder.getInt32ToEnumFieldOrThrow(1));
    try {
      testMapOrBuilder.getInt32ToEnumFieldOrThrow(-1);
      fail();
    } catch (IllegalArgumentException e) {
      // expected
    }

    assertEquals(MessageValue.newBuilder().setValue(11).build(),
        testMapOrBuilder.getInt32ToMessageFieldOrThrow(1));
    try {
      testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1);
      fail();
    } catch (IllegalArgumentException e) {
      // expected
    }

    assertEquals(11, testMapOrBuilder.getStringToInt32FieldOrThrow("1"));
    try {
      testMapOrBuilder.getStringToInt32FieldOrThrow("-1");
      fail();
    } catch (IllegalArgumentException e) {
      // expected
    }

    try {
      testMapOrBuilder.getStringToInt32FieldOrThrow(null);
      fail();
    } catch (NullPointerException e) {
      // expected
    }
  }

  public void testPut() {
    TestMap.Builder builder = TestMap.newBuilder();
    builder.putInt32ToInt32Field(1, 11);
    assertEquals(11, builder.getInt32ToInt32FieldOrThrow(1));

    builder.putInt32ToStringField(1, "a");
    assertEquals("a", builder.getInt32ToStringFieldOrThrow(1));
    try {
      builder.putInt32ToStringField(1, null);
      fail();
    } catch (NullPointerException e) {
      // expected
    }

    builder.putInt32ToBytesField(1, TestUtil.toBytes("11"));
    assertEquals(TestUtil.toBytes("11"), builder.getInt32ToBytesFieldOrThrow(1));
    try {
      builder.putInt32ToBytesField(1, null);
      fail();
    } catch (NullPointerException e) {
      // expected
    }

    builder.putInt32ToEnumField(1, TestMap.EnumValue.FOO);
    assertEquals(TestMap.EnumValue.FOO, builder.getInt32ToEnumFieldOrThrow(1));
    try {
      builder.putInt32ToEnumField(1, null);
      fail();
    } catch (NullPointerException e) {
      // expected
    }

    builder.putStringToInt32Field("a", 1);
    assertEquals(1, builder.getStringToInt32FieldOrThrow("a"));
    try {
      builder.putStringToInt32Field(null, -1);
    } catch (NullPointerException e) {
      // expected
    }
  }

  public void testRemove() {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    assertEquals(11, builder.getInt32ToInt32FieldOrThrow(1));
    for (int times = 0; times < 2; times++) {
      builder.removeInt32ToInt32Field(1);
      assertEquals(-1, builder.getInt32ToInt32FieldOrDefault(1, -1));
    }

    assertEquals("11", builder.getInt32ToStringFieldOrThrow(1));
    for (int times = 0; times < 2; times++) {
      builder.removeInt32ToStringField(1);
      assertNull(builder.getInt32ToStringFieldOrDefault(1, null));
    }

    assertEquals(TestUtil.toBytes("11"), builder.getInt32ToBytesFieldOrThrow(1));
    for (int times = 0; times < 2; times++) {
      builder.removeInt32ToBytesField(1);
      assertNull(builder.getInt32ToBytesFieldOrDefault(1, null));
    }

    assertEquals(TestMap.EnumValue.FOO, builder.getInt32ToEnumFieldOrThrow(1));
    for (int times = 0; times < 2; times++) {
      builder.removeInt32ToEnumField(1);
      assertNull(builder.getInt32ToEnumFieldOrDefault(1, null));
    }

    assertEquals(11, builder.getStringToInt32FieldOrThrow("1"));
    for (int times = 0; times < 2; times++) {
      builder.removeStringToInt32Field("1");
      assertEquals(-1, builder.getStringToInt32FieldOrDefault("1", -1));
    }

    try {
      builder.removeStringToInt32Field(null);
      fail();
    } catch (NullPointerException e) {
      // expected
    }
  }

  // Regression test for b/20494788
  public void testMapInitializationOrder() throws Exception {
    assertEquals("RedactAllTypes", map_test.RedactAllTypes
        .getDefaultInstance().getDescriptorForType().getName());

    map_test.Message1.Builder builder =
        map_test.Message1.newBuilder();
    builder.putMapField("key", true);
    map_test.Message1 message = builder.build();
    Message mapEntry = (Message) message.getRepeatedField(
        message.getDescriptorForType().findFieldByName("map_field"), 0);
    assertEquals(2, mapEntry.getAllFields().size());
  }

  public void testReservedWordsFieldNames() {
    ReservedAsMapField.newBuilder().build();
    ReservedAsMapFieldWithEnumValue.newBuilder().build();
  }

  private static <K, V> Map<K, V> newMap(K key1, V value1) {
    Map<K, V> map = new HashMap<K, V>();
    map.put(key1, value1);
    return map;
  }

  private static <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) {
    Map<K, V> map = new HashMap<K, V>();
    map.put(key1, value1);
    map.put(key2, value2);
    return map;
  }

  public void testGetMap() {
    TestMap.Builder builder = TestMap.newBuilder();
    setMapValuesUsingAccessors(builder);
    assertMapValuesSet(builder);
    TestMap message = builder.build();
    assertEquals(
        message.getStringToInt32Field(),
        message.getStringToInt32FieldMap());
    assertEquals(
        message.getInt32ToBytesField(),
        message.getInt32ToBytesFieldMap());
    assertEquals(
        message.getInt32ToEnumField(),
        message.getInt32ToEnumFieldMap());
    assertEquals(
        message.getInt32ToMessageField(),
        message.getInt32ToMessageFieldMap());
  }
}


text:
package org.apache.sis.internal.sql.postgis;

import java.sql.ResultSet;
import java.io.InputStream;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.apache.sis.internal.sql.feature.BinaryEncoding;
import org.apache.sis.internal.sql.feature.InfoStatements;
import org.apache.sis.internal.sql.feature.ValueGetter;
import org.apache.sis.coverage.grid.GridCoverage;

/**
 * Reader of rasters encoded in Well Known Binary (WKB) format.
 * At the time of writing this class, raster WKB is a PostGIS-specific format.
 *
 *
Multi-threading

 * {@code RasterGetter} instances shall be thread-safe.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.2
 *
 * @see org.apache.sis.internal.sql.feature.GeometryGetter
 *
 * @since 1.2
 * @module
 */
final class RasterGetter extends ValueGetter<GridCoverage> {
    /**
     * The Coordinate Reference System if {@link InfoStatements} cannot map the SRID.
     * This is {@code null} if there is no default.
     */
    private final CoordinateReferenceSystem defaultCRS;

    /**
     * The way binary data are encoded in the raster column.
     */
    private final BinaryEncoding encoding;

    /**
     * Creates a new reader. The same instance can be reused for parsing an arbitrary
     * amount of rasters sharing the same default CRS.
     *
     * @param  defaultCRS  the CRS to use if none can be mapped from the SRID, or {@code null} if none.
     * @param  encoding    the way binary data are encoded in the raster column.
     */
    RasterGetter(final CoordinateReferenceSystem defaultCRS, final BinaryEncoding encoding) {
        super(GridCoverage.class);
        this.defaultCRS = defaultCRS;
        this.encoding   = encoding;
    }

    /**
     * Gets the value in the column at specified index.
     * The given result set must have its cursor position on the line to read.
     * This method does not modify the cursor position.
     *
     * @param  stmts        prepared statements for fetching CRS from SRID, or {@code null} if none.
     * @param  source       the result set from which to get the value.
     * @param  columnIndex  index of the column in which to get the value.
     * @return raster value in the given column. May be {@code null}.
     * @throws Exception if an error occurred. May be an SQL error, a WKB parsing error, etc.
     */
    @Override
    public GridCoverage getValue(final InfoStatements stmts, final ResultSet source, final int columnIndex) throws Exception {
        InputStream stream = source.getBinaryStream(columnIndex);
        if (stream != null && stmts instanceof ExtendedInfo) {
            stream = encoding.decode(stream);
            final RasterReader reader = ((ExtendedInfo) stmts).getRasterReader();
            reader.defaultCRS = defaultCRS;
            return reader.readAsCoverage(reader.channel(stream));
        }
        return null;
    }
}


text:
using UnityEngine;
using System.Collections;

public class UI_Checker : MonoBehaviour
{
    GameObject _uiM;

	// Use this for initialization
	void Start ()
    {
        _uiM = GameObject.Find("OverlayUI");
        _uiM.SendMessage("Setup");
    }
}


text:
var ftdi = require('../hello_world/hello.js'),
	fs = require('fs'),
	protocols = {};

fs.readdirSync('./protocols/').forEach((protocolFile) => {
	console.log(protocolFile.substr(0, protocolFile.lastIndexOf('.')));
	protocols[protocolFile.substr(0, protocolFile.lastIndexOf('.'))] = require('./protocols/' + protocolFile);
});

console.log(protocols);
ftdi.find(0x1781, 0x0c31, function(err, devices) {
	if(err) {
		throw(err);
	}
	console.log('Devices:', devices);
	if(devices.length === 0)  {
		console.log('Tellstick not found.');
		process.exit();
	}
	var td = new ftdi.FtdiDevice(devices[0]);
	console.log(td);
	var buf = Buffer.alloc(0);
	td.open({
		baudrate: td.deviceSettings.productId == 0x0C31 ? 9600 : 4800,
    		databits: 8,
	    	stopbits: 1,
	    	parity: 'none'
		}, function(err) {
		console.log('Open:', err, arguments);

		var sub = td.on('data', function(data) {
			//console.log('Received:', data.toString('hex'));
			buf = Buffer.concat([buf, data]);
			if(buf.indexOf(10) > -1) {
				var msg = Buffer.from(buf.slice(0, buf.indexOf(13)));
				buf = Buffer.from(buf.slice(buf.indexOf(10) + 1));
				console.log('Processing:', msg.toString());

				switch(msg.slice(0, 2).toString()) {
					case '+V':
						console.log('Firmware version:', msg.slice(2).toString());
						break;
					case '+W':
						var params = {};
						msg.slice(2)
							.toString()
							.split(';')
							.filter((keyval) => keyval.length != '')
							.forEach(function(keyval) {
								var tmp = keyval.split(':');
								params[tmp[0]] = tmp[1];
						});
						if(protocols[params.protocol]) {
							console.log(params.protocol, protocols[params.protocol].decodeData(params));
						}
						else {
							console.log('No parser available', params);
						}
						break;
					default:
						console.log('data', msg.toString(), msg.toString('hex'));
						break;
				}
			}
		});

		td.write(Buffer.from('V+'), function(err) {
			console.log('Version info requested', err);
		});
		td.write(Buffer.from('D+'), function(err) {
			console.log('Debug requested', err);
		});
		//console.log(protocols['arctech'].getStringSelflearningForCode(15402826, 3, 1));
//		var c=1, t=300;
//		td.write(protocols['arctech'].getCommand({model:'selflearning', house: 15402826, unit: null, method: protocols['arctech'].methods.TELLSTICK_TURNOFF, repeat:5}), function(err) {
//			console.log('Device command sent', err);
			/*setTimeout(() => {
				td.write(protocols['arctech'].getStringSelflearningForCode(15402826, 1, c), function(err) {
					console.log('Device command sent', err);
					setTimeout(() => {
						td.write(protocols['arctech'].getStringSelflearningForCode(15402826, 2, c), function(err) {
							console.log('Device command sent', err);
							setTimeout(() => {
								td.write(protocols['arctech'].getStringSelflearningForCode(15402826, 3, c), function(err) {
									console.log('Device command sent', err);
								});
							}, t);
						});
					}, t);
				});
			}, t);*/
//		});
	});
});


text:
#include "Core/SurfaceBehavior/SurfaceOptics/ThinDielectricFilm.h"
#include "Core/SurfaceBehavior/Property/ExactDielectricFresnel.h"
#include "Common/assertion.h"
#include "Math/Random.h"
#include "Core/LTABuildingBlock/SidednessAgreement.h"
#include "Core/Texture/TConstantTexture.h"
#include "Core/Texture/TSampler.h"
#include "Math/math.h"

namespace ph
{

ThinDielectricFilm::ThinDielectricFilm(
	const std::shared_ptr<DielectricFresnel>& fresnel,
	const std::vector<SampledSpectralStrength>& reflectanceTable,
	const std::vector<SampledSpectralStrength>& transmittanceTable) :

	SurfaceOptics(),

	m_fresnel(fresnel),
	m_reflectanceTable(reflectanceTable),
	m_transmittanceTable(transmittanceTable)
{
	PH_ASSERT(fresnel);
	PH_ASSERT_EQ(reflectanceTable.size(), 91);
	PH_ASSERT_EQ(transmittanceTable.size(), 91);

	m_phenomena.set({ESurfacePhenomenon::DELTA_REFLECTION, ESurfacePhenomenon::DELTA_TRANSMISSION});
	m_numElementals = 2;
}

ESurfacePhenomenon ThinDielectricFilm::getPhenomenonOf(const SurfaceElemental elemental) const
{
	PH_ASSERT_LT(elemental, 2);

	return elemental == REFLECTION ? ESurfacePhenomenon::DELTA_REFLECTION :
	                                 ESurfacePhenomenon::DELTA_TRANSMISSION;
}

void ThinDielectricFilm::calcBsdf(
	const BsdfEvaluation::Input& in,
	BsdfEvaluation::Output&      out,
	const SidednessAgreement&    sidedness) const
{
	out.bsdf.setValues(0.0_r);
}

void ThinDielectricFilm::calcBsdfSample(
	const BsdfSample::Input&  in,
	BsdfSample::Output&       out,
	const SidednessAgreement& sidedness) const
{
	const bool canReflect  = in.elemental == ALL_ELEMENTALS || in.elemental == REFLECTION;
	const bool canTransmit = in.elemental == ALL_ELEMENTALS || in.elemental == TRANSMISSION;

	if(!canReflect && !canTransmit)
	{
		out.setMeasurability(false);
		return;
	}

	const Vector3R& N = in.X.getShadingNormal();

	SpectralStrength F;
	m_fresnel->calcReflectance(N.dot(in.V), &F);
	const real reflectProb = F.avg();

	bool sampleReflect  = canReflect;
	bool sampleTransmit = canTransmit;

	// we cannot sample both path, choose one randomly
	if(sampleReflect && sampleTransmit)
	{
		const real dart = Random::genUniformReal_i0_e1();
		if(dart < reflectProb)
		{
			sampleTransmit = false;
		}
		else
		{
			sampleReflect = false;
		}
	}

	PH_ASSERT(sampleReflect || sampleTransmit);

	// calculate reflected L
	out.L = in.V.mul(-1.0_r).reflect(N).normalizeLocal();

	real degree = math::to_degrees(N.absDot(out.L));
	std::size_t index = math::clamp(static_cast<std::size_t>(degree + 0.5_r), std::size_t(0), std::size_t(90));

	SampledSpectralStrength scale(0);

	if(sampleReflect)
	{
		if(!sidedness.isSameHemisphere(in.X, in.V, out.L))
		{
			out.setMeasurability(false);
			return;
		}

		scale = m_reflectanceTable[index];

		// account for probability
		if(in.elemental == ALL_ELEMENTALS)
		{
			scale.divLocal(reflectProb);
		}
	}
	else if(sampleTransmit && m_fresnel->calcRefractDir(in.V, N, &(out.L)))
	{
		if(!sidedness.isOppositeHemisphere(in.X, in.V, out.L))
		{
			out.setMeasurability(false);
			return;
		}

		scale = m_transmittanceTable[index];

		/*if(in.transported == ETransport::RADIANCE)
		{
			real etaI = m_fresnel->getIorOuter();
			real etaT = m_fresnel->getIorInner();
			if(N.dot(out.L) < 0.0_r)
			{
				std::swap(etaI, etaT);
			}
			F.mulLocal(etaT * etaT / (etaI * etaI));
		}*/

		// account for probability
		if(in.elemental == ALL_ELEMENTALS)
		{
			scale.divLocal(1.0_r - reflectProb);
		}
	}
	else
	{
		// RARE: may be called due to numerical error
		out.setMeasurability(false);
		return;
	}

	SpectralStrength value;
	value.setSampled(scale / N.absDot(out.L));
	out.pdfAppliedBsdf.setValues(value);
	out.setMeasurability(true);
}

void ThinDielectricFilm::calcBsdfSamplePdfW(
	const BsdfPdfQuery::Input& in,
	BsdfPdfQuery::Output&      out,
	const SidednessAgreement&  sidedness) const
{
	out.sampleDirPdfW = 0.0_r;
}

}// end namespace ph


text:
package com.siyeh.ig.junit;

import com.siyeh.ig.testFrameworks.BaseAssertEqualsBetweenInconvertibleTypesInspection;

public class AssertEqualsBetweenInconvertibleTypesInspection extends BaseAssertEqualsBetweenInconvertibleTypesInspection {

  @Override
  protected boolean checkTestNG() {
    return false;
  }
}


text:
static inline Class preferredByteArrayClass(void) {
    return [HFAttributedByteArray class];
}

@implementation ProcessMemoryDocument

- (void)openProcessWithPID:(pid_t)pid {
    HFByteSlice *byteSlice = [[[HFProcessMemoryByteSlice alloc] initWithAddressSpaceOfPID:pid] autorelease];
    if (byteSlice) {
        HFByteArray *byteArray = [[[preferredByteArrayClass() alloc] init] autorelease];
        [byteArray insertByteSlice:byteSlice inRange:HFRangeMake(0, 0)];
        [controller setByteArray:byteArray];
    }
}

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Doodle.js -- Making Things Move: Ch.8, p.203: Springing in One Dimension with Friction</title>


text:
'use strict';

const assert      = require('assert');
const card        = require('../lib/builders/card');
const generateContext = require('../lib/context-generator');

describe('operators', function(){
  let context = generateContext();
  it('adds a simple card object to the response', function(){
    let cardInput = {title: "hello", content: "hello world"};
    card(cardInput, context);
    assert.deepEqual({type: "Simple", title: "hello", content: "hello world"}, context.responseBody.card);
  });

});


text:
@import Foundation;
#import "STPage.h"

@protocol STDocumentData <NSObject>

- (void)addPage: (id <STPage>)page;
- (void)deselectAllLayers;

@end

@protocol STDocument <NSObject>
@optional

- (void)setCurrentPage: (id <STPage>)page;
- (id <STPage>)currentPage;

- (id)window;

- (id <STDocumentData>)documentData;

- (void)setSelectedLayers: (NSArray *)layers;

@end


text:
from jacket.tests.compute.functional.api_sample_tests import test_servers
from jacket.tests.compute.unit.image import fake

class PersonalitySampleJsonTest(test_servers.ServersSampleBase):
    extension_name = 'os-personality'

    def test_servers_post(self):
        self._post_server(use_common_server_api_samples=False)

    def test_servers_rebuild(self):
        subs = {
            'image_id': fake.get_valid_image_id(),
            'host': self._get_host(),
            'glance_host': self._get_glance_host(),
            'access_ip_v4': '1.2.3.4',
            'access_ip_v6': '80fe::'
        }
        uuid = self._post_server(use_common_server_api_samples=False)
        response = self._do_post('servers/%s/action' % uuid,
                                 'server-action-rebuild-req', subs)
        subs['hostid'] = '[a-f0-9]+'
        subs['id'] = uuid
        self._verify_response('server-action-rebuild-resp',
                              subs, response, 202)


text:
package com.auth0.lock.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.auth0.lock.Lock;
import com.auth0.lock.R;

import java.util.ArrayList;

public class SocialSignUpFragment extends BaseTitledFragment {

    private static final String SOCIAL_FRAGMENT_STRATEGIES_ARGUMENT = "strategies";

    public SocialSignUpFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            Bundle bundle = getArguments();
            ArrayList<String> services = bundle.getStringArrayList(SOCIAL_FRAGMENT_STRATEGIES_ARGUMENT);
            Lock lock = Lock.getLock(getActivity());
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.com_auth0_social_list_container, SmallSocialListFragment.newFragment(services))
                    .replace(R.id.com_auth0_signup_form_container, SignUpFormFragment.newFragment(lock.shouldUseEmail(), lock.shouldLoginAfterSignUp(), lock.getAuthenticationParameters()))
                    .commit();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.com_auth0_fragment_social_sign_up, container, false);
    }

    @Override
    protected int getTitleResource() {
        return R.string.com_auth0_database_signup_title;
    }

    public static SocialSignUpFragment newFragment(ArrayList<String> services) {
        Bundle arguments = new Bundle();
        arguments.putStringArrayList(SOCIAL_FRAGMENT_STRATEGIES_ARGUMENT, services);
        SocialSignUpFragment fragment = new SocialSignUpFragment();
        fragment.setArguments(arguments);
        return fragment;
    }

}


text:
from Crypto.Cipher import AES
from Crypto import Random

# Pretty straightforward functions to deal with AES

def create_key(length=16):
    return Random.get_random_bytes(length)

def encrypt(key, message):
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    return iv + cipher.encrypt(message)

def decrypt(key, message):
    iv = message[:AES.block_size]
    cipher = AES.new(key, AES.MODE_CFB, iv)
    return cipher.decrypt(message[AES.block_size:])


text:
<refentry xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          id="table.footnote.number.format">
<refmeta>
<refentrytitle>table.footnote.number.format</refentrytitle>
<refmiscinfo role="type">string</refmiscinfo>
</refmeta>
<refnamediv>
<refname>table.footnote.number.format</refname>
<refpurpose>Identifies the format used for footnote numbers in tables</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment id='table.footnote.number.format.frag'>
<xsl:param name="table.footnote.number.format" select="'a'"/>
</src:fragment>
</refsynopsisdiv>

<refsect1><title>Description</title>

<para>The <parameter>table.footnote.number.format</parameter> specifies the format
to use for footnote numeration (1, i, I, a, or A) in tables.</para>

</refsect1>
</refentry>


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using wallabag.Api.EventArgs;

namespace wallabag.Api
{
    public partial class WallabagClient : IWallabagClient
    {
        private HttpClient _httpClient;
        private string _version;

        /// <summary>
        /// Gets or sets if exceptions should be thrown.
        /// </summary>
        public bool ThrowHttpExceptions { get; set; }

        /// <summary>
        /// Gets the timeout in milliseconds for each HTTP request.
        /// </summary>
        public TimeSpan Timeout => _httpClient.Timeout;

        /// <summary>
        /// Returns the API version of the current instance.
        /// Empty if not fetched yet via <see cref="GetVersionAsync(bool, CancellationToken)"/> or
        /// <see cref="GetVersionNumberAsync(bool, CancellationToken)"/>.
        /// </summary>
        public string ApiVersion { get => _version; }

        /// <summary>
        /// Initializes a new instance of WallabagClient.
        /// </summary>
        /// <param name="uri">The Uri of the wallabag instance of the user.</param>
        /// <param name="clientId">The OAuth client id of the app.</param>
        /// <param name="clientSecret">The OAuth client secret of the app.</param>
        /// <param name="timeout">Number in milliseconds after the request will be cancelled.</param>
        /// <param name="throwHttpExceptions">Value that indicates if exceptions should be thrown.</param>
        public WallabagClient(
            Uri uri,
            string clientId,
            string clientSecret,
            int timeout = 0,
            bool throwHttpExceptions = false)
        {
            InstanceUri = uri;
            ClientId = clientId;
            ClientSecret = clientSecret;

            if (!string.IsNullOrEmpty(AccessToken) && !string.IsNullOrEmpty(RefreshToken))
            {
                AccessToken = AccessToken;
                RefreshToken = RefreshToken;
            }

            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json");

            if (timeout > 0)
                _httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);

            ThrowHttpExceptions = throwHttpExceptions;
        }

        public void Dispose() => _httpClient.Dispose();

        /// <summary>
        /// Returns the version number of the current wallabag instance.
        /// </summary>
        /// <returns>
        /// The version number of the server as string. Empty if it fails.
        /// </returns>
        public async Task<string> GetVersionNumberAsync(bool forceRefresh = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(_version) || forceRefresh)
                _version = await ExecuteHttpRequestAsync<string>(HttpRequestMethod.Get, BuildApiRequestUri("/version"), cancellationToken, requiresAuthentication: false);

            return _version;
        }

        /// <summary>
        /// Returns the version number of the current wallabag instance as <see cref="ApiVersion"/>.
        /// </summary>
        public async Task<Version> GetVersionAsync(bool forceRefresh = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            string versionNumber = await GetVersionNumberAsync(forceRefresh, cancellationToken);

            Version.TryParse(versionNumber, out var result);

            return result;
        }

        /// <summary>
        /// Creates a valid relative Uri for <see cref="ExecuteHttpRequestAsync{T}(HttpRequestMethod, Uri, CancellationToken, Dictionary{string, object}, bool)"/>.
        /// </summary>
        /// <param name="s">The string.</param>
        private Uri BuildApiRequestUri(string s) => new Uri($"api{s}.json", UriKind.Relative);

        /// <summary>
        /// Execute a HTTP request and deserialize it immediately.
        /// </summary>
        /// <typeparam name="T">The object you want to fetch and that is the type of the deserialization.</typeparam>
        /// <param name="httpRequestMethod">The type of the http method.</param>
        /// <param name="requestSubUri">The relative string that is attached to the <see cref="InstanceUri"/>.</param>
        /// <param name="parameters">Parameters that should be submitted along with the request.</param>
        /// <param name="requiresAuthentication">Indicating, if the default Authorization header should be attached to the request.</param>
        /// <returns>If successful, the response as <typeparamref name="T"/>, otherwise the default value of <typeparamref name="T"/>.</returns>
        private async Task<T> ExecuteHttpRequestAsync<T>(
            HttpRequestMethod httpRequestMethod,
            Uri requestSubUri,
            CancellationToken cancellationToken,
            Dictionary<string, object> parameters = default(Dictionary<string, object>),
            bool requiresAuthentication = true)
        {
            // Before executing the request check if the cancellation was requested
            cancellationToken.ThrowIfCancellationRequested();

            // Execute the PreRequestExecution event
            var args = new PreRequestExecutionEventArgs()
            {
                RequestMethod = httpRequestMethod,
                RequestUriSubString = requestSubUri.ToString(),
                Parameters = parameters
            };
            PreRequestExecution?.Invoke(this, args);

            // Add the Authorization header if required
            if (requiresAuthentication)
            {
                if (string.IsNullOrEmpty(AccessToken))
                    throw new Exception("Access token not available. Please create one using the RequestTokenAsync() method first.");

                _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", await GetAccessTokenAsync(cancellationToken));

                // The access token exists, but it's outdated and couldn't be updated due to several reasons.
                if (!string.IsNullOrEmpty(AccessToken) && DateTime.UtcNow.Subtract(LastTokenRefreshDateTime).TotalSeconds > 3600)
                    return default(T);
            }

            // Build the URI
            string requestUriString = new Uri(InstanceUri, requestSubUri).ToString();

            if (httpRequestMethod == HttpRequestMethod.Get && parameters?.Count > 0)
            {
                requestUriString += "?";

                foreach (var item in parameters)
                {
                    object value = item.Value;

                    if (item.Value is bool)
                        value = (bool)item.Value ? 1 : 0;

                    requestUriString += $"{item.Key}={value}&";
                }

                // Remove the last ampersand (&).
                requestUriString = requestUriString.Remove(requestUriString.Length - 1);
            }

            var requestUri = new Uri(requestUriString);

            string httpMethodString = "GET";
            switch (httpRequestMethod)
            {
                case HttpRequestMethod.Delete: httpMethodString = "DELETE"; break;
                case HttpRequestMethod.Patch: httpMethodString = "PATCH"; break;
                case HttpRequestMethod.Post: httpMethodString = "POST"; break;
                case HttpRequestMethod.Put: httpMethodString = "PUT"; break;
            }

            var method = new HttpMethod(httpMethodString);
            var request = new HttpRequestMessage(method, requestUri);

            if (parameters != null && httpRequestMethod != HttpRequestMethod.Get)
                request.Content = new StringContent(JsonConvert.SerializeObject(parameters, new JsonConverter[] { new Common.JsonBoolConverter() }), System.Text.Encoding.UTF8, "application/json");

            HttpResponseMessage response = null;
            try
            {
                response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);
                AfterRequestExecution?.Invoke(this, new AfterRequestExecutionEventArgs(args, response));

                if (response.IsSuccessStatusCode)
                    return await ParseJsonFromStreamAsync<T>(await response.Content.ReadAsStreamAsync(), cancellationToken);
                else
                    return default(T);
            }
            catch (HttpRequestException)
            {
                AfterRequestExecution?.Invoke(this, new AfterRequestExecutionEventArgs(args, response));
                if (ThrowHttpExceptions) throw;
                return default(T);
            }
        }

        private Task<T> ParseJsonFromStreamAsync<T>(Stream s, CancellationToken cancellationToken)
        {
            return Task.Factory.StartNew(() =>
            {
                using (var st = s)
                using (var sr = new StreamReader(st))
                using (JsonReader reader = new JsonTextReader(sr))
                {
                    var serializer = new JsonSerializer();

                    // read the json from a stream
                    // json size doesn't matter because only a small piece is read at a time from the HTTP request
                    return serializer.Deserialize<T>(reader);
                }
            }, cancellationToken);
        }

        /// <summary>
        /// The type of the HTTP request.
        /// </summary>
        public enum HttpRequestMethod { Delete, Get, Patch, Post, Put }

        /// <summary>
        /// Event that is fired before a HTTP request to the server is started.
        /// </summary>
        public event EventHandler<PreRequestExecutionEventArgs> PreRequestExecution;

        /// <summary>
        /// Event that is fired after the HTTP request is complete.
        /// </summary>
        public event EventHandler<AfterRequestExecutionEventArgs> AfterRequestExecution;
    }
}


text:
angular.module('flight-search',[
  'ngMaterial',
  'ui.router',
  'services',
  'directives',
  'flight'
]);


text:
#import <UIKit/UIKit.h>
#import "MPUAbstractContainerViewController.h"
#import "MPULoadTransactionController.h"
#import "MPUSummaryController.h"
#import "MPUErrorController.h"
#import "MPULoadTransactionController.h"
#import "MPUSendReceiptController.h"
#import "MPUPrintReceiptController.h"
#import "MPUApplicationSelectionController.h"
#import "MPULoginController.h"

@interface MPUSummaryContainerViewController : MPUAbstractContainerViewController<MPULoadTransactionDelegate,
                                                                                MPUSummaryDelegate,
                                                                                MPUErrorDelegate,
                                                                                MPUSendReceiptDelegate,
                                                                                MPUPrintReceiptDelegate,
                                                                                MPULoginDelegate>

@property (nonatomic, strong) NSString *transactionIdentifer;
@property (nonatomic, copy) MPUSummaryCompleted completed;

@end


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace FCT.LLC.BusinessService.Entities
{
    [Table("tblBusinessModel")]
    public partial class tblBusinessModel
    {
        [Key]
        [Column(Order = 0)]
        public int Id { get; set; }

        [Key]
        [Column(Order = 1)]
        [StringLength(50)]
        public string BusinessModelName { get; set; }
    }
}


text:
package mealplaner.plugins.preference;

import static mealplaner.commons.NonnegativeInteger.ONE;
import static mealplaner.commons.NonnegativeInteger.TWO;
import static mealplaner.model.meal.MealBuilder.meal;
import static mealplaner.model.settings.SettingsBuilder.setting;
import static mealplaner.plugins.preference.mealextension.CookingPreference.VERY_POPULAR;
import static mealplaner.plugins.preference.settingextension.PreferenceSettings.RARE_NONE;
import static testcommons.PluginsXmlUtils.assertSaveAndReloadMealWorksCorrectly;
import static testcommons.PluginsXmlUtils.assertSaveAndReloadSettingWorksCorrectly;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import mealplaner.model.meal.Meal;
import mealplaner.model.settings.Settings;
import mealplaner.plugins.preference.mealextension.CookingPreferenceFact;
import mealplaner.plugins.preference.settingextension.CookingPreferenceSubSetting;
import testcommons.PluginsUtils;
import testcommons.XmlInteraction;

class CookingPreferenceXmlTest extends XmlInteraction {
  @BeforeEach
  void setUp() {
    PluginsUtils.setupMessageBundles(new CookingPreferencePlugin());
  }

  @Test
  void roundTripWithCookingTimeCanBeSavedCorrectly() {
    Meal meal = meal()
        .name("Test1")
        .daysPassed(ONE)
        .addFact(new CookingPreferenceFact(VERY_POPULAR))
        .create();

    assertSaveAndReloadMealWorksCorrectly(meal, DESTINATION_FILE_PATH, new CookingPreferencePlugin());
  }

  @Test
  void roundTripWithCookingTimeSubSettingWorksCorrectly() {
    Settings settings = setting()
        .numberOfPeople(TWO)
        .addSetting(new CookingPreferenceSubSetting(RARE_NONE))
        .create();

    assertSaveAndReloadSettingWorksCorrectly(settings, new CookingPreferencePlugin(), DESTINATION_FILE_PATH);
  }
}


text:
//
//	XMAnnouncerCategory.h
//
//	Create by 瑞 王 on 18/12/2015
//	Copyright © 2015. All rights reserved.
//

//	Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport

#import <UIKit/UIKit.h>

/**
 *  主播分类
 */
@interface XMAnnouncerCategory : NSObject

@property (nonatomic, assign) NSInteger id;
@property (nonatomic, strong) NSString * kind;
@property (nonatomic, assign) NSInteger orderNum;
@property (nonatomic, strong) NSString * vcategoryName;

-(instancetype)initWithDictionary:(NSDictionary *)dictionary;

-(NSDictionary *)toDictionary;
@end


text:
package freemind.modes.mindmapmode.actions;

import freemind.main.HtmlTools;
import freemind.modes.mindmapmode.MindMapController;
import freemind.modes.mindmapmode.MindMapMapModel;
import freemind.modes.mindmapmode.MindMapNodeModel;

public class UsePlainTextAction extends NodeGeneralAction {

	public UsePlainTextAction(final MindMapController modeController) {
		super(modeController, "use_plain_text", null,
				new SingleNodeOperation() {

					public void apply(MindMapMapModel map,
							MindMapNodeModel selected) {
						// modeController.getController().setProperty(
						// "use_rich_text_in_new_long_nodes", "false");
						String nodeText = selected.getText();
						if (HtmlTools.isHtmlNode(nodeText)) {
							modeController.setNodeText(selected,
									HtmlTools.htmlToPlain(nodeText));
						}
					}
				});
	}

	// public boolean isEnabled() {
	// if (1 == 0) {
	// // Dan: The following code probably needs that the node context menu
	// // gets somehow refreshed
	// // whenever it pops. But I do not know how to ensure that.
	// for (ListIterator it = controller.getView().getSelecteds()
	// .listIterator(); it.hasNext();) {
	// NodeView selected = (NodeView) it.next();
	// String nodeText = selected.getModel().toString();
	// if (nodeText.startsWith("<html>")) {
	// return true;
	// }
	// }
	// return false;
	// }
	// return true;
	// }

}


text:
 package x
 import a._
 /*caret*/class f
 class g( ) extends k {
   def foo( ) = return true
 }
/*
abstract
case
class
final
implicit
import
lazy
object
override
package
private
protected
sealed
trait
*/