text:
require 'active_cucumber/cucumparer'
require 'active_cucumber/cucumberator'
require 'active_cucumber/active_record_builder'
require 'active_cucumber/creator'

# The main namespace for this gem
module ActiveCucumber

  # Returns the attributes to create an instance of the given ActiveRecord class
  # that matches the given vertical Cucumber table
  def self.attributes_for activerecord_class, cucumber_table, context: {}
    builder = ActiveRecordBuilder.new activerecord_class, context
    builder.attributes_for ActiveCucumber.vertical_table(cucumber_table)
  end

  # Creates entries of the given ActiveRecord class
  # specified by the given horizontal Cucumber table
  def self.create_many activerecord_class, cucumber_table, context: {}
    builder = ActiveRecordBuilder.new activerecord_class, context
    builder.create_many ActiveCucumber.horizontal_table(cucumber_table)
  end

  # Creates an entry of the given ActiveRecord class
  # specified by the given vertical Cucumber table
  def self.create_one activerecord_class, cucumber_table, context: {}
    builder = ActiveRecordBuilder.new activerecord_class, context
    builder.create_record ActiveCucumber.vertical_table(cucumber_table)
  end

  # Verifies that the database table for the given ActiveRecord class
  # matches the given horizontal Cucumber table.
  #
  # Sorts records by creation date.
  def self.diff_all! clazz, cucumber_table, context: {}
    cucumparer = Cucumparer.new clazz, cucumber_table, context
    cucumber_table.diff! cucumparer.to_horizontal_table
  end

  # Verifies that the given object matches the given vertical Cucumber table
  def self.diff_one! object, cucumber_table, context: {}
    cucumparer = Cucumparer.new object.class, cucumber_table, context
    cucumber_table.diff! cucumparer.to_vertical_table(object)
  end

  # Returns the given horizontal Cucumber table in standardized format
  def self.horizontal_table table
    table.hashes
  end

  # Returns the given vertical Cucumber table in standardized format
  def self.vertical_table table
    table.rows_hash
  end

end


text:
CLEAN_GOOGLE_IMAGE_SCRIPT=${CLEAN_GOOGLE_IMAGE_SCRIPT:-"$(dirname $0)/clean_google_image.sh"}
EXTRACT_DISK_TO_GCS_SCRIPT=${EXTRACT_DISK_TO_GCS_SCRIPT:-"$(dirname $0)/extract_disk_to_gcs.sh"}

function ensure_empty_ssh_key() {
  ACCOUNT_NAME=$(echo "$ACCOUNT" | sed "s/\(.*\)@.*/\1/")
  ACCOUNT_NAME=$LOGNAME
  SSH_KEY_FILE=${SSH_KEY_FILE:-"$HOME/.ssh/${ACCOUNT_NAME}_empty_key"}

  # https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys
  if [[ ! -f $SSH_KEY_FILE ]]; then
    echo "Creating $SSH_KEY_FILE SSH key"
    ssh-keygen -N "" -t rsa -f $SSH_KEY_FILE -C $ACCOUNT_NAME
  fi
}

function create_cleaner_instance() {
  # see https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#instance-only
  local ssh_key=$(cat ${SSH_KEY_FILE}.pub)
  if [[ $ssh_key == ssh-rsa* ]]; then
      ssh_key="$LOGNAME:$ssh_key"
  fi
  gcloud compute instances create ${CLEANER_INSTANCE} \
      --metadata ssh-keys="$ssh_key" \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --machine-type n1-highmem-4 \
      --scopes storage-rw \
      --boot-disk-type pd-ssd \
      --boot-disk-size 20GB \
      --image-family ubuntu-1604-lts \
      --image-project ubuntu-os-cloud
}

function delete_cleaner_instance() {
  echo "Deleting cleaner instance '${CLEANER_INSTANCE}'"
  gcloud compute instances delete ${CLEANER_INSTANCE} \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --quiet || true
  CLEANER_INSTANCE=

  if [[ "$BUILD_INSTANCE" != "" ]]; then
    echo "`date`: Deleting disk '$BUILD_INSTANCE'"
    gcloud compute disks delete $BUILD_INSTANCE \
        --project $PROJECT \
        --account $ACCOUNT \
        --zone $ZONE \
        --quiet || true
  fi
}

# Clean PROTOTYPE_DISK by attaching it to an existing WORKER_INSTANCE.
# This will attach/detach the disk but leave WORKER_INSTANCE running.
function extract_clean_prototype_disk() {
  local prototype_disk="$1"
  local worker_instance="$2"
  local output_file="$3"

  if [[ $output_file != "" ]]; then
    if [[ "$output_file" != gs://*.tar.gz ]]; then
      echo "$output_file is not a gs:// path to a tar.gz file"
      exit -1
    fi
  fi

  echo "`date`: Preparing '$worker_instance'"
  gcloud compute instances attach-disk ${worker_instance} \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --disk $prototype_disk \
      --device-name spinnaker

  # Wait for sever/key to be ready so next commands wont fail
  for i in {1..10}; do
    if gcloud compute ssh ${worker_instance} \
        --project $PROJECT \
        --account $ACCOUNT \
        --zone $ZONE \
        --ssh-key-file $SSH_KEY_FILE \
        --command="exit 0"
    then
        break
    fi
  done

  if ! gcloud compute scp  \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --ssh-key-file $SSH_KEY_FILE \
      ${CLEAN_GOOGLE_IMAGE_SCRIPT} \
      ${EXTRACT_DISK_TO_GCS_SCRIPT} \
      ${worker_instance}:. ; then
    # Assume we are in the same project and try the internal IP.
    # Note that the ssh commands only assume we are in the same project.
    echo "Could not use gcloud to copy files to the project."
    echo "Using scp directly."
    local worker_internal_ip=$(gcloud compute instances describe \
        --project $PROJECT \
        --account $ACCOUNT \
        --zone $ZONE \
        ${worker_instance} \
        | grep networkIP \
        | sed "s/.*: \([0-9\.]\+\)/\1/")

    scp -i $SSH_KEY_FILE \
       -o StrictHostKeyChecking=no \
       -o UserKnownHostsFile=/dev/null \
        ${CLEAN_GOOGLE_IMAGE_SCRIPT} \
        ${EXTRACT_DISK_TO_GCS_SCRIPT} \
        ${LOGNAME}@${worker_internal_ip}:~
  fi

  echo "`date`: Cleaning in '$worker_instance'"
  gcloud compute ssh ${worker_instance} \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --ssh-key-file $SSH_KEY_FILE \
      --command="sudo bash ~${LOGNAME}/clean_google_image.sh spinnaker"

  if [[ $output_file != "" ]]; then
    echo "`date`: Extracting disk as tar file '$output_file.'"
    gcloud compute ssh ${worker_instance} \
        --project $PROJECT \
        --account $ACCOUNT \
        --zone $ZONE \
        --ssh-key-file $SSH_KEY_FILE \
        --command="sudo bash ~${LOGNAME}/extract_disk_to_gcs.sh spinnaker $output_file"
  fi

  gcloud compute instances detach-disk ${worker_instance} \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --disk $prototype_disk
  echo "`date`: Finished cleaning disk '$prototype_disk'."
}

# Create TARGET_IMAGE from PROTOTYPE_DISK (optionally in TARGET_FAMILY).
# This will leave the disk instact
function image_from_prototype_disk() {
  local target_image="$1"
  local prototype_disk="$2"
  local target_family="$3"

  delete_image_if_exists $target_image

  local args="--project $PROJECT --account $ACCOUNT"

  if [ -n "$target_family" ]; then
    args="$args --family $target_family"
  fi

  echo "`date`: Creating image '$target_image' in project '$PROJECT'"
  if [[ $prototype_disk = gs://*.tar.gz ]]; then
    echo "Creating from URI $prototype_disk"
    gcloud compute images create $target_image \
        --source-uri $prototype_disk \
        $args
  else
    echo "Creating from source-disk $prototype_disk"
    gcloud compute images create $target_image \
        --source-disk $prototype_disk \
        --source-disk-zone $ZONE \
        $args
  fi
}

function delete_disk_if_exists() {
  local target_disk="$1"

  echo "gcloud compute disks describe $target_disk --project $PROJECT --account $ACCOUNT --zone $ZONE"
  if gcloud compute disks describe $target_disk \
        --project $PROJECT \
        --account $ACCOUNT \
        --zone $ZONE &> /dev/null; then
    echo "`date`: Deleting preexisting disk '$target_disk' in '$PROJECT'"
    gcloud compute disks delete $target_disk \
           --project $PROJECT \
           --account $ACCOUNT \
           --zone $ZONE
  fi
}

function delete_image_if_exists() {
  local target_image="$1"

  if gcloud compute images describe $target_image \
      --project $PROJECT \
      --account $ACCOUNT &> /dev/null; then
    echo "`date`: Deleting preexisting image '$target_image' in '$PROJECT'"
    gcloud compute images delete $target_image \
      --project $PROJECT \
      --account $ACCOUNT \
      --quiet
  fi
}

function delete_build_instance() {
  echo "`date`: Cleaning up prototype instance '$PROTOTYPE_INSTANCE'"
  gcloud compute instances delete $PROTOTYPE_INSTANCE \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --quiet
  PROTOTYPE_INSTANCE=
}

function cleanup_instances_on_error() {
  if [[ "$PROTOTYPE_INSTANCE" != "" ]]; then
    delete_build_instance
  fi

  echo "Deleting cleaner instance '${CLEANER_INSTANCE}'"
  wait $CLEANER_INSTANCE_PID || true
  gcloud compute instances delete ${CLEANER_INSTANCE} \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --quiet || true
}

function delete_prototype_disk() {
  echo "Deleting cleaner instance ${CLEANER_INSTANCE}"
  gcloud compute instances delete ${CLEANER_INSTANCE} \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --quiet || true

  echo "`date`: Deleting disk '$BUILD_INSTANCE'"
  gcloud compute disks delete $BUILD_INSTANCE \
      --project $PROJECT \
      --account $ACCOUNT \
      --zone $ZONE \
      --quiet || true
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * The default manager that stores registered aspects in memory.
 *
 * Registrations are lost if the manager object is destroyed.
 *
 * @category PHP
 * @package AspectPHP_Manager
 * @author Matthias Molitor <matthias@matthimatiker.de>
 * @copyright 2012 Matthias Molitor
 * @license http://www.opensource.org/licenses/BSD-3-Clause BSD License
 * @link https://github.com/Matthimatiker/AspectPHP
 * @since 12.01.2012
 */
class AspectPHP_Manager_Standard implements AspectPHP_Manager
{

    /**
     * The registered aspects.
     *
     * @var array(AspectPHP_Aspect)
     */
    protected $aspects = array();

    /**
     * Contains advisors of each registered aspect.
     *
     * A string that identifies an aspect object is used as key.
     *
     * @var array(string=>AspectPHP_Advisor_Container)
     */
    protected $advisorsByAspect = array();

    /**
     * Helper object that is used to extract advisors from aspects.
     *
     * @var AspectPHP_Advice_Extractor
     */
    protected $extractor = null;

    /**
     * Creates and initializes the manager.
     */
    public function __construct()
    {
        $this->extractor = new AspectPHP_Advice_Extractor();
    }

    /**
     * See {@link AspectPHP_Manager::register()} for details.
     *
     * @param AspectPHP_Aspect $aspect
     */
    public function register(AspectPHP_Aspect $aspect)
    {
        $this->aspects[] = $aspect;
        $this->advisorsByAspect[spl_object_hash($aspect)] = $this->extractAdvisors($aspect);
    }

    /**
     * See {@link AspectPHP_Manager::unregister()} for details.
     *
     * @param AspectPHP_Aspect $aspect
     */
    public function unregister(AspectPHP_Aspect $aspect)
    {
        $index = array_search($aspect, $this->aspects, true);
        if ($index === false) {
            // Aspect not found.
            return;
        }
        unset($this->aspects[$index]);
        unset($this->advisorsByAspect[spl_object_hash($aspect)]);
    }

    /**
     * See {@link AspectPHP_Manager::getAspects()} for details.
     *
     * @return array(AspectPHP_Aspect)
     */
    public function getAspects()
    {
        return $this->aspects;
    }

    /**
     * See {@link AspectPHP_Manager::getAdvicesFor()} for details.
     *
     * @param string $method
     * @return AspectPHP_Advisor_Container
     * @todo Refactoring: move parts of method to container
     * @todo Return just advices, update type in interface
     */
    public function getAdvicesFor($method)
    {
        $container = new AspectPHP_Advisor_Container();
        foreach ($this->advisorsByAspect as $advisors) {
            /* @var $advisors AspectPHP_Advisor_Container */
            foreach (AspectPHP_Advice_Type::all() as $type) {
                /* @var $type string */
                foreach ($advisors->{$type}() as $advisor) {
                    /* @var $advisor AspectPHP_Advisor */
                    if ($advisor->getPointcut()->matches($method)) {
                        $container->{$type}()->add($advisor);
                    }
                }
            }
        }
        return $container;
    }

    /**
     * Extracts all advisors from the given aspect.
     *
     * @param AspectPHP_Aspect $aspect
     * @return AspectPHP_Advisor_Container
     */
    protected function extractAdvisors(AspectPHP_Aspect $aspect)
    {
        return $this->extractor->getAdvicesFrom($aspect);
    }

}


text:
// Radio -----------------------------------------------------------------//
$( document ).ready(function() {
	$('.pmd-radio input').after(' ');
	//-- Radio Ripple Effect --//
	$(".pmd-radio-ripple-effect").on('mousedown', function(e) {
		var rippler = $(this);
		$('.ink').remove();
		// create .ink element if it doesn't exist
		if(rippler.find(".ink").length == 0) {
			rippler.append('');
		}
		var ink = rippler.find(".ink");
		// prevent quick double clicks
		ink.removeClass("animate");
		// set .ink diametr
		if(!ink.height() && !ink.width())
		{
			var d = Math.max(rippler.outerWidth(), rippler.outerHeight());
			ink.css({height: 15, width: 15});
		}
		// get click coordinates
		var x = e.pageX - rippler.offset().left - ink.width()/2;
		var y = e.pageY - rippler.offset().top - ink.height()/2;
		// set .ink position and add class .animate
		ink.css({
		  top: y+'px',
		  left:x+'px'
		}).addClass("animate");
		setTimeout(function(){
			ink.remove();
		}, 1500);
	})
})


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class IoAndroidDrafts extends React.Component<IconBaseProps> { }
export = IoAndroidDrafts;


text:
namespace fiberdyne {

class Scheduler
{
	//bool m_ContinueRunning;
	concurrency::concurrent_queue<std::shared_ptr<TEXTask>> 	m_ReadyList;	// The place we take input from
	std::shared_ptr<TEXTask>  m_CurrentTask;

protected:

public:
	Scheduler();

	virtual void ScheduleTask(const std::shared_ptr<TEXTask> &atask);
	//virtual void Shutdown();

	virtual void operator()();

	std::shared_ptr<TEXTask> GetCurrentTask() const { return m_CurrentTask;}
};

}


text:
/* Depandances PROVIDE :
 * =====================
 */
stage.provide("consoles.streaming");
 /*
 * Depandances REQUIRE :
 * =====================
 */
stage.require("streaming");
stage.require("consoles.inSocket");

if (stage.DEBUG){

	// DEVELOPPEMENT MONITOR IMPLEMENTATION
	stage.console.registerMonitor("STREAMING", "inSocket", function(){

		var streamingOverload = function(typeLog, obj){

			var obj = stage.setContext(stage.consoles.inSocket.view.log, this)(typeLog, obj);
			var ele = stage.build(this.logContainer, obj);
			return ele;
		};

		var transportType = stage.io.transport.inSocket.streaming.transport;
		var wrapperStreaming = stage.consoles.inSocket.wrapperTemplate( transportType, "STREAMING" );

		var infos = function(){

			return 	"Browser compatible : "+(stage.io.transport.inSocket.streaming.active || "OFF")+	"  &nbsp";
		}();

		return {
			logTypeToDisplay:"MONITOR",
			name:"STREAMING",
			type:"log",
			topPost:true,
			logLimit:0,
			infos:infos,
			logMonitor: stage.consoles.inSocket.logMonitor,
			builder:  stage.consoles.inSocket.view.template,
			logUpdate : stage.consoles.inSocket.view.logUpdate,

			// stageLog bulder
			stageLog:function(parent, context){

				return {
					LOG:{
						active:true,
						parent: parent,
						deleteAuto: false,
						effect:null,
						overLoad:stage.setContext(streamingOverload, context)
					}
				}
			},

			stage:{

				streaming: function(url, localSettings){
					return wrapperStreaming(url, localSettings);
				}

			}

		} // End return

	}); // End register

} // End if debug


text:
import yaml
from os import unlink
import regex
from globalvars import GlobalVars

import pytest

from blacklists import Blacklist, YAMLParserCIDR, YAMLParserASN, YAMLParserNS, load_blacklists
from helpers import files_changed, blacklist_integrity_check, not_regex_search_ascii_and_unicode
from phone_numbers import NUMBER_REGEX, NUMBER_REGEX_START, NUMBER_REGEX_END, NUMBER_REGEX_MINIMUM_DIGITS, NUMBER_REGEX_MAXIMUM_DIGITS, \
    process_numlist, get_maybe_north_american_not_in_normalized_but_in_all, is_digit_count_in_number_regex_range, matches_number_regex, \
    matches_number_regex_start, matches_number_regex_end
from findspam import FindSpam

def test_number_lists():
    errors = {}
    no_exacts = []
    maybe_north_american_already = []
    all_errors = []

    def clear_errors():
        errors['fails_number_regex'] = []
        errors['no_unique'] = []
        errors['blacklist_dup_with_no_unique'] = []
        errors['blacklist_dup_with_unique'] = []
        errors['duplicate_normializations'] = []

    def get_sorted_current_errors_and_clear_errors():
        current_errors = [error for sub in [errors[error_group] for error_group in errors] for error in sub]
        clear_errors()
        return current_errors

    def test_a_number_list(list_type, number_list, blacklist_normalized=None):
        line_number = 0
        all_processed = set()
        this_list_all_normalized = set()
        lines_no_unique = []
        lines_duplicate_blacklist_with_no_unique = []
        lines_duplicate_blacklist_with_unique = []
        for pattern in number_list:
            line_number += 1
            entry_description = "{} number ({})::{}:: ".format(list_type, line_number, pattern)
            (processed_pattern, this_normalized) = number_list[pattern]
            unique_normalized = this_normalized - this_list_all_normalized
            duplicate_normalized = this_normalized - unique_normalized
            maybe_north_american_not_in_all = get_maybe_north_american_not_in_normalized_but_in_all(processed_pattern, this_normalized, this_list_all_normalized)
            if maybe_north_american_not_in_all:
                maybe_north_american_already.append(entry_description + "has maybe North American form already in all normalized: {}".format(maybe_north_american_not_in_all))
            this_list_all_normalized |= unique_normalized
            digit_count = len(regex.findall(r'\d', processed_pattern))
            digit_count_text = " ({} digits is OK)".format(digit_count)
            if not is_digit_count_in_number_regex_range(digit_count):
                digit_count_text = ": {} digits is not >= {} and <= {}".format(digit_count, NUMBER_REGEX_MINIMUM_DIGITS, NUMBER_REGEX_MAXIMUM_DIGITS)
            if not matches_number_regex(processed_pattern):
                errors['fails_number_regex'].append(entry_description + "fails NUMBER_REGEX{}::{}".format(digit_count_text, processed_pattern))
            else:
                this_no_exacts = []
                if not matches_number_regex_start(processed_pattern):
                    this_no_exacts.append("Does not match NUMBER_REGEX_START.")
                if not matches_number_regex_end(processed_pattern):
                    this_no_exacts.append("Does not match NUMBER_REGEX_END.")
                if len(this_no_exacts) > 0:
                    no_exacts.append(entry_description + " ".join(this_no_exacts) + digit_count_text + "::" + pattern)
            if not unique_normalized:
                errors['no_unique'].append(entry_description + "has no unique normalized entries. Duplicate normalized entries: {}".format(duplicate_normalized))
                lines_no_unique.append(str(line_number))
            if blacklist_normalized:
                this_normalized_in_blacklist = this_normalized & blacklist_normalized
                this_normalized_not_in_blacklist = this_normalized - blacklist_normalized
                if this_normalized_in_blacklist:
                    not_in_blacklist_text = ":: normalized not in blacklist: {}".format(this_normalized_not_in_blacklist)
                    error_text = entry_description + "has duplicate normalized entries on the blacklist: {}".format(this_normalized_in_blacklist) + not_in_blacklist_text
                    if this_normalized_not_in_blacklist:
                        lines_duplicate_blacklist_with_unique.append(str(line_number))
                        errors['blacklist_dup_with_unique'].append(error_text)
                    else:
                        lines_duplicate_blacklist_with_no_unique.append(str(line_number))
                        errors['blacklist_dup_with_no_unique'].append(error_text)
            if duplicate_normalized:
                errors['duplicate_normializations'].append(entry_description + "Has duplicate normalized entries: {}".format(duplicate_normalized))
        lines_no_unique.reverse()
        deletion_list = []
        for error_group in errors:
            if errors[error_group]:
                has_errors = True
                # The following produces a sequence of commands which can be used in vi/vim to delete the entries in the appropriate file which have errors.
                # It's intended use is in the transition from not checking normalizations to applying homoglyphs and checking normalizations.
                line_list = [error.split('(')[1].split(')')[0] for error in errors[error_group]]
                line_list.reverse()
                deletion_list.append('{}: to remove {}: {}'.format(list_type, error_group, 'Gdd'.join(line_list) + 'Gdd'))
        if (deletion_list):
            print('\n')
            print('USE ONLY ONE OF THE FOLLOWING PER RUN OF THESE TESTS. Using more than one will result in the wrong lines being deleted:')
            print('\n'.join(deletion_list))
            print('\n\n')
        return all_processed, this_list_all_normalized

    clear_errors()
    FindSpam.reload_blacklists()
    blacklist_processed, blacklist_normalized = test_a_number_list("blacklisted", GlobalVars.blacklisted_numbers_full)
    all_errors.extend(get_sorted_current_errors_and_clear_errors())
    test_a_number_list("watched", GlobalVars.watched_numbers_full, blacklist_normalized=blacklist_normalized)
    all_errors.extend(get_sorted_current_errors_and_clear_errors())
    no_exacts_count = len(no_exacts)
    if (no_exacts_count > 0):
        pluralize = "" if no_exacts_count == 1 else "s"
        print("\n\t".join(["{} pattern{} can't match exactly:".format(no_exacts_count, pluralize)] + no_exacts))
    maybe_north_american_already_count = len(maybe_north_american_already)
    if (maybe_north_american_already_count > 0):
        pluralize = "" if maybe_north_american_already_count == 1 else "s"
        print("\n\t".join(["{} pattern{} are maybe North American with the alternate version already in all normalized:".format(maybe_north_american_already_count, pluralize)] + maybe_north_american_already))
    error_count = len(all_errors)
    if error_count > 0:
        pluralize = "" if error_count == 1 else "s"
        # Failure is, currently, disabled. In order for these tests to pass CI testing, they require substantial changes to the
        #   blacklisted_numbers.txt and watched_numbers.txt files in order to remove effectively duplicate entries,
        #   correct entries which overlap, etc. Given the dynamic nature of those lists, it's highly likely that changes to
        #   those lists will result in merge conflicts, potentially significant merge conflicts. As such, my plan is to
        #   wait until after this is merged to enable the potential for failures here and perform the needed changes to those
        #   files.
        # The output which is provided here and above should make it substantially easier to make the needed changes.
        pytest.fail("\n\t".join(["{} error{} have occurred (NOTE: you should find the normalized duplicate entry and decide which is better to keep):".format(error_count, pluralize)] + all_errors))

def test_blacklist_integrity():
    errors = blacklist_integrity_check()

    if len(errors) == 1:
        pytest.fail(errors[0])
    elif len(errors) > 1:
        pytest.fail("\n\t".join(["{} errors have occurred:".format(len(errors))] + errors))

def test_remote_diff():
    file_set = set("abcdefg")
    true_diff = "a c k p"
    false_diff = "h j q t"
    assert files_changed(true_diff, file_set)
    assert not files_changed(false_diff, file_set)

def yaml_validate_existing(filename, cls):
    return Blacklist((filename, cls)).validate()

def test_yaml_blacklist():
    with open('test_ip.yml', 'w') as y:
        yaml.dump({
            'Schema': 'yaml_cidr',
            'Schema_version': '2019120601',
            'items': [
                {'ip': '1.2.3.4'},
                {'ip': '2.3.4.5', 'disable': True},
                {'ip': '3.4.5.6', 'comment': 'comment'},
            ]}, y)
    blacklist = Blacklist(('test_ip.yml', YAMLParserCIDR))
    with pytest.raises(ValueError) as e:
        blacklist.add('1.3.34')
    with pytest.raises(ValueError) as e:
        blacklist.add({'ip': '1.3.4'})
    with pytest.raises(ValueError) as e:
        blacklist.add({'ip': '1.2.3.4'})
    with pytest.raises(ValueError) as e:
        blacklist.add({'ip': '2.3.4.5'})
    with pytest.raises(ValueError) as e:
        blacklist.remove({'ip': '34.45.56.67'})
    blacklist.add({'ip': '1.3.4.5'})
    assert '1.2.3.4' in blacklist.parse()
    assert '2.3.4.5' not in blacklist.parse()
    assert '3.4.5.6' in blacklist.parse()
    blacklist.remove({'ip': '3.4.5.6'})
    assert '3.4.5.6' not in blacklist.parse()
    unlink('test_ip.yml')

    yaml_validate_existing('blacklisted_cidrs.yml', YAMLParserCIDR)
    yaml_validate_existing('watched_cidrs.yml', YAMLParserCIDR)

def test_yaml_asn():
    with open('test_asn.yml', 'w') as y:
        yaml.dump({
            'Schema': 'yaml_asn',
            'Schema_version': '2019120601',
            'items': [
                {'asn': '123'},
                {'asn': '234', 'disable': True},
                {'asn': '345', 'comment': 'comment'},
            ]}, y)
    blacklist = Blacklist(('test_asn.yml', YAMLParserASN))
    with pytest.raises(ValueError) as e:
        blacklist.add('123')
    with pytest.raises(ValueError) as e:
        blacklist.add({'asn': 'invalid'})
    with pytest.raises(ValueError) as e:
        blacklist.add({'asn': '123'})
    with pytest.raises(ValueError) as e:
        blacklist.add({'asn': '234'})
    with pytest.raises(ValueError) as e:
        blacklist.remove({'asn': '9897'})
    assert '123' in blacklist.parse()
    assert '234' not in blacklist.parse()
    assert '345' in blacklist.parse()
    blacklist.remove({'asn': '345'})
    assert '345' not in blacklist.parse()
    unlink('test_asn.yml')

    yaml_validate_existing('watched_asns.yml', YAMLParserASN)

# test_yaml_nses currently takes 105s to run, so we want it to start up first, with everything else running in parallel.
@pytest.mark.xdist_group(name="long_runner_1")
def test_yaml_nses():
    with open('test_nses.yml', 'w') as y:
        yaml.dump({
            'Schema': 'yaml_ns',
            'Schema_version': '2019120601',
            'items': [
                {'ns': 'example.com.'},
                {'ns': 'example.net.', 'disable': True},
                {'ns': 'example.org.', 'comment': 'comment'},
            ]}, y)
    blacklist = Blacklist(('test_nses.yml', YAMLParserNS))
    assert 'example.com.' in blacklist.parse()
    assert 'EXAMPLE.COM.' not in blacklist.parse()
    with pytest.raises(ValueError) as e:
        blacklist.add({'ns': 'example.com.'})
    with pytest.raises(ValueError) as e:
        blacklist.add({'ns': 'EXAMPLE.COM.'})
    assert 'example.net.' not in blacklist.parse()
    assert 'example.org.' in blacklist.parse()
    blacklist.remove({'ns': 'example.org.'})
    assert 'example.org.' not in blacklist.parse()
    unlink('test_nses.yml')

    yaml_validate_existing('blacklisted_nses.yml', YAMLParserNS)
    yaml_validate_existing('watched_nses.yml', YAMLParserNS)


text:
package com.netflix.discovery;

import com.netflix.appinfo.HealthCheckCallback;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.config.ConfigurationManager;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author Nitesh Kant
 */
public class DiscoveryClientHealthTest extends AbstractDiscoveryClientTester {

    @Override
    protected void setupProperties() {
        super.setupProperties();
        ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "true");
    }

    @Override
    protected InstanceInfo.Builder newInstanceInfoBuilder(int renewalIntervalInSecs) {
        InstanceInfo.Builder builder = super.newInstanceInfoBuilder(renewalIntervalInSecs);
        builder.setStatus(InstanceInfo.InstanceStatus.STARTING);
        return builder;
    }

    @Test
    public void testCallback() throws Exception {
        MyHealthCheckCallback myCallback = new MyHealthCheckCallback(true);
        client.registerHealthCheckCallback(myCallback);

        Assert.assertTrue(client instanceof DiscoveryClient);
        DiscoveryClient clientImpl = (DiscoveryClient) client;

        InstanceInfoReplicator instanceInfoReplicator = clientImpl.getInstanceInfoReplicator();
        instanceInfoReplicator.run();

        Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.STARTING,
                clientImpl.getInstanceInfo().getStatus());
        Assert.assertFalse("Healthcheck callback invoked when status is STARTING.", myCallback.isInvoked());

        clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE);
        Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.OUT_OF_SERVICE,
                clientImpl.getInstanceInfo().getStatus());

        myCallback.reset();
        instanceInfoReplicator.run();
        Assert.assertFalse("Healthcheck callback invoked when status is OOS.", myCallback.isInvoked());

        clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.DOWN);
        Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.DOWN,
                clientImpl.getInstanceInfo().getStatus());
        myCallback.reset();
        instanceInfoReplicator.run();

        Assert.assertTrue("Healthcheck callback not invoked.", myCallback.isInvoked());
        Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.UP,
                clientImpl.getInstanceInfo().getStatus());
    }

    @Test
    public void testHandler() throws Exception {
        MyHealthCheckHandler myHealthCheckHandler = new MyHealthCheckHandler(InstanceInfo.InstanceStatus.UP);
        client.registerHealthCheck(myHealthCheckHandler);

        Assert.assertTrue(client instanceof DiscoveryClient);
        DiscoveryClient clientImpl = (DiscoveryClient) client;

        InstanceInfoReplicator instanceInfoReplicator = clientImpl.getInstanceInfoReplicator();

        Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.STARTING,
                clientImpl.getInstanceInfo().getStatus());
        instanceInfoReplicator.run();

        Assert.assertTrue("Healthcheck callback not invoked when status is STARTING.", myHealthCheckHandler.isInvoked());
        Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP,
                clientImpl.getInstanceInfo().getStatus());

        clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE);
        Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.OUT_OF_SERVICE,
                clientImpl.getInstanceInfo().getStatus());
        myHealthCheckHandler.reset();
        instanceInfoReplicator.run();

        Assert.assertTrue("Healthcheck callback not invoked when status is OUT_OF_SERVICE.", myHealthCheckHandler.isInvoked());
        Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP,
                clientImpl.getInstanceInfo().getStatus());

        clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.DOWN);
        Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.DOWN,
                clientImpl.getInstanceInfo().getStatus());
        myHealthCheckHandler.reset();
        instanceInfoReplicator.run();

        Assert.assertTrue("Healthcheck callback not invoked when status is DOWN.", myHealthCheckHandler.isInvoked());
        Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP,
                clientImpl.getInstanceInfo().getStatus());

        clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.UP);
        myHealthCheckHandler.reset();
        myHealthCheckHandler.shouldException = true;
        instanceInfoReplicator.run();

        Assert.assertTrue("Healthcheck callback not invoked when status is UP.", myHealthCheckHandler.isInvoked());
        Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.DOWN,
                clientImpl.getInstanceInfo().getStatus());
    }

    private static class MyHealthCheckCallback implements HealthCheckCallback {

        private final boolean health;
        private volatile boolean invoked;

        private MyHealthCheckCallback(boolean health) {
            this.health = health;
        }

        @Override
        public boolean isHealthy() {
            invoked = true;
            return health;
        }

        public boolean isInvoked() {
            return invoked;
        }

        public void reset() {
            invoked = false;
        }
    }

    private static class MyHealthCheckHandler implements HealthCheckHandler {

        private final InstanceInfo.InstanceStatus health;
        private volatile boolean invoked;
        volatile boolean shouldException;

        private MyHealthCheckHandler(InstanceInfo.InstanceStatus health) {
            this.health = health;
        }

        public boolean isInvoked() {
            return invoked;
        }

        public void reset() {
            shouldException = false;
            invoked = false;
        }

        @Override
        public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) {
            invoked = true;
            if (shouldException) {
                throw new RuntimeException("test induced exception");
            }
            return health;
        }
    }
}


text:
<?php

namespace Redmine\Tests\Api;

use Redmine\Api\Attachment;

/**
 * @coversDefaultClass Redmine\Api\Attachment
 *
 * @author     Malte Gerth <mail@malte-gerth.de>
 */
class AttachmentTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test lastCallFailed().
     *
     * @covers       ::__construct
     * @covers       ::lastCallFailed
     * @dataProvider responseCodeProvider
     * @test
     */
    public function testLastCallFailedTrue($responseCode, $hasFailed)
    {
        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('getResponseCode')
            ->willReturn($responseCode);

        // Create the object under test
        $api = new Attachment($client);

        // Perform the tests
        $this->assertSame($hasFailed, $api->lastCallFailed());
    }

    /**
     * Data provider for response code and expected state.
     *
     * @return array[]
     */
    public function responseCodeProvider()
    {
        return array(
            array(199, true),
            array(200, false),
            array(201, false),
            array(202, true),
            array(400, true),
            array(403, true),
            array(404, true),
            array(500, true),
        );
    }

    /**
     * Test show().
     *
     * @covers ::get
     * @covers ::show
     * @test
     */
    public function testShowReturnsClientGetResponse()
    {
        // Test values
        $getResponse = 'API Response';

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('get')
            ->with($this->equalTo('/attachments/5.json'))
            ->willReturn($getResponse);

        // Create the object under test
        $api = new Attachment($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->show(5));
    }

    /**
     * Test download().
     *
     * @covers ::get
     * @covers ::download
     * @test
     */
    public function testDownloadReturnsUndecodedClientGetResponse()
    {
        // Test values
        $getResponse = 'API Response';

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('get')
            ->with($this->equalTo('/attachments/5'), false)
            ->willReturn($getResponse);

        // Create the object under test
        $api = new Attachment($client);

        // Perform the tests
        $this->assertSame($getResponse, $api->download(5));
    }

    /**
     * Test upload().
     *
     * @covers ::post
     * @covers ::upload
     * @test
     */
    public function testUploadReturnsClientPostResponse()
    {
        // Test values
        $postRequestData = 'API Response';
        $postResponse = 'API Response';

        // Create the used mock objects
        $client = $this->getMockBuilder('Redmine\Client')
            ->disableOriginalConstructor()
            ->getMock();
        $client->expects($this->once())
            ->method('post')
            ->with(
                $this->equalTo('/uploads.json'),
                $this->equalTo($postRequestData)
            )
            ->willReturn($postResponse);

        // Create the object under test
        $api = new Attachment($client);

        // Perform the tests
        $this->assertSame($postResponse, $api->upload($postRequestData));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Lime.Protocol.Serialization.Newtonsoft.Converters
{
    public static class JTokenExtensions
    {
        public static object GetTokenValue(this JToken token)
        {
            if (token is JValue jValue)
            {
                return jValue.Value;
            }

            if (token is JArray jArray)
            {
                return jArray
                    .Select(GetTokenValue)
                    .ToArray();
            }

            if (token is IDictionary<string, JToken> dictionary)
            {
                return dictionary.ToDictionary(k => k.Key, v => GetTokenValue(v.Value));
            }

            throw new ArgumentException("Unknown token type");
        }

        public static Document ToDocument(
            this JToken jToken,
            MediaType mediaType,
            JsonSerializer serializer,
            IDocumentTypeResolver documentTypeResolver)
        {
            Document document;
            if (documentTypeResolver.TryGetTypeForMediaType(mediaType, out var documentType))
            {
                try
                {
                    if (mediaType.IsJson)
                    {
                        document = (Document) serializer.Deserialize(jToken.CreateReader(), documentType);
                    }
                    else if (jToken != null)
                    {
                        var parseFunc = TypeUtilEx.GetParseFuncForType(documentType);
                        document = (Document) parseFunc(jToken.ToString());
                    }
                    else
                    {
                        document = (Document) Activator.CreateInstance(documentType);
                    }

                    return document;
                }
                catch (JsonException) { }
                catch (ArgumentException) { }
                catch (TypeLoadException)
                {
                    // Ignore deserialization exceptions and return a Plain/Json document instead
                }
            }

            if (mediaType.IsJson)
            {
                if (jToken is IDictionary<string, JToken> contentJsonObject)
                {
                    var contentDictionary = contentJsonObject.ToDictionary(k => k.Key, v => v.Value.GetTokenValue());
                    document = new JsonDocument(contentDictionary, mediaType);
                }
                else
                {
                    throw new ArgumentException("The property is not a JSON");
                }
            }
            else
            {
                document = new PlainDocument(jToken.ToString(), mediaType);
            }
            return document;
        }
    }
}


text:
/*******************************************
PutFrameCoordinator internal include file
*******************************************/
#ifndef __KINESIS_VIDEO_PUT_FRAME_COORDINATOR_INCLUDE_I__
#define __KINESIS_VIDEO_PUT_FRAME_COORDINATOR_INCLUDE_I__

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

typedef struct __FrameOrderTrackData FrameOrderTrackData;
struct __FrameOrderTrackData {
    PTrackInfo pTrackInfo;

    // current number of frames in the queue
    volatile UINT32 frameCount;

    PStackQueue frameQueue;
};
typedef struct __FrameOrderTrackData* PFrameOrderTrackData;

typedef STATUS (*FrameTimestampCompareFunc)(PFrameOrderTrackData, PFrameOrderTrackData, UINT64, PBOOL);

typedef struct __FrameOrderCoordinator FrameOrderCoordinator;
struct __FrameOrderCoordinator {
    // whether any eofr frame has been put
    volatile BOOL eofrPut;

    FrameOrderTrackData putFrameTrackDataList[MAX_SUPPORTED_TRACK_COUNT_PER_STREAM];

    UINT32 putFrameTrackDataListCount;

    // indicate whether any frame with FRAME_FLAG_KEY_FRAME set was received
    volatile BOOL keyFrameDetected;

    // number of tracks that has frame in the queue
    volatile UINT32 trackWithFrame;

    MUTEX lock;

    PStreamInfo pStreamInfo;

    FrameTimestampCompareFunc frameTimestampCompareFn;
};
typedef struct __FrameOrderCoordinator* PFrameOrderCoordinator;

////////////////////////////////////////////////////
// Function definitions
////////////////////////////////////////////////////
STATUS createFrameOrderCoordinator(PKinesisVideoStream, PFrameOrderCoordinator*);
STATUS freeFrameOrderCoordinator(PKinesisVideoStream, PFrameOrderCoordinator*);
STATUS frameOrderCoordinatorPutFrame(PKinesisVideoStream, PFrame);
STATUS frameOrderCoordinatorFlush(PKinesisVideoStream);

/**
 *
 * Normally, if the frame timestamps are different, frameOrderCoordinatorAudioVideoCompareFn would return -1 if frame 1's
 * timestamp is smaller and 1 otherwise. But if two frames' timestamp are equal after applying mkv timecode scale, and
 * one of them has key frame flag, then whichever frame that is put next must have the key frame flag, and the other one
 * should not have key frame flag, otherwise, previous cluster's ending frame would have the same timestamp as the next cluster.
 * The compare function would set the key frame flag correctly in such cases.
 *
 * @UINT64 - IN - timestamp of frame 1.
 * @PFrameOrderTrackData - IN - PFrameOrderTrackData that frame 1 belongs to.
 * @UINT64 - IN - timestamp of frame 2.
 * @PFrameOrderTrackData - IN - PFrameOrderTrackData that frame 2 belongs to.
 * @UINT64 - IN - custom data. In this case, the mkv timecode scale.
 * @PBOOL - OUT - compare result. If TRUE, first frame go first, else second frame go first.
 *
 * @return - STATUS - status code of the operation.
 */
STATUS audioVideoFrameTimestampComparator(PFrameOrderTrackData, PFrameOrderTrackData, UINT64, PBOOL);

#ifdef __cplusplus
}
#endif
#endif /*__KINESIS_VIDEO_PUT_FRAME_COORDINATOR_INCLUDE_I__*/


text:
//
//  ZMDES.h
//  ZMArchitecture
//
//  Created by ZM on 16/9/18.
//  Copyright © 2016年 ZM. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ZMDES : NSObject

/**
 *  DES加密算法: CBC模式
 */
+ (NSString *)zm_encryptDESwithText:(NSString *)sText;//加密
+ (NSString *)zm_decryptDESwithText:(NSString *)sText;//解密

/**
 *  DES 原始方法
 *  DES加密算法: ECB模式
 */
//加密
+(NSString *)zm_encryptUseDES:(NSString *)clearText key:(NSString *)key;
//解密
+(NSString*)zm_decryptUseDES:(NSString*)cipherText key:(NSString*)key;

@end


text:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Automation;
using Castle.Core.Internal;
using WhiteSharp.Drawing;

namespace WhiteSharp.Extensions
{
    public static class AutomationElementExtension
    {
        internal static bool IsOffScreen(this AutomationElement automationElement)
        {
            try
            {
                return automationElement.Current.IsOffscreen;
            }
            catch (ElementNotAvailableException)
            {
                return true;
            }
            catch (InvalidOperationException)
            {
                return true;
            }
        }

        internal static string GetId(this AutomationElement automationElement)
        {
            string[] identifiers =
            {
                "AutomationId",
                "Name",
                "Control Type",
                "Class Name"
            };

            var propertyList = new[]
            {
                automationElement.Current.AutomationId,
                automationElement.Current.Name,
                automationElement.Current.ControlType.ToString(),
                automationElement.Current.ClassName
            };

            return identifiers[Array.FindIndex(propertyList, 0, x => !String.IsNullOrEmpty(x))] + " = " +
                   propertyList.First(x => !String.IsNullOrEmpty(x));
        }

        public static string GetName(this AutomationElement automationElement)
        {
            return automationElement.Current.Name;
        }

        public static string GetHelpText(this AutomationElement automationElement)
        {
            return automationElement.Current.HelpText;
        }

        public static string GetText(this AutomationElement automationElement)
        {
            SelectionPattern selectionPattern;
            ValuePattern valuePattern;

            string value = null;
            string selectedItemName = null;
            string name = automationElement.Current.Name;
            string helpText = automationElement.Current.HelpText;

            if (automationElement.Current.ControlType.Equals(ControlType.Edit))
            {
                valuePattern = (ValuePattern)automationElement.GetCurrentPattern(ValuePattern.Pattern);
                value = valuePattern.Current.Value;
            }

            if (automationElement.Current.ControlType.Equals(ControlType.ComboBox))
            {
                object p;
                if (automationElement.TryGetCurrentPattern(SelectionPattern.Pattern, out p))
                {
                    selectionPattern = (SelectionPattern)p;
                    selectedItemName = selectionPattern.Current.GetSelection().First().Current.Name;
                }
                if (automationElement.TryGetCurrentPattern(ValuePattern.Pattern, out p))
                {
                    valuePattern = (ValuePattern)p;
                    value = valuePattern.Current.Value;
                }
            }

            var text = new[]
            {
                value,
                selectedItemName,
                name,
                helpText
            }.FirstOrDefault(x => !x.IsNullOrEmpty()) ?? "";

            return text;
        }

        public static string Title(this AutomationElement element)
        {
            string returnName;
            try
            {
                returnName = element.FindFirst(TreeScope.Children,
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TitleBar)).Current.Name;
            }
            catch (Exception)
            {
                return "";
            }
            return returnName;
        }

        public static void DrawHighlight(this AutomationElement element)
        {
            var rectangle = element.Current.BoundingRectangle;

            if (rectangle != Rect.Empty)
            {
                new FrameRectangle(rectangle).Highlight();
            }
        }
    }
}


text:
package org.jkiss.dbeaver.ext.generic.model.meta;

import org.eclipse.core.runtime.IConfigurationElement;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel;
import org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaObject;
import org.jkiss.dbeaver.model.impl.AbstractDescriptor;
import org.jkiss.dbeaver.registry.RegistryConstants;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;

import java.util.HashMap;
import java.util.Map;

public class GenericMetaModelDescriptor extends AbstractDescriptor {

    private IConfigurationElement contributorConfig;
    private ObjectType implType;
    private GenericMetaModel instance;

    private String id;
    private final Map<String, GenericMetaObject> objects = new HashMap<>();
    private String[] driverClass;

    public GenericMetaModelDescriptor() {
        super("org.jkiss.dbeaver.ext.generic");
        implType = new ObjectType(GenericMetaModel.class.getName());
        instance = new GenericMetaModel();
        instance.descriptor = this;
    }

    public GenericMetaModelDescriptor(IConfigurationElement cfg) {
        super(cfg);
        this.contributorConfig = cfg;

        this.id = cfg.getAttribute(RegistryConstants.ATTR_ID);
        IConfigurationElement[] objectList = cfg.getChildren("object");
        if (!ArrayUtils.isEmpty(objectList)) {
            for (IConfigurationElement childConfig : objectList) {
                GenericMetaObject metaObject = new GenericMetaObject(childConfig);
                objects.put(metaObject.getType(), metaObject);
            }
        }
        String driverClassList = cfg.getAttribute("driverClass");
        if (CommonUtils.isEmpty(driverClassList)) {
            this.driverClass = new String[0];
        } else {
            this.driverClass = driverClassList.split(",");
        }

        implType = new ObjectType(cfg.getAttribute("class"));
    }

    public String getId()
    {
        return id;
    }

    @NotNull
    public String[] getDriverClass() {
        return driverClass;
    }

    public GenericMetaObject getObject(String id)
    {
        return objects.get(id);
    }

    public GenericMetaModel getInstance() throws DBException {
        if (instance != null) {
            return instance;
        }
        Class<? extends GenericMetaModel> implClass = implType.getObjectClass(GenericMetaModel.class);
        if (implClass == null) {
            throw new DBException("Can't create generic meta model instance '" + implType.getImplName() + "'");
        }
        try {
            instance = implClass.newInstance();
        } catch (Throwable e) {
            throw new DBException("Can't instantiate meta model", e);
        }
        instance.descriptor = this;
        return instance;
    }

}


text:
/* Author: Ioan Sucan */

#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <moveit/robot_state/conversions.h>
#include <moveit/kinematic_constraints/utils.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/math/constants/constants.hpp>
#include <ros/ros.h>

static const std::string ROBOT_DESCRIPTION = "robot_description";

int main(int argc, char** argv)
{
  ros::init(argc, argv, "initialize_demo_db", ros::init_options::AnonymousName);

  boost::program_options::options_description desc;
  desc.add_options()("help", "Show help message")("host", boost::program_options::value<std::string>(), "Host for the "
                                                                                "DB.")(
      "port", boost::program_options::value<std::size_t>(), "Port for the DB.");

  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
  boost::program_options::notify(vm);

  if (vm.count("help"))
  {
    std::cout << desc << std::endl;
    return 1;
  }
  // Set up db
  warehouse_ros::DatabaseConnection::Ptr conn = moveit_warehouse::loadDatabase();
  if (vm.count("host") && vm.count("port"))
    conn->setParams(vm["host"].as<std::string>(), vm["port"].as<std::size_t>());
  if (!conn->connect())
    return 1;

  ros::AsyncSpinner spinner(1);
  spinner.start();

  ros::NodeHandle nh;
  planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION);
  if (!psm.getPlanningScene())
  {
    ROS_ERROR("Unable to initialize PlanningSceneMonitor");
    return 1;
  }

  moveit_warehouse::PlanningSceneStorage pss(conn);
  moveit_warehouse::ConstraintsStorage cs(conn);
  moveit_warehouse::RobotStateStorage rs(conn);
  pss.reset();
  cs.reset();
  rs.reset();

  // add default planning scenes
  moveit_msgs::PlanningScene psmsg;
  psm.getPlanningScene()->getPlanningSceneMsg(psmsg);
  psmsg.name = "default";
  pss.addPlanningScene(psmsg);
  ROS_INFO("Added default scene: '%s'", psmsg.name.c_str());

  moveit_msgs::RobotState rsmsg;
  robot_state::robotStateToRobotStateMsg(psm.getPlanningScene()->getCurrentState(), rsmsg);
  rs.addRobotState(rsmsg, "default");
  ROS_INFO("Added default state");

  const std::vector<std::string>& gnames = psm.getRobotModel()->getJointModelGroupNames();
  for (std::size_t i = 0; i < gnames.size(); ++i)
  {
    const robot_model::JointModelGroup* jmg = psm.getRobotModel()->getJointModelGroup(gnames[i]);
    if (!jmg->isChain())
      continue;
    const std::vector<std::string>& lnames = jmg->getLinkModelNames();
    if (lnames.empty())
      continue;

    moveit_msgs::OrientationConstraint ocm;
    ocm.link_name = lnames.back();
    ocm.header.frame_id = psm.getRobotModel()->getModelFrame();
    ocm.orientation.x = 0.0;
    ocm.orientation.y = 0.0;
    ocm.orientation.z = 0.0;
    ocm.orientation.w = 1.0;
    ocm.absolute_x_axis_tolerance = 0.1;
    ocm.absolute_y_axis_tolerance = 0.1;
    ocm.absolute_z_axis_tolerance = boost::math::constants::pi<double>();
    ocm.weight = 1.0;
    moveit_msgs::Constraints cmsg;
    cmsg.orientation_constraints.resize(1, ocm);
    cmsg.name = ocm.link_name + ":upright";
    cs.addConstraints(cmsg, psm.getRobotModel()->getName(), jmg->getName());
    ROS_INFO("Added default constraint: '%s'", cmsg.name.c_str());
  }
  ROS_INFO("Default MoveIt! Warehouse was reset.");

  ros::shutdown();

  return 0;
}


text:
#ifndef Rice__Data_Type_defn__hpp_
#define Rice__Data_Type_defn__hpp_

#include "Class_defn.hpp"
#include "Data_Type_fwd.hpp"
#include "detail/ruby.hpp"
#include <memory>
#include <map>
#include <set>

/*!
 *  \example map/map.cpp
 */

namespace Rice
{

namespace detail
{
  class Abstract_Caster;
}

class Module;

//! The base class for all instantiations of Data_Type.
class Data_Type_Base
  : public Module_impl<Class, Data_Type_Base>
{
public:
  //! Default constructor.
  Data_Type_Base();

  //! Constructor.
  Data_Type_Base(VALUE v);

  //! Destructor.
  virtual ~Data_Type_Base() = 0;

  // Must be public to workaround gcc 3.3
  typedef std::map<VALUE, detail::Abstract_Caster *> Casters;

  virtual detail::Abstract_Caster * caster() const = 0;

  static Casters & casters();

private:
  static Casters * casters_;
};

//! Define a new data class in the namespace given by module.
/*! The class will have a base class of Object.
 *  \param T the C++ type of the wrapped class.
 *  \param module the the Module in which to define the class.
 *  \return the new class.
 */
template<typename T>
Rice::Data_Type<T> define_class_under(
    Object module,
    char const * name);

//! Define a new data class in the namespace given by module.
/*! The class with have a base class determined by Base_T (specifically,
 *  Data_Type<Base_T>::klass).  Therefore, the type Base_T must already
 *  have been registered using define_class<> or define_class_under<>.
 *  \param T the C++ type of the wrapped class.
 *  \param module the the Module in which to define the class.
 *  \return the new class.
 */
template<typename T, typename Base_T>
Rice::Data_Type<T> define_class_under(
    Object module,
    char const * name);

//! Define a new data class in the default namespace.
/*! The class will have a base class of Object.
 *  \param T the C++ type of the wrapped class.
 *  \return the new class.
 */
template<typename T>
Rice::Data_Type<T> define_class(
    char const * name);

//! Define a new data class in the default namespace.
/*! The class with have a base class determined by Base_T (specifically,
 *  Data_Type<Base_T>::klass).  Therefore, the type Base_T must already
 *  have been registered using define_class<> or define_class_under<>.
 *  \param T the C++ type of the wrapped class.
 *  \param module the the Module in which to define the class.
 *  \return the new class.
 */
template<typename T, typename Base_T>
Rice::Data_Type<T> define_class(
    char const * name);

//! Define an implicit conversion rule between two types.
/*! Given two types, which can be custom types already
 *  wrapped into Rice or fundamental C++ types, this
 *  tells Rice that the two types can be used interchangably.
 *  \param From_T The type to convert from
 *  \param To_T The type to convert to
 */
template<typename From_T, typename To_T>
void define_implicit_cast();

//! A mechanism for binding ruby types to C++ types.
/*! This class binds run-time types (Ruby VALUEs) to compile-time types
 *  (C++ types).  The binding can occur only once.
 */
template<typename T>
class Data_Type
  : public Module_impl<Data_Type_Base, Data_Type<T> >
{
public:
  //! The C++ type being held.
  typedef T Type;

  //! Default constructor which does not bind.
  /*! No member functions must be called on this Data_Type except bind,
   *  until the type is bound.
   */
  Data_Type();

  //! Constructor which takes a Module.
  /*! Binds the type to the given VALUE according to the rules given
   *  above.
   *  \param klass the module to which to bind.
   */
  Data_Type(Module const & v);

  //! Destructor.
  virtual ~Data_Type();

  //! Explictly return the Ruby type.
  /*! \return the ruby class to which the type is bound.
   */
  static Module klass();

  //! Assignment operator which takes a Module
  /*! \param klass must be the class to which this data type is already
   *  bound.
   *  \return *this
   */
  virtual Data_Type & operator=(Module const & klass);

  //! Define a constructor for the class.
  /*! Creates a singleton method allocate and an instance method called
   *  initialize which together create a new instance of the class.  The
   *  allocate method allocates memory for the object reference and the
   *  initialize method constructs the object.
   *  \param constructor an object that has a static member function
   *  construct() that constructs a new instance of T and sets the object's data
   *  member to point to the new instance.  A helper class Constructor
   *  is provided that does precisely this.
   *  For example:
   *  \code
   *    define_class<Foo>("Foo")
   *      .define_constructor(Constructor<Foo>());
   *  \endcode
   */
  template<typename Constructor_T>
  Data_Type<T> & define_constructor(
      Constructor_T constructor,
      Arguments * arguments = 0);

  template<typename Constructor_T>
  Data_Type<T> & define_constructor(
      Constructor_T constructor,
      Arg const& arg);

  //! Register a Director class for this class.
  /*! For any class that uses Rice::Director to enable polymorphism
   *  across the languages, you need to register that director proxy
   *  class with this method. Not doing so will cause the resulting
   *  library to die at run time when it tries to convert the base
   *  type into the Director proxy type, and cannot find an appropriate Caster.
   *
   *  This method takes no arguments, just needs the type of the
   *  Director proxy class.
   *
   *  For example:
   *  \code
   *    class FooDirector : public Foo, public Rice::Director {
   *      ...
   *    };
   *
   *    define_class<Foo>("Foo")
   *      .define_director<FooDirector>()
   *      .define_constructor(Constructor<FooDirector, Rice::Object>());
   *  \endcode
   */
  template<typename Director_T>
  Data_Type<T>& define_director();

  //! Convert ruby object x to type T.
  /*! \param x the object to convert.
   *  \return the C++ object wrapped inside object x.
   */
  static T * from_ruby(Object x);

  //! Determine if the type is bound.
  /*! \return true if the object is bound, false otherwise.
   */
  static bool is_bound();

  virtual detail::Abstract_Caster * caster() const;

  static std_unique_ptr<detail::Abstract_Caster> caster_;

protected:
  //! Bind a Data_Type to a VALUE.
  /*! Throws an exception if the Data_Type is already bound to a
   *  different class.  Any existing instances of the Data_Type will be
   *  bound after this function returns.
   *  \param klass the ruby type to which to bind.
   *  \return *this
   */
  template<typename Base_T>
  static Data_Type bind(Module const & klass);

  template<typename T_>
  friend Rice::Data_Type<T_> define_class_under(
      Object module,
      char const * name);

  template<typename T_, typename Base_T_>
  friend Rice::Data_Type<T_> define_class_under(
      Object module,
      char const * name);

  template<typename T_>
  friend Rice::Data_Type<T_> Rice::define_class(
      char const * name);

  template<typename T_, typename Base_T_>
  friend Rice::Data_Type<T_> define_class(
      char const * name);

private:
  template<typename T_>
  friend class Data_Type;

  static void check_is_bound();

  static VALUE klass_;

  typedef std::set<Data_Type<T> *> Instances;

  static Instances & unbound_instances()
  {
    static Instances unbound_instances;
    return unbound_instances;
  }
};

} // namespace Rice

#include "Data_Type.ipp"

#endif // Rice__Data_Type_defn__hpp_


text:
namespace policy {

namespace {

const char kKey1[] = "Key 1";
const char kKey2[] = "Key 2";
const char kPolicy1[] = "Test policy 1";
const char kPolicy2[] = "Test policy 2";
const char kData1[] = "Testing data 1";
const char kData2[] = "Testing data 2";
const char kURL[] = "http://localhost";
const size_t kMaxSize = 100;

}  // namespace

class CouldExternalDataStoreTest : public testing::Test {
 public:
  CouldExternalDataStoreTest();

  void SetUp() override;

 protected:
  const std::string kData1Hash;
  const std::string kData2Hash;

  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
  base::ScopedTempDir temp_dir_;
  std::unique_ptr<ResourceCache> resource_cache_;

 private:
  DISALLOW_COPY_AND_ASSIGN(CouldExternalDataStoreTest);
};

CouldExternalDataStoreTest::CouldExternalDataStoreTest()
    : kData1Hash(crypto::SHA256HashString(kData1)),
      kData2Hash(crypto::SHA256HashString(kData2)),
      task_runner_(new base::TestSimpleTaskRunner) {
}

void CouldExternalDataStoreTest::SetUp() {
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  resource_cache_.reset(new ResourceCache(temp_dir_.path(), task_runner_));
}

TEST_F(CouldExternalDataStoreTest, StoreAndLoad) {
  // Write an entry to a store.
  CloudExternalDataStore store(kKey1, task_runner_, resource_cache_.get());
  EXPECT_TRUE(store.Store(kPolicy1, kData1Hash, kData1));

  // Check that loading and verifying the entry against an invalid hash fails.
  std::string data;
  EXPECT_FALSE(store.Load(kPolicy1, kData2Hash, kMaxSize, &data));

  // Check that loading and verifying the entry against its hash succeeds.
  EXPECT_TRUE(store.Load(kPolicy1, kData1Hash, kMaxSize, &data));
  EXPECT_EQ(kData1, data);
}

TEST_F(CouldExternalDataStoreTest, StoreTooLargeAndLoad) {
  // Write an entry to a store.
  CloudExternalDataStore store(kKey1, task_runner_, resource_cache_.get());
  EXPECT_TRUE(store.Store(kPolicy1, kData1Hash, kData2));

  // Check that the entry has been written to the resource cache backing the
  // store.
  std::map<std::string, std::string> contents;
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(kData2, contents.begin()->second);

  // Check that loading the entry fails when the maximum allowed data size is
  // smaller than the entry size.
  std::string data;
  EXPECT_FALSE(store.Load(kPolicy1, kData1Hash, 1, &data));

  // Verify that the oversized entry has been detected and removed from the
  // resource cache.
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  EXPECT_TRUE(contents.empty());
}

TEST_F(CouldExternalDataStoreTest, StoreInvalidAndLoad) {
  // Construct a store entry whose hash and contents do not match.
  CloudExternalDataStore store(kKey1, task_runner_, resource_cache_.get());
  EXPECT_TRUE(store.Store(kPolicy1, kData1Hash, kData2));

  // Check that the entry has been written to the resource cache backing the
  // store.
  std::map<std::string, std::string> contents;
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(kData2, contents.begin()->second);

  // Check that loading and verifying the entry against its hash fails.
  std::string data;
  EXPECT_FALSE(store.Load(kPolicy1, kData1Hash, kMaxSize, &data));

  // Verify that the corrupted entry has been detected and removed from the
  // resource cache.
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  EXPECT_TRUE(contents.empty());
}

TEST_F(CouldExternalDataStoreTest, Prune) {
  // Write two entries to a store.
  CloudExternalDataStore store(kKey1, task_runner_, resource_cache_.get());
  EXPECT_TRUE(store.Store(kPolicy1, kData1Hash, kData1));
  EXPECT_TRUE(store.Store(kPolicy2, kData2Hash, kData2));

  // Check that loading and verifying the entries against their hashes succeeds.
  std::string data;
  EXPECT_TRUE(store.Load(kPolicy1, kData1Hash, kMaxSize, &data));
  EXPECT_EQ(kData1, data);
  EXPECT_TRUE(store.Load(kPolicy2, kData2Hash, kMaxSize, &data));
  EXPECT_EQ(kData2, data);

  // Prune the store, allowing only an entry for the first policy with its
  // current hash to be kept.
  CloudExternalDataManager::Metadata metadata;
  metadata[kPolicy1] =
      CloudExternalDataManager::MetadataEntry(kURL, kData1Hash);
  store.Prune(metadata);

  // Check that the entry for the second policy has been removed from the
  // resource cache backing the store.
  std::map<std::string, std::string> contents;
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(kData1, contents.begin()->second);

  // Prune the store, allowing only an entry for the first policy with a
  // different hash to be kept.
  metadata[kPolicy1] =
      CloudExternalDataManager::MetadataEntry(kURL, kData2Hash);
  store.Prune(metadata);

  // Check that the entry for the first policy has been removed from the
  // resource cache.
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  EXPECT_TRUE(contents.empty());
}

TEST_F(CouldExternalDataStoreTest, SharedCache) {
  // Write entries to two stores for two different cache_keys sharing a cache.
  CloudExternalDataStore store1(kKey1, task_runner_, resource_cache_.get());
  EXPECT_TRUE(store1.Store(kPolicy1, kData1Hash, kData1));
  CloudExternalDataStore store2(kKey2, task_runner_, resource_cache_.get());
  EXPECT_TRUE(store2.Store(kPolicy2, kData2Hash, kData2));

  // Check that the entries have been assigned to the correct keys in the
  // resource cache backing the stores.
  std::map<std::string, std::string> contents;
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(kData1, contents.begin()->second);
  resource_cache_->LoadAllSubkeys(kKey2, &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(kData2, contents.begin()->second);

  // Check that each entry can be loaded from the correct store.
  std::string data;
  EXPECT_TRUE(store1.Load(kPolicy1, kData1Hash, kMaxSize, &data));
  EXPECT_EQ(kData1, data);
  EXPECT_FALSE(store1.Load(kPolicy2, kData2Hash, kMaxSize, &data));

  EXPECT_FALSE(store2.Load(kPolicy1, kData1Hash, kMaxSize, &data));
  EXPECT_TRUE(store2.Load(kPolicy2, kData2Hash, kMaxSize, &data));
  EXPECT_EQ(kData2, data);

  // Prune the first store, allowing no entries to be kept.
  CloudExternalDataManager::Metadata metadata;
  store1.Prune(metadata);

  // Check that the part of the resource cache backing the first store is empty.
  resource_cache_->LoadAllSubkeys(kKey1, &contents);
  EXPECT_TRUE(contents.empty());

  // Check that the part of the resource cache backing the second store is
  // unaffected.
  resource_cache_->LoadAllSubkeys(kKey2, &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(kData2, contents.begin()->second);
}

}  // namespace policy


text:
0.2.7
----------
2014-03-19

* fixed checking if objects are iterable

0.2.6
----------
2013-09-02

* removed pipe_exception_handler (did more harm than good most of the time)

0.2.5
----------
2013-08-13

* Maybe returns None when called with None
* not calling repr() on stuff if we don't need to

0.2.4
----------
2013-07-13

* added drop_first
* fixed unicode formatting problem

0.2.3
----------
2013-04-24

* added sort_by.descending
* group_by returns item iterator instead of a dictionary

0.2.2
----------
2013-04-16

* X objects create bound methods on classes
* added support for X division

0.2.1
----------
2013-02-10

* added automatic regex conditions
* renamed xcurry to xpartial (turns out currying is something else)

0.2.0
----------
2012-11-14

* added support for X >=, <=, - and ** operations
* fixed static item handling in ds_builder

0.1.9
----------
2012-11-05

* added xcurry
* improved XObject naming

0.1.8
----------
2012-10-31

* added as_kwargs
* added take_until
* X object implicit piping (without ~)
* fixed naming X-objects so it doesn't fail with tuples

0.1.7
----------
2012-10-25

* friendlier debugging
* added changelog


text:
package renderer

import (
	"errors"
	"fmt"
	"github.com/zupzup/calories/model"
	"github.com/zupzup/calories/util"
	"testing"
	"time"
)

func TestJSONError(t *testing.T) {
	r := JSONRenderer{}
	res, err := r.Error(errors.New("someError"))
	expected := fmt.Sprint("{\"success\":false,\"message\":\"someError\"}")
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONWeightHistory(t *testing.T) {
	r := JSONRenderer{}
	var weights []model.Weight
	now := time.Now()
	weights = append(weights, model.Weight{
		Created: now,
		Weight:  85.0,
	})
	config := model.Config{}
	res, err := r.WeightHistory(weights, &config)
	expected := fmt.Sprintf("[{\"created\":\"%s\",\"weight\":85,\"formatted\":\"85.0 kg\"}]", now.Format(time.RFC3339Nano))
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONConfig(t *testing.T) {
	r := JSONRenderer{}
	now := time.Now()
	res, err := r.Config(&model.Config{
		Height:     185.0,
		Activity:   1.5,
		Birthday:   now,
		Gender:     "male",
		UnitSystem: util.Metric,
	}, &model.Weight{Weight: 85.0}, 2000.0, 1500.0, 18)
	expected := fmt.Sprintf("{\"weight\":\"85.0 kg\",\"height\":\"185.0 cm\",\"activity\":1.5,\"birthday\":\"%s\",\"age\":18,\"gender\":\"male\",\"unitSystem\":\"metric\",\"amr\":2000,\"bmr\":1500}", now.Format(util.DateFormat))
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONAddWeight(t *testing.T) {
	r := JSONRenderer{}
	res, err := r.AddWeight(85.0, &model.Config{})
	expectedString := "Added weight: 85.0 kg"
	expected := fmt.Sprintf("{\"success\":true,\"message\":\"%s\"}", expectedString)
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONDaysNoEntries(t *testing.T) {
	r := JSONRenderer{}
	days := model.Days{}
	now := time.Now()
	res, err := r.Days(days, now, now)
	expected := fmt.Sprintf("{\"From\":\"%s\",\"To\":\"%s\",\"Days\":[]}", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano))
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONDaysEntries(t *testing.T) {
	r := JSONRenderer{}
	now := time.Now()
	days := model.Days{}
	entries := model.Entries{}
	entries = append(entries, model.Entry{
		Created:   now,
		EntryDate: now.Format(util.DateFormat),
		Calories:  1000,
		Food:      "Schnitzel",
		BMR:       1500.0,
		AMR:       2000.0,
	})
	days = append(days, &model.Day{
		Used:    1000,
		Date:    now,
		Entries: entries,
	})
	res, err := r.Days(days, now, now)
	expected := fmt.Sprintf("{\"From\":\"%s\",\"To\":\"%s\",\"Days\":[{\"entries\":[{\"id\":0,\"created\":\"%s\",\"entryDate\":\"%s\",\"calories\":1000,\"food\":\"Schnitzel\",\"bmr\":1500,\"amr\":2000}],\"used\":1000,\"date\":\"%s\"}]}", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Format(util.DateFormat), now.Format(time.RFC3339Nano))
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONAddEntry(t *testing.T) {
	r := JSONRenderer{}
	res, err := r.AddEntry("01.01.2017", 1000, "Schnitzel")
	expectedString := "Added Entry for 01.01.2017 with 1000 calories (Schnitzel)"
	expected := fmt.Sprintf("{\"success\":true,\"message\":\"%s\"}", expectedString)
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONClearEntries(t *testing.T) {
	r := JSONRenderer{}
	res, err := r.ClearEntries("01.01.2017")
	expectedString := "Cleared all entries for 01.01.2017"
	expected := fmt.Sprintf("{\"success\":true,\"message\":\"%s\"}", expectedString)
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONClearEntry(t *testing.T) {
	r := JSONRenderer{}
	res, err := r.ClearEntry("01.01.2017", &model.Entry{Calories: 1000.0, Food: "Schnitzel"})
	expectedString := "Cleared entry 1000 Schnitzel for 01.01.2017"
	expected := fmt.Sprintf("{\"success\":true,\"message\":\"%s\"}", expectedString)
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}

func TestJSONImport(t *testing.T) {
	r := JSONRenderer{}
	res, err := r.Import("file.csv", 10, 5)
	expectedString := "Imported data from file.csv with 10 entries and 5 weights"
	expected := fmt.Sprintf("{\"success\":true,\"message\":\"%s\"}", expectedString)
	if res != expected || err != nil {
		t.Errorf("Error, actual: %v expected: %v", res, expected)
		return
	}
}


text:
[Mozc - a Japanese Input Method Editor designed for multi-platform](https://github.com/google/mozc)
===================================

Copyright 2010-2016, Google Inc.

Mozc is a Japanese Input Method Editor (IME) designed for multi-platform such as
Android OS, Apple OS X, Chromium OS, GNU/Linux and Microsoft Windows.  This
OpenSource project originates from
[Google Japanese Input](http://www.google.com/intl/ja/ime/).

Build Status
------------

|Android + OS X + Linux + NaCl |Windows |
|:----------------------------:|:------:|
[![Build Status](https://travis-ci.org/google/mozc.svg?branch=master)](https://travis-ci.org/google/mozc) |[![Build status](https://ci.appveyor.com/api/projects/status/1rvmtp7f80jv7ehf/branch/master?svg=true)](https://ci.appveyor.com/project/google/mozc/branch/master) |

What's Mozc?
------------
For historical reasons, the project name *Mozc* has two different meanings:

1. Internal code name of Google Japanese Input that is still commonly used
   inside Google.
2. Project name to release a subset of Google Japanese Input in the form of
   source code under OSS license without any warranty nor user support.

In this repository, *Mozc* means the second definition unless otherwise noted.

Detailed differences between Google Japanese Input and Mozc are described in [About Branding](doc/about_branding.md).

Build Instructions
------------------

* [How to build Mozc in Docker](doc/build_mozc_in_docker.md): Android, NaCl, and Linux desktop builds.
* [How to build Mozc in OS X](doc/build_mozc_in_osx.md): OS X build.
* [How to build Mozc in Windows](doc/build_mozc_in_windows.md): Windows build.

Release Plan
------------

tl;dr. **There is no stable version.**

As described in [About Branding](doc/about_branding.md) page, Google does
not promise any official QA for OSS Mozc project.  Because of this,
Mozc does not have a concept of *Stable Release*.  Instead we change version
number every time when we introduce non-trivial change.  If you are
interested in packaging Mozc source code, or developing your own products
based on Mozc, feel free to pick up any version.  They should be equally
stable (or equally unstable) in terms of no official QA process.

[Release History](doc/release_history.md) page may have additional
information and useful links about recent changes.

License
-------

All Mozc code written by Google is released under
[The BSD 3-Clause License](http://opensource.org/licenses/BSD-3-Clause).
For thrid party code under [src/third_party](src/third_party) directory,
see each sub directory to find the copyright notice.  Note also that
outside [src/third_party](src/third_party) following directories contain
thrid party code.

###[src/data/dictionary_oss/](src/data/dictionary_oss)
Mixed.
See [src/data/dictionary_oss/README.txt](src/data/dictionary_oss/README.txt)

###[src/data/test/dictionary/](src/data/test/dictionary)
The same to [src/data/dictionary_oss/](src/data/dictionary_oss).
See [src/data/dictionary_oss/README.txt](src/data/dictionary_oss/README.txt)

###[src/data/test/stress_test/](src/data/test/stress_test)
Public Domain.  See the comment in
[src/data/test/stress_test/sentences.txt](src/data/test/stress_test/sentences.txt)

###[src/data/unicode/](src/data/unicode)
UNICODE, INC. LICENSE AGREEMENT.
See each file header for details.


text:
// +build !ignore_autogenerated

// This file was autogenerated by deepcopy-gen. Do not edit it manually!

package v1

import (
	batch_v1 "k8s.io/api/batch/v1"
	core_v1 "k8s.io/api/core/v1"
	v1beta1 "k8s.io/api/extensions/v1beta1"
	conversion "k8s.io/apimachinery/pkg/conversion"
	runtime "k8s.io/apimachinery/pkg/runtime"
	reflect "reflect"
)

// GetGeneratedDeepCopyFuncs returns the generated funcs, since we aren't registering them.
//
// Deprecated: deepcopy registration will go away when static deepcopy is fully implemented.
func GetGeneratedDeepCopyFuncs() []conversion.GeneratedDeepCopyFunc {
	return []conversion.GeneratedDeepCopyFunc{
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*MasterSpec).DeepCopyInto(out.(*MasterSpec))
			return nil
		}, InType: reflect.TypeOf(&MasterSpec{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*PserverSpec).DeepCopyInto(out.(*PserverSpec))
			return nil
		}, InType: reflect.TypeOf(&PserverSpec{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*TrainerJobScaleStatus).DeepCopyInto(out.(*TrainerJobScaleStatus))
			return nil
		}, InType: reflect.TypeOf(&TrainerJobScaleStatus{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*TrainerSpec).DeepCopyInto(out.(*TrainerSpec))
			return nil
		}, InType: reflect.TypeOf(&TrainerSpec{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*TrainingJob).DeepCopyInto(out.(*TrainingJob))
			return nil
		}, InType: reflect.TypeOf(&TrainingJob{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*TrainingJobList).DeepCopyInto(out.(*TrainingJobList))
			return nil
		}, InType: reflect.TypeOf(&TrainingJobList{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*TrainingJobSpec).DeepCopyInto(out.(*TrainingJobSpec))
			return nil
		}, InType: reflect.TypeOf(&TrainingJobSpec{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*TrainingJobStatus).DeepCopyInto(out.(*TrainingJobStatus))
			return nil
		}, InType: reflect.TypeOf(&TrainingJobStatus{})},
		{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
			in.(*TrainingResourceStatus).DeepCopyInto(out.(*TrainingResourceStatus))
			return nil
		}, InType: reflect.TypeOf(&TrainingResourceStatus{})},
	}
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MasterSpec) DeepCopyInto(out *MasterSpec) {
	*out = *in
	in.Resources.DeepCopyInto(&out.Resources)
	if in.ReplicaSpec != nil {
		in, out := &in.ReplicaSpec, &out.ReplicaSpec
		if *in == nil {
			*out = nil
		} else {
			*out = new(v1beta1.ReplicaSet)
			(*in).DeepCopyInto(*out)
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterSpec.
func (in *MasterSpec) DeepCopy() *MasterSpec {
	if in == nil {
		return nil
	}
	out := new(MasterSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PserverSpec) DeepCopyInto(out *PserverSpec) {
	*out = *in
	in.Resources.DeepCopyInto(&out.Resources)
	if in.ReplicaSpec != nil {
		in, out := &in.ReplicaSpec, &out.ReplicaSpec
		if *in == nil {
			*out = nil
		} else {
			*out = new(v1beta1.ReplicaSet)
			(*in).DeepCopyInto(*out)
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PserverSpec.
func (in *PserverSpec) DeepCopy() *PserverSpec {
	if in == nil {
		return nil
	}
	out := new(PserverSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TrainerJobScaleStatus) DeepCopyInto(out *TrainerJobScaleStatus) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrainerJobScaleStatus.
func (in *TrainerJobScaleStatus) DeepCopy() *TrainerJobScaleStatus {
	if in == nil {
		return nil
	}
	out := new(TrainerJobScaleStatus)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TrainerSpec) DeepCopyInto(out *TrainerSpec) {
	*out = *in
	in.Resources.DeepCopyInto(&out.Resources)
	if in.ReplicaSpec != nil {
		in, out := &in.ReplicaSpec, &out.ReplicaSpec
		if *in == nil {
			*out = nil
		} else {
			*out = new(batch_v1.Job)
			(*in).DeepCopyInto(*out)
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrainerSpec.
func (in *TrainerSpec) DeepCopy() *TrainerSpec {
	if in == nil {
		return nil
	}
	out := new(TrainerSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TrainingJob) DeepCopyInto(out *TrainingJob) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	in.Status.DeepCopyInto(&out.Status)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrainingJob.
func (in *TrainingJob) DeepCopy() *TrainingJob {
	if in == nil {
		return nil
	}
	out := new(TrainingJob)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *TrainingJob) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	} else {
		return nil
	}
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TrainingJobList) DeepCopyInto(out *TrainingJobList) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	out.ListMeta = in.ListMeta
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]TrainingJob, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrainingJobList.
func (in *TrainingJobList) DeepCopy() *TrainingJobList {
	if in == nil {
		return nil
	}
	out := new(TrainingJobList)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *TrainingJobList) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	} else {
		return nil
	}
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TrainingJobSpec) DeepCopyInto(out *TrainingJobSpec) {
	*out = *in
	if in.Volumes != nil {
		in, out := &in.Volumes, &out.Volumes
		*out = make([]core_v1.Volume, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	if in.VolumeMounts != nil {
		in, out := &in.VolumeMounts, &out.VolumeMounts
		*out = make([]core_v1.VolumeMount, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	in.Master.DeepCopyInto(&out.Master)
	in.Pserver.DeepCopyInto(&out.Pserver)
	in.Trainer.DeepCopyInto(&out.Trainer)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrainingJobSpec.
func (in *TrainingJobSpec) DeepCopy() *TrainingJobSpec {
	if in == nil {
		return nil
	}
	out := new(TrainingJobSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TrainingJobStatus) DeepCopyInto(out *TrainingJobStatus) {
	*out = *in
	out.ScaleStatus = in.ScaleStatus
	if in.ReplicaStatuses != nil {
		in, out := &in.ReplicaStatuses, &out.ReplicaStatuses
		*out = make([]*TrainingResourceStatus, len(*in))
		for i := range *in {
			if (*in)[i] == nil {
				(*out)[i] = nil
			} else {
				(*out)[i] = new(TrainingResourceStatus)
				(*in)[i].DeepCopyInto((*out)[i])
			}
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrainingJobStatus.
func (in *TrainingJobStatus) DeepCopy() *TrainingJobStatus {
	if in == nil {
		return nil
	}
	out := new(TrainingJobStatus)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TrainingResourceStatus) DeepCopyInto(out *TrainingResourceStatus) {
	*out = *in
	if in.ResourceStates != nil {
		in, out := &in.ResourceStates, &out.ResourceStates
		*out = make(map[ResourceState]int, len(*in))
		for key, val := range *in {
			(*out)[key] = val
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrainingResourceStatus.
func (in *TrainingResourceStatus) DeepCopy() *TrainingResourceStatus {
	if in == nil {
		return nil
	}
	out := new(TrainingResourceStatus)
	in.DeepCopyInto(out)
	return out
}


text:
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home/home.component';
// import { AboutComponent } from './about/about.component';
import { DictionariesComponent } from './dictionaries/dictionaries.component';
// import { NnAnalysisComponent } from './nn-analysis/nn-analysis.component';
// import { FurnitureNnAnalysisComponent } from './furniture-nn-analysis/furniture-nn-analysis.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  // { path: 'about', component: AboutComponent},
  { path: 'dictionaries', component: DictionariesComponent},
  // { path: 'nn-analysis', component: NnAnalysisComponent},
  // { path: 'furniture-nn-analysis', component: FurnitureNnAnalysisComponent}
];

export const routing = RouterModule.forRoot(routes);


text:
#pragma once
#ifndef EL_IO_C_H
#define EL_IO_C_H

#ifdef __cplusplus
extern "C" {
#endif

typedef enum {
  EL_AUTO,
  EL_ASCII,
  EL_ASCII_MATLAB,
  EL_BINARY,
  EL_BINARY_FLAT,
  EL_BMP,
  EL_JPG,
  EL_JPEG,
  EL_MATRIX_MARKET,
  EL_PNG,
  EL_PPM,
  EL_XBM,
  EL_XPM,
  EL_FileFormat_MAX
} ElFileFormat;

EL_EXPORT ElError ElQtImageFormat
( ElFileFormat format, const char** formatStr );
EL_EXPORT ElError ElFileExtension
( ElFileFormat format, const char** fileExt );
EL_EXPORT ElError ElFormatFromExtension
( const char* ext, ElFileFormat* format );
EL_EXPORT ElError ElDetectFormat
( const char* filename, ElFileFormat* format );

/* TODO: FileSize wrapper. What should the input/output types be? */

typedef enum {
  EL_GRAYSCALE,
  EL_GRAYSCALE_DISCRETE,
  EL_RED_BLACK_GREEN,
  EL_BLUE_RED
} ElColorMap;

/* Color maps
   ========== */
EL_EXPORT ElError ElSetColorMap( ElColorMap map );
EL_EXPORT ElError ElGetColorMap( ElColorMap* map );
EL_EXPORT ElError ElSetNumDiscreteColors( ElInt numColors );
EL_EXPORT ElError ElNumDiscreteColors( ElInt* numColors );

/* Display
   ======= */
EL_EXPORT ElError ElProcessEvents( int numMsecs );

EL_EXPORT ElError ElDisplay_i( ElConstMatrix_i A, const char* title );
EL_EXPORT ElError ElDisplay_s( ElConstMatrix_s A, const char* title );
EL_EXPORT ElError ElDisplay_d( ElConstMatrix_d A, const char* title );
EL_EXPORT ElError ElDisplay_c( ElConstMatrix_c A, const char* title );
EL_EXPORT ElError ElDisplay_z( ElConstMatrix_z A, const char* title );

EL_EXPORT ElError ElDisplayDist_i( ElConstDistMatrix_i A, const char* title );
EL_EXPORT ElError ElDisplayDist_s( ElConstDistMatrix_s A, const char* title );
EL_EXPORT ElError ElDisplayDist_d( ElConstDistMatrix_d A, const char* title );
EL_EXPORT ElError ElDisplayDist_c( ElConstDistMatrix_c A, const char* title );
EL_EXPORT ElError ElDisplayDist_z( ElConstDistMatrix_z A, const char* title );

EL_EXPORT ElError ElDisplayDistMultiVec_i
( ElConstDistMultiVec_i X, const char* title );
EL_EXPORT ElError ElDisplayDistMultiVec_s
( ElConstDistMultiVec_s X, const char* title );
EL_EXPORT ElError ElDisplayDistMultiVec_d
( ElConstDistMultiVec_d X, const char* title );
EL_EXPORT ElError ElDisplayDistMultiVec_c
( ElConstDistMultiVec_c X, const char* title );
EL_EXPORT ElError ElDisplayDistMultiVec_z
( ElConstDistMultiVec_z X, const char* title );

EL_EXPORT ElError ElDisplayGraph( ElConstGraph graph, const char* title );
EL_EXPORT ElError ElDisplayDistGraph
( ElConstDistGraph graph, const char* title );

EL_EXPORT ElError ElDisplaySparse_i
( ElConstSparseMatrix_i A, const char* title );
EL_EXPORT ElError ElDisplaySparse_s
( ElConstSparseMatrix_s A, const char* title );
EL_EXPORT ElError ElDisplaySparse_d
( ElConstSparseMatrix_d A, const char* title );
EL_EXPORT ElError ElDisplaySparse_c
( ElConstSparseMatrix_c A, const char* title );
EL_EXPORT ElError ElDisplaySparse_z
( ElConstSparseMatrix_z A, const char* title );

EL_EXPORT ElError ElDisplayDistSparse_i
( ElConstDistSparseMatrix_i A, const char* title );
EL_EXPORT ElError ElDisplayDistSparse_s
( ElConstDistSparseMatrix_s A, const char* title );
EL_EXPORT ElError ElDisplayDistSparse_d
( ElConstDistSparseMatrix_d A, const char* title );
EL_EXPORT ElError ElDisplayDistSparse_c
( ElConstDistSparseMatrix_c A, const char* title );
EL_EXPORT ElError ElDisplayDistSparse_z
( ElConstDistSparseMatrix_z A, const char* title );

/* Print
   ===== */
/*
  TODO: Extend to support more general output streams. This is a bit
        problematic due to difficulties in converting between FILE* and
        std::ostream
*/
EL_EXPORT ElError ElPrint_i( ElConstMatrix_i A, const char* title );
EL_EXPORT ElError ElPrint_s( ElConstMatrix_s A, const char* title );
EL_EXPORT ElError ElPrint_d( ElConstMatrix_d A, const char* title );
EL_EXPORT ElError ElPrint_c( ElConstMatrix_c A, const char* title );
EL_EXPORT ElError ElPrint_z( ElConstMatrix_z A, const char* title );

EL_EXPORT ElError ElPrintDist_i( ElConstDistMatrix_i A, const char* title );
EL_EXPORT ElError ElPrintDist_s( ElConstDistMatrix_s A, const char* title );
EL_EXPORT ElError ElPrintDist_d( ElConstDistMatrix_d A, const char* title );
EL_EXPORT ElError ElPrintDist_c( ElConstDistMatrix_c A, const char* title );
EL_EXPORT ElError ElPrintDist_z( ElConstDistMatrix_z A, const char* title );

EL_EXPORT ElError ElPrintDistMultiVec_i
( ElConstDistMultiVec_i X, const char* title );
EL_EXPORT ElError ElPrintDistMultiVec_s
( ElConstDistMultiVec_s X, const char* title );
EL_EXPORT ElError ElPrintDistMultiVec_d
( ElConstDistMultiVec_d X, const char* title );
EL_EXPORT ElError ElPrintDistMultiVec_c
( ElConstDistMultiVec_c X, const char* title );
EL_EXPORT ElError ElPrintDistMultiVec_z
( ElConstDistMultiVec_z X, const char* title );

EL_EXPORT ElError ElPrintGraph( ElConstGraph graph, const char* title );
EL_EXPORT ElError ElPrintDistGraph( ElConstDistGraph graph, const char* title );

EL_EXPORT ElError ElPrintSparse_i( ElConstSparseMatrix_i A, const char* title );
EL_EXPORT ElError ElPrintSparse_s( ElConstSparseMatrix_s A, const char* title );
EL_EXPORT ElError ElPrintSparse_d( ElConstSparseMatrix_d A, const char* title );
EL_EXPORT ElError ElPrintSparse_c( ElConstSparseMatrix_c A, const char* title );
EL_EXPORT ElError ElPrintSparse_z( ElConstSparseMatrix_z A, const char* title );

EL_EXPORT ElError ElPrintDistSparse_i
( ElConstDistSparseMatrix_i A, const char* title );
EL_EXPORT ElError ElPrintDistSparse_s
( ElConstDistSparseMatrix_s A, const char* title );
EL_EXPORT ElError ElPrintDistSparse_d
( ElConstDistSparseMatrix_d A, const char* title );
EL_EXPORT ElError ElPrintDistSparse_c
( ElConstDistSparseMatrix_c A, const char* title );
EL_EXPORT ElError ElPrintDistSparse_z
( ElConstDistSparseMatrix_z A, const char* title );

/* Read
   ==== */
EL_EXPORT ElError ElRead_i
( ElMatrix_i A, const char* filename, ElFileFormat format );
EL_EXPORT ElError ElRead_s
( ElMatrix_s A, const char* filename, ElFileFormat format );
EL_EXPORT ElError ElRead_d
( ElMatrix_d A, const char* filename, ElFileFormat format );
EL_EXPORT ElError ElRead_c
( ElMatrix_c A, const char* filename, ElFileFormat format );
EL_EXPORT ElError ElRead_z
( ElMatrix_z A, const char* filename, ElFileFormat format );

EL_EXPORT ElError ElReadDist_i
( ElDistMatrix_i A, const char* filename, ElFileFormat format,
  bool sequential );
EL_EXPORT ElError ElReadDist_s
( ElDistMatrix_s A, const char* filename, ElFileFormat format,
  bool sequential );
EL_EXPORT ElError ElReadDist_d
( ElDistMatrix_d A, const char* filename, ElFileFormat format,
  bool sequential );
EL_EXPORT ElError ElReadDist_c
( ElDistMatrix_c A, const char* filename, ElFileFormat format,
  bool sequential );
EL_EXPORT ElError ElReadDist_z
( ElDistMatrix_z A, const char* filename, ElFileFormat format,
  bool sequential );

/* Spy
   === */
EL_EXPORT ElError ElSpy_i( ElConstMatrix_i A, const char* title, ElInt tol );
EL_EXPORT ElError ElSpy_s( ElConstMatrix_s A, const char* title, float tol );
EL_EXPORT ElError ElSpy_d( ElConstMatrix_d A, const char* title, double tol );
EL_EXPORT ElError ElSpy_c( ElConstMatrix_c A, const char* title, float tol );
EL_EXPORT ElError ElSpy_z( ElConstMatrix_z A, const char* title, double tol );

EL_EXPORT ElError ElSpyDist_i
( ElConstDistMatrix_i A, const char* title, ElInt tol );
EL_EXPORT ElError ElSpyDist_s
( ElConstDistMatrix_s A, const char* title, float tol );
EL_EXPORT ElError ElSpyDist_d
( ElConstDistMatrix_d A, const char* title, double tol );
EL_EXPORT ElError ElSpyDist_c
( ElConstDistMatrix_c A, const char* title, float tol );
EL_EXPORT ElError ElSpyDist_z
( ElConstDistMatrix_z A, const char* title, double tol );

/* Write
   ===== */
EL_EXPORT ElError ElWrite_i
( ElConstMatrix_i A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWrite_s
( ElConstMatrix_s A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWrite_d
( ElConstMatrix_d A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWrite_c
( ElConstMatrix_c A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWrite_z
( ElConstMatrix_z A, const char* basename, ElFileFormat format,
  const char* title );

EL_EXPORT ElError ElWriteDist_i
( ElConstDistMatrix_i A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWriteDist_s
( ElConstDistMatrix_s A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWriteDist_d
( ElConstDistMatrix_d A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWriteDist_c
( ElConstDistMatrix_c A, const char* basename, ElFileFormat format,
  const char* title );
EL_EXPORT ElError ElWriteDist_z
( ElConstDistMatrix_z A, const char* basename, ElFileFormat format,
  const char* title );

#ifdef __cplusplus
} // extern "C"
#endif

#endif /* ifndef EL_IO_C_H */