text:
;(function(){
  angular.module('angular-markdown', []);
})();

//markdown.md-loader.directive.js
;(function(){
  angular.module('angular-markdown').directive('mdLoader', directiveFactory);
  function directiveFactory(){
    return {
      scope: {
        url: '@',
        ret: '=',
        mdCallback: '&'
      },
      link: function(scope, el, attr, vm){
        vm.init(scope, el, attr);
      },
      controller: controller
    }
    controller.$inject = ['$compile', 'mdService'];
    function controller($compile, mdService){
      this.init = function(scope, el, attr){
        var url = scope.url;
        if(url){
          var promise = mdService.fetch(url).then(function(res){
            el.html(marked(res))
            $compile(el.contents())(scope);
          });
          scope.mdCallback({promise: promise});
        }
      }
    }
  }
})();

//markdown.md-fetch.sevice.js
;(function(){
  angular.module('angular-markdown').factory('mdService', factory);
  factory.$inject = ['$http', '$q'];
  function factory($http, $q){
    return {
      fetch: function(url){
        var d = $q.defer();
        $http.get(url, {cache:false}).
        success(function(res){
          d.resolve(res);
        });
        return d.promise;
      }
    }
  }
})();

redpajama_set_name: RedPajamaGithub


text:
#include <phosg/Time.hh>
#include <phosg/UnitTest.hh>
#include <phosg/Process.hh>
#include <string>

#include "Pool.hh"
#include "SimpleAllocator.hh"
#include "LogarithmicAllocator.hh"
#include "HashTable.hh"

using namespace std;
using namespace sharedstructures;

const string pool_name_prefix = "HashTableTest-cc-pool-";

shared_ptr<Allocator> create_allocator(shared_ptr<Pool> pool,
    const string& allocator_type) {
  if (allocator_type == "simple") {
    return shared_ptr<Allocator>(new SimpleAllocator(pool));
  }
  if (allocator_type == "logarithmic") {
    return shared_ptr<Allocator>(new LogarithmicAllocator(pool));
  }
  throw invalid_argument("unknown allocator type: " + allocator_type);
}

void expect_key_missing(const HashTable& table, const void* k,
    size_t s) {
  try {
    table.at(k, s);
    expect(false);
  } catch (const out_of_range& e) { }
}

void verify_state(
    const unordered_map<string, string>& expected,
    const HashTable& table) {
  expect_eq(expected.size(), table.size());
  for (const auto& it : expected) {
    expect_eq(it.second, table.at(it.first.data(), it.first.size()));
  }

  auto missing_elements = expected;
  for (const auto& it : table) {
    auto missing_it = missing_elements.find(it.first);
    expect_ne(missing_it, missing_elements.end());
    expect_eq(missing_it->second, it.second);
    missing_elements.erase(missing_it);
  }
  expect_eq(true, missing_elements.empty());
}

void run_basic_test(const string& allocator_type) {
  printf("-- [%s] basic\n", allocator_type.c_str());

  shared_ptr<Pool> pool(new Pool(pool_name_prefix + allocator_type));
  shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
  HashTable table(alloc, 0, 6);

  unordered_map<string, string> expected;
  size_t initial_pool_allocated = alloc->bytes_allocated();

  expect_eq(0, table.size());
  expect_eq(6, table.bits());

  table.insert("key1", 4, "value1", 6);
  expected.emplace("key1", "value1");
  verify_state(expected, table);
  table.insert("key2", 4, "value2", 6);
  expected.emplace("key2", "value2");
  verify_state(expected, table);
  table.insert("key3", 4, "value3", 6);
  expected.emplace("key3", "value3");
  verify_state(expected, table);

  expect_eq(true, table.erase("key2", 4));
  expected.erase("key2");
  verify_state(expected, table);

  expect_eq(false, table.erase("key2", 4));
  verify_state(expected, table);

  table.insert("key1", 4, "value0", 6);
  expected["key1"] = "value0";
  verify_state(expected, table);

  table.clear();
  expected.clear();
  verify_state(expected, table);

  // The empty table should not leak any allocated memory
  expect_eq(initial_pool_allocated, alloc->bytes_allocated());
}

void run_collision_test(const string& allocator_type) {
  printf("-- [%s] collision\n", allocator_type.c_str());

  // Writing 5 keys to a 4-slot hashtable forces a collision

  shared_ptr<Pool> pool(new Pool(pool_name_prefix + allocator_type));
  shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
  HashTable table(alloc, 0, 2);

  unordered_map<string, string> expected;
  size_t initial_pool_allocated = alloc->bytes_allocated();

  expect_eq(0, table.size());

  table.insert("key1", 4, "value1", 6);
  table.insert("key2", 4, "value2", 6);
  table.insert("key3", 4, "value3", 6);
  table.insert("key4", 4, "value4", 6);
  table.insert("key5", 4, "value5", 6);
  expected.emplace("key1", "value1");
  expected.emplace("key2", "value2");
  expected.emplace("key3", "value3");
  expected.emplace("key4", "value4");
  expected.emplace("key5", "value5");
  verify_state(expected, table);

  while (!expected.empty()) {
    auto it = expected.begin();
    table.erase(it->first);
    expected.erase(it);
    verify_state(expected, table);
  }

  // The empty table should not leak any allocated memory
  expect_eq(initial_pool_allocated, alloc->bytes_allocated());
}

void run_conditional_writes_test(const string& allocator_type) {
  printf("-- [%s] conditional writes\n", allocator_type.c_str());

  shared_ptr<Pool> pool(new Pool(pool_name_prefix + allocator_type));
  shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
  HashTable table(alloc, 0, 6);

  size_t initial_pool_allocated = table.get_allocator()->bytes_allocated();
  expect_eq(0, table.size());

  expect_eq(true, table.insert("key1", 4, "value1", 6));
  expect_eq(true, table.insert("key2", 4, "value2", 6));

  // Check that conditions on the same key work
  {
    HashTable::CheckRequest check("key1", 4, "value2", 6);
    expect_eq(false, table.insert("key1", 4, "value1_1", 8, &check));
    expect_eq("value1", table.at("key1", 4));

    check.value = "value1";
    expect_eq(true, table.insert("key1", 4, "value1_1", 8, &check));
    expect_eq("value1_1", table.at("key1", 4));
  }

  // Check that conditions on other keys work
  {
    HashTable::CheckRequest check("key2", 4, "value1");
    expect_eq(false, table.insert("key1", 4, "value1", 6, &check));
    expect_eq("value1_1", table.at("key1", 4));

    check.value = "value2";
    expect_eq(true, table.insert("key1", 4, "value1", 6, &check));
    expect_eq("value1", table.at("key1", 4));
  }

  // Check that missing conditions work
  {
    HashTable::CheckRequest check("key2", 4);
    expect_eq(false, table.insert("key3", 4, "value3", 6, &check));
    expect_eq(false, table.exists("key3", 4));
  }
  {
    HashTable::CheckRequest check("key3", 4);
    expect_eq(true, table.insert("key3", 4, "value3", 6, &check));
    expect_eq("value3", table.at("key3", 4));
  }

  // Check that conditional deletes work
  {
    HashTable::CheckRequest check("key1", 4, "value2", 6);
    expect_eq(false, table.erase("key1", 4, &check));
    expect_eq("value1", table.at("key1", 4));

    check.value = "value1";
    expect_eq(true, table.erase("key1", 4, &check));
    expect_eq(false, table.exists("key1", 4));
  }

  {
    HashTable::CheckRequest check("key3", 4);
    expect_eq(false, table.erase("key2", 4, &check));
    expect_eq("value2", table.at("key2", 4));
  }
  {
    HashTable::CheckRequest check("key1", 4);
    expect_eq(true, table.erase("key2", 4, &check));
    expect_eq(false, table.exists("key2", 4));
  }
  expect_eq(true, table.erase("key3", 4));

  // The empty table should not leak any allocated memory
  expect_eq(0, table.size());
  expect_eq(initial_pool_allocated, table.get_allocator()->bytes_allocated());
}

template <typename T>
static bool insert_typed(HashTable& table, const char* key, T v) {
  return table.insert(key, strlen(key), &v, sizeof(v));
}

template <typename T>
static T at_typed(HashTable& table, const char* key) {
  string ret = table.at(key, strlen(key));
  if (ret.size() != sizeof(T)) {
    throw out_of_range("key didn\'t match expected size");
  }
  return *(const T*)ret.data();
}

void run_incr_test(const string& allocator_type) {
  printf("-- [%s] incr\n", allocator_type.c_str());

  shared_ptr<Pool> pool(new Pool(pool_name_prefix + allocator_type));
  shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
  HashTable table(alloc, 0, 6);

  size_t initial_pool_allocated = table.get_allocator()->bytes_allocated();

  // Add some keys
  expect_eq(0, table.size());
  expect_eq(true, insert_typed<int8_t>(table, "int8", 40));
  expect_eq(true, insert_typed<int16_t>(table, "int16", 4000));
  expect_eq(true, insert_typed<int32_t>(table, "int32", 60000000));
  expect_eq(true, insert_typed<int64_t>(table, "int64", 800000000000000));
  expect_eq(true, insert_typed<float>(table, "float", 10.0));
  expect_eq(true, insert_typed<double>(table, "double", 15.5));
  expect_eq(true, table.insert("string", 6, "7 bytes", 7));
  expect_eq(7, table.size());

  // incr should create the key if it doesn't exist
  expect_eq(-10, table.incr("int8-2", (int64_t)-10));
  expect_eq(-4000, table.incr("int16-2", (int64_t)-4000));
  expect_eq(-60000000, table.incr("int32-2", (int64_t)-60000000));
  expect_eq(-800000000000000, table.incr("int64-2", (int64_t)-800000000000000));
  expect_eq(-10.0, table.incr("float-2", -10.0));
  expect_eq(-15.5, table.incr("double-2", -15.5));
  expect_eq(13, table.size());

  // All the keys should have the values we set, but the keys created by incr
  // should all be 64 bits
  expect_eq(40, at_typed<int8_t>(table, "int8"));
  expect_eq(4000, at_typed<int16_t>(table, "int16"));
  expect_eq(60000000, at_typed<int32_t>(table, "int32"));
  expect_eq(800000000000000, at_typed<int64_t>(table, "int64"));
  expect_eq(10.0, at_typed<float>(table, "float"));
  expect_eq(15.5, at_typed<double>(table, "double"));
  expect_eq(-10, at_typed<int64_t>(table, "int8-2"));
  expect_eq(-4000, at_typed<int64_t>(table, "int16-2"));
  expect_eq(-60000000, at_typed<int64_t>(table, "int32-2"));
  expect_eq(-800000000000000, at_typed<int64_t>(table, "int64-2"));
  expect_eq(-10.0, at_typed<double>(table, "float-2"));
  expect_eq(-15.5, at_typed<double>(table, "double-2"));
  expect_eq(13, table.size());

  // incr should return the new value of the key
  expect_eq(44, table.incr("int8", (int64_t)4));
  expect_eq(4010, table.incr("int16", (int64_t)10));
  expect_eq(60000100, table.incr("int32", (int64_t)100));
  expect_eq(800000000001000, table.incr("int64", (int64_t)1000));
  expect_eq(30.0, table.incr("float", 20.0));
  expect_eq(25.5, table.incr("double", 10.0));
  expect_eq(-14, table.incr("int8-2", (int64_t)-4));
  expect_eq(-4010, table.incr("int16-2", (int64_t)-10));
  expect_eq(-60000100, table.incr("int32-2", (int64_t)-100));
  expect_eq(-800000000001000, table.incr("int64-2", (int64_t)-1000));
  expect_eq(-30.0, table.incr("float-2", -20.0));
  expect_eq(-25.5, table.incr("double-2", -10.0));
  expect_eq(13, table.size());

  // Test incr() on keys of the wrong type
  try {
    table.incr("string", 6, (int64_t)14);
    expect(false);
  } catch (const out_of_range& e) { }
  try {
    table.incr("string", 6, 15.0);
    expect(false);
  } catch (const out_of_range& e) { }

  table.clear();
  expect_eq(0, table.size());

  // The empty table should not leak any allocated memory
  expect_eq(initial_pool_allocated, table.get_allocator()->bytes_allocated());
}

void run_concurrent_readers_test(const string& allocator_type) {
  printf("-- [%s] concurrent readers\n", allocator_type.c_str());

  // Make sure everything is initialized before starting child processes
  {
    shared_ptr<Pool> pool(new Pool(pool_name_prefix + allocator_type));
    shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
    HashTable table(alloc, 0, 4);
  }

  unordered_set<pid_t> child_pids;
  while ((child_pids.size() < 8) && !child_pids.count(0)) {
    pid_t pid = fork();
    if (pid == -1) {
      break;
    } else {
      child_pids.emplace(pid);
    }
  }

  if (child_pids.count(0)) {
    // Child process: try up to a second to get the key
    shared_ptr<Pool> pool(new Pool(pool_name_prefix + allocator_type));
    shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
    HashTable table(alloc, 0, 4);

    int64_t value = 100;
    string value_str = to_string(value);
    uint64_t start_time = now();
    do {
      try {
        auto res = table.at("key1", 4);
        if (res == value_str) {
          fprintf(stderr, "-- [%s]   child %d saw value %" PRId64 "\n",
              allocator_type.c_str(), getpid_cached(), value);
          value++;
          value_str = to_string(value);
        }
      } catch (const out_of_range& e) { }
      usleep(1); // Yield to other processes
    } while ((value < 110) && (now() < (start_time + 1000000)));

    if (now() >= (start_time + 1000000)) {
      fprintf(stderr, "-- [%s]   child %d timed out\n", allocator_type.c_str(),
          getpid_cached());
    }

    // We succeeded if we saw all the values from 100 to 110
    _exit(value != 110);

  } else {
    // Parent process: write the key, then wait for children to terminate
    shared_ptr<Pool> pool(new Pool(pool_name_prefix + allocator_type));
    shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
    HashTable table(alloc, 0, 4);

    for (int64_t value = 100; value < 110; value++) {
      usleep(50000);
      table.insert("key1", 4, to_string(value));
    }

    int num_failures = 0;
    int exit_status;
    pid_t exited_pid;
    while ((exited_pid = wait(&exit_status)) != -1) {
      child_pids.erase(exited_pid);
      bool exited = WIFEXITED(exit_status);
      bool signaled = WIFSIGNALED(exit_status);
      int status = WEXITSTATUS(exit_status);
      int signal = WTERMSIG(exit_status);
      if (exited && (exit_status == 0)) {
        printf("-- [%s]   child %d terminated successfully\n",
            allocator_type.c_str(), exited_pid);
      } else {
        printf("-- [%s]   child %d failed (%d; exited=%d signaled=%d status=%d signal=%d)\n",
            allocator_type.c_str(), exited_pid, exit_status, exited, signaled, status, signal);
        num_failures++;
      }
    }

    expect_eq(true, child_pids.empty());
    expect_eq(0, num_failures);
  }
}

int main(int, char**) {
  int retcode = 0;

  vector<string> allocator_types({"simple", "logarithmic"});
  try {
    for (const string& allocator_type : allocator_types) {
      Pool::delete_pool(pool_name_prefix + allocator_type);
      run_basic_test(allocator_type);
      Pool::delete_pool(pool_name_prefix + allocator_type);
      run_conditional_writes_test(allocator_type);
      Pool::delete_pool(pool_name_prefix + allocator_type);
      run_collision_test(allocator_type);
      Pool::delete_pool(pool_name_prefix + allocator_type);
      run_incr_test(allocator_type);
      Pool::delete_pool(pool_name_prefix + allocator_type);
      run_concurrent_readers_test(allocator_type);
    }
    printf("all tests passed\n");

  } catch (const exception& e) {
    printf("failure: %s\n", e.what());
    retcode = 1;
  }
  for (const auto& allocator_type : allocator_types) {
    Pool::delete_pool(pool_name_prefix + allocator_type);
  }

  return retcode;
}


text:
<?php

namespace LoLTool\Bundle\LoLToolBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * SpellRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SpellRepository extends EntityRepository
{
}


text:
require "spec_helper"
require "support/connections/active_record"

require "encrypt_attributes/model"

class User < ActiveRecord::Base
  include EncryptAttributes::Model
  encrypt_attrs :secret
end unless defined?(User)

describe User do
  after(:all) { User.delete_all }
  include_examples "adapter"
end


text:
package org.agmip.translators.soil;

import java.util.ArrayList;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class used to reduce number of soil layers, it reduces the number of soil
 * layers according the criteria decorator. If at the end of the process the
 * soil layers number is greater than the max, we will aggregate all the deepest
 * layers into a single one without taking into account the criteria.
 *
 * @author jucufi
 * @author dripoche
 *
 */
public class LayerReducer {
	private static final Logger log = LoggerFactory.getLogger(LayerReducer.class);
	private LayerReducerDecorator decorator;
	private int maxSoilLayers;
	private int MAX_SOIL_LAYERS = 5;

	// Soil information under soil section
	public static String SLLL = "slll";
	public static String SLDUL = "sldul";
	public static String SLBDM = "slbdm";
	public static String SKSAT = "sksat";
	public static String SLLB = "sllb";
	public static String SLOC = "sloc";

	public LayerReducer(LayerReducerDecorator decorator) {
		this.decorator = decorator;
		this.maxSoilLayers = MAX_SOIL_LAYERS;
	}

	/**
	 * Process all the soil layers and return a new structure with aggregated
	 * data.
	 *
	 * @param soilsData
	 * @return
	 */
	public ArrayList<HashMap<String, String>> process(ArrayList<HashMap<String, String>> soilsData) {
		HashMap<String, String> previousSoil;
		ArrayList<HashMap<String, String>> aggregatedSoilsData;
		HashMap<String, String> aggregatedSoil;
		boolean aggregate;
		boolean enforceAggregation;
		previousSoil = null;
		aggregate = true;
		enforceAggregation = false;
		aggregatedSoilsData = new ArrayList<HashMap<String, String>>();
		ArrayList<HashMap<String, String>> normalizedSoilsData = normalizeSoilLayers(soilsData);
		log.debug("Formated soil data : " + normalizedSoilsData);
		int i = 0;
		for (HashMap<String, String> currentSoil : normalizedSoilsData) {
			i++;
			if (previousSoil != null) {
				if (aggregatedSoilsData.size() == getMaxSoilLayers()) {
					// ok max is reached up to now we enforce aggregation
					enforceAggregation = true;
				}
				aggregate = decorator.shouldAggregateSoils(currentSoil, previousSoil) || enforceAggregation;
				if (aggregate) {
					log.debug("Aggregating soil layers... " + i + " and " + (i - 1));
					log.debug("soil " + i + " " + currentSoil);
					log.debug("soil " + (i - 1) + " " + previousSoil);
					// Compute the new map
					aggregatedSoil = decorator.computeSoil(currentSoil, previousSoil);
					if (aggregatedSoilsData.contains(previousSoil)) {
						aggregatedSoilsData.remove(previousSoil);
					}
					// Set as previous soil treated
					previousSoil = aggregatedSoil;
					aggregatedSoilsData.add(aggregatedSoil);
				} else {
					previousSoil = currentSoil;
					log.debug("Adding soil layer ...");
					log.debug("soil " + i + " " + currentSoil);
					aggregatedSoilsData.add(currentSoil);
				}
			} else {
				previousSoil = currentSoil;
				aggregatedSoilsData.add(currentSoil);
			}
		}
		log.debug("Information about soil aggregation");
		log.debug("Soil layers before : " + soilsData.size());
		log.debug("Soil layers after  : " + aggregatedSoilsData.size());
		return aggregatedSoilsData;
	}

	public int getMaxSoilLayers() {
		return maxSoilLayers;
	}

	/**
	 * Set the max of soil layers at the end on reduction
	 *
	 * @param maxSoilLayers
	 */
	public void setMaxSoilLayers(int maxSoilLayers) {
		this.maxSoilLayers = maxSoilLayers;
	}

	/**
	 * Fill each layer with all parameters. In the json structure when a
	 * parameter value is missing we must take the value of the previous layer.
	 *
	 * @param soilsData
	 * @return
	 */
	public ArrayList<HashMap<String, String>> normalizeSoilLayers(ArrayList<HashMap<String, String>> soilsData) {
		HashMap<String, String> referenceSoil;
		ArrayList<HashMap<String, String>> newSoilsData;
		referenceSoil = soilsData.get(0);
		newSoilsData = new ArrayList<HashMap<String, String>>();
		if (referenceSoil != null) {
			for (HashMap<String, String> currentSoil : soilsData) {
				// create a new soil with reference parameters
				HashMap<String, String> fullCurrentSoil = new HashMap<String, String>(referenceSoil);
				for (String key : referenceSoil.keySet()) {
					if (currentSoil.containsKey(key)) {
						fullCurrentSoil.put(key, currentSoil.get(key));
					}
				}
				newSoilsData.add(fullCurrentSoil);
			}
		}
		return newSoilsData;
	}

}


text:
"use strict";

const _ = require("lodash");
const Helper = require("../../helper");

exports.commands = ["quit"];
exports.allowDisconnected = true;

exports.input = function(network, chan, cmd, args) {
	const client = this;

	client.networks = _.without(client.networks, network);
	network.destroy();
	client.save();
	client.emit("quit", {
		network: network.uuid,
	});

	if (network.irc) {
		const quitMessage = args[0] ? args.join(" ") : Helper.config.leaveMessage;
		network.irc.quit(quitMessage);
	}

	return true;
};


text:
package aws

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/iot"
	"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAwsIotEndpoint() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsIotEndpointRead,
		Schema: map[string]*schema.Schema{
			"endpoint_address": {
				Type:     schema.TypeString,
				Computed: true,
			},
		},
	}
}

func dataSourceAwsIotEndpointRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).iotconn
	input := &iot.DescribeEndpointInput{}

	output, err := conn.DescribeEndpoint(input)
	if err != nil {
		return fmt.Errorf("error while describing iot endpoint: %s", err)
	}
	endpointAddress := aws.StringValue(output.EndpointAddress)
	d.SetId(endpointAddress)
	if err := d.Set("endpoint_address", endpointAddress); err != nil {
		return fmt.Errorf("error setting endpoint_address: %s", err)
	}
	return nil
}


text:
//
using System;
using System.Text;
#if JAVA
using Alachisoft.TayzGrid.Runtime.Serialization;
#else
using Alachisoft.NosDB.Common.Serialization;
#endif
#if JAVA
using Alachisoft.TayzGrid.Runtime.Serialization.IO;
#else
using Alachisoft.NosDB.Common.Serialization.IO;
#endif
using System.Collections;
using Alachisoft.NosDB.Common.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Alachisoft.NosDB.Common.DataStructures
{
    /// <summary>
    /// Contains new hashmap and related information for client
    /// </summary>
    public sealed class NewHashmap : ICompactSerializable
    {
        private long _lastViewId;
        private Hashtable _map;
        private ArrayList _members;
        private byte[] _buffer;
        private bool _updateMap = false;

        /// <summary>
        /// Default constructor
        /// </summary>
        public NewHashmap()
        {
        }

        public NewHashmap(long lastViewid, Hashtable map, ArrayList members)
        {
            this._lastViewId = lastViewid;
            this._map = map;
            this._members = new ArrayList(members.Count);

            foreach (Address address in members)
            {
                this._members.Add(address.IpAddress.ToString());
            }
        }

        /// <summary>
        /// Last view id that was published
        /// </summary>
        public long LastViewId
        {
            get { return this._lastViewId; }
        }

        /// <summary>
        /// New hash map
        /// </summary>
        public Hashtable Map
        {
            get { return this._map; }
        }

        /// <summary>
        /// Just change the view id
        /// </summary>
        public bool UpdateMap
        {
            get { return _updateMap; }
            set { _updateMap = value; }
        }

        /// <summary>
        /// List of server members (string representation of IP addresses)
        /// </summary>
        public ArrayList Members
        {
            get { return this._members; }
        }

        /// <summary>
        /// Returned the serialized object of NewHashmap
        /// </summary>
        public byte[] Buffer
        {
            get { return this._buffer; }
        }

        /// <summary>
        /// Serialize NewHashmap
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="serializationContext">Serialization context used to serialize the object</param>
        public static void Serialize(NewHashmap instance, string serializationContext, bool updateClientMap)
        {
            Hashtable mapInfo = null;
            if (instance != null)
            {
                mapInfo = new Hashtable();
                mapInfo.Add("ViewId", instance._lastViewId);
                mapInfo.Add("Members", instance._members);
                mapInfo.Add("Map", instance._map);
                mapInfo.Add("UpdateMap", updateClientMap);

                BinaryFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                formatter.Serialize(stream, mapInfo);
                instance._buffer = stream.ToArray();
            }
            //this._buffer = CompactBinaryFormatter.ToByteBuffer(this, serializationContext);
        }

        /// <summary>
        /// Deserialize NewHashmap
        /// </summary>
        /// <param name="serializationContext"></param>
        /// <returns></returns>
        public static NewHashmap Deserialize(byte[] buffer, string serializationContext)
        {
            NewHashmap hashmap = null;

            if (buffer != null && buffer.Length > 0)
            {
                BinaryFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream(buffer);
                Hashtable map = formatter.Deserialize(stream) as Hashtable;
                if (map != null)
                {
                    hashmap = new NewHashmap();
                    hashmap._lastViewId = (long)map["ViewId"];
                    hashmap._members = (ArrayList)map["Members"];
                    hashmap._map = (Hashtable)map["Map"];
                    hashmap._updateMap = (map["UpdateMap"] != null) ? (bool)map["UpdateMap"] : false;
                }
            }
            return hashmap;
        }

        #region ICompactSerializable Members

        /// <summary>
        /// Deserialize the object
        /// </summary>
        /// <param name="reader"></param>
        public void Deserialize(CompactReader reader)
        {
            this._lastViewId = reader.ReadInt64();
            this._members = reader.ReadObject() as ArrayList;
            this._map = reader.ReadObject() as Hashtable;
            this._updateMap = reader.ReadBoolean();
        }

        /// <summary>
        /// Serialize the object
        /// </summary>
        /// <param name="writer"></param>
        public void Serialize(CompactWriter writer)
        {
            writer.Write(this._lastViewId);
            writer.WriteObject(this._members);
            writer.WriteObject(this._map);
            writer.Write(this._updateMap);
        }

        #endregion

        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("{ ("); builder.Append(this._lastViewId); builder.Append(") ");
            builder.Append("[");
            for (int i = 0; i < this.Members.Count; i++)
            {
                builder.Append(this.Members[i]);
                if (i < (this.Members.Count - 1))
                {
                    builder.Append(",");
                }
            }
            builder.Append("] }");
            return builder.ToString();
        }
    }
}


text:
package com.badlogic.gdx.elita;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.scenes.scene2d.Stage;

import java.util.ArrayList;

@SuppressWarnings("unused")
public abstract class Screen<TGame extends Game> extends InputAdapter implements com.badlogic.gdx.Screen {

    private final TGame game;
    private final ArrayList<Stage> stages;

    private final InputMultiplexer inputs;

    public Screen(final TGame game) {
        this.game = game;
        this.stages = new ArrayList<Stage>();

        this.inputs = new InputMultiplexer();
        Gdx.input.setInputProcessor(this.inputs);
        Gdx.input.setCatchBackKey(true);

        this.inputs.addProcessor(this);
    }

    @Override
    public void show() {
        this.game.log("Showing screen: " + getName());
    }

    @Override
    public void resize(int width, int height) {
        this.game.log("Resizing screen: " + getName() + " to: " + width + " x " + height );
        for(Stage stage : this.stages) {
            stage.getViewport().update(width, height, true);
        }
    }

    @Override
    public void render(float delta) {
        // update and draw the actors
        for(Stage stage : this.stages) {
            stage.act(delta);
            stage.draw();
        }
    }

    @Override
    public void hide() {
        this.game.log("Hiding screen: " + getName() );

        dispose();
    }

    @Override
    public void pause() {
        this.game.log("Pausing screen: " + getName() );
    }

    @Override
    public void resume() {
        this.game.log("Resuming screen: " + getName() );
    }

    @Override
    public void dispose() {
        this.game.log("Disposing screen: " + getName());

        for(Stage stage : this.stages) {
            stage.dispose();
        }
    }

    public TGame getGame() { return this.game; }

    protected InputMultiplexer getInputMultiplexer() { return this.inputs; }

    protected void addStage(final Stage stage) {
        this.game.log("Added stage: " + stage.getClass().getSimpleName());
        this.stages.add(stage);
    }

    protected void addStage(final Stage stage, final int index) {
        this.game.log("Added stage: " + stage.getClass().getSimpleName() + " at index: " + index);
        this.stages.add(index, stage);
    }

    protected void addStageAndProcessor(final Stage stage) {
        this.game.log("Added stage and processor: " + stage.getClass().getSimpleName());

        this.addStage(stage);
        this.getInputMultiplexer().addProcessor(stage);
    }

    protected void addStageAndProcessor(final Stage stage, final int index) {
        this.game.log("Added stage: " + stage.getClass().getSimpleName() + " and processor at index: " + index);

        this.addStage(stage);
        this.getInputMultiplexer().addProcessor(index, stage);
    }

    protected String getName() {
        return ((Object) this).getClass().getSimpleName();
    }

    @Override
    public boolean keyDown(int keyCode) {
        if (keyCode == Input.Keys.BACK || keyCode == Input.Keys.ESCAPE) {
            onBackKeyPressed();
        }
        return super.keyDown(keyCode);
    }

    protected abstract void onBackKeyPressed();
}


text:
package order

import (
	"errors"
	"go2o/core/domain/interface/cart"
	"go2o/core/domain/interface/order"
)

// 订单拆单
type wholesaleOrderBreaker struct {
	repo order.IOrderRepo
}

func newWholesaleOrderBreaker(repo order.IOrderRepo) *wholesaleOrderBreaker {
	return &wholesaleOrderBreaker{
		repo: repo,
	}
}

func (w *wholesaleOrderBreaker) BreakUp(c cart.ICart,
	data order.IPostedData) ([]order.IOrder, error) {
	switch c.Kind() {
	case cart.KWholesale:
		return w.breakupWholesaleOrder(c, data)
	}
	return []order.IOrder{}, errors.New("not support cart kind")
}

func (w *wholesaleOrderBreaker) breakupWholesaleOrder(c cart.ICart,
	data order.IPostedData) ([]order.IOrder, error) {
	checked := data.CheckedData()
	items := c.CheckedItems(checked)
	if len(items) == 0 {
		return []order.IOrder{}, order.ErrNoCheckedItem
	}
	// 将购物车的商品按运营商拆分
	vendorItemsMap := w.breakSellerItemMap(items)
	if l := len(vendorItemsMap); l == 0 {
		return []order.IOrder{}, cart.ErrNoChecked
	}
	var list []order.IOrder
	cc := c.(cart.ICart)
	buyerId := cc.BuyerId()
	for sellerId, items := range vendorItemsMap {
		o := w.createWholesaleOrder(sellerId, buyerId, items, data)
		list = append(list, o)
	}
	return list, nil
}

// 创建批发订单
func (w *wholesaleOrderBreaker) createWholesaleOrder(sellerId int64,
	buyerId int64, items []*cart.ItemPair, data order.IPostedData) order.IOrder {
	v := &order.Order{
		BuyerId:   buyerId,
		OrderType: int32(order.TWholesale),
		State:     int32(order.StatAwaitingPayment),
	}
	o := w.repo.CreateOrder(v)
	wo := o.(order.IWholesaleOrder)
	wo.SetItems(items)
	wo.SetComment(data.GetComment(sellerId))
	wo.SetAddress(data.AddressId())

	return o
}

// 生成运营商与订单商品的映射
func (w *wholesaleOrderBreaker) breakSellerItemMap(items []*cart.ItemPair) map[int64][]*cart.ItemPair {
	mp := make(map[int64][]*cart.ItemPair)
	for _, v := range items {
		list, ok := mp[v.SellerId]
		if !ok {
			list = []*cart.ItemPair{}
		}
		mp[v.SellerId] = append(list, v)
	}
	return mp
}


text:
namespace base {
class Value;
}

namespace ash {

// Class to watch sms without Libcros.
class COMPONENT_EXPORT(CHROMEOS_NETWORK) NetworkSmsHandler
    : public ShillPropertyChangedObserver {
 public:
  static const char kNumberKey[];
  static const char kTextKey[];
  static const char kTimestampKey[];

  class Observer {
   public:
    virtual ~Observer() {}

    // Called when a new message arrives. |message| contains the message which
    // is a dictionary value containing entries for kNumberKey, kTextKey, and
    // kTimestampKey.
    virtual void MessageReceived(const base::Value& message) = 0;
  };

  NetworkSmsHandler(const NetworkSmsHandler&) = delete;
  NetworkSmsHandler& operator=(const NetworkSmsHandler&) = delete;

  ~NetworkSmsHandler() override;

  // Requests an immediate check for new messages.
  void RequestUpdate();

  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  // ShillPropertyChangedObserver
  void OnPropertyChanged(const std::string& name,
                         const base::Value& value) override;

 private:
  friend class NetworkHandler;
  friend class NetworkSmsHandlerTest;

  class NetworkSmsDeviceHandler;
  class ModemManagerNetworkSmsDeviceHandler;
  class ModemManager1NetworkSmsDeviceHandler;

  NetworkSmsHandler();

  // Requests the devices from the network manager, sets up observers, and
  // requests the initial list of messages.
  void Init();

  // Adds |message| to the list of received messages. If the length of the
  // list exceeds the maximum number of retained messages, erase the least
  // recently received message.
  void AddReceivedMessage(const base::Value& message);

  // Notify observers that |message| was received.
  void NotifyMessageReceived(const base::Value& message);

  // Called from NetworkSmsDeviceHandler when a message is received.
  void MessageReceived(const base::Value& message);

  // Callback to handle the manager properties with the list of devices.
  void ManagerPropertiesCallback(absl::optional<base::Value> properties);

  // Requests properties for each entry in |devices|.
  void UpdateDevices(const base::Value& devices);

  // Callback to handle the device properties for |device_path|.
  // A NetworkSmsDeviceHandler will be instantiated for each cellular device.
  void DevicePropertiesCallback(const std::string& device_path,
                                absl::optional<base::Value> properties);

  // Called when the cellular device's object path changes. This means that
  // there has been an update to the device's SIM (removed or inserted) and that
  // a new handler should be created for the device's new object path.
  void OnObjectPathChanged(const base::Value& object_path);

  base::ObserverList<Observer, true>::Unchecked observers_;
  std::unique_ptr<NetworkSmsDeviceHandler> device_handler_;
  std::vector<base::Value> received_messages_;
  std::string cellular_device_path_;
  base::WeakPtrFactory<NetworkSmsHandler> weak_ptr_factory_{this};
};

}  // namespace ash

#endif  // CHROMEOS_ASH_COMPONENTS_NETWORK_NETWORK_SMS_HANDLER_H_


text:
package ca.antonious.habittracker.habitinteractiontests;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import ca.antonious.habittracker.habitstorage.IHabitRepository;
import ca.antonious.habittracker.interactions.RemoveCompletion;
import ca.antonious.habittracker.models.Habit;
import ca.antonious.habittracker.models.HabitCompletion;

import static org.mockito.Mockito.*;

/**
 * Created by George on 2016-09-13.
 */
public class RemoveCompletionTests {
    private IHabitRepository habitRepository;
    private RemoveCompletion removeCompletion;

    private Habit habitWithoutCompletion;
    private Habit habitWithCompletion;

    @Before
    public void set_up() {
        habitWithoutCompletion = new Habit();
        habitWithoutCompletion.setId("Habit-ID");
        habitWithoutCompletion.setName("AwesomeHabit");
        habitWithoutCompletion.setStartDate(new Date(1));
        habitWithoutCompletion.setDaysToComplete(Arrays.asList(Calendar.SUNDAY));

        HabitCompletion habitCompletion = new HabitCompletion(new Date(1));
        habitCompletion.setId("Completion-ID");

        habitWithCompletion = new Habit();
        habitWithCompletion.setId("Habit-ID");
        habitWithCompletion.setName("AwesomeHabit");
        habitWithCompletion.setStartDate(new Date(1));
        habitWithCompletion.setDaysToComplete(Arrays.asList(Calendar.SUNDAY));
        habitWithCompletion.setCompletions(Arrays.asList(habitCompletion));

        habitRepository = mock(IHabitRepository.class);
        removeCompletion = new RemoveCompletion(habitRepository);
    }

    @Test
    public void test_remove_ifHabitDoesNotExist_thenNoRepositoryUpdatesOccur() {
        when(habitRepository.getHabit("Habit-ID")).thenReturn(null);
        removeCompletion.remove("Habit-ID", "Completion-ID");

        verify(habitRepository, never()).updateHabit(Mockito.any(Habit.class));
    }

    @Test
    public void test_remove_ifHabitExistsButCompletionDoesNot_thenNoRepositoryUpdatesOccur() {
        when(habitRepository.getHabit("Habit-ID")).thenReturn(habitWithoutCompletion);
        removeCompletion.remove("Habit-ID", "Completion-ID");

        verify(habitRepository, never()).updateHabit(Mockito.any(Habit.class));
    }

    @Test
    public void test_remove_ifHabitAndCompletionExists_thenHabitIsUpdated() {
        when(habitRepository.getHabit("Habit-ID")).thenReturn(habitWithCompletion);
        removeCompletion.remove("Habit-ID", "Completion-ID");

        verify(habitRepository).updateHabit(habitWithoutCompletion);
    }

}


text:
var groups = require('./groups');
var users = require('./users');
var documents = require('./documents');

// declare router
var router = require('express').Router();

// init REST API Endpoints
router.use('/groups', groups);
router.use('/users', users);
router.use('/documents', documents);

// return message for all other requests
router.use('/', function(req, res) {
    res.send('Welcome to the StickShelf RESTful API');
});

// export the router
module.exports = router;


text:
#include "PositionInfo.h"
#include "Utilities.h"
#include "WorldState.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;

PositionInfo::PositionInfo(WorldState *pWorldState, InfoState *pInfoState)
    : InfoStateBase(pWorldState, pInfoState),
      mPlayerWithBallList_UpdateTime(Time(-3, 0)) {}

void PositionInfo::UpdateRoutine() {
  UpdateDistMatrix();
  UpdateOffsideLine();
  UpdateOppGoalInfo();

  /** 每个周期clear一次 */
  mPlayer2BallList.clear();
  mTeammate2BallList.clear();
  mOpponent2BallList.clear();

  for (int i = 0; i < 1 + 2 * TEAMSIZE; ++i) {
    mPlayer2PlayerList[i].clear();
    mTeammate2PlayerList[i].clear();
    mOpponent2PlayerList[i].clear();
  }

  mXSortTeammateList.clear();
  mXSortOpponentList.clear();
}

void PositionInfo::UpdateDistMatrix() {
  for (int i = 0; i < 1 + 2 * TEAMSIZE; ++i) {
    for (int j = 0; j < 1 + 2 * TEAMSIZE; ++j) {
      mDistMatrix[i][j] = -1.0;
    }
  }

  for (int i = 0; i < TEAMSIZE; ++i) {
    mTeammateDir2Ball[i] = 0.0;
    mOpponentDir2Ball[i] = 0.0;
  }

  const vector<PlayerState *> &player_list = mpWorldState->GetPlayerList();

  for (vector<PlayerState *>::const_iterator it = player_list.begin();
       it != player_list.end(); ++it) {
    if ((*it)->IsAlive()) {
      int index = Unum2Index((*it)->GetUnum());
      Vector rel_pos = (*it)->GetPos() - mpWorldState->GetBall().GetPos();
      mDistMatrix[0][index] = rel_pos.Mod();
      mDistMatrix[index][index] = 0.0;

      // 更新球员相对于球的角度
      if ((*it)->GetUnum() > 0) {
        mTeammateDir2Ball[(*it)->GetUnum() - 1] = rel_pos.Dir();
      } else {
        mOpponentDir2Ball[-(*it)->GetUnum() - 1] = rel_pos.Dir();
      }
    }
  }

  const uint player_list_size = player_list.size();
  for (unsigned int i = 0; i < player_list_size; ++i) {
    const PlayerState *pi = player_list[i];
    if (pi->IsAlive()) {
      for (unsigned int j = i + 1; j < player_list_size; ++j) {
        const PlayerState *pj = player_list[j];
        if (pj->IsAlive()) {
          int index1 = Unum2Index(pi->GetUnum());
          int index2 = Unum2Index(pj->GetUnum());
          mDistMatrix[index1][index2] = mDistMatrix[index2][index1] =
              pi->GetPos().Dist(pj->GetPos());
        }
      }
    }
  }
}

const double &PositionInfo::GetBallDistToPlayer(Unum unum) const {
  return mDistMatrix[0][Unum2Index(unum)];
}

const double &PositionInfo::GetPlayerDistToPlayer(Unum unum1,
                                                  Unum unum2) const {
  return mDistMatrix[Unum2Index(unum1)][Unum2Index(unum2)];
}

void PositionInfo::UpdateOffsideLine() {
  const BallState &ball_state = mpWorldState->GetBall();
  const PlayerState *pPlayer = 0;

  double first = 0.0;
  double second = 0.0;
  Unum f_unum = 0;
  Unum s_unum = 0;

  // teammate offside line
  for (int i = 1; i <= TEAMSIZE; ++i) {
    pPlayer = &(mpWorldState->GetOpponent(i));
    if (pPlayer->IsAlive() == false) {
      continue;
    }

    if (pPlayer->GetPos().X() > second) {
      if (pPlayer->GetPos().X() > first) {
        second = first;
        s_unum = f_unum;
        first = pPlayer->GetPos().X();
        f_unum = i;
      } else {
        second = pPlayer->GetPos().X();
        s_unum = i;
      }
    }
  }

  if (ball_state.GetPosConf() > PlayerParam::instance().minValidConf() &&
      ball_state.GetPos().X() > second) {
    mTeammateOffsideLineOpp = 0;
    mTeammateOffsideLine = ball_state.GetPos().X();
    mTeammateOffsideLineConf = ball_state.GetPosConf();
    mTeammateOffsideLineSpeed = ball_state.GetVel().X();
  } else {
    mTeammateOffsideLine = second;
    if (s_unum == 0) {
      mTeammateOffsideLineOpp = 0;
      mTeammateOffsideLineConf = 0.0;
      mTeammateOffsideLineSpeed = 0.0;
    } else {
      mTeammateOffsideLineOpp = s_unum;
      mTeammateOffsideLineConf = mpWorldState->GetOpponent(s_unum).GetPosConf();
      mTeammateOffsideLineSpeed =
          mpWorldState->GetOpponent(s_unum).GetVel().X();
    }
  }

  // opponent offside line
  first = 0.0;
  second = 0.0;
  f_unum = 0;
  s_unum = 0;
  for (int i = 1; i <= TEAMSIZE; ++i) {
    pPlayer = &(mpWorldState->GetTeammate(i));
    if (pPlayer->IsAlive() == false) {
      continue;
    }

    if (pPlayer->GetPos().X() < second) {
      if (pPlayer->GetPos().X() < first) {
        second = first;
        s_unum = f_unum;
        first = pPlayer->GetPos().X();
        f_unum = i;
      } else {
        second = pPlayer->GetPos().X();
        s_unum = i;
      }
    }
  }
  if (ball_state.GetPosConf() > PlayerParam::instance().minValidConf() &&
      ball_state.GetPos().X() < second) {
    mOpponentOffsideLineTm = 0;
    mOpponentOffsideLine = ball_state.GetPos().X();
    mOpponentOffsideLineConf = ball_state.GetPosConf();
    mOpponentOffsideLineSpeed = ball_state.GetVel().X();
  } else {
    mOpponentOffsideLine = second;
    if (s_unum == 0) {
      mOpponentOffsideLineTm = 0;
      mOpponentOffsideLineConf = 0.0;
      mOpponentOffsideLineSpeed = 0.0;
    } else {
      mOpponentOffsideLineTm = s_unum;
      mOpponentOffsideLineConf = mpWorldState->GetTeammate(s_unum).GetPosConf();
      mOpponentOffsideLineSpeed =
          mpWorldState->GetTeammate(s_unum).GetVel().X();
    }
  }
}

void PositionInfo::UpdateOppGoalInfo() {
  mOppGoal2Ball = Vector(ServerParam::instance().PITCH_LENGTH / 2.0, 0.0) -
                  mpWorldState->GetBall().GetPos();
  mOppLeftPost2Ball = ServerParam::instance().oppLeftGoalPost() -
                      mpWorldState->GetBall().GetPos();
  mOppRightPost2Ball = ServerParam::instance().oppRightGoalPost() -
                       mpWorldState->GetBall().GetPos();
  mOppGoal2BallAngle = mOppGoal2Ball.Dir();
  mOppLeftPost2BallAngle = mOppLeftPost2Ball.Dir();
  mOppRightPost2BallAngle = mOppRightPost2Ball.Dir();
}

const list<KeyPlayerInfo> &PositionInfo::GetXSortTeammate() {
  if (mXSortTeammateList.empty()) {
    KeyPlayerInfo kp;
    for (int i = 1; i <= TEAMSIZE; i++) {
      if (mpWorldState->GetTeammate(i).IsAlive() == true &&
          mpWorldState->GetTeammate(i).GetPosConf() > FLOAT_EPS) {
        kp.mUnum = i;
        kp.mValue = mpWorldState->GetTeammate(i).GetPos().X();
        mXSortTeammateList.push_back(kp);
      }
    }
    mXSortTeammateList.sort();
  }
  return mXSortTeammateList;
}

const list<KeyPlayerInfo> &PositionInfo::GetXSortOpponent() {
  if (mXSortOpponentList.empty()) {
    KeyPlayerInfo kp;
    for (int i = 1; i <= TEAMSIZE; i++) {
      if (mpWorldState->GetOpponent(i).IsAlive() == true &&
          mpWorldState->GetOpponent(i).GetPosConf() > FLOAT_EPS) {
        kp.mUnum = i;
        kp.mValue = mpWorldState->GetOpponent(i).GetPos().X();
        mXSortOpponentList.push_back(kp);
      }
    }
    mXSortOpponentList.sort();
  }
  return mXSortOpponentList;
}

AngleDeg PositionInfo::GetShootAngle(AngleDeg left, AngleDeg right,
                                     const PlayerState &state,
                                     AngleDeg &interval) {
  vector<pair<Unum, AngleDeg>> tmp;
  for (vector<PlayerState *>::const_iterator it =
           mpWorldState->GetPlayerList().begin();
       it != mpWorldState->GetPlayerList().end(); ++it) {
    if ((*it)->IsAlive() && (*it)->GetPosConf() > FLOAT_EPS &&
        (*it)->GetUnum() != state.GetUnum() &&
        ((*it)->GetPos() - state.GetPos()).Dir() + Rad2Deg(1 / 10) > left &&
        ((*it)->GetPos() - state.GetPos()).Dir() - Rad2Deg(1 / 10) <
            right) { //介于左右门柱之间
      tmp.push_back(pair<Unum, AngleDeg>(
          (*it)->GetUnum(), ((*it)->GetPos() - state.GetPos()).Dir()));
    }
  }
  if (tmp.size() != 0) {
    sort(tmp.begin(), tmp.end(), PlayerDirCompare());
    vector<pair<int, AngleDeg>> dis;
    int i = 0;
    vector<pair<int, AngleDeg>>::const_iterator it;
    for (it = tmp.begin(); it != tmp.end(); ++it) {
      if (i == 0) {
        dis.push_back(pair<int, AngleDeg>(
            i++, ((*it).second - left /* - Rad2Deg(1/10) - Rad2Deg(1/3)*/)));
      } else {
        dis.push_back(pair<int, AngleDeg>(
            i++, ((*it).second -
                  (*(it - 1)).second) /*- 2*Rad2Deg(1/10) - Rad2Deg(1/3)*/));
      }
    }
    dis.push_back(pair<int, AngleDeg>(
        i, (right - (*(it - 1)).second) /*- Rad2Deg(1/10) - Rad2Deg(1/3)*/));
    sort(dis.begin(), dis.end(), PlayerDirCompare());

    if (dis.back().first == 0) {
      interval = dis.back().second - Rad2Deg(1.0 / 10.0) - Rad2Deg(1.0 / 4.0);
      return MinMax(left + 1,
                    dis.back().second / 2 + left - Rad2Deg(1.0 / 10.0) -
                        Rad2Deg(1.0 / 4.0),
                    right - 1);
    } else if (dis.back().first == i) {
      interval = dis.back().second - Rad2Deg(1.0 / 10.0) - Rad2Deg(1.0 / 4.0);
      return MinMax(left + 1,
                    right - dis.back().second / 2 + Rad2Deg(1.0 / 10.0) +
                        Rad2Deg(1.0 / 4.0),
                    right - 1);
    } else {
      interval =
          dis.back().second - 2 * Rad2Deg(1.0 / 10.0) - Rad2Deg(1.0 / 4.0);
      return MinMax(left + 1,
                    (*(tmp.begin() + dis.back().first - 1)).second +
                        dis.back().second / 2,
                    right - 1);
    }
  } else {
    interval = right - left;
    return (left + right) / 2;
  }
}

//到某个点距离的按大小排列队员(F)
vector<Unum>
PositionInfo::GetClosePlayerToPoint(const Vector &bp,
                                    const Unum &exclude_unum) const {
  vector<pair<Unum, double>> tmp;

  for (vector<PlayerState *>::const_iterator it =
           mpWorldState->GetPlayerList().begin();
       it != mpWorldState->GetPlayerList().end(); ++it) {
    if ((*it)->IsAlive() && (*it)->GetPosConf() > FLOAT_EPS &&
        (*it)->GetUnum() != exclude_unum) { // 算距离自己的球员时把自己排除掉
      tmp.push_back(
          pair<Unum, double>((*it)->GetUnum(), (*it)->GetPos().Dist2(bp)));
    }
  }

  sort(tmp.begin(), tmp.end(), PlayerDistCompare());

  vector<Unum> ret;
  for (vector<pair<Unum, double>>::iterator it = tmp.begin(); it != tmp.end();
       ++it) {
    ret.push_back(it->first);
  }

  return ret;
}

const vector<Unum> &PositionInfo::GetClosePlayerToBall() {
  if (mPlayer2BallList.empty()) {
    mPlayer2BallList = GetClosePlayerToPoint(mpWorldState->GetBall().GetPos());
  }
  return mPlayer2BallList;
}

const vector<Unum> &PositionInfo::GetCloseTeammateToBall() {
  if (mTeammate2BallList.empty()) {
    const vector<Unum> &player2ball = GetClosePlayerToBall();
    for (vector<Unum>::const_iterator it = player2ball.begin();
         it != player2ball.end(); ++it) {
      if ((*it) > 0) {
        mTeammate2BallList.push_back(*it);
      }
    }
  }
  return mTeammate2BallList;
}

const vector<Unum> &PositionInfo::GetCloseOpponentToBall() {
  if (mOpponent2BallList.empty()) {
    const vector<Unum> &player2ball = GetClosePlayerToBall();
    for (vector<Unum>::const_iterator it = player2ball.begin();
         it != player2ball.end(); ++it) {
      if ((*it) < 0) {
        mOpponent2BallList.push_back(-(*it));
      }
    }
  }
  return mOpponent2BallList;
}

vector<Unum> PositionInfo::GetCloseOpponentToPoint(const Vector &bp) {
  vector<Unum> opp2point;
  const vector<Unum> &player2ball = GetClosePlayerToPoint(bp);
  for (vector<Unum>::const_iterator it = player2ball.begin();
       it != player2ball.end(); ++it) {
    if ((*it) < 0) {
      opp2point.push_back(-(*it));
    }
  }

  return opp2point;
}

const vector<Unum> &PositionInfo::GetClosePlayerToPlayer(Unum i) {
  int index = Unum2Index(i);
  if (mPlayer2PlayerList[index].empty()) {
    mPlayer2PlayerList[index] =
        GetClosePlayerToPoint(mpWorldState->GetPlayer(i).GetPos(), i);
  }
  return mPlayer2PlayerList[index];
}

const vector<Unum> &PositionInfo::GetCloseTeammateToPlayer(Unum i) {
  int index = Unum2Index(i);
  if (mTeammate2PlayerList[index].empty()) {
    const vector<Unum> &player2player = GetClosePlayerToPlayer(i);
    for (vector<Unum>::const_iterator it = player2player.begin();
         it != player2player.end(); ++it) {
      if ((*it) > 0) {
        mTeammate2PlayerList[index].push_back(*it);
      }
    }
  }
  return mTeammate2PlayerList[index];
}

const vector<Unum> &PositionInfo::GetCloseOpponentToPlayer(Unum i) {
  int index = Unum2Index(i);
  if (mOpponent2PlayerList[index].empty()) {
    const vector<Unum> &player2player = GetClosePlayerToPlayer(i);
    for (vector<Unum>::const_iterator it = player2player.begin();
         it != player2player.end(); ++it) {
      if ((*it) < 0) {
        mOpponent2PlayerList[index].push_back(-(*it));
      }
    }
  }
  return mOpponent2PlayerList[index];
}

//距离球最近按距离且可踢(F)
const vector<Unum> &PositionInfo::GetPlayerWithBallList() {
  if (mPlayerWithBallList_UpdateTime != mpWorldState->CurrentTime()) {
    mPlayerWithBallList.clear();
    if (GetClosePlayerToBall().size() > 0) {
      for (unsigned int i = 0; i < GetClosePlayerToBall().size(); ++i) {
        Unum unum = GetClosePlayerToBall()[i];
        if (mpWorldState->GetPlayer(unum).IsKickable()) {
          mPlayerWithBallList.push_back(unum);
        }
      }
    }
    mPlayerWithBallList_UpdateTime = mpWorldState->CurrentTime();
  }
  return mPlayerWithBallList;
}

Unum PositionInfo::GetPlayerWithBall(const double buffer) {
  Unum tm_with_ball = GetTeammateWithBall(buffer);
  Unum opp_with_ball = GetOpponentWithBall(buffer);

  if (tm_with_ball > 0)
    return tm_with_ball;
  return -opp_with_ball;
}

Unum PositionInfo::GetTeammateWithBall() {
  if (mpWorldState->GetBall().GetPosConf() < FLOAT_EPS) {
    return 0;
  }

  if (GetPlayerWithBallList().empty()) {
    return 0;
  } else {
    for (unsigned int i = 0; i < GetPlayerWithBallList().size(); ++i) {
      if (GetPlayerWithBallList()[i] > 0) {
        return GetPlayerWithBallList()[i];
      }
    }
    return 0;
  }
}

/**
 * buffer误差范围内得到一个可踢球的队友
 * @return
 */
Unum PositionInfo::GetTeammateWithBall(const double buffer) {
  if (mpWorldState->GetBall().GetPosConf() < FLOAT_EPS) {
    return 0;
  }

  for (unsigned int i = 0; i < GetCloseTeammateToBall().size(); ++i) {
    Unum tm = GetCloseTeammateToBall()[i];
    if (mpWorldState->GetTeammate(tm).IsKickable(mpWorldState->GetBall(),
                                                 buffer)) {
      return tm;
    }
    if (GetBallDistToTeammate(tm) > 2.0)
      break; //(因为list是按距离顺序排好的,剩下的就不用了)
  }

  return 0;
}

Unum PositionInfo::GetOpponentWithBall() {
  if (mpWorldState->GetBall().GetPosConf() < FLOAT_EPS) {
    return 0;
  }

  if (GetPlayerWithBallList().empty()) {
    return 0;
  } else {
    for (unsigned int i = 0; i < GetPlayerWithBallList().size(); ++i) {
      if (GetPlayerWithBallList()[i] < 0) {
        return -GetPlayerWithBallList()[i];
      }
    }
    return 0;
  }
}

/**
 * @param buffer
 * @return
 */
Unum PositionInfo::GetOpponentWithBall(const double buffer) {
  if (mpWorldState->GetBall().GetPosConf() < FLOAT_EPS) {
    return 0;
  }

  for (unsigned int i = 0; i < GetCloseOpponentToBall().size(); ++i) {
    Unum opp = GetCloseOpponentToBall()[i];
    if (mpWorldState->GetOpponent(opp).IsKickable(mpWorldState->GetBall(),
                                                  buffer)) {
      return opp;
    }
    if (GetBallDistToOpponent(opp) > 2.0)
      break;
  }

  return 0;
}


text: I am a BroomMorph that pushes morphs left.


text:
"""
Run all tests with:
    $ python -m unittest test
"""

import logging        as mod_logging
import unittest       as mod_unittest
import srtm           as mod_srtm
from srtm import data as mod_data
from srtm import main as mod_main
from srtm import utils as mod_utils

mod_logging.basicConfig(level=mod_logging.DEBUG,
                        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

class Tests(mod_unittest.TestCase):

    def test_dead_sea(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        self.assertEqual(-415, geo_elevation_data.get_elevation(31.5, 35.5))

    def test_over_60(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        self.assertTrue(geo_elevation_data.get_elevation(55., 55.) > 0) # type: ignore
        self.assertEqual(None, geo_elevation_data.get_elevation(65., 65.))
        self.assertEqual(None, geo_elevation_data.get_elevation(75., 75.))

    def test_random_points(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        self.assertEqual(597, geo_elevation_data.get_elevation(24.056313, 35.003152))
        self.assertEqual(63, geo_elevation_data.get_elevation(46., 13.))
        self.assertEqual(2714, geo_elevation_data.get_elevation(46.999999, 13.))
        self.assertEqual(1643, geo_elevation_data.get_elevation(46.999999, 13.999999))
        self.assertEqual(553, geo_elevation_data.get_elevation(46., 13.999999))
        self.assertEqual(203, geo_elevation_data.get_elevation(45.2732, 13.7139))
        self.assertEqual(460, geo_elevation_data.get_elevation(45.287, 13.905))

    def test_around_zero_longitude(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        self.assertEqual(61, geo_elevation_data.get_elevation(51.2, 0.0))
        self.assertEqual(100, geo_elevation_data.get_elevation(51.2, -0.1))
        self.assertEqual(59, geo_elevation_data.get_elevation(51.2, 0.1))

    def test_around_zero_latitude(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        self.assertEqual(393, geo_elevation_data.get_elevation(0, 15))
        self.assertEqual(423, geo_elevation_data.get_elevation(-0.1, 15))
        self.assertEqual(381, geo_elevation_data.get_elevation(0.1, 15))

    def test_point_with_invalid_elevation(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        self.assertEqual(None, geo_elevation_data.get_elevation(47.0, 13.07))

    def test_point_without_file(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        print(geo_elevation_data.get_elevation(0, 0))

    def test_files_equality(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        self.assertEqual(geo_elevation_data.get_file(47.0, 13.99),
                          geo_elevation_data.get_file(47.0, 13.0))
        self.assertEqual(geo_elevation_data.get_file(47.99, 13.99),
                          geo_elevation_data.get_file(47.0, 13.0))

        self.assertEqual(geo_elevation_data.get_file(-47.0, 13.99),
                          geo_elevation_data.get_file(-47.0, 13.0))
        self.assertEqual(geo_elevation_data.get_file(-47.99, 13.99),
                          geo_elevation_data.get_file(-47.0, 13.0))

        self.assertEqual(geo_elevation_data.get_file(-47.0, -13.99),
                          geo_elevation_data.get_file(-47.0, -13.0))
        self.assertEqual(geo_elevation_data.get_file(-47.99, -13.99),
                          geo_elevation_data.get_file(-47.0, -13.0))

        self.assertEqual(geo_elevation_data.get_file(47.0, -13.99),
                          geo_elevation_data.get_file(47.0, -13.0))
        self.assertEqual(geo_elevation_data.get_file(47.99, -13.99),
                          geo_elevation_data.get_file(47.0, -13.0))

    def test_invalit_coordinates_for_file(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        geo_file = geo_elevation_data.get_file(47.0, 13.99)

        try:
            self.assertFalse(geo_file.get_elevation(1, 1)) # type: ignore
        except Exception as e:
            message = str(e)
            self.assertEqual('Invalid latitude 1 for file N47E013.hgt', message)

        try:
            self.assertFalse(geo_file.get_elevation(47, 1)) # type: ignore
        except Exception as e:
            message = str(e)
            self.assertEqual('Invalid longitude 1 for file N47E013.hgt', message)

    def test_invalid_file(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        geo_file = geo_elevation_data.get_file(-47.0, -13.99)
        self.assertEqual(None, geo_file)

    def test_coordinates_in_file(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        geo_file = geo_elevation_data.get_file(47.0, 13.99)

        print('file:', geo_file)

        self.assertEqual(geo_file.get_elevation(47, 13), geo_file.get_elevation(47, 13)) # type: ignore

    def test_coordinates_row_col_conversion(self) -> None:
        geo_elevation_data = mod_srtm.get_data()
        geo_file = geo_elevation_data.get_file(47.0, 13.99)

        print('file:', geo_file)

        r, c = geo_file.get_row_and_column(47, 13) # type: ignore
        lat, long = geo_file.get_lat_and_long(r, c) # type: ignore
        self.assertEqual(lat, 47)
        self.assertEqual(long, 13)

        r, c = geo_file.get_row_and_column(46.5371, 8.1264) # type: ignore
        lat, long = geo_file.get_lat_and_long(r, c) # type: ignore
        self.assertAlmostEqual(lat, 46.5371, delta=geo_file.resolution) # type: ignore
        self.assertAlmostEqual(long, 8.1264, delta=geo_file.resolution) # type: ignore

    def test_without_approximation(self) -> None:
        geo_elevation_data = mod_srtm.get_data()

        self.assertEqual(geo_elevation_data.get_elevation(47.1, 13.1, approximate=False),
                          geo_elevation_data.get_elevation(47.1, 13.1))

        # SRTM elevations are always integers:
        elevation = geo_elevation_data.get_elevation(47.1, 13.1)
        self.assertTrue(int(elevation) == elevation) # type: ignore

    def test_with_approximation(self) -> None:
        geo_elevation_data = mod_srtm.get_data()

        self.assertNotEquals(geo_elevation_data.get_elevation(47.1, 13.1, approximate=True),
                             geo_elevation_data.get_elevation(47.1, 13.1))

        # When approximating a random point, it probably won't be a integer:
        elevation = geo_elevation_data.get_elevation(47.1, 13.1, approximate=True)
        self.assertTrue(int(elevation) != elevation) # type: ignore

    def test_approximation(self) -> None:
        # TODO(TK) Better tests for approximation here:
        geo_elevation_data = mod_srtm.get_data()
        elevation_without_approximation = geo_elevation_data.get_elevation(47, 13)
        elevation_with_approximation = geo_elevation_data.get_elevation(47, 13, approximate=True)

        print(elevation_without_approximation)
        print(elevation_with_approximation)

        self.assertNotEqual(elevation_with_approximation, elevation_without_approximation)
        self.assertTrue(abs(elevation_with_approximation - elevation_without_approximation) < 30) # type: ignore

    def test_IDW(self) -> None:
        print("Testing: IDW")

        # Setup with local tile
        with open("test_files/N44W072.hgt","rb") as hgtfile:
            hgt = hgtfile.read()
        tilemap = mod_data.GeoElevationData({},{}, file_handler=mod_utils.FileHandler(""))
        tile = mod_data.GeoElevationFile('N44W072.hgt', hgt, tilemap)
        tilemap.srtm3_files["N44W072.hgt"] = ""
        tilemap.files["N44W072.hgt"] = tile
        lat, long = 44.1756325, -71.5965699
        elevation = tilemap._IDW(lat, long)
        print("Location: {}, {}".format(lat, long))
        print("Elevation: {}".format(elevation))
        print()
        self.assertLessEqual(elevation, 814)
        self.assertGreaterEqual(elevation, 801)
        self.assertTrue(tilemap._IDW(-47.0, -13.99) is None)

    def test_InverseDistanceWeighted(self) -> None:
        print("Testing: InverseDistanceWeighted")

        # Setup minimal tile config
        with open("test_files/N44W072.hgt","rb") as hgtfile:
            hgt = hgtfile.read()
        tilemap = mod_data.GeoElevationData({},{}, file_handler=mod_utils.FileHandler())
        tile = mod_data.GeoElevationFile('N44W072.hgt', hgt, tilemap)

        # tuples of (lat, lon, lowerbound, upperbound)
        controlpoints = [(44.1756325, -71.5965699, 801, 814), # middle of tile (x,y)
                         (44, -71.5965699, 520, 532), # bottom edge (1200, y)
                         (44.1756325, -70.99975, 148, 152), # right edge (x, 1200)
                         (44.99975, -71.5965699, 525, 538), # top edge (0, y)
                         (44.1756325, -71.99975, 272, 279), # left edge (x, 0)
                         (44, -72, 341, 341)] # Exact cell coordinates, no interpolation

        for location in controlpoints:
            print("Location: {}, {}".format(location[0], location[1]))
            nearest_neighbor_elevation = tile.get_elevation(location[0], location[1])
            IDW5_elevation = tile._InverseDistanceWeighted(location[0], location[1])
            IDW13_elevation = tile._InverseDistanceWeighted(location[0], location[1], radius=2)
            print("Nearest: " + str(nearest_neighbor_elevation))
            print("Interpolated(5): {}".format(IDW5_elevation))
            print("Interpolated(13): {}".format(IDW13_elevation))
            print()
            self.assertGreaterEqual(IDW5_elevation, location[2])
            self.assertLessEqual(IDW5_elevation, location[3])
            self.assertGreaterEqual(IDW13_elevation, location[2])
            self.assertLessEqual(IDW13_elevation, location[3])

        self.assertRaises(ValueError, tile._InverseDistanceWeighted, 44, -71, radius=0)

    def test_batch_mode(self) -> None:

        # Two pulls that are far enough apart to require multiple files

        # With batch_mode=False, both files should be kept
        geo_elevation_data = mod_srtm.get_data(batch_mode=False)

        elevation1 = geo_elevation_data.get_elevation(42.3467, 71.0972)
        self.assertTrue(elevation1 > 0) # type: ignore
        self.assertTrue(len(geo_elevation_data.files) == 1)

        elevation2 = geo_elevation_data.get_elevation(43.0382, 87.9298)
        self.assertTrue(elevation2 > 0) # type: ignore
        self.assertTrue(len(geo_elevation_data.files) == 2)

        # With batch_mode=True, only the most recent file should be kept
        geo_elevation_data = mod_srtm.get_data(batch_mode=True)
        elevation1 = geo_elevation_data.get_elevation(42.3467, 71.0972)
        self.assertTrue(elevation1 > 0) # type: ignore
        self.assertTrue(len(geo_elevation_data.files) == 1)
        keys1 = geo_elevation_data.files.keys()

        elevation2 = geo_elevation_data.get_elevation(43.0382, 87.9298)
        self.assertTrue(len(geo_elevation_data.files) == 1)
        self.assertFalse(geo_elevation_data.files.keys() == keys1)

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


text:
package org.libelektra;

import com.sun.jna.Pointer;

/**
 * Key is an essential class that encapsulates key name , value and metainfo.
 */
public class Key implements Iterable<String> {

	private static final String WARNINGS = "warnings";
	// constants
	public static final int KEY_END = 0;
	public static final int KEY_NAME = 1;
	public static final int KEY_VALUE = 1 << 1;
	public static final int KEY_OWNER = 1 << 2;
	public static final int KEY_COMMENT = 1 << 3;
	public static final int KEY_BINARY = 1 << 4;
	public static final int KEY_UID = 1 << 5;
	public static final int KEY_GID = 1 << 6;
	public static final int KEY_MODE = 1 << 7;
	public static final int KEY_ATIME = 1 << 8;
	public static final int KEY_MTIME = 1 << 9;
	public static final int KEY_CTIME = 1 << 10;
	public static final int KEY_SIZE = 1 << 11;
	public static final int KEY_FUNC = 1 << 12;
	public static final int KEY_DIR = 1 << 14;
	public static final int KEY_META = 1 << 15;
	public static final int KEY_NULL = 1 << 16;
	public static final int KEY_CASCADING_NAME = 1 << 20;
	public static final int KEY_META_NAME = 1 << 21;

	/**
	 * Indicates a generic key exception occured.
	 */
	public static class KeyException extends java.lang.RuntimeException {

		private static final long serialVersionUID = 637936674538102511L;

	}

	/**
	 * Indicates an invalid key name has been used.
	 */
	public static class KeyInvalidName extends KeyException {

		private static final long serialVersionUID = -7659317176138893895L;

	}

	/**
	 * Indicates a key's type conversion failed.
	 */
	public static class KeyTypeConversion extends KeyException {

		private static final long serialVersionUID = -8648296754188373810L;

	}

	/**
	 * Indicates a key's type does not match its value.
	 */
	public static class KeyTypeMismatch extends KeyException {

		private static final long serialVersionUID = 8035874860117969698L;

	}

	private Pointer key;

	/**
	 * Helper constructor for duplication by pointer in long format
	 *
	 * @param p
	 *            Pointer in long format
	 */
	protected Key(final long p) {
		key = new Pointer(p);
		incRef();
	}

	/**
	 * Helper constructor for duplication by pointer
	 *
	 * @param p
	 *            Pointer as Pointer object
	 */
	protected Key(final Pointer p) {
		key = p;
		incRef();
	}

	/**
	 * Basic constructor of key class
	 *
	 * @param name
	 *            Key name; first part of key-value pair
	 * @param args
	 *            Arguments used for key value. Example:<br>
	 *            Key.KEY_VALUE, "custom key value", Key.KEY_END
	 * @return New key object
	 */
	protected static Key create(final String name, final Object... args) {
		return new Key(Elektra.INSTANCE.keyNew(name, args));
	}

	/**
	 * Basic constructor of key class
	 *
	 * @param name
	 *            Key name; first part of key-value pair
	 * @param value
	 *            Key value; will be determine from the object by calling {@link Object#toString()}, null is supported too
	 * @param meta
	 *            Metadata that should be added to this key, null keys will be filtered away
	 * @return New key object
	 */
	public static Key create(final String name, final Object value, final Key... meta) {
		int size = 0;
		for (final Key m : meta) {
			if (m != null) {
				size++;
			}
		}
		// 3 -> KEY_VALUE, value, KEY_END, 4 -> one more for KEY_META
		size += size > 0 ? 4 : 3;
		final Object[] args = new Object[size];
		int cur = 0;
		args[cur++] = Integer.valueOf(KEY_VALUE);
		args[cur++] = value != null ? value.toString() : null;
		if (size > 3) {
			args[cur++] = Integer.valueOf(KEY_META);
			for (final Key m : meta) {
				args[cur++] = m;
			}
		}
		args[cur] = Integer.valueOf(KEY_END);
		return create(name, args);
	}

	/**
	 * Basic constructor of key class
	 *
	 * @param name
	 *            Key name; first part of key-value pair
	 * @param meta
	 *            Metadata that should be added to this key. Will filter null values.
	 * @return New key object
	 */
	public static Key create(final String name, final Key... meta) {
		return create(name, null, meta);
	}

	/**
	 * Clean-up method to release key reference
	 */
	public void release() {

		if (key != null) {
			decRef();
			if (getRef() == 0) {
				Elektra.INSTANCE.keyDel(key);
			}
		}
		key = null;
	}

	/**
	 * Clean-up method to inform underlying c-library about the release of the key reference in jna-binding
	 */
	@Override
	protected void finalize() throws Throwable {
		release();
	}

	/**
	 * Helper function that does null comparison
	 *
	 * @return Boolean if key is null
	 */
	public boolean isNull() {

		return key == null;
	}

	/**
	 * Basic java function that represents object as String
	 *
	 * @return Key name in String format
	 */
	@Override
	public String toString() {
		return getName();
	}

	/**
	 * Iterable interface function
	 *
	 * @return Custom KeyNameIterator
	 */
	@Override
	public java.util.Iterator<String> iterator() {
		return new KeyNameIterator(this);
	}

	/**
	 * Data type specific accessor function
	 *
	 * @return Key value in boolean format
	 */
	public boolean getBoolean() {
		return Boolean.parseBoolean(getString());
	}

	/**
	 * Data type specific accessor function
	 *
	 * @return Key value in byte format
	 */
	public byte getByte() {
		return Byte.parseByte(getString());
	}

	/**
	 * Data type specific accessor function
	 *
	 * @return Key value in short integer format
	 */
	public short getShort() {
		return Short.parseShort(getString());
	}

	/**
	 * Data type specific accessor function
	 *
	 * @return Key value in integer format
	 */
	public int getInteger() {
		return Integer.parseInt(getString());
	}

	/**
	 * Data type specific accessor function
	 *
	 * @return Key value in long integer format
	 */
	public long getLong() {
		return Long.parseLong(getString());
	}

	/**
	 * Data type specific accessor function
	 *
	 * @return Key value in float format
	 */
	public float getFloat() {
		return Float.parseFloat(getString());
	}

	/**
	 * Data type specific accessor function
	 *
	 * @return Key value in double format
	 */
	public double getDouble() {
		return Double.parseDouble(getString());
	}

	/**
	 * Data type specific setter function
	 *
	 * @param v
	 *            Boolean value to set
	 */
	public void setBoolean(final boolean v) {
		setString(Boolean.toString(v));
	}

	/**
	 * Data type specific setter function
	 *
	 * @param v
	 *            Byte value to set
	 */
	public void setByte(final byte v) {
		setString(Byte.toString(v));
	}

	/**
	 * Data type specific setter function
	 *
	 * @param v
	 *            Short integer value to set
	 */
	public void setShort(final short v) {
		setString(Short.toString(v));
	}

	/**
	 * Data type specific setter function
	 *
	 * @param v
	 *            Integer value to set
	 */
	public void setInteger(final int v) {
		setString(Integer.toString(v));
	}

	/**
	 * Data type specific setter function
	 *
	 * @param v
	 *            Long integer value to set
	 */
	public void setLong(final long v) {
		setString(Long.toString(v));
	}

	/**
	 * Data type specific setter function
	 *
	 * @param v
	 *            Float value to set
	 */
	public void setFloat(final float v) {
		setString(Float.toString(v));
	}

	/**
	 * Data type specific setter function
	 *
	 * @param v
	 *            Double value to set
	 */
	public void setDouble(final double v) {
		setString(Double.toString(v));
	}

	/**
	 * Helper function to set proper error meta for key
	 *
	 * @param text
	 *            Reason for the error
	 * @param args
	 *            Custom arguments
	 */
	public void setError(final String text, final Object... args) {
		final StackTraceElement[] e = Thread.currentThread().getStackTrace();
		setMeta("error", "number description ingroup module file line function reason");
		setMeta("error/number", "102");
		setMeta("error/description", "jni/java error");
		setMeta("error/ingroup", "plugin");
		setMeta("error/module", e[1].getClassName() + " " + e[1].getMethodName());
		setMeta("error/file", e[1].getFileName());
		setMeta("error/line", Integer.toString(e[1].getLineNumber()));
		setMeta("error/mountpoint", getName());
		setMeta("error/configfile", getString());
		setMeta("error/reason", String.format(text, args));
	}

	/**
	 * Helper function to add warning meta for key
	 *
	 * @param text
	 *            Reason for the warning
	 * @param args
	 *            Custom arguments
	 */
	public void addWarning(final String text, final Object... args) {
		final StackTraceElement[] e = Thread.currentThread().getStackTrace();
		final Key k = getMeta(WARNINGS);
		final StringBuilder builder = new StringBuilder(WARNINGS + "/#");
		if (!k.isNull()) {
			builder.append(k.getString());
			builder.setCharAt(11, (char) (builder.charAt(11) + 1));
			if (builder.charAt(11) > '9') {
				builder.setCharAt(11, '0');
				builder.setCharAt(10, (char) (builder.charAt(10) + 1));
				if (builder.charAt(10) > '9') {
					builder.setCharAt(10, '0');
				}
			}
			setMeta(Key.WARNINGS, builder.substring(10));
		} else {
			builder.append("00");
			setMeta(Key.WARNINGS, "00");
		}
		setMeta(builder + "", "number description ingroup module file line function reason");
		setMeta(builder + "/number", "103");
		setMeta(builder + "/description", "jni/java warning");
		setMeta(builder + "/ingroup", "plugin");
		setMeta(builder + "/module", e[1].getClassName() + " " + e[1].getMethodName());
		setMeta(builder + "/file", e[1].getFileName());
		setMeta(builder + "/line", Integer.toString(e[1].getLineNumber()));
		setMeta(builder + "/mountpoint", getName());
		setMeta(builder + "/configfile", getString());
		setMeta(builder + "/reason", String.format(text, args));
	}

	/*
	 * Wrapped methods
	 */

	/**
	 * Duplicates the key
	 *
	 * @return New Key object containing the same information as this key
	 */
	public Key dup() {
		return new Key(Elektra.INSTANCE.keyDup(get()));
	}

	/**
	 * Copies the information from the source key into this key. Does nothing if null is provided.
	 *
	 * @param source
	 *            Source Key object containing the information to copy
	 */
	public void copy(final Key source) {
		if (source != null) {
			Elektra.INSTANCE.keyCopy(get(), source.get());
		}
	}

	/**
	 * Increments the reference counter for this key
	 */
	protected void incRef() {
		Elektra.INSTANCE.keyIncRef(key);
	}

	/**
	 * Decrements the reference counter for this key
	 */
	protected void decRef() {
		Elektra.INSTANCE.keyDecRef(key);
	}

	/**
	 * Gets the reference counter for this key
	 *
	 * @return Reference counter as integer
	 */
	public int getRef() {
		return Elektra.INSTANCE.keyGetRef(get());
	}

	/**
	 * Tries to rewind the meta information for this key
	 *
	 * @return 0 in case of no errors; 1 if key is not found; 2 if metakey is not found
	 */
	public int rewindMeta() {
		return Elektra.INSTANCE.keyRewindMeta(get());
	}

	/**
	 * Gets the next meta information for this key
	 *
	 * @return new Key object containing the next meta information
	 */
	public Key nextMeta() {
		return new Key(Elektra.INSTANCE.keyNextMeta(get()));
	}

	/**
	 * Gets the current meta information for this key
	 *
	 * @return new Key object containing the current meta information
	 */
	public Key currentMeta() {
		return new Key(Elektra.INSTANCE.keyNextMeta(get()));
	}

	/**
	 * Helper function to copy some meta information from a source Key to this key.
	 *
	 * @param source
	 *            Key object that is used as source
	 * @param metaName
	 *            Key name of the meta to be copied
	 * @return 1 if meta was successfully copied, 0 if source doesn't contain the required meta and nothing had to be done, -1 in case of an
	 *         error or if the source parameter was null
	 */
	public int copyMeta(final Key source, final String metaName) {
		if (source == null) {
			return -1;
		}
		return Elektra.INSTANCE.keyCopyMeta(get(), source.get(), metaName);
	}

	/**
	 * Helper function to copy all meta information from a source key to this key
	 *
	 * @param source
	 *            Key object that is used as source
	 * @return 1 if meta was successfully copied, 0 if source doesn't contain any meta and nothing had to be done, -1 in case of an error or
	 *         if the source parameter was null
	 */
	public int copyAllMeta(final Key source) {
		if (source == null) {
			return -1;
		}
		return Elektra.INSTANCE.keyCopyAllMeta(get(), source.get());
	}

	/**
	 * Getter for meta information
	 *
	 * @param metaName
	 *            Key name of meta information to be fetched
	 * @return New Key object containing the requested meta information
	 */
	public Key getMeta(final String metaName) {
		return new Key(Elektra.INSTANCE.keyGetMeta(get(), metaName));
	}

	/**
	 * Setter for meta information
	 *
	 * @param metaName
	 *            Key name of meta information to be set
	 * @param newMetaString
	 *            Meta value to be set
	 * @return -1 in case of an error, 0 if no meta with given name is available for the key and value > 0 representing the size of
	 *         newMetaString if update successful
	 */
	public int setMeta(final String metaName, final String newMetaString) {
		return Elektra.INSTANCE.keySetMeta(get(), metaName, newMetaString);
	}

	/**
	 * Helper function to compare two keys. Compares the key name with normal String comparison.
	 *
	 * @param other
	 *            Other Key object that is used in comparison
	 * @return 0 if key name is equal; -1 if this key name has lower alphabetical order than the other key; 1 if this key has higher
	 *         alphabetical order
	 */
	public int cmp(final Key other) {
		if (other == null) {
			throw new IllegalArgumentException("other should be a key, not null");
		}
		return Elektra.INSTANCE.keyCmp(get(), other.get());
	}

	/**
	 * Helper function to check for relation between keys
	 *
	 * @param other
	 *            Other Key object that is used in relation check
	 * @return 0 if other is equal to this; > 0 if other is sub-key of this key; < 0 otherwise or in case of an error
	 */
	public int rel(final Key other) {
		if (other == null) {
			throw new IllegalArgumentException("other should be a key, not null");
		}
		return Elektra.INSTANCE.keyRel(get(), other.get());
	}

	/**
	 * Helper function to check if synchronization is necessary
	 *
	 * @return 1 if needs sync, 0 if no change done and -1 in case of a null pointer
	 */
	public int needsSync() {
		return Elektra.INSTANCE.keyNeedSync(get());
	}

	/**
	 * Helper function to check if key is sub-key of other key
	 *
	 * @param other
	 *            Key that is used in check as parent key
	 * @return Boolean if this key is (non-direct) sub-key of other-key
	 */
	public boolean isBelow(final Key other) {
		if (other == null) {
			throw new IllegalArgumentException("other should be a key, not null");
		}
		return Elektra.INSTANCE.keyIsBelow(other.get(), get()) == 1;
	}

	/**
	 * Helper function to check if key is other key or sub-key of other key
	 *
	 * @param other
	 *            Key that is used in check as parent key
	 * @return Boolean if this key is other key or (non-direct) sub-key of other-key
	 */
	public boolean isBelowOrSame(final Key other) {
		if (other == null) {
			throw new IllegalArgumentException("other should be a key, not null");
		}
		return Elektra.INSTANCE.keyIsBelowOrSame(other.get(), get()) == 1;
	}

	/**
	 * Helper function to check if key is direct sub-key of other key
	 *
	 * @param other
	 *            Key that is used in check as parent key
	 * @return Boolean if this key is direct sub-key of other key ("child")
	 */
	public boolean isDirectBelow(final Key other) {
		if (other == null) {
			throw new IllegalArgumentException("other should be a key, not null");
		}
		return Elektra.INSTANCE.keyIsDirectBelow(other.get(), get()) == 1;
	}

	/**
	 * Helper function to check if key is set to inactive
	 *
	 * @return Boolean if this key is inactive
	 */
	public boolean isInactive() {
		return Elektra.INSTANCE.keyIsInactive(get()) == 1;
	}

	/**
	 * Helper function to check if key is binary key
	 *
	 * @return Boolean if this key is a binary key
	 */
	public boolean isBinary() {
		return Elektra.INSTANCE.keyIsBinary(get()) == 1;
	}

	/**
	 * Helper function to check if key is string key
	 *
	 * @return Boolean if this key is a string key
	 */
	public boolean isString() {
		return Elektra.INSTANCE.keyIsString(get()) == 1;
	}

	/**
	 * Helper function to get key name (key part of "key-value" pair)
	 *
	 * @return Key name as String
	 */
	public String getName() {
		return Elektra.INSTANCE.keyName(key);
	}

	/**
	 * Helper function to get key name size
	 *
	 * @return Length of key name
	 */
	public int getNameSize() {
		return Elektra.INSTANCE.keyGetNameSize(get());
	}

	/**
	 * Helper function to set key name
	 *
	 * @param name
	 *            New key name to use
	 * @throws KeyInvalidName
	 */
	public void setName(final String name) throws KeyInvalidName {
		if (Elektra.INSTANCE.keySetName(get(), name) == -1) {
			throw new KeyInvalidName();
		}
	}

	/**
	 * Helper function to get key base name
	 *
	 * @return Key base name as String
	 */
	public String getBaseName() {
		return Elektra.INSTANCE.keyBaseName(get());
	}

	/**
	 * Helper function to get key base name length
	 *
	 * @return Length of key base name
	 */
	public int getBaseNameSize() {
		return Elektra.INSTANCE.keyGetBaseNameSize(get());
	}

	/**
	 * Helper function to set key base name; will replace current base name with new base name
	 *
	 * @param baseName
	 *            New key base name to use
	 * @throws KeyInvalidName
	 */
	public void setBaseName(final String baseName) throws KeyInvalidName {
		if (Elektra.INSTANCE.keySetBaseName(get(), baseName) == -1) {
			throw new KeyInvalidName();
		}
	}

	/**
	 * Helper function to add key base name; will add given base name to current key so that new key is sub key of current key
	 *
	 * @param baseName
	 *            New key base name to add
	 * @throws KeyInvalidName
	 */
	public void addBaseName(final String baseName) throws KeyInvalidName {
		if (Elektra.INSTANCE.keyAddBaseName(get(), baseName) == -1) {
			throw new KeyInvalidName();
		}
	}

	/**
	 * Helper function to get key value size/length
	 *
	 * @return Length of key value
	 */
	public int getValueSize() {
		return Elektra.INSTANCE.keyGetValueSize(get());
	}

	/**
	 * Helper function to get representation of key value
	 *
	 * @return Key value in String format
	 * @throws KeyTypeMismatch
	 */
	public String getString() throws KeyTypeMismatch {
		if (isBinary()) {
			throw new KeyTypeMismatch();
		}
		return Elektra.INSTANCE.keyString(key);
	}

	/**
	 * Helper function to set new key value
	 *
	 * @param newString
	 *            New key value to set
	 * @return value > 0 representing saved bytes (+null byte), -1 in case of an error (null key)
	 */
	public int setString(final String newString) {
		return Elektra.INSTANCE.keySetString(get(), newString);
	}

	/**
	 * Native pointer used by JNA
	 *
	 * @return Native pointer object for this key
	 */
	protected Pointer get() {
		return key;
	}
}