text:
package infrastructure_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/cloudfoundry/bosh-agent/infrastructure"
	fakeplat "github.com/cloudfoundry/bosh-agent/platform/fakes"
	boshlog "github.com/cloudfoundry/bosh-utils/logger"
)

var _ = Describe("SettingsSourceFactory", func() {
	Describe("New", func() {
		var (
			options  SettingsOptions
			platform *fakeplat.FakePlatform
			logger   boshlog.Logger
			factory  SettingsSourceFactory
		)

		BeforeEach(func() {
			options = SettingsOptions{}
			platform = fakeplat.NewFakePlatform()
			logger = boshlog.NewLogger(boshlog.LevelNone)
		})

		JustBeforeEach(func() {
			factory = NewSettingsSourceFactory(options, platform, logger)
		})

		Context("when UseRegistry is set to true", func() {
			BeforeEach(func() {
				options.UseRegistry = true
			})

			ItConfiguresSourcesToUseRegistry := func(useServerName bool) {
				Context("when using HTTP source", func() {
					BeforeEach(func() {
						options.Sources = []SourceOptions{
							HTTPSourceOptions{URI: "http://fake-url"},
						}
					})

					It("returns a settings source that uses HTTP to fetch settings", func() {
						resolver := NewRegistryEndpointResolver(NewDigDNSResolver(platform.GetRunner(), logger))
						httpMetadataService := NewHTTPMetadataService("http://fake-url", nil, "", "", "", resolver, platform, logger)
						multiSourceMetadataService := NewMultiSourceMetadataService(httpMetadataService)
						registryProvider := NewRegistryProvider(multiSourceMetadataService, platform, useServerName, platform.GetFs(), logger)
						httpSettingsSource := NewComplexSettingsSource(multiSourceMetadataService, registryProvider, logger)

						settingsSource, err := factory.New()
						Expect(err).ToNot(HaveOccurred())
						Expect(settingsSource).To(Equal(httpSettingsSource))
					})
				})

				Context("when using ConfigDrive source", func() {
					BeforeEach(func() {
						options.Sources = []SourceOptions{
							ConfigDriveSourceOptions{
								DiskPaths: []string{"/fake-disk-path"},

								MetaDataPath: "fake-meta-data-path",
								UserDataPath: "fake-user-data-path",

								SettingsPath: "fake-settings-path",
							},
						}
					})

					It("returns a settings source that uses config drive to fetch settings", func() {
						resolver := NewRegistryEndpointResolver(NewDigDNSResolver(platform.GetRunner(), logger))
						configDriveMetadataService := NewConfigDriveMetadataService(
							resolver,
							platform,
							[]string{"/fake-disk-path"},
							"fake-meta-data-path",
							"fake-user-data-path",
							logger,
						)
						multiSourceMetadataService := NewMultiSourceMetadataService(configDriveMetadataService)
						registryProvider := NewRegistryProvider(multiSourceMetadataService, platform, useServerName, platform.GetFs(), logger)
						configDriveSettingsSource := NewComplexSettingsSource(multiSourceMetadataService, registryProvider, logger)

						settingsSource, err := factory.New()
						Expect(err).ToNot(HaveOccurred())
						Expect(settingsSource).To(Equal(configDriveSettingsSource))
					})
				})

				Context("when using File source", func() {
					BeforeEach(func() {
						options.Sources = []SourceOptions{
							FileSourceOptions{
								MetaDataPath: "fake-meta-data-path",
								UserDataPath: "fake-user-data-path",

								SettingsPath: "fake-settings-path",
							},
						}
					})

					It("returns a settings source that uses file to fetch settings", func() {
						fileMetadataService := NewFileMetadataService(
							"fake-meta-data-path",
							"fake-user-data-path",
							"fake-settings-path",
							platform.GetFs(),
							logger,
						)
						multiSourceMetadataService := NewMultiSourceMetadataService(fileMetadataService)
						registryProvider := NewRegistryProvider(multiSourceMetadataService, platform, useServerName, platform.GetFs(), logger)
						fileSettingsSource := NewComplexSettingsSource(multiSourceMetadataService, registryProvider, logger)

						settingsSource, err := factory.New()
						Expect(err).ToNot(HaveOccurred())
						Expect(settingsSource).To(Equal(fileSettingsSource))
					})
				})

				Context("when using CDROM source", func() {
					BeforeEach(func() {
						options.Sources = []SourceOptions{
							CDROMSourceOptions{
								FileName: "fake-file-name",
							},
						}
					})

					It("returns error because it is not supported", func() {
						_, err := factory.New()
						Expect(err).To(HaveOccurred())
						Expect(err.Error()).To(ContainSubstring("CDROM source is not supported when registry is used"))
					})
				})
			}

			Context("when UseServerName is set to true", func() {
				BeforeEach(func() { options.UseServerName = true })
				ItConfiguresSourcesToUseRegistry(true)
			})

			Context("when UseServerName is set to false", func() {
				BeforeEach(func() { options.UseServerName = false })
				ItConfiguresSourcesToUseRegistry(false)
			})
		})

		Context("when UseRegistry is set to false", func() {
			Context("when using HTTP source", func() {
				BeforeEach(func() {
					options = SettingsOptions{
						Sources: []SourceOptions{
							HTTPSourceOptions{},
						},
					}
				})

				It("returns error because it is not supported", func() {
					_, err := factory.New()
					Expect(err).To(HaveOccurred())
					Expect(err.Error()).To(ContainSubstring("HTTP source is not supported without registry"))
				})
			})

			Context("when using ConfigDrive source", func() {
				BeforeEach(func() {
					options = SettingsOptions{
						Sources: []SourceOptions{
							ConfigDriveSourceOptions{
								DiskPaths: []string{"/fake-disk-path"},

								MetaDataPath: "fake-meta-data-path",

								SettingsPath: "fake-settings-path",
							},
						},
					}
				})

				It("returns a settings source that uses config drive to fetch settings", func() {
					configDriveSettingsSource := NewConfigDriveSettingsSource(
						[]string{"/fake-disk-path"},
						"fake-meta-data-path",
						"fake-settings-path",
						platform,
						logger,
					)

					multiSettingsSource, err := NewMultiSettingsSource(configDriveSettingsSource)
					Expect(err).ToNot(HaveOccurred())

					settingsSource, err := factory.New()
					Expect(err).ToNot(HaveOccurred())
					Expect(settingsSource).To(Equal(multiSettingsSource))
				})
			})

			Context("when using File source", func() {
				BeforeEach(func() {
					options = SettingsOptions{
						Sources: []SourceOptions{
							FileSourceOptions{},
						},
					}
				})

				It("returns error because it is not supported", func() {
					_, err := factory.New()
					Expect(err).To(HaveOccurred())
					Expect(err.Error()).To(ContainSubstring("File source is not supported without registry"))
				})
			})

			Context("when using CDROM source", func() {
				BeforeEach(func() {
					options = SettingsOptions{
						Sources: []SourceOptions{
							CDROMSourceOptions{
								FileName: "fake-file-name",
							},
						},
					}
				})

				It("returns a settings source that uses the CDROM to fetch settings", func() {
					cdromSettingsSource := NewCDROMSettingsSource(
						"fake-file-name",
						platform,
						logger,
					)

					multiSettingsSource, err := NewMultiSettingsSource(cdromSettingsSource)
					Expect(err).ToNot(HaveOccurred())

					settingsSource, err := factory.New()
					Expect(err).ToNot(HaveOccurred())
					Expect(settingsSource).To(Equal(multiSettingsSource))
				})
			})
		})
	})
})


text:
/*
 * Matthew Huizar
 * ITSE 1430
 * 11/20/2017
 */
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MovieLib
{
    /// Represents a movie.
    public class Movie : IValidatableObject
    {
        /// Gets or sets the unique identifier.
        public int Id { get; set; }

        /// Gets or sets the title.
        /// <value>Never returns null.</value>
        public string Title
        {
            get => _title ?? "";
            set => _title = value?.Trim();
        }

        /// Gets or sets the description.
        public string Description
        {
            get => _description ?? "";
            set => _description = value?.Trim();
        }

        /// Gets or sets the length.
        public int Length { get; set; } = 0;

        /// Determines if owned.
        public bool IsOwned { get; set; }

        public override string ToString() => Title;

        /// Validates the object.
        /// <returns>The error message or null.</returns>
        public IEnumerable<ValidationResult> Validate( ValidationContext validationContext )
        {
            //Name cannot be empty
            if (String.IsNullOrEmpty(Title))
                yield return new ValidationResult("Title cannot be empty.", new[] { nameof(Title) });

            //Length >= 0
            if (Length < 0)
                yield return new ValidationResult("Length must be >= 0.", new[] { nameof(Length) });
        }

        private string _title;
        private string _description;
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
 * This will be removed in next versions as it is not handled in the babel-loader
 * See: https://github.com/geowarin/friendly-errors-webpack-plugin/issues/2
 */
function cleanStackTrace(message) {
  return message
    .replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, ''); // at ... ...:x:y
}

function cleanMessage(message) {
  return message
    .replace('Module build failed: ', '');
}

function isBabelSyntaxError(e) {
  return e.name === 'ModuleBuildError' &&
    e.message.indexOf('SyntaxError') >= 0;
}

function transform(error) {
  if (isBabelSyntaxError(error)) {
    return Object.assign({}, error, {
      message: cleanStackTrace(cleanMessage(error.message) + '\n'),
      severity: 1000,
      name: 'Syntax Error',
    });
  }

  return error;
}

module.exports = transform;


text:
import {
  TestComponentBuilder,
  describe,
  expect,
  injectAsync,
  it
} from 'angular2/testing';
import {Component} from 'angular2/core';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {AboutComponent} from './about.component';

export function main() {
  describe('About component', () => {
    it('should work',
      injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        return tcb.createAsync(TestComponent)
          .then((rootTC) => {
            let aboutDOMEl = rootTC.debugElement.children[0].nativeElement;

            expect(DOM.querySelectorAll(aboutDOMEl, 'h2')[0].textContent).toEqual('Features');
          });
      }));
  });
}

@Component({
  selector: 'test-cmp',
  directives: [AboutComponent],
  template: '<sd-about></sd-about>'
})
class TestComponent {}


text:
module AddressHelper
end


text:
<!--pytest-codeblocks:skipfile-->
<!-- markdownlint-disable -->

# Installation

Quilt has two user-facing components:

* A Python client
* A web catalog

## Python client

Python 3.6 or higher is required.

```bash
$ pip install quilt3[pyarrow]
```

If you do not need to serialize and deserialize dataframes with Quilt, you can
obtain a smaller install, useful in disk-constrained environments like AWS Lambda,
with `pip install quilt3`.

If you plan to use [Quilt Catalog Local Development Mode](Catalog/LocalMode.md),
add `catalog` extra while installing `quilt3`, e.g.:

```bash
$ pip install quilt3[catalog,pyarrow]
```

If you wish to use AWS resources, such as S3 buckets, you will need valid AWS credentials.
If this is your first time using the AWS CLI, run the following:

```bash
$ pip install awscli
$ aws configure
```

If you are already using the AWS CLI, you may use your existing profile, or [create a new profile](https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html).

### Developer

Install the current Quilt client from `master`:

```bash
$ pip install git+https://github.com/quiltdata/quilt.git#subdirectory=api/python
```

## Web catalog and backend services (on AWS)

See [Enterprise install](technical-reference.md) for installation instructions.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Pisteidenlaskija</string>
    <string name="player_name_label">Pelaaja Nimi</string>
    <string name="main_default_name">Pelaaja</string>
    <string name="large_number_error_toast">Virhe: pistemäärä on liian suuri</string>
    <string name="image_player_icon">Player-symboli</string>
    <string name="image_group_icon">Ryhmäkuvake</string>
    <string name="hint_player_name">Nimi</string>
    <string name="editor_activity_title_edit_name">Muokkaa Nimeä</string>
    <string name="editor_activity_title_add_score">Lisää pisteitä</string>
    <string name="edit_player_current_score">Nykyinen pistemäärä</string>
    <string name="action_save">Tallentaa</string>
    <string name="action_reset_scores">Nollaa Tulokset</string>
    <string name="action_edit">Muokata</string>
    <string name="action_delete_all_players">Poista kaikki Pelaajat</string>
    <string name="action_delete">Poistaa</string>
    <string name="action_donate">Lahjoita kehittäjälle</string>
    <string name="donate_title">Lahjoittaa</string>
    <string name="donate_greeting">Hei!</string>
    <string name="donate_message">Nimeni on Amanda. Jos käytät tätä sovellusta, jonka olen kehittänyt, harkitse lahjoitussovelluksen ostamista. Lahjoitussovellus ei tee mitään, mutta lahjoituksesi osoittaa minulle, että vapaa-aika-mainosten sovellusten kehittämiseen käytetty aika on arvostettu. Kiitos!</string>
    <string name="button_donate">Hanki se Google Playssa</string>
    <string name="Small">Pieni</string>
    <string name="large">Suuri</string>
    <string name="medium">keskikokoinen</string>
    <string name="small_heart">pieni sydän</string>
    <string name="medium_heart">keskimmäinen sydän</string>
    <string name="large_heart">suuri sydän</string>
 </resources>


text:
package edu.usc.pgroup.floe.flake.messaging.dispersion;

/**
 * @author kumbhare
 */
public interface PelletUpdateListener {
    /**
     * Called whenever a new pellet is added.
     * @param pelletId pellet instance id which has been added.
     */
    void pelletAdded(String pelletId);

    /**
     * Called whenever a pellet is removed.
     * @param pelletId pellet instance id which has been added.
     */
    void pelletRemoved(String pelletId);
}


text:
""" A viewer for mlab scene. Adds a button to open up the engine.
"""

# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.

# Standard library imports
from os.path import join

# Enthought library imports
from tvtk.tools.ivtk import IVTK
from tvtk.pyface.api import DecoratedScene
from traits.api import Callable
from pyface.api import ImageResource
from pyface.action.api import Action, Group
from pyface.resource.api import resource_path

# Local imports
from mayavi.core.common import error
from mayavi.preferences.api import set_scene_preferences, \
        get_scene_preferences

###############################################################################
# A decorated scene with an additional button.
###############################################################################
class MayaviScene(DecoratedScene):
    """ A scene UI, similar to a decorated scene, but with more buttons.
    """

    image_search_path = [join(resource_path(), 'images'), ]

    ##########################################################################
    # Non-public interface.
    ##########################################################################
    def show_engine(self):
        """ Open the engine view corresponding to the engine of the
            scene.
        """
        from mayavi.core.registry import registry
        from mayavi.core.ui.engine_rich_view import EngineRichView
        try:
            engine = registry.find_scene_engine(self)
        except TypeError:
            error('This scene is not managed by Mayavi')
        return EngineRichView(engine=engine).scene_editing_view(scene=self)

    ######################################################################
    # Trait handlers.
    ######################################################################
    def _actions_default(self):
        actions = [ Group(
                    Action(tooltip="View the Mayavi pipeline",
                        image=ImageResource('m2',
                                search_path=self.image_search_path),
                        on_perform=self.show_engine,
                        ),
                        ),
                        ]
        actions.extend(DecoratedScene._actions_default(self))
        return actions

def mayavi_scene_factory(parent):
    """A mayavi scene factory that creates a scene with preferences
    appropriately set."""
    p = get_scene_preferences()
    s = MayaviScene(parent, stereo=p['stereo'])
    set_scene_preferences(s, p)
    return s

###############################################################################
# A viewer making use of the MayaviScene
###############################################################################
class MayaviViewer(IVTK):
    """ A viewer window for mlab.
    """

    _scene_factory = Callable(mayavi_scene_factory)

    def _size_default(self):
        return (400, 300)

def viewer_factory(size=(400, 350)):
    viewer = MayaviViewer()
    viewer.menu_bar_manager = None
    viewer.size=size
    viewer.open()
    return viewer

if __name__ == '__main__':
    from mayavi.tools.show import show
    viewer_factory()
    show()


text:
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <linux/io.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/addrspace.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <asm/mmu.h>

/*
 * Remap an arbitrary physical address space into the kernel virtual
 * address space. Needed when the kernel wants to access high addresses
 * directly.
 *
 * NOTE! We need to allow non-page-aligned mappings too: we will obviously
 * have to convert them into an offset in a page-aligned mapping, but the
 * caller shouldn't need to know that small detail.
 */
void __iomem * __init_refok
__ioremap_caller(phys_addr_t phys_addr, unsigned long size,
		 pgprot_t pgprot, void *caller)
{
	struct vm_struct *area;
	unsigned long offset, last_addr, addr, orig_addr;
	void __iomem *mapped;

	/* Don't allow wraparound or zero size */
	last_addr = phys_addr + size - 1;
	if (!size || last_addr < phys_addr)
		return NULL;

	/*
	 * If we can't yet use the regular approach, go the fixmap route.
	 */
	if (!mem_init_done)
		return ioremap_fixed(phys_addr, size, pgprot);

	/*
	 * First try to remap through the PMB.
	 * PMB entries are all pre-faulted.
	 */
	mapped = pmb_remap_caller(phys_addr, size, pgprot, caller);
	if (mapped && !IS_ERR(mapped))
		return mapped;

	/*
	 * Mappings have to be page-aligned
	 */
	offset = phys_addr & ~PAGE_MASK;
	phys_addr &= PAGE_MASK;
	size = PAGE_ALIGN(last_addr+1) - phys_addr;

	/*
	 * Ok, go for it..
	 */
	area = get_vm_area_caller(size, VM_IOREMAP, caller);
	if (!area)
		return NULL;
	area->phys_addr = phys_addr;
	orig_addr = addr = (unsigned long)area->addr;

	if (ioremap_page_range(addr, addr + size, phys_addr, pgprot)) {
		vunmap((void *)orig_addr);
		return NULL;
	}

	return (void __iomem *)(offset + (char *)orig_addr);
}
EXPORT_SYMBOL(__ioremap_caller);

/*
 * Simple checks for non-translatable mappings.
 */
static inline int iomapping_nontranslatable(unsigned long offset)
{
#ifdef CONFIG_29BIT
	/*
	 * In 29-bit mode this includes the fixed P1/P2 areas, as well as
	 * parts of P3.
	 */
	if (PXSEG(offset) < P3SEG || offset >= P3_ADDR_MAX)
		return 1;
#endif

	return 0;
}

void __iounmap(void __iomem *addr)
{
	unsigned long vaddr = (unsigned long __force)addr;
	struct vm_struct *p;

	/*
	 * Nothing to do if there is no translatable mapping.
	 */
	if (iomapping_nontranslatable(vaddr))
		return;

	/*
	 * There's no VMA if it's from an early fixed mapping.
	 */
	if (iounmap_fixed(addr) == 0)
		return;

	/*
	 * If the PMB handled it, there's nothing else to do.
	 */
	if (pmb_unmap(addr) == 0)
		return;

	p = remove_vm_area((void *)(vaddr & PAGE_MASK));
	if (!p) {
		printk(KERN_ERR "%s: bad address %p\n", __func__, addr);
		return;
	}

	kfree(p);
}
EXPORT_SYMBOL(__iounmap);


text:
#ifndef OSDINSTANCE_HPP_
#define OSDINSTANCE_HPP_

#include <GL/gl.h>
#include <string>
#include <ft2build.h>
#include <boost/format.hpp>
#include FT_FREETYPE_H

namespace glxosd {
class ConfigurationManager;
class FontRenderer;
class OSDInstance {
private:
	bool firstFrame;
	int currentFrameCount; // The number of frames from the last FPS calculation
	uint64_t previousTime; //The time of the previous FPS calculation
	double framesPerSecond; //Current FPS
	FontRenderer *renderer;

	std::string frameLoggingMessage;

	std::string osdText;
	std::string frameLoggingDumpInProgressMessage;
	boost::format fpsFormat;

	void update(long currentMilliseconds);
	void renderText(unsigned int width, unsigned int height);
	void createFontRenderer(ConfigurationManager &configurationManager);

public:
	OSDInstance();
	void render(unsigned int width, unsigned int height);
	virtual ~OSDInstance();
};
} /* namespace glxosd */
#endif


text:
import types from './types.json'
import foundations from './foundations.json'
import oxides from './oxides.json'
import acids from './acids.json'
import salts from './salts.json'

export default {
  state: {
    types,
    substances: [].concat(oxides, foundations, acids, salts),
    favorites: JSON.parse(localStorage.getItem('favorites')) || [],
  },
  getters: {
    isFavotite: (state) => (title) => {
      return state.favorites.find((sub) => (sub.title.search(title) !== -1 || sub.title === title));
    },
    getType: (state) => (type) => {
      return state.types.find((item) => item.type === type);
    },
    getSubstances: (state) => (type) => {
      let subs = [];
      state.substances.forEach((item) => {
        if(item.type === type) subs.push(item);
      });
      return subs;
    }
  },
  mutations: {
    addFavorite(state, sub) {
      state.favorites.push(sub);
      localStorage.setItem('favorites', JSON.stringify(state.favorites));
    },
    removeFavorite(state, sub) {
      state.favorites.forEach((item, i) => {
        if(item.title.search(sub.title) !== -1 || item.title === sub.title) state.favorites.splice(i, 1);
      });
      localStorage.setItem('favorites', JSON.stringify(state.favorites));
    }
  }
}


text:
#include "pybind11/detail/common.h"
#include "pybind11/pybind11.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"

namespace {

inline int DataTypeId(tensorflow::DataType dt) { return static_cast<int>(dt); }

// A variant of tensorflow::DataTypeString which uses fixed-width names
// for floating point data types. This behavior is compatible with that of
// existing pure Python DType.
const std::string DataTypeStringCompat(tensorflow::DataType dt) {
  switch (dt) {
    case tensorflow::DataType::DT_HALF:
      return "float16";
    case tensorflow::DataType::DT_HALF_REF:
      return "float16_ref";
    case tensorflow::DataType::DT_FLOAT:
      return "float32";
    case tensorflow::DataType::DT_FLOAT_REF:
      return "float32_ref";
    case tensorflow::DataType::DT_DOUBLE:
      return "float64";
    case tensorflow::DataType::DT_DOUBLE_REF:
      return "float64_ref";
    default:
      return tensorflow::DataTypeString(dt);
  }
}

}  // namespace

namespace tensorflow {

constexpr DataTypeSet kNumPyIncompatibleTypes =
    ToSet(DataType::DT_RESOURCE) | ToSet(DataType::DT_VARIANT);

inline bool DataTypeIsNumPyCompatible(DataType dt) {
  return !kNumPyIncompatibleTypes.Contains(dt);
}

}  // namespace tensorflow

namespace py = pybind11;

PYBIND11_MODULE(_dtypes, m) {
  py::class_<tensorflow::DataType>(m, "DType")
      .def(py::init([](py::object obj) {
        auto id = static_cast<int>(py::int_(obj));
        if (tensorflow::DataType_IsValid(id) &&
            id != static_cast<int>(tensorflow::DT_INVALID)) {
          return static_cast<tensorflow::DataType>(id);
        }
        throw py::type_error(
            py::str("%d does not correspond to a valid tensorflow::DataType")
                .format(id));
      }))
      // For compatibility with pure-Python DType.
      .def_property_readonly("_type_enum", &DataTypeId)
      .def_property_readonly(
          "as_datatype_enum", &DataTypeId,
          "Returns a `types_pb2.DataType` enum value based on this data type.")

      .def_property_readonly("name",
                             [](tensorflow::DataType self) {
#if PY_MAJOR_VERSION < 3
                               return py::bytes(DataTypeStringCompat(self));
#else
                               return DataTypeStringCompat(self);
#endif
                             })
      .def_property_readonly(
          "size",
          [](tensorflow::DataType self) {
            return tensorflow::DataTypeSize(tensorflow::BaseType(self));
          })

      .def("__repr__",
           [](tensorflow::DataType self) {
             return py::str("tf.{}").format(DataTypeStringCompat(self));
           })
      .def("__str__",
           [](tensorflow::DataType self) {
             return py::str("<dtype: {!r}>")
#if PY_MAJOR_VERSION < 3
                 .format(py::bytes(DataTypeStringCompat(self)));
#else
                 .format(DataTypeStringCompat(self));
#endif
           })
      .def("__hash__", &DataTypeId)

      .def_property_readonly(
          "is_numpy_compatible",
          [](tensorflow::DataType self) {
            return tensorflow::DataTypeIsNumPyCompatible(
                tensorflow::BaseType(self));
          },
          "Returns whether this data type has a compatible NumPy data type.")

      .def_property_readonly(
          "is_bool",
          [](tensorflow::DataType self) {
            return tensorflow::BaseType(self) == tensorflow::DT_BOOL;
          },
          "Returns whether this is a boolean data type.")
      .def_property_readonly(
          "is_complex",
          [](tensorflow::DataType self) {
            return tensorflow::DataTypeIsComplex(tensorflow::BaseType(self));
          },
          "Returns whether this is a complex floating point type.")
      .def_property_readonly(
          "is_floating",
          [](tensorflow::DataType self) {
            return tensorflow::DataTypeIsFloating(tensorflow::BaseType(self));
          },
          "Returns whether this is a (non-quantized, real) floating point "
          "type.")
      .def_property_readonly(
          "is_integer",
          [](tensorflow::DataType self) {
            return tensorflow::DataTypeIsInteger(tensorflow::BaseType(self));
          },
          "Returns whether this is a (non-quantized) integer type.")
      .def_property_readonly(
          "is_quantized",
          [](tensorflow::DataType self) {
            return tensorflow::DataTypeIsQuantized(tensorflow::BaseType(self));
          },
          "Returns whether this is a quantized data type.")
      .def_property_readonly(
          "is_unsigned",
          [](tensorflow::DataType self) {
            return tensorflow::DataTypeIsUnsigned(tensorflow::BaseType(self));
          },
          R"doc(Returns whether this type is unsigned.

Non-numeric, unordered, and quantized types are not considered unsigned, and
this function returns `False`.)doc");
}


text:
package com.palantir.atlasdb.autobatch;

import static org.assertj.core.api.Assertions.assertThat;

import com.codahale.metrics.Histogram;
import com.codahale.metrics.Metric;
import com.google.common.collect.ImmutableMap;
import com.palantir.tritium.metrics.registry.MetricName;
import com.palantir.tritium.metrics.registry.SharedTaggedMetricRegistries;
import java.util.Map;
import org.junit.Test;

public class BatchSizeRecorderTest {
    private static final String SAFE_IDENTIFIER = "identifier";

    @Test
    public void metersResults() {
        BatchSizeRecorder batchSizeRecorder = BatchSizeRecorder.create(SAFE_IDENTIFIER, ImmutableMap.of());
        batchSizeRecorder.markBatchProcessed(5);
        batchSizeRecorder.markBatchProcessed(10);

        Histogram histogram = (Histogram) SharedTaggedMetricRegistries.getSingleton()
                .getMetrics()
                .get(MetricName.builder()
                        .safeName(BatchSizeRecorder.AUTOBATCHER_METER)
                        .putSafeTags("identifier", SAFE_IDENTIFIER)
                        .build());

        assertThat(histogram).isNotNull();
        assertThat(histogram.getCount()).isEqualTo(2);
        assertThat(histogram.getSnapshot().getMean()).isEqualTo(7.5);
    }

    @Test
    public void tagsArePassedThrough() {
        Map<String, String> customTags = ImmutableMap.<String, String>builder()
                .put("tag1", "value1")
                .put("tag2", "value2")
                .build();
        BatchSizeRecorder recorder = BatchSizeRecorder.create(SAFE_IDENTIFIER, customTags);

        recorder.markBatchProcessed(5);

        Map<MetricName, Metric> metrics =
                SharedTaggedMetricRegistries.getSingleton().getMetrics();
        assertThat(metrics.keySet())
                .anyMatch(metricName -> metricName.safeTags().entrySet().containsAll(customTags.entrySet()));
    }
}


text:
use std::io;
#[cfg(windows)]
use std::net;
use std::net::SocketAddr;

use net::connector::UdpConnector;
use net::IpVersionMode;

mod notify;
mod search;
mod ssdp;
pub mod listen;
pub mod multicast;

pub use message::multicast::Multicast;
pub use message::search::{SearchRequest, SearchResponse, SearchListener};
pub use message::notify::{NotifyMessage, NotifyListener};
pub use message::listen::Listen;

#[cfg(not(windows))]
use ifaces;

/// Multicast Socket Information
pub const UPNP_MULTICAST_IPV4_ADDR: &'static str = "239.255.255.250";
pub const UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR: &'static str = "FF02::C";
pub const UPNP_MULTICAST_PORT: u16 = 1900;

/// Default TTL For Multicast
pub const UPNP_MULTICAST_TTL: u32 = 2;

/// Enumerates different types of SSDP messages.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum MessageType {
    /// A notify message.
    Notify,
    /// A search message.
    Search,
    /// A response to a search message.
    Response,
}

#[derive(Clone)]
pub struct Config {
    pub ipv4_addr: String,
    pub ipv6_addr: String,
    pub port: u16,
    pub ttl: u32,
    pub mode: IpVersionMode,
}

impl Config {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn set_ipv4_addr<S: Into<String>>(mut self, value: S) -> Self {
        self.ipv4_addr = value.into();
        self
    }

    pub fn set_ipv6_addr<S: Into<String>>(mut self, value: S) -> Self {
        self.ipv6_addr = value.into();
        self
    }

    pub fn set_port(mut self, value: u16) -> Self {
        self.port = value;
        self
    }

    pub fn set_ttl(mut self, value: u32) -> Self {
        self.ttl = value;
        self
    }

    pub fn set_mode(mut self, value: IpVersionMode) -> Self {
        self.mode = value;
        self
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            ipv4_addr: UPNP_MULTICAST_IPV4_ADDR.to_string(),
            ipv6_addr: UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR.to_string(),
            port: UPNP_MULTICAST_PORT,
            ttl: UPNP_MULTICAST_TTL,
            mode: IpVersionMode::Any,
        }
    }
}

/// Generate `UdpConnector` objects for all local `IPv4` interfaces.
fn all_local_connectors(multicast_ttl: Option<u32>, filter: &IpVersionMode) -> io::Result<Vec<UdpConnector>> {
    trace!("Fetching all local connectors");
    map_local(|&addr| match (filter, addr) {
        (&IpVersionMode::V4Only, SocketAddr::V4(n)) |
        (&IpVersionMode::Any, SocketAddr::V4(n)) => {
            Ok(Some(try!(UdpConnector::new((*n.ip(), 0), multicast_ttl))))
        }
        (&IpVersionMode::V6Only, SocketAddr::V6(n)) |
        (&IpVersionMode::Any, SocketAddr::V6(n)) => Ok(Some(try!(UdpConnector::new(n, multicast_ttl)))),
        _ => Ok(None),
    })
}

/// Invoke the closure for every local address found on the system
///
/// This method filters out _loopback_ and _global_ addresses.
fn map_local<F, R>(mut f: F) -> io::Result<Vec<R>>
    where F: FnMut(&SocketAddr) -> io::Result<Option<R>>
{
    let addrs_iter = try!(get_local_addrs());

    let mut obj_list = Vec::with_capacity(addrs_iter.len());

    for addr in addrs_iter {
        trace!("Found {}", addr);
        match addr {
            SocketAddr::V4(n) if !n.ip().is_loopback() => {
                if let Some(x) = try!(f(&addr)) {
                    obj_list.push(x);
                }
            }
            // Filter all loopback and global IPv6 addresses
            SocketAddr::V6(n) if !n.ip().is_loopback() && !n.ip().is_global() => {
                if let Some(x) = try!(f(&addr)) {
                    obj_list.push(x);
                }
            }
            _ => (),
        }
    }

    Ok(obj_list)
}

/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(windows)]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
    let host_iter = try!(net::lookup_host(""));
    Ok(host_iter.collect())
}

/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(not(windows))]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
    let iface_iter = try!(ifaces::Interface::get_all()).into_iter();
    Ok(iface_iter.filter(|iface| iface.kind != ifaces::Kind::Packet)
        .filter_map(|iface| iface.addr)
        .collect())
}


text:
import React from 'react';
import './Loading.scss'

const Loading = () => (
  <div className="loader">
    Loading...
  </div>
);

export default Loading;


text:
NSString *const kWAYTheDarkSideGlobalPersistentDomainInterfaceStyleKey = @"AppleInterfaceStyle";
NSString *const kWAYTheDarkSideGlobalPersistentDomainDarkInterfaceStyleValue = @"Dark";
NSString *const kWAYTheDarkSideAppleInterfaceThemeChangedNotification = @"AppleInterfaceThemeChangedNotification";

static BOOL _WAYTheDarkSideRecentValue;
static BOOL _WAYTheDarkSideValueKnown;
static NSMapTable *_WAYTheDarkSideEnteringBlocksMapTable;
static NSMapTable *_WAYTheDarkSideLeavingBlocksMapTable;

@implementation WAYTheDarkSide

+ (void) initialize {

	// Initialize two NSMapTables which hold the blocks per object.
	// NSMapTables are used since NSDictionary copies the keys and not all objects implement NSCopying
	_WAYTheDarkSideEnteringBlocksMapTable = [NSMapTable weakToStrongObjectsMapTable];
	_WAYTheDarkSideLeavingBlocksMapTable = [NSMapTable weakToStrongObjectsMapTable];

	// Subscribe to the Distributed Notification for the Interface Style switch
	[[NSDistributedNotificationCenter defaultCenter] addObserverForName:kWAYTheDarkSideAppleInterfaceThemeChangedNotification
																 object:nil
																  queue:[NSOperationQueue mainQueue]
															 usingBlock:^(NSNotification *notification) {
																 BOOL isDarkMode = [self applicationIsOnTheDarkSide];
																 // The blocks are only performed if an actual change happened
																 if (!_WAYTheDarkSideValueKnown || _WAYTheDarkSideRecentValue!=isDarkMode) {
																	 [self _broadcastDarkMode:isDarkMode];
																	 _WAYTheDarkSideRecentValue = isDarkMode;
																	 _WAYTheDarkSideValueKnown = YES;
																 }
															 }];
}

+ (BOOL) applicationReadyForTheDarkSide {
	return NSAppKitVersionNumber > NSAppKitVersionNumber10_9;
}

+ (BOOL) applicationIsOnTheDarkSide {
	NSDictionary *globalPersistentDomain = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain];
	@try {
		NSString *interfaceStyle = [globalPersistentDomain valueForKey:kWAYTheDarkSideGlobalPersistentDomainInterfaceStyleKey];
		return [interfaceStyle isEqualToString:kWAYTheDarkSideGlobalPersistentDomainDarkInterfaceStyleValue];
	}
	@catch (NSException *exception) {
		return NO;
	}
}

+ (void) _broadcastDarkMode:(BOOL) isDarkMode {
	NSEnumerator *e = [(isDarkMode)?_WAYTheDarkSideEnteringBlocksMapTable:_WAYTheDarkSideLeavingBlocksMapTable objectEnumerator];

	for ( void(^block)(void) in e.allObjects) {
		if (block)
			block();
	}
}

+ (void) welcomeObject:(id)object withBlock:(void (^)(void))eventHandler
		   immediately:(BOOL)flag {
#ifdef DEBUG
	if ([_WAYTheDarkSideEnteringBlocksMapTable objectForKey:object]) {
		NSLog(@"WARNING: Re-defining block for object '%@' which is performed while entering the Dark Mode.", object);
	}
#endif
	[_WAYTheDarkSideEnteringBlocksMapTable setObject:[eventHandler copy]
												forKey:object];
	if (flag && [self applicationIsOnTheDarkSide]) {
		eventHandler();
	}
}

+ (void) outcastObject:(id)object withBlock:(void (^)(void))eventHandler
		   immediately:(BOOL)flag {
#ifdef DEBUG
	if ([_WAYTheDarkSideLeavingBlocksMapTable objectForKey:object]) {
		NSLog(@"WARNING: Re-defining block for object '%@' which is performed while entering the Dark Mode.", object);
	}
#endif
	[_WAYTheDarkSideLeavingBlocksMapTable setObject:[eventHandler copy]
											   forKey:object];
	if (flag && ![self applicationIsOnTheDarkSide]) {
		eventHandler();
	}
}

+ (void) welcomeApplicationWithBlock:(void (^)(void))eventHandler immediately:(BOOL)flag {
	[self welcomeObject:[NSApplication sharedApplication].delegate
			  withBlock:eventHandler
			immediately:flag];
}

+ (void) outcastApplicationWithBlock:(void (^)(void))eventHandler immediately:(BOOL)flag {
	[self outcastObject:[NSApplication sharedApplication].delegate
			  withBlock:eventHandler
			immediately:flag];
}

@end


text:
function [fun,pp,Mspline,splinePrs]=fitSpline(knots,x,y,smoothness,extrapDeg);
% [fun,pp,Mspline,splinePrs]=fitSpline(knots,x,y,smoothness,extrapDeg);
%
%  Fit a function y = f(x) with a spline defined using a set of knots
% (discontinuities of a piecewise-polynomial function), using MSE loss
%
% Inputs:
%   knots - breaks between polynomial pieces
%   x,y - spline minimizes (f(x)-y).^2
%   smoothness - derivs of 1 less are continuous
%           (e.g., smoothness=3 -> 2nd derivs are continuous)
%   extrapDeg - degree polynomial for extrapolation on ends
%
% Outputs:
%   fun - function pointer to nonlinearity (uses 'ppval')
%   pp - piecewise polynomial structure
%   Mspline - matrix for converting params to spline coeffs
%   splinePrs -  coefs=Mspline*splinePrse

Mspline = splineParamMatrix(knots,smoothness,extrapDeg);
prs0 = zeros(size(Mspline,2),1);  % Initial params

%fprintf('(fitSpline) fitting spline with mse\r');
opts = optimset('maxiter', 1e4, 'maxfunevals',1e6,'display','off','LargeScale','off');
[splinePrs,err] = fminunc(@splineMSE,prs0,opts,knots,x(:),y(:),Mspline);

% Create function handle for resulting spline
[fun,pp] = makeSplineFun(knots, Mspline*splinePrs);

% ================ LOSS FUNCTION =====================
function err = splineMSE(prs, knots,x,y,M);
% MSE loss for spline fitting

ff = makeSplineFun(knots, M*prs);
err = sum((y-ff(x)).^2);


text:
module Editor
  module Views
    class ApplicationLayout
      include Editor::Layout
      require_relative '../../../lib/ui/links'
      include UI::Links

      def mathjax_script(doc)
        if doc and doc.render_options['format']
          "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
        else
          ''
        end
      end

      def export_link(document)
        # link_to 'Export', "/editor/export/#{document.id}"
        # image_link '/images/export.png', "/editor/export/#{document.id}", "export document #"
        "/export_latex/#{document.id}"
        image_link '/images/export.png', "/editor/export_latex/#{document.id}", "export document as .adoc and .tex"
      end

      #####################################################
      #
      #   3. EDITOR LINKS
      #
      #####################################################

      def edit_document_link(session, document_id)
        link_to 'Back to editor', basic_link("#{current_user(session).screen_name}",   "editor/document/#{document_id}")
      end

      def new_section_link(document)
        #   html.tag(:a, 'New section', href: "/editor/new_section/#{document.id}")
        image_link '/images/new_section.png', "/editor/new_section/#{document.id}?child", 'new section'
      end

      def add_pdf_link(document)
        image_link '/images/attach.png', "/editor/add_pdf/#{document.id}", 'new section with attached image or pdf file'
      end

      def new_associated_document_link(document)
        image_link '/images/site.png', "/editor/new_associated_document/#{document.id}", 'new associated document'
      end

      def move_section_to_level_of_parent_link(document)
        image_link '/images/move_to_parent_level.png', "/editor/move/#{document.id}/?move_to_parent_level", 'move section to level of parent'
      end

      def move_section_to_child_level_link(document)
        image_link '/images/move_to_child_level.png', "/editor/move/#{document.id}/?move_to_child_level", 'make section child of ...'
      end

      def move_up_in_toc_link(document)
        image_link '/images/move_up.png', "/editor/move/#{document.id}/?move_up_in_toc", 'move section up in toc'
      end

      def move_down_in_toc_link(document)
        image_link '/images/move_down.png', "/editor/move/#{document.id}/?move_down_in_toc", 'move section down in toc'
      end

      def delete_document_link(document)
        image_link('/images/delete_document.png', "/editor/prepare_to_delete_document/#{document.id}?tree", 'delete document')
      end

      def delete_section_link(document)
        image_link('/images/delete_section.png', "/editor/prepare_to_delete_document/#{document.id}?section", 'delete section')
      end

      def publish_document_link(document)
        if document.root_document.acl_get(:world) =~ /r/
          image_link('/images/publish_document_green.png', "/editor/publish_all/#{document.id}", 'publish/unpublish document')
        else
          image_link('/images/publish_document_blue.png', "/editor/publish_all/#{document.id}", 'publish/unpublish document')
        end
      end

      def publish_section_link(document)
        if document.acl_get(:world) =~ /r/
          image_link('/images/publish_section_green.png', "/editor/publish_section/#{document.id}", 'publish/unpublish section')
        else
          image_link('/images/publish_section_blue.png', "/editor/publish_section/#{document.id}", 'publish/unpublish section')
        end
      end

      def check_in_out_link(document)
        # html.tag(:a, 'Check in/out', href: '#')
        image_link('/images/check_in_out.png', '#', 'check document out #')
      end

      def edit_toc_link(document)
        image_link('/images/edit_toc.png', "/editor/edit_toc/#{document.id}", 'rearrange table of contents')
      end

      def upload_file_link
        link_to 'upload', "/uploader/file"
      end

      def get_document_link(document)
        link_to 'Get', "/editor/get/#{document.id}"
      end

      def put_document_link(document)
        link_to 'Put', "/editor/put/#{document.id}"
      end

      def section_settings_link(document)
        image_link '/images/section_settings.png', "/editor/document/options/#{document.id}?section", 'section settings'
      end

      def upload_image_link(option=nil)
        # session[:current_document_id] = document.id if document
        if option == nil
          image_link '/images/upload_image.png', "/uploader/image", 'upload image'
        else
          image_link '/images/upload_image.png', "/uploader/image?#{option}", 'upload image'
        end
      end

      def export_latex_link(document)
        "/export_latex/#{document.id}"
      end

    end
  end
end


text:
(function () {
  'use strict';

  describe('LBaaS v2 Update Member List Wizard Controller', function() {
    var ctrl, workflowSpy, scope;
    var model = {
      submit: function() {
        return 'updated';
      },
      initialize: angular.noop
    };
    var workflow = 'foo';

    beforeEach(module('horizon.framework.util'));
    beforeEach(module('horizon.dashboard.project.lbaasv2'));
    beforeEach(module(function ($provide) {
      workflowSpy = jasmine.createSpy('workflow').and.returnValue(workflow);
      $provide.value('horizon.dashboard.project.lbaasv2.workflow.model', model);
      $provide.value('horizon.dashboard.project.lbaasv2.workflow.workflow', workflowSpy);
    }));
    beforeEach(inject(function ($controller, $injector) {
      scope = $injector.get('$rootScope').$new();
      spyOn(model, 'initialize').and.callThrough();
      ctrl = $controller('UpdateMemberListWizardController', {
        $scope: scope,
        $routeParams: {loadbalancerId: 'loadbalancerId',
                       poolId: 'poolId'}});
    }));

    it('defines the controller', function() {
      expect(ctrl).toBeDefined();
    });

    it('calls initialize on the given model', function() {
      expect(model.initialize).toHaveBeenCalledWith('members', false, 'loadbalancerId', 'poolId');
    });

    it('sets scope.workflow to the given workflow', function() {
      expect(scope.workflow).toBe(workflow);
    });

    it('initializes workflow with correct properties', function() {
      expect(workflowSpy).toHaveBeenCalledWith('Add/Remove Pool Members',
        'fa fa-pencil', ['members']);
    });

    it('defines scope.submit', function() {
      expect(scope.submit).toBe(model.submit);
      expect(scope.submit()).toBe('updated');
    });

  });

})();


text:
// This file contains the interface to the ESC via SPI\n
#ifdef USE_ETHERCAT

#define	_ETHERCATHW_ 1
#include "ethercat_hw.h"
#undef	_ETHERCATHW_
#define	_ETHERCATHW_ 0
#include "ethercat.h"
#include "ethercat_slave_fsm.h"
#include "ethercat_appl.h"
#include "setup.h"
#include "dio.h"

/////////////////////////////////////////////////////////////////
TSYNCMAN		TmpSyncMan;
UINT8			EscMbxReadEcatCtrl;

/////////////////////////////////////////////////////////////////////////////
void GetInterruptRegister( )
{
#if AL_EVENT_ENABLED
	DISABLE_AL_EVENT_INT;
#endif

	/* select the SPI */
	SPI_SEL = SPI_ACTIVE;
	/* reset transmission flag */
	SSPIF=0;
	/* there have to be at least 15 ns after the SPI_SEL signal was active (0) before
	   the transmission shall be started */
	/* write to SSPBUF register starts the SSI access,
	   read the sm mailbox read ecatenable byte
	   (has to be synchronous to the al event flags) */
	SSPBUF = (UINT8) (ESC_ADDR_SM_MBXREAD_ECATCTRL >> 5);
	/* SSI is busy */
	while( SSPIF == 0 );
	/* get first byte of AL Event register */

	EscAlEvent.Byte[0] = SSPBUF;

	/* reset SSI interrupt flag */
	SSPIF = 0;
	/* write to SSPBUF register starts the SSI access
	   read the sm mailbox read ecatenable byte */
	SSPBUF = (UINT8) (((ESC_ADDR_SM_MBXREAD_ECATCTRL & 0x1F) << 3) | ESC_RD);
	/* write to SSPBUF register starts the SSI access */
	while( SSPIF == 0 );
	/* get first byte of AL Event register */

	EscAlEvent.Byte[1] = SSPBUF;

	/* reset SSI interrupt flag */
	SSPIF = 0;
	/* if the SPI transmission rate is higher than 15 MBaud, the Busy detection shall be
	   done here */

	/* write to SSPBUF register starts the SSI access
	   read the sm mailbox read ecatenable byte (last byte) */
	SSPBUF = 0xFF;
	/* write to SSPBUF register starts the SSI access */
	while( SSPIF == 0 );
	/* get first byte of AL Event register */
	EscMbxReadEcatCtrl = SSPBUF;
	/* reset SSI interrupt flag */
	SSPIF = 0;
	/* there has to be at least 15 ns + CLK/2 after the transmission is finished
	   before the SPI_SEL signal shall be 1 */

	SPI_SEL = SPI_DEACTIVE;
#if AL_EVENT_ENABLED
	ENABLE_AL_EVENT_INT;
#endif
}

/////////////////////////////////////////////////////////////////////////////
void ISR_GetInterruptRegister( )
{
	/////////////////////////////////////////////////////////////////////////////////////////
	/**
	 \brief  The function operates a SPI access without addressing.

			 The first two bytes of an access to the EtherCAT ASIC always deliver the interupt
			 register. It will be saved in the global EscAlEvent
	*////////////////////////////////////////////////////////////////////////////////////////

	SPI_SEL = SPI_ACTIVE;				/* select the SPI */
	SSPIF=0;							/* reset transmission flag */

	/* there have to be at least 15 ns after the SPI_SEL signal was active (0) before
	   the transmission shall be started */
	/* write to SSPBUF register starts the SSI access,
	   read the sm mailbox read ecatenable byte
	   (has to be synchronous to the al event flags) */
	SSPBUF = 0;

	while( SSPIF == 0 );				/* SSI is busy */
	EscAlEvent.Byte[0] = SSPBUF;		/* get first byte of AL Event register */
	SSPIF = 0;							/* reset SSI interrupt flag */

	/* write to SSPBUF register starts the SSI access
	   read the sm mailbox read ecatenable byte */
	SSPBUF = ESC_RD;					/* write to SSPBUF register starts the SSI access */

	while( SSPIF == 0 );
	EscAlEvent.Byte[1] = SSPBUF;		/* get first byte of AL Event register */
	SSPIF = 0;							/* reset SSI interrupt flag */

	/* if the SPI transmission rate is higher than 15 MBaud, the Busy detection shall be
	   done here */

	SPI_SEL = SPI_DEACTIVE;
}
/////////////////////////////////////////////////////////////////////////////
void AddressingEsc( UINT16 Address, UINT8 Command )
{
	/////////////////////////////////////////////////////////////////////////////////////////
	/**
	 \param Address 	EtherCAT ASIC address ( upper limit is 0x1FFF )	for access.
	 \param Command	ESC_WR performs a write access; ESC_RD performs a read access.

	 \brief The function addresses the EtherCAT ASIC via SPI for a following SPI access.
	*////////////////////////////////////////////////////////////////////////////////////////

	UBYTETOWORD tmp;
	tmp.Word = ( Address << 3 ) | Command;

	SPI_SEL = SPI_ACTIVE;				/* select the SPI */
	SSPIF=0;							/* reset transmission flag */

	/* there have to be at least 15 ns after the SPI_SEL signal was active (0) before
	   the transmission shall be started */
	/* send the first address/command byte to the ESC */
	SSPBUF = tmp.Byte[1];

	while( !SSPIF );					/* wait until the transmission of the byte is finished */
	EscAlEvent.Byte[0] = SSPBUF;		/* get first byte of AL Event register */
	SSPIF=0;							/* reset transmission flag */
	SSPBUF = tmp.Byte[0];				/* send the second address/command byte to the ESC */
	while( !SSPIF );					/* wait until the transmission of the byte is finished */
	EscAlEvent.Byte[1] = SSPBUF;		/* get second byte of AL Event register */
	SSPIF = 0;							/* reset transmission flag */

	/* if the SPI transmission rate is higher than 15 MBaud, the Busy detection shall be
	done here */
}
/////////////////////////////////////////////////////////////////////////////
void ISR_AddressingEsc( UINT16 Address, UINT8 Command )
{
	/////////////////////////////////////////////////////////////////////////////////////////
	/**
	 \param Address 	EtherCAT ASIC address ( upper limit is 0x1FFF )	for access.
	 \param Command	ESC_WR performs a write access; ESC_RD performs a read access.

	 \brief The function addresses the EtherCAT ASIC via SPI for a following SPI access.
	*////////////////////////////////////////////////////////////////////////////////////////

	UBYTETOWORD tmp;
	char read;
	tmp.Word = ( Address << 3 ) | Command;

	/* select the SPI */
	SPI_SEL = SPI_ACTIVE;
	/* reset transmission flag */
	SSPIF=0;
	/* there have to be at least 15 ns after the SPI_SEL signal was active (0) before
	   the transmission shall be started */
	/* send the first address/command byte to the ESC */
	SSPBUF = tmp.Byte[1];
	/* wait until the transmission of the byte is finished */
	while( !SSPIF );
	read=SSPBUF; //Throw-away
	/* reset transmission flag */
	SSPIF=0;
	/* send the second address/command byte to the ESC */
	SSPBUF = tmp.Byte[0];
	/* wait until the transmission of the byte is finished */
	while( !SSPIF );
	read=SSPBUF; //Throw-away
	/* reset transmission flag */
	SSPIF = 0;

	/* if the SPI transmission rate is higher than 15 MBaud, the Busy detection shall be
	   done here */

}

/////////////////////////////////////////////////////////////////////////////
void ISR_EscReadAccess( UINT8 *pData, UINT16 Address, UINT16 Len )
{
	/////////////////////////////////////////////////////////////////////////////////////////
	/**
	 \param pData		Pointer to a byte array which holds data to write or saves read data.
	 \param Address 	EtherCAT ASIC address ( upper limit is 0x1FFF )	for access.
	 \param Len			Access size in Bytes.

	 \return	Indicates if the access was succesful ( TRUE ).

	 \brief  This function operates the SPI access to the EtherCAT ASIC.
	*////////////////////////////////////////////////////////////////////////////////////////
	UINT16 i = Len;
	UINT8 data = 0;

	/* send the address and command to the ESC */
 	ISR_AddressingEsc( Address, ESC_RD );
	/* loop for all bytes to be read */
	while ( i-- > 0 )
	{
		if ( i == 0 )
		{
			/* when reading the last byte the DI pin shall be 1 */
			data = 0xFF;
		}
		/* reset transmission flag */
		SSPIF = 0;
		/* start transmission */
		SSPBUF = data;
		/* wait until transmission finished */
		while ( !SSPIF );
		/* get data byte */
		*pData++ = SSPBUF;
	}
	/* reset transmission flag */
	SSPIF = 0;
	/* there has to be at least 15 ns + CLK/2 after the transmission is finished
	   before the SPI_SEL signal shall be 1 */
	SPI_SEL = SPI_DEACTIVE;

	/* at this time the result of the transmission can be checked */

}

/////////////////////////////////////////////////////////////////////////////
void ISR_EscWriteAccess( UINT8 *pData, UINT16 Address, UINT16 Len )
{
	/////////////////////////////////////////////////////////////////////////////////////////
	/**
	 \param pData		Pointer to a byte array which holds data to write or saves read data.
	 \param Address 	EtherCAT ASIC address ( upper limit is 0x1FFF )	for access.
	 \param Len			Access size in Bytes.

	 \return	Indicates if the access was succesful ( TRUE ).

	 \brief  This function operates the SPI access to the EtherCAT ASIC.
	*////////////////////////////////////////////////////////////////////////////////////////

	UINT16 i = Len;
	unsigned char tmp;
	/* send the address and command to the ESC */
 	ISR_AddressingEsc( Address, ESC_WR );
	/* loop for all bytes to be written */
	while ( i-- > 0 )
	{
		/* reset transmission flag */
		SSPIF = 0;
		/* start transmission */
		SSPBUF = *pData;
		/* wait until transmission finished */
		while ( !SSPIF );
		tmp=SSPBUF;  //Throw away read
		/* increment data pointer */
		pData++;
	}

	/* reset transmission flag */
	SSPIF = 0;
	/* there has to be at least 15 ns + CLK/2 after the transmission is finished
	   before the SPI_SEL signal shall be 1 */
	SPI_SEL = SPI_DEACTIVE;

	/* at this time the result of the transmission can be checked */

}
/////////////////////////////////////////////////////////////////////////////
void HW_Main(void)
{
	//Handle state changes and watchdog from main() cyclic loop
	GetInterruptRegister();

	//Handle Watchdog
	if (u16WdValue != 0 && bEcatOutputUpdateRunning && bEcatFirstOutputsReceived)
	{
#ifdef EC_USE_WATCHDOG
		//check the watchdog only in OP
		//generate the ms-timer
		long ts=get_timestamp_us();
		if ( ts-ec_wd_timestamp> EC_WATCHDOG_US)
		{
			//watchdog expired
			ec_watchdog_expired=1;
			nAlStatusCode = ALSTATUSCODE_SMWATCHDOG;
			AL_ControlInd(STATE_SAFEOP);
		}
#endif
	}

	// check AL_CONTROL event first
	if ( EscAlEvent.Byte[0] & ((UINT8) AL_CONTROL_EVENT) )
	{
		/* get the AL Control register sent by the Master to acknowledge the interrupt */
		HW_EscReadAccess( &EscAlControl.Byte[0], ESC_ADDR_ALCONTROL, sizeof(UALCONTROL) );
		/* ECAT_CHANGE_BEGIN V3.11 */
		/* acknowledge AL-Control-event and the SM-Change event (because it was handled too) */
		EscAlEvent.Byte[0] &= ~(((UINT8) AL_CONTROL_EVENT) | ((UINT8) SM_CHANGE_EVENT));
		/* ECAT_CHANGE_END V3.11 */
		AL_ControlInd(EscAlControl.Byte[0]);
	}

#if SM_CHANGE_SUPPORTED
	if ( EscAlEvent.Byte[0] & SM_CHANGE_EVENT )
	{
		// call AL_Control with status unchanged
		AL_ControlInd(nAlStatus & STATE_MASK);
		EscAlEvent.Byte[0] &= ~((UINT8) SM_CHANGE_EVENT);
	}
#endif
}
/////////////////////////////////////////////////////////////////////////////
void HW_EscReadAccess( UINT8 *pData, UINT16 Address, UINT16 Len )
{
	////////////////////////////////////////////////////////////////////////////////////////
	/**
	 \param pData		Pointer to a byte array which holds data to write or saves read data.
	 \param Address 	EtherCAT ASIC address ( upper limit is 0x1FFF )	for access.
	 \param Len			Access size in Bytes.

	 \return	Indicates if the access was succesful ( TRUE ).

	 \brief  This function operates the SPI access to the EtherCAT ASIC.
	*////////////////////////////////////////////////////////////////////////////////////////

	/* HBu 24.01.06: if the SPI will be read by an interrupt routine too the
     mailbox reading may be interrupted but an interrupted
     reading will remain in a SPI transmission fault that will
     reset the internal Sync Manager status. Therefore the reading
     will be divided in 1-byte reads with disabled interrupt */

	UINT16 i = Len;

	while ( i-- > 0 )						/* loop for all bytes to be read */
	{
#if AL_EVENT_ENABLED
		/* the reading of data from the ESC can be interrupted by the
		   AL Event ISR, in that case the address has to be reinitialized,
		   in that case the status flag will indicate an error because
		   the reading operation was interrupted without setting the last
		   sent byte to 0xFF */
		DISABLE_AL_EVENT_INT;
#endif

		AddressingEsc( Address, ESC_RD );
		/* start transmission */
		SSPBUF = 0xFF;						/* when reading the last byte the DI pin shall be 1 */
		while ( !SSPIF );					/* wait until transmission finished */
		*pData++ = SSPBUF;					/* get data byte */

		/* enable the ESC interrupt to get the AL Event ISR the chance to interrupt,
		   if the next byte is the last the transmission shall not be interrupted,
		   otherwise a sync manager could unlock the buffer, because the last was
		   read internally */
		ENABLE_AL_EVENT_INT;

		/* there has to be at least 15 ns + CLK/2 after the transmission is finished
		   before the SPI_SEL signal shall be 1 */
		SPI_SEL = SPI_DEACTIVE;

		Address++;							/* next address */
		SSPIF = 0;							/* reset transmission flag */
	}
}

/////////////////////////////////////////////////////////////////////////////
void HW_EscWriteAccess( UINT8 *pData, UINT16 Address, UINT16 Len )
{
	/////////////////////////////////////////////////////////////////////////////////////////
	/**
	 \param pData		Pointer to a byte array which holds data to write or saves read data.
	 \param Address 	EtherCAT ASIC address ( upper limit is 0x1FFF )	for access.
	 \param Len			Access size in Bytes.

	 \return	Indicates if the access was succesful ( TRUE ).

	 \brief  This function operates the SPI access to the EtherCAT ASIC.
	*////////////////////////////////////////////////////////////////////////////////////////

	UINT16 i = Len;
	unsigned char tmp;

	/* loop for all bytes to be written */
	while ( i-- > 0 )
	{
		/* the reading of data from the ESC can be interrupted by the
		   AL Event ISR, so evrey byte will be written seperate */
		DISABLE_AL_EVENT_INT;
	 	AddressingEsc( Address, ESC_WR );		/* HBu 24.01.06: wrong parameter ESC_RD */
		SSPIF = 0;
		SSPBUF = *pData++;						/* start transmission */
		while ( !SSPIF );						/* wait until transmission finished */
		tmp = SSPBUF;							//Throw away read
		/* enable the ESC interrupt to get the AL Event ISR the chance to interrupt */
		ENABLE_AL_EVENT_INT;
		Address++;								/* next address */
		SSPIF = 0;
		/* reset transmission flag */
		/* there has to be at least 15 ns + CLK/2 after the transmission is finished
		   before the SPI_SEL signal shall be 1 */
		SPI_SEL = SPI_DEACTIVE;
	}
}
/////////////////////////////////////////////////////////////////////////////
void 	HW_ResetIntMask(UINT16 intMask)
{
	UINT16 mask;
	HW_EscReadAccess( (UINT8 *)(&mask), ESC_ADDR_ALEVENTMASK, 2 );
	mask &= intMask;
#if AL_EVENT_ENABLED
	DISABLE_AL_EVENT_INT;
	if ( mask == 0 )
	{
		bAlEventEnabled = FALSE;
		START_TIMER;
	}
#endif
	HW_EscWriteAccess( (UINT8 *)(&mask), ESC_ADDR_ALEVENTMASK, 2 );

#if AL_EVENT_ENABLED
	ENABLE_AL_EVENT_INT;
#endif
}

/////////////////////////////////////////////////////////////////////////////////////////
/**
 \param	intMask		interrupt mask (enabled interrupt shall be one)

 \brief	This function makes a logical or with the AL Event Mask register
*////////////////////////////////////////////////////////////////////////////////////////

void 	HW_SetIntMask(UINT16 intMask)
{
	UINT16 mask;
	HW_EscReadAccess( (UINT8 *)(&mask), ESC_ADDR_ALEVENTMASK, 2 );
	mask |= intMask;
#if AL_EVENT_ENABLED
	DISABLE_AL_EVENT_INT;
	STOP_TIMER;
	ACK_TIMER_INT;
	bAlEventEnabled = TRUE;
#endif
	HW_EscWriteAccess( (UINT8 *)(&mask), ESC_ADDR_ALEVENTMASK, 2 );
#if AL_EVENT_ENABLED
	ENABLE_AL_EVENT_INT;
#endif
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/**
 \param alStatus	The new EtherCAT ASIC state.

 \brief  The function changes the state of the EtherCAT ASIC to the requested.
*////////////////////////////////////////////////////////////////////////////////////////

void HW_SetAlStatus(UINT8 alStatus, UINT8 alStatusCode)
{
	UINT16 state = alStatus;
	HW_EscWriteAccess( (UINT8 *)(&state), ESC_ADDR_ALSTATUS, 2 );
	if (alStatusCode != 0xFF)
	{
		state = alStatusCode;
		HW_EscWriteAccess( (UINT8 *)(&state), ESC_ADDR_ALSTATUSCODE, 2 );
	}
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/**
 \param 	channel		Sync Manager channel

 \brief	This function disables a Sync Manager channel
*////////////////////////////////////////////////////////////////////////////////////////

void HW_DisableSyncManChannel(UINT8 channel)
{
	UINT8 value = 1;
	/* HBu 13.02.06: the offset of the Sync manager settings had to be added */
	HW_EscWriteAccess( &value, ESC_ADDR_SYNCMAN+sizeof(TSYNCMAN)*channel+ESC_OFFS_SMSETTINGS+ESC_OFFS_PDIDISABLE, 1 );
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/**
 \param 	channel		Sync Manager channel

 \brief	This function enables a Sync Manager channel
*////////////////////////////////////////////////////////////////////////////////////////

void HW_EnableSyncManChannel(UINT8 channel)
{
	UINT8 value = 0;
	/* HBu 13.02.06: the offset of the Sync manager settings had to be added */
	HW_EscWriteAccess( &value, ESC_ADDR_SYNCMAN+sizeof(TSYNCMAN)*channel+ESC_OFFS_SMSETTINGS+ESC_OFFS_PDIDISABLE, 1 );
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/**
 \param pPdSyncMan	Pointer to a return pointer to the SYNC Manager channel describing
                     of two Sync Manager channels

 \return	Indicates if the SYNC Manager channel descriptions could be delivered completely
 			(0: finished).

 \brief  This function is called to read the SYNC Manager channel descriptions of the
 			process data SYNC Managers.
*////////////////////////////////////////////////////////////////////////////////////////

TSYNCMAN * HW_GetSyncMan(UINT8 channel)
{
	// get a temporary structure of the Sync Manager:
	HW_EscReadAccess( (UINT8 *) &TmpSyncMan, ESC_ADDR_SYNCMAN + (channel * sizeof(TSYNCMAN)), sizeof(TSYNCMAN) );
	return &TmpSyncMan;
}

#endif


text:
package org.apache.flink.table.runtime.operators.bundle;

import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness;
import org.apache.flink.table.runtime.operators.bundle.trigger.CountBundleTrigger;
import org.apache.flink.util.Collector;

import org.junit.Test;

import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * Tests for {@link MapBundleOperator}.
 */
public class MapBundleOperatorTest {

	@Test
	public void testSimple() throws Exception {
		@SuppressWarnings("unchecked")
		TestMapBundleFunction func = new TestMapBundleFunction();
		CountBundleTrigger<Tuple2<String, String>> trigger = new CountBundleTrigger<>(3);
		KeySelector<Tuple2<String, String>, String> keySelector =
				(KeySelector<Tuple2<String, String>, String>) value -> value.f0;

		OneInputStreamOperatorTestHarness<Tuple2<String, String>, String> op =
				new OneInputStreamOperatorTestHarness<>(
						new MapBundleOperator<>(func, trigger, keySelector));
		op.open();
		synchronized (op.getCheckpointLock()) {
			StreamRecord<Tuple2<String, String>> input = new StreamRecord<>(null);

			input.replace(new Tuple2<>("k1", "v1"));
			op.processElement(input);

			input.replace(new Tuple2<>("k1", "v2"));
			op.processElement(input);

			assertEquals(0, func.getFinishCount());

			input.replace(new Tuple2<>("k2", "v3"));
			op.processElement(input);

			assertEquals(1, func.getFinishCount());
			assertThat(Arrays.asList("k1=v1,v2", "k2=v3"), is(func.getOutputs()));

			input.replace(new Tuple2<>("k3", "v4"));
			op.processElement(input);

			input.replace(new Tuple2<>("k4", "v5"));
			op.processElement(input);

			assertEquals(1, func.getFinishCount());

			op.close();
			assertEquals(2, func.getFinishCount());
			assertThat(Arrays.asList("k3=v4", "k4=v5"), is(func.getOutputs()));
		}
	}

	private static class TestMapBundleFunction extends MapBundleFunction<String, String, Tuple2<String, String>, String> {

		private int finishCount = 0;
		private List<String> outputs = new ArrayList<>();

		@Override
		public String addInput(@Nullable String value, Tuple2<String, String> input) throws Exception {
			if (value == null) {
				return input.f1;
			} else {
				return value + "," + input.f1;
			}
		}

		@Override
		public void finishBundle(Map<String, String> buffer, Collector<String> out) throws Exception {
			finishCount++;
			outputs.clear();
			for (Map.Entry<String, String> entry : buffer.entrySet()) {
				outputs.add(entry.getKey() + "=" + entry.getValue());
			}
		}

		int getFinishCount() {
			return finishCount;
		}

		List<String> getOutputs() {
			return outputs;
		}
	}
}


text:
class Client
{
public:
    enum class State
    {
        Uninitialized,
        Initialized,
        Logged_in,
        Playing
    };

private:
    bool connected;
    std::vector<sf::Packet> recv_queue;
    std::vector<sf::Packet> send_queue;

public:
    State state;
    std::shared_ptr<sf::TcpSocket> socket;
    PacketHandler packet_handler;

    std::string username;
    std::vector<std::shared_ptr<Character>> characters;
    std::string selected_character;
    unsigned short map_id;

    std::string transfer_data;
    unsigned int transfer_id;
    sf::Clock transfer_clock;

    std::vector<std::pair<sf::Packet, int>> action_queue;
    sf::Clock action_clock;
    sf::Clock ping_clock;
    int latency;

    Client();
    void Tick();
    bool Connected();
    void Send(sf::Packet packet);
    sf::Packet Recv();

    Character *GetCharacter(std::string name);
    void RemoveCharacter(std::string name);
};

#endif // CLIENT_HPP_INCLUDED


text:
use strict;  use warnings;  use Image::ExifTool;  use File::Find;  use IO::Tee;

# first, create a time check:
END { print "This Perl program ran for ", time() - $^T, " seconds.  All changes reported.\n"}

# prepare an output log:
my $llf = "jpgorhor.txt";
my $llfh;
open( $llfh, '>', $llf ) or die("Can't initialise $llf: $!");
my $tee = IO::Tee->new( $llfh, \*STDOUT );
select $tee;

#  now work through the directory, recursively (looking for rotatable jpegs):
#
#  first define a suitable ExifTool object to be used in the subroutine (and two counters):
my $exifTool = new Image::ExifTool;  my $cdir = 0; my $cfls = 0; my $cjpg = 0; my $cchg = 0;

# now do all of the work:
find(\&rotatable_jpegs, ".");   # finished!
print "Finished! Looked in $cdir Directories at $cfls Files of which $cjpg were jpegs\n";
print "$cchg corrections were made to jpeg Orientation tags\n";

#  the subroutine to find those jpegs that are set for rotation, and clear that:
sub rotatable_jpegs
{
#   print the current directory, as a progress indicator:
    if (-d) {
	    print "looking in Directory > $_\n";
		$cdir++;
		} else {
        $cfls++;
#       (first check if the found item is named as a jpeg:)
        if (/\.jpg$/i) {
#       (this is matching the filename to .jpg case-insensitive)
            $cjpg++;
#           so pull out the contents of the Orientation tag:
            $exifTool->ImageInfo($_);
		    my $v = $exifTool->GetValue('Orientation');
#           check that $v exists (to avoid 'Use of uninitialized value $v' error)
#           and if it's a Rotation:
		    if (defined $v && $v =~ /Rotate/) {
#			    note as much (again to show progress):
		        print "jpeg: $_ > $v changed to Horizontal\n"; $cchg++;
#               then set it to Horizontal:
		        $exifTool->SetNewValue('Orientation#' => 1); $exifTool->WriteInfo($_);
		    }
	    }
	}
}


text:
using UnrealBuildTool;
using System.IO;

public class ReliabilityHandlerComponent : ModuleRules
{
    public ReliabilityHandlerComponent(TargetInfo Target)
    {
        PublicDependencyModuleNames.AddRange(
            new string[] {
				"Core",
                "PacketHandler",
            }
        );
    }
}


text:
// Copyright (c) kuicker.org. All rights reserved.
// Modified By      YYYY-MM-DD
// kevinjong        2016-03-21 - Creation

using System;

namespace IsTo
{
	public partial class IsToConverter
	{
		public class FromEnum
		{
			// ToString
			private static Func<Type, object, string> _ToString;
			public new static Func<Type, object, string> ToString
			{
				get
				{
					return null == _ToString
						? ToStringDefault
						: _ToString;
				}
				set
				{
					_ToString = value;
				}
			}

			private static string ToStringDefault(
				Type fromType,
				object value)
			{
				var result = value.ToString();
				return result;
			}
		}
	}
}


text:
AT.prototype.atPwdFormHelpers = {
    disabled: function() {
        return AccountsTemplates.disabled();
    },
    fields: function() {
        var parentData = Template.currentData();
        var state = (parentData && parentData.state) || AccountsTemplates.getState();
        return _.filter(AccountsTemplates.getFields(), function(s) {
            return _.contains(s.visible, state);
        });
    },
    showForgotPasswordLink: function() {
        var parentData = Template.currentData();
        var state = (parentData && parentData.state) || AccountsTemplates.getState();
        return state === "signIn" && AccountsTemplates.options.showForgotPasswordLink;
    },
    showReCaptcha: function() {
      var parentData = Template.currentData();
      var state = (parentData && parentData.state) || AccountsTemplates.getState();
      return state === "signUp" && AccountsTemplates.options.showReCaptcha;
    },
};

var toLowercaseUsername = function(value){
  return value.toLowerCase().replace(/\s+/gm, '');
};

AT.prototype.atPwdFormEvents = {
    // Form submit
    "submit #at-pwd-form": function(event, t) {
        event.preventDefault();
        $("#at-btn").blur();

        AccountsTemplates.setDisabled(true);

        var parentData = Template.currentData();
        var state = (parentData && parentData.state) || AccountsTemplates.getState();
        var preValidation = (state !== "signIn");

        // Client-side pre-validation
        // Validates fields values
        // NOTE: This is the only place where password validation can be enforced!
        var formData = {};
        var someError = false;
        var errList = [];
        _.each(AccountsTemplates.getFields(), function(field){
            // Considers only visible fields...
            if (!_.contains(field.visible, state))
                return;

            var fieldId = field._id;

            var rawValue = field.getValue(t);
            var value = field.fixValue(rawValue);
            // Possibly updates the input value
            if (value !== rawValue) {
                field.setValue(t, value);
            }
            if (value !== undefined && value !== "") {
                formData[fieldId] = value;
            }

            // Validates the field value only if current state is not "signIn"
            if (preValidation && field.getStatus() !== false){
                var validationErr = field.validate(value, "strict");
                if (validationErr) {
                    if (field.negativeValidation)
                        field.setError(validationErr);
                    else{
                        var fId = T9n.get(field.getDisplayName(), markIfMissing=false);
                        //errList.push(fId + ": " + err);
                        errList.push({
                            field: field.getDisplayName(),
                            err: validationErr
                        });
                    }
                    someError = true;
                }
                else
                    field.setSuccess();
            }
        });

        // Clears error and result
        AccountsTemplates.clearError();
        AccountsTemplates.clearResult();
        AccountsTemplates.clearMessage();
        // Possibly sets errors
        if (someError){
            if (errList.length)
                AccountsTemplates.state.form.set("error", errList);
            AccountsTemplates.setDisabled(false);
            //reset reCaptcha form
            if (state === "signUp" && AccountsTemplates.options.showReCaptcha) {
                grecaptcha.reset();
            }
            return;
        }

        // Extracts username, email, and pwds
        var current_password = formData.current_password;
        var email = formData.email;
        var password = formData.password;
        var password_again = formData.password_again;
        var username = formData.username;
        var username_and_email = formData.username_and_email;
        // Clears profile data removing username, email, and pwd
        delete formData.current_password;
        delete formData.email;
        delete formData.password;
        delete formData.password_again;
        delete formData.username;
        delete formData.username_and_email;

        if (AccountsTemplates.options.confirmPassword){
            // Checks passwords for correct match
            if (password_again && password !== password_again){
                var pwd_again = AccountsTemplates.getField("password_again");
                if (pwd_again.negativeValidation)
                    pwd_again.setError(AccountsTemplates.texts.errors.pwdMismatch);
                else
                    AccountsTemplates.state.form.set("error", [{
                        field: pwd_again.getDisplayName(),
                        err: AccountsTemplates.texts.errors.pwdMismatch
                    }]);
                AccountsTemplates.setDisabled(false);
                //reset reCaptcha form
                if (state === "signUp" && AccountsTemplates.options.showReCaptcha) {
                  grecaptcha.reset();
                }
                return;
            }
        }

        // -------
        // Sign In
        // -------
        if (state === "signIn") {
            var pwdOk = !!password;
            var userOk = true;
            var loginSelector;
            if (email) {
                if (AccountsTemplates.options.lowercaseUsername) {
                  email = toLowercaseUsername(email);
                }

                loginSelector = {email: email};
            }
            else if (username) {
                if (AccountsTemplates.options.lowercaseUsername) {
                  username = toLowercaseUsername(username);
                }
                loginSelector = {username: username};
            }
            else if (username_and_email) {
                if (AccountsTemplates.options.lowercaseUsername) {
                  username_and_email = toLowercaseUsername(username_and_email);
                }
                loginSelector = username_and_email;
            }
            else
                userOk = false;

            // Possibly exits if not both 'password' and 'username' are non-empty...
            if (!pwdOk || !userOk){
                AccountsTemplates.state.form.set("error", [AccountsTemplates.texts.errors.loginForbidden]);
                AccountsTemplates.setDisabled(false);
                return;
            }

            return Meteor.loginWithPassword(loginSelector, password, function(error) {

             // AccountsTemplates.routes[state].redirect =
              if (Meteor.userId()) {
                var currentUser = Meteor.user()

                if (currentUser.profile.role == "admin") {
                  AccountsTemplates.routes[state].redirect = "/admin"
                } else {
                  AccountsTemplates.routes[state].redirect = "/user"
                }
              }
                AccountsTemplates.submitCallback(error, state);
            });
        }

        // -------
        // Sign Up
        // -------
        if (state === "signUp") {
            // Possibly gets reCaptcha response
            if (AccountsTemplates.options.showReCaptcha) {
              formData.reCaptchaResponse = grecaptcha.getResponse();
            }

            var hash = Accounts._hashPassword(password);
            return Meteor.call("ATCreateUserServer", {
                username: username,
                email: email,
                password: hash,
                profile: formData,
            }, function(error){
                AccountsTemplates.submitCallback(error, undefined, function(){
                    if (AccountsTemplates.options.sendVerificationEmail && AccountsTemplates.options.enforceEmailVerification){
                        AccountsTemplates.submitCallback(error, state, function () {
                            AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.signUpVerifyEmail);
                            // Cleans up input fields' content
                            _.each(AccountsTemplates.getFields(), function(field){
                                // Considers only visible fields...
                                if (!_.contains(field.visible, state))
                                    return;

                                var elem = t.$("#at-field-" + field._id);

                                // Naïve reset
                                if (field.type === "checkbox") elem.prop('checked', false);
                                else elem.val("");

                            });
                            AccountsTemplates.setDisabled(false);
                            AccountsTemplates.avoidRedirect = true;
                        });
                    }
                    else {
                        var loginSelector;

                        if (email) {
                            if (AccountsTemplates.options.lowercaseUsername) {
                              email = toLowercaseUsername(email);
                            }

                            loginSelector = {email: email};
                        }
                        else if (username) {
                            if (AccountsTemplates.options.lowercaseUsername) {
                              username = toLowercaseUsername(username);
                            }
                            loginSelector = {username: username};
                        }
                        else {
                            if (AccountsTemplates.options.lowercaseUsername) {
                              username_and_email = toLowercaseUsername(username_and_email);
                            }
                            loginSelector = username_and_email;
                        }

                        Meteor.loginWithPassword(loginSelector, password, function(error) {
                            AccountsTemplates.submitCallback(error, state, function(){
                                AccountsTemplates.setState("signIn");
                            });
                        });
                    }
                });
            });
        }

        //----------------
        // Forgot Password
        //----------------
        if (state === "forgotPwd"){
            return Accounts.forgotPassword({
                email: email
            }, function(error) {
                AccountsTemplates.submitCallback(error, state, function(){
                    AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.emailSent);
                    t.$("#at-field-email").val("");
                });
            });
        }

        //--------------------------------
        // Reset Password / Enroll Account
        //--------------------------------
        if (state === "resetPwd" || state === "enrollAccount") {
            var paramToken = FlowRouter.getParam('paramToken');
            return Accounts.resetPassword(paramToken, password, function(error) {
                AccountsTemplates.submitCallback(error, state, function(){
                    var pwd_field_id;
                    if (state === "resetPwd")
                        AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.pwdReset);
                    else // Enroll Account
                        AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.pwdSet);
                    t.$("#at-field-password").val("");
                    if (AccountsTemplates.options.confirmPassword)
                        t.$("#at-field-password_again").val("");
                });
            });
        }

        //----------------
        // Change Password
        //----------------
        if (state === "changePwd"){
            return Accounts.changePassword(current_password, password, function(error) {
                AccountsTemplates.submitCallback(error, state, function(){
                    AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.pwdChanged);
                    t.$("#at-field-current_password").val("");
                    t.$("#at-field-password").val("");
                    if (AccountsTemplates.options.confirmPassword)
                        t.$("#at-field-password_again").val("");
                });
            });
        }
    },
};


text:
namespace Reaper
{
using namespace vk;

void vulkan_create_shader_module(VkShaderModule& shaderModule, VkDevice device, const std::string& fileName)
{
    std::vector<char> fileContents = readWholeFile(fileName);

    VkShaderModuleCreateInfo shader_module_create_info = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, nullptr, 0,
                                                          fileContents.size(),
                                                          reinterpret_cast<const uint32_t*>(&fileContents[0])};

    Assert(vkCreateShaderModule(device, &shader_module_create_info, nullptr, &shaderModule) == VK_SUCCESS);

    VulkanSetDebugName(device, shaderModule, fileName.c_str());
}
} // namespace Reaper


text:
class CreateRssSubcriptionIps < ActiveRecord::Migration
  def self.up
    create_table :rss_subscription_ips do |t|
      t.column :rss_stats_id,     :integer
      t.column :ip,               :string, :limit => 15
      t.column :created_at,       :datetime
    end
    add_index(:rss_subscription_ips, :rss_stats_id)
    add_index(:rss_subscription_ips, :ip)
  end

  def self.down
    drop_table :rss_subscription_ips
  end
end


text:
package org.jbpm.services.ejb.api;

import javax.ejb.Local;

import org.jbpm.services.api.DeploymentEventListener;
import org.jbpm.services.api.RuntimeDataService;

@Local
public interface RuntimeDataServiceEJBLocal extends RuntimeDataService, DeploymentEventListener {

}


text:
using Microsoft.SharePoint.Client;
using System.Management.Automation;
using SharePointPnP.PowerShell.CmdletHelpAttributes;

namespace SharePointPnP.PowerShell.Commands
{
    [Cmdlet(VerbsLifecycle.Request, "PnPReIndexWeb")]
    [CmdletAlias("Request-PnPReIndexWeb")]
    [CmdletHelp("Marks the web for full indexing during the next incremental crawl",
        Category = CmdletHelpCategory.Webs)]
    public class RequestReIndexWeb : SPOWebCmdlet
    {

        protected override void ExecuteCmdlet()
        {
            SelectedWeb.ReIndexWeb();
        }
    }
}


text:
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package jodd.cache;

import java.util.Collections;
import java.util.Map;

/**
 * Simple no-cache implementations of {@link Cache} for situation when cache
 * needs to be quickly turned-off.
 */
public class NoCache<K, V> implements Cache<K, V> {

	@Override
	public int limit() {
		return 0;
	}

	@Override
	public long timeout() {
		return 0;
	}

	@Override
	public void put(final K key, final V object) {
		// ignore
	}

	@Override
	public void put(final K key, final V object, final long timeout) {
		// ignore
	}

	@Override
	public V get(final K key) {
		return null;
	}

	@Override
	public int prune() {
		return 0;
	}

	@Override
	public boolean isFull() {
		return true;
	}

	@Override
	public V remove(final K key) {
		return null;
	}

	@Override
	public void clear() {
		// ignore
	}

	@Override
	public int size() {
		return 0;
	}

	@Override
	public boolean isEmpty() {
		return true;
	}

	@Override
	public Map<K, V> snapshot(final boolean peek) {
		return Collections.emptyMap();
	}
}


text:
package raw.blockChain.services.miner;

import raw.blockChain.api.BlockHeader;
import raw.blockChain.services.thickNode.ThickNode;

public interface LocalThickNodeListener {

	/**
	 * {@link ThickNode}s will call this method to inform a local
	 * {@link Miner} that a new block was found by the network.
	 *
	 * @param header a new {@link BlockHeader}
	 * @return <tt>true</tt> if notification went well, <tt>false</tt> otherwise
	 */
	public boolean notifyNewBlockHeaderFromNet(BlockHeader header);

}


text:
package alluxio.util.webui;

/**
 * Displays information about a storage directory in the UI.
 */
public class UIStorageDir {
  private final String mTierAlias;
  private final String mDirPath;
  private final long mCapacityBytes;
  private final long mUsedBytes;

  /**
   * Creates a new instance of {@link UIStorageDir}.
   *
   * @param tierAlias tier alias
   * @param dirPath directory path
   * @param capacityBytes capacity in bytes
   * @param usedBytes used capacity in bytes
   */
  public UIStorageDir(String tierAlias, String dirPath, long capacityBytes, long usedBytes) {
    mTierAlias = tierAlias;
    mDirPath = dirPath;
    mCapacityBytes = capacityBytes;
    mUsedBytes = usedBytes;
  }

  /**
   * Gets capacity bytes.
   *
   * @return capacity in bytes
   */
  public long getCapacityBytes() {
    return mCapacityBytes;
  }

  /**
   * Gets dir path.
   *
   * @return directory path
   */
  public String getDirPath() {
    return mDirPath;
  }

  /**
   * Gets tier alias.
   *
   * @return tier alias
   */
  public String getTierAlias() {
    return mTierAlias;
  }

  /**
   * Gets used bytes.
   *
   * @return used capacity in bytes
   */
  public long getUsedBytes() {
    return mUsedBytes;
  }
}


text:
from __future__ import division, print_function
import os
import numpy as np
import array

def read_meta_header(filename):
    """Return a dictionary of meta data from meta header file"""
    fileIN = open(filename, "r")
    line = fileIN.readline()

    meta_dict = {}
    tag_set = []
    tag_set.extend(['ObjectType', 'NDims', 'DimSize', 'ElementType', 'ElementDataFile', 'ElementNumberOfChannels'])
    tag_set.extend(['BinaryData', 'BinaryDataByteOrderMSB', 'CompressedData', 'CompressedDataSize'])
    tag_set.extend(['Offset', 'CenterOfRotation', 'AnatomicalOrientation', 'ElementSpacing', 'TransformMatrix'])
    tag_set.extend(['Comment', 'SeriesDescription', 'AcquisitionDate', 'AcquisitionTime', 'StudyDate', 'StudyTime'])

    tag_flag = [False] * len(tag_set)
    while line:
        tags = str.split(line, '=')
        # print(tags[0])
        for i in range(len(tag_set)):
            tag = tag_set[i]
            if (str.strip(tags[0]) == tag) and (not tag_flag[i]):
                # print(tags[1])
                content = str.strip(tags[1])
                if tag in ['ElementSpacing', 'Offset', 'CenterOfRotation', 'TransformMatrix']:
                    meta_dict[tag] = [float(s) for s in content.split()]
                elif tag in ['NDims', 'ElementNumberOfChannels']:
                    meta_dict[tag] = int(content)
                elif tag in ['DimSize']:
                    meta_dict[tag] = [int(s) for s in content.split()]
                elif tag in ['BinaryData', 'BinaryDataByteOrderMSB', 'CompressedData']:
                    if content == "True":
                        meta_dict[tag] = True
                    else:
                        meta_dict[tag] = False
                else:
                    meta_dict[tag] = content
                tag_flag[i] = True
        line = fileIN.readline()
    # print(comment)
    fileIN.close()
    return meta_dict

def load_raw_data_with_mhd(filename):
    meta_dict = read_meta_header(filename)
    dim = int(meta_dict['NDims'])
    if "ElementNumberOfChannels" in meta_dict:
        element_channels = int(meta_dict["ElementNumberOfChannels"])
    else:
        element_channels = 1
    # print(dim)
    # print(meta_dict['ElementType'])
    if meta_dict['ElementType'] == 'MET_FLOAT':
        np_type = np.float32
    elif meta_dict['ElementType'] == 'MET_DOUBLE':
        np_type = np.float64
    elif meta_dict['ElementType'] == 'MET_CHAR':
        np_type = np.byte
    elif meta_dict['ElementType'] == 'MET_UCHAR':
        np_type = np.ubyte
    elif meta_dict['ElementType'] == 'MET_SHORT':
        np_type = np.short
    elif meta_dict['ElementType'] == 'MET_USHORT':
        np_type = np.ushort
    elif meta_dict['ElementType'] == 'MET_INT':
        np_type = np.int32
    elif meta_dict['ElementType'] == 'MET_UINT':
        np_type = np.uint32
    else:
        raise NotImplementedError("ElementType " + meta_dict['ElementType'] + " not understood.")
    arr = list(meta_dict['DimSize'])
    # print(arr)
    volume = np.prod(arr[0:dim - 1])
    # print(volume)
    pwd = os.path.split(filename)[0]
    if pwd:
        data_file = pwd + '/' + meta_dict['ElementDataFile']
    else:
        data_file = meta_dict['ElementDataFile']

    shape = (arr[dim - 1], volume, element_channels)
    with open(data_file,'rb') as fid:
        data = np.fromfile(fid, count=np.prod(shape),dtype = np_type)
    data.shape = shape

    # Begin 3D fix
    arr.reverse()
    if element_channels > 1:
        data = data.reshape(arr + [element_channels])
    else:
        data = data.reshape(arr)
    # End 3D fix

    return (data, meta_dict)

def write_meta_header(filename, meta_dict):
    header = ''
    # do not use tags = meta_dict.keys() because the order of tags matters
    tags = ['ObjectType', 'NDims', 'BinaryData',
            'BinaryDataByteOrderMSB', 'CompressedData', 'CompressedDataSize',
            'TransformMatrix', 'Offset', 'CenterOfRotation',
            'AnatomicalOrientation', 'ElementSpacing',
            'DimSize', 'ElementNumberOfChannels', 'ElementType', 'ElementDataFile',
            'Comment', 'SeriesDescription', 'AcquisitionDate',
            'AcquisitionTime', 'StudyDate', 'StudyTime']
    for tag in tags:
        if tag in meta_dict.keys():
            header += '%s = %s\n' % (tag, meta_dict[tag])
    f = open(filename, 'w')
    f.write(header)
    f.close()

def dump_raw_data(filename, data, dsize, element_channels=1):
    """ Write the data into a raw format file. Big endian is always used. """
    data = data.reshape(dsize[0], -1, element_channels)
    rawfile = open(filename, 'wb')
    if data.dtype == np.float32:
        array_string = 'f'
    elif data.dtype == np.double or data.dtype == np.float64:
        array_string = 'd'
    elif data.dtype == np.short:
        array_string = 'h'
    elif data.dtype == np.ushort:
        array_string = 'H'
    elif data.dtype == np.int32:
        array_string = 'i'
    elif data.dtype == np.uint32:
        array_string = 'I'
    else:
        raise NotImplementedError("ElementType " + str(data.dtype) + " not implemented.")
    a = array.array(array_string)
    a.fromlist(list(data.ravel()))
    # if is_little_endian():
    #    a.byteswap()
    a.tofile(rawfile)
    rawfile.close()

def write_mhd_file(mhdfile, data, **meta_dict):
    assert(mhdfile[-4:] == '.mhd')
    meta_dict['ObjectType'] = 'Image'
    meta_dict['BinaryData'] = 'True'
    meta_dict['BinaryDataByteOrderMSB'] = 'False'
    if data.dtype == np.float32:
        meta_dict['ElementType'] = 'MET_FLOAT'
    elif data.dtype == np.double or data.dtype == np.float64:
        meta_dict['ElementType'] = 'MET_DOUBLE'
    elif data.dtype == np.byte:
        meta_dict['ElementType'] = 'MET_CHAR'
    elif data.dtype == np.uint8 or data.dtype == np.ubyte:
        meta_dict['ElementType'] = 'MET_UCHAR'
    elif data.dtype == np.short or data.dtype == np.int16:
        meta_dict['ElementType'] = 'MET_SHORT'
    elif data.dtype == np.ushort or data.dtype == np.uint16:
        meta_dict['ElementType'] = 'MET_USHORT'
    elif data.dtype == np.int32:
        meta_dict['ElementType'] = 'MET_INT'
    elif data.dtype == np.uint32:
        meta_dict['ElementType'] = 'MET_UINT'
    else:
        raise NotImplementedError("ElementType " + str(data.dtype) + " not implemented.")
    dsize = list(data.shape)
    if 'ElementNumberOfChannels' in meta_dict.keys():
        element_channels = int(meta_dict['ElementNumberOfChannels'])
        assert(dsize[-1] == element_channels)
        dsize = dsize[:-1]
    else:
        element_channels = 1
    dsize.reverse()
    meta_dict['NDims'] = str(len(dsize))
    meta_dict['DimSize'] = dsize
    meta_dict['ElementDataFile'] = os.path.split(mhdfile)[1].replace('.mhd',
                                                                     '.raw')

    # Tags that need conversion of list to string
    tags = ['ElementSpacing', 'Offset', 'DimSize', 'CenterOfRotation', 'TransformMatrix']
    for tag in tags:
        if tag in meta_dict.keys() and not isinstance(meta_dict[tag], str):
            meta_dict[tag] = ' '.join([str(i) for i in meta_dict[tag]])
    write_meta_header(mhdfile, meta_dict)

    pwd = os.path.split(mhdfile)[0]
    if pwd:
        data_file = pwd + '/' + meta_dict['ElementDataFile']
    else:
        data_file = meta_dict['ElementDataFile']

    dump_raw_data(data_file, data, dsize, element_channels=element_channels)


text:
package org.abimon.mods.minecraft.colouredBlocks;

import java.awt.Color;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;

public interface IColourable
{
	public void clearColour(World world, int x, int y, int z, EntityPlayer player);
	public Color getColour(World world, int x, int y, int z, EntityPlayer player);
}


text:
package org.spockframework.mock;

import java.util.List;
import java.util.Map;

import org.spockframework.util.CollectionUtil;
import org.spockframework.util.IMultiset;
import org.spockframework.util.LinkedHashMultiset;

/**
 * Thrown to indicate that a mandatory interaction matched too many invocations.
 *
 * @author Peter Niederwieser
 */
public class TooManyInvocationsError extends InteractionNotSatisfiedError {
  private final IMockInteraction interaction;
  private final List<IMockInvocation> acceptedInvocations;
  private String message;

  public TooManyInvocationsError(IMockInteraction interaction, List<IMockInvocation> acceptedInvocations) {
    this.interaction = interaction;
    this.acceptedInvocations = acceptedInvocations;
  }

  public IMockInteraction getInteraction() {
    return interaction;
  }

  public List<IMockInvocation> getAcceptedInvocations() {
    return acceptedInvocations;
  }

  @Override
  public synchronized String getMessage() {
    if (message != null) return message;

    IMultiset<IMockInvocation> uniqueInvocations = new LinkedHashMultiset<IMockInvocation>();
    for (IMockInvocation invocation : CollectionUtil.reverse(acceptedInvocations)) {
      uniqueInvocations.add(invocation);
    }

    StringBuilder builder = new StringBuilder();
    builder.append("Too many invocations for:\n\n");
    builder.append(interaction);
    builder.append("\n\n");
    builder.append("Matching invocations (ordered by last occurrence):\n\n");

    int count = 0;
    for (Map.Entry<IMockInvocation, Integer> entry : uniqueInvocations.entrySet()) {
      builder.append(entry.getValue());
      builder.append(" * ");
      builder.append(entry.getKey());
      if (count++ == 0) {
        builder.append("   <-- this triggered the error");
      }
      builder.append("\n");
    }
    builder.append("\n");

    message = builder.toString();
    return message;
  }
}