text:
package com.binaryedu.business.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.binaryedu.business.model.IUser;
import com.binaryedu.business.model.impl.User;
import com.binaryedu.business.service.ICommunicationService;
import com.binaryedu.business.transferobject.ResetPasswordTO;
import com.binaryedu.business.transferobject.UserAccountTO;
import com.binaryedu.exceptions.BinaryException;
import com.binaryedu.exceptions.BinaryExceptionCodes;

public class CommunicationService implements ICommunicationService
{
	protected final Log logger = LogFactory.getLog(this.getClass());
	private final String URL = "http://binaryedu.herokuapp.com/";
//	private final String URL = "http://localhost:8080/BinaryEduWeb/";

	private static final ICommunicationService INSTANCE = new CommunicationService();

	private CommunicationService()
	{

	}

	public static ICommunicationService getInstance()
	{
		return INSTANCE;
	}

	@Override
	public void sendVerificationEmail(UserAccountTO newUserTO) throws BinaryException
	{
		sendEmail(newUserTO.getEmail(), "Verify your account", "Verify Account", "
This is your verification mail. Click on the link to activate your Binary Edu account:

" +
				"" +
				URL + "activateAccount.htm?email="
				+ newUserTO.getEmail() + "&key=" + newUserTO.getActivationKey() + "
" +
				"
If clicking on the link does not work, you can copy and paste this link into a web browser.
" +
				"
Regards,
Binary Edu Team
");
	}

	@Override
	public void sendNewPassword(String email, String password) throws BinaryException
	{
		sendEmail(email, "Your New Password", "New Password", "
Your new password for Binary Edu web site is " + password + "
" +
				"
Regards,
Binary Edu Team
");
	}

	@Override
	public void sendResetPasswordEmail(ResetPasswordTO resetPasswordTO) throws BinaryException
	{
		sendEmail(resetPasswordTO.getEmail(), "Reset your password",
				"Reset Password Request", "
Click the following link to generate a new password for your account:
" +
				"
" +
				URL + "resetPassword.htm?email=" +
				resetPasswordTO.getEmail() + "&key=" + resetPasswordTO.getKey() +
				"
" +
				"
If clicking on the link does not work, you can copy and paste this link into a web browser.
" +
				"
Regards,
Binary Edu Team
");

	}

	protected void sendEmail(String email, String subject, String heading, String content) throws BinaryException
	{

		IUser[] userList = new User[1];
		User user = new User();
		user.setEmail(email);
		userList[0] = user;

		sendEmail(userList, subject, heading, content);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.binaryedu.business.service.ICommunicationService#sendEmail(com.binaryedu
	 * .business.model.IUser[], java.lang.String, java.lang.String)
	 */

	protected void sendEmail(IUser[] users, String subject, String heading, String content) throws BinaryException
	{
		try
		{
			Properties props = new Properties();
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.host", "smtp.live.com");
			props.put("mail.smtp.port", "587");
			props.put("mail.user", "binaryedu@outlook.com");
			props.put("mail.password", "dhamaka123");
			props.put("mail.smtp.auth", "true");

			Authenticator auth = new SMTPAuthenticator();

			Session mailSession = Session.getDefaultInstance(props, auth);
			Transport transport = mailSession.getTransport();

			MimeMessage message = new MimeMessage(mailSession);
			InternetAddress fromAddress = new InternetAddress("binaryedu@outlook.com");
			fromAddress.setPersonal("Binary Edu");
			message.setFrom(fromAddress);
			message.setSubject(subject);
			message.setContent(getEmailHead(heading) + content + getEmailTail(), "text/html");
			for (IUser user : users)
			{
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
			}

			transport.connect();
			transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
			transport.close();
		}
		catch (AddressException e)
		{
			logger.error(e.getStackTrace());
			throw new BinaryException(BinaryExceptionCodes.UNABLE_TO_SEND_EMAIL);
		}
		catch (NoSuchProviderException e)
		{
			logger.error(e.getStackTrace());
			throw new BinaryException(BinaryExceptionCodes.UNABLE_TO_SEND_EMAIL);
		}
		catch (UnsupportedEncodingException e)
		{
			logger.error("UnsupportedEncodingException", e);
			throw new BinaryException(BinaryExceptionCodes.UNABLE_TO_SEND_EMAIL);
		}
		catch (MessagingException e)
		{
			logger.error("MessagingException", e);
			throw new BinaryException(BinaryExceptionCodes.UNABLE_TO_SEND_EMAIL);
		}

	}

	/**
	 * SimpleAuthenticator is used to do simple authentication when the SMTP
	 * server requires it.
	 */
	private static class SMTPAuthenticator extends javax.mail.Authenticator
	{

		public javax.mail.PasswordAuthentication getPasswordAuthentication()
		{
			String username = "binaryedu@outlook.com";
			String password = "dhamaka123";
			return new javax.mail.PasswordAuthentication(username, password);
		}
	}

	private String getEmailHead(String heading)
	{
		return  "\r\n" +
				"
\r\n" +
				"
\r\n" +
				"	\r\n" +
				"
\r\n" +
				"
\r\n" +
				"	\r\n" +
				"
\r\n" +
				"
\r\n" +
				"\r\n" +
				"" + heading + "\r\n" +
				"\r\n" +
				"
\r\n" +
				"
\r\n" +
				"";
	}

	private String getEmailTail()
	{
		return "\r\n" +
				"	\r\n" +
				"
\r\n" +
				"
\r\n" +
				"	\r\n" +
				"
\r\n" +
				"
\r\n" +
				"	\r\n" +
				"
\r\n" +
				"
\r\n" +
				"";
	}

//	public static void main(String[] args) throws BinaryException {
//		ICommunicationService service = CommunicationService.getInstance();
//		service.sendNewPassword("parambirs@gmail.com", "abc123");
//	}
}


text:
// An ultra-lightweight testing framework designed for use with microcontroller
// applications. Its only dependency is on TensorFlow Lite's ErrorReporter
// interface, where log messages are output. This is designed to be usable even
// when no standard C or C++ libraries are available, and without any dynamic
// memory allocation or reliance on global constructors.
//
// To build a test, you use syntax similar to gunit, but with some extra
// decoration to create a hidden 'main' function containing each of the tests to
// be run. Your code should look something like:
// ----------------------------------------------------------------------------
// #include "path/to/this/header"
//
// TF_LITE_MICRO_TESTS_BEGIN
//
// TF_LITE_MICRO_TEST(SomeTest) {
//   TF_LITE_LOG_EXPECT_EQ(true, true);
// }
//
// TF_LITE_MICRO_TESTS_END
// ----------------------------------------------------------------------------
// If you compile this for your platform, you'll get a normal binary that you
// should be able to run. Executing it will output logging information like this
// to stderr (or whatever equivalent is available and written to by
// ErrorReporter):
// ----------------------------------------------------------------------------
// Testing SomeTest
// 1/1 tests passed
// ~~~ALL TESTS PASSED~~~
// ----------------------------------------------------------------------------
// This is designed to be human-readable, so you can just run tests manually,
// but the string "~~~ALL TESTS PASSED~~~" should only appear if all of the
// tests do pass. This makes it possible to integrate with automated test
// systems by scanning the output logs and looking for that magic value.
//
// This framework is intended to be a rudimentary alternative to no testing at
// all on systems that struggle to run more conventional approaches, so use with
// caution!

#ifndef TENSORFLOW_LITE_MICRO_TESTING_MICRO_TEST_H_
#define TENSORFLOW_LITE_MICRO_TESTING_MICRO_TEST_H_

#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/system_setup.h"

namespace micro_test {
extern int tests_passed;
extern int tests_failed;
extern bool is_test_complete;
extern bool did_test_fail;
}  // namespace micro_test

namespace tflite {

// This additional helper function is used (instead of directly calling
// tflite::InitializeTarget from the TF_LITE_MICRO_TESTS_BEGIN macro) to avoid
// adding a dependency from every bazel test target to micro:system_setp (which
// is the target that implements InitializeTarget().
//
// The underlying issue here is that the use of the macros results in
// dependencies that can be containted within the micro/testing:micro_test
// target bleeding on to all the tests.
inline void InitializeTest() { InitializeTarget(); }
}  // namespace tflite

#define TF_LITE_MICRO_TESTS_BEGIN   \
  /* CFU-Playground: These now defined in micro_test_globals.cc */\
  /*namespace micro_test { */       \
  /*int tests_passed;      */       \
  /*int tests_failed;      */       \
  /*bool is_test_complete; */       \
  /*bool did_test_fail; */          \
  /*} */                            \
                                    \
  /* CFU-Playground: REPLACE_NAME_ macro */ \
  int REPLACE_NAME_(int argc, char** argv) { \
    micro_test::tests_passed = 0;   \
    micro_test::tests_failed = 0;   \
    tflite::InitializeTest();

#define TF_LITE_MICRO_TESTS_END                                       \
  MicroPrintf("%d/%d tests passed", micro_test::tests_passed,         \
              (micro_test::tests_failed + micro_test::tests_passed)); \
  if (micro_test::tests_failed == 0) {                                \
    MicroPrintf("~~~ALL TESTS PASSED~~~\n");                          \
    return kTfLiteOk;                                                 \
  } else {                                                            \
    MicroPrintf("~~~SOME TESTS FAILED~~~\n");                         \
    return kTfLiteError;                                              \
  }                                                                   \
  }

// TODO(petewarden): I'm going to hell for what I'm doing to this poor for loop.
#define TF_LITE_MICRO_TEST(name)                                           \
  MicroPrintf("Testing " #name);                                           \
  for (micro_test::is_test_complete = false,                               \
      micro_test::did_test_fail = false;                                   \
       !micro_test::is_test_complete; micro_test::is_test_complete = true, \
      micro_test::tests_passed += (micro_test::did_test_fail) ? 0 : 1,     \
      micro_test::tests_failed += (micro_test::did_test_fail) ? 1 : 0)

#define TF_LITE_MICRO_EXPECT(x)                               \
  do {                                                        \
    if (!(x)) {                                               \
      MicroPrintf(#x " failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                       \
    }                                                         \
  } while (false)

// TODO(b/139142772): this macro is used with types other than ints even though
// the printf specifier is %d.
#define TF_LITE_MICRO_EXPECT_EQ(x, y)                                    \
  do {                                                                   \
    auto vx = x;                                                         \
    auto vy = y;                                                         \
    if ((vx) != (vy)) {                                                  \
      MicroPrintf(#x " == " #y " failed at %s:%d (%d vs %d)", __FILE__,  \
                  __LINE__, static_cast<int>(vx), static_cast<int>(vy)); \
      micro_test::did_test_fail = true;                                  \
    }                                                                    \
  } while (false)

#define TF_LITE_MICRO_EXPECT_NE(x, y)                                   \
  do {                                                                  \
    if ((x) == (y)) {                                                   \
      MicroPrintf(#x " != " #y " failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                                 \
    }                                                                   \
  } while (false)

// TODO(wangtz): Making it more generic once needed.
#define TF_LITE_MICRO_ARRAY_ELEMENT_EXPECT_NEAR(arr1, idx1, arr2, idx2,       \
                                                epsilon)                      \
  do {                                                                        \
    auto delta = ((arr1)[(idx1)] > (arr2)[(idx2)])                            \
                     ? ((arr1)[(idx1)] - (arr2)[(idx2)])                      \
                     : ((arr2)[(idx2)] - (arr1)[(idx1)]);                     \
    if (delta > epsilon) {                                                    \
      MicroPrintf(#arr1 "[%d] (%f) near " #arr2 "[%d] (%f) failed at %s:%d",  \
                  static_cast<int>(idx1), static_cast<float>((arr1)[(idx1)]), \
                  static_cast<int>(idx2), static_cast<float>((arr2)[(idx2)]), \
                  __FILE__, __LINE__);                                        \
      micro_test::did_test_fail = true;                                       \
    }                                                                         \
  } while (false)

// The check vx != vy is needed to properly handle the case where both
// x and y evaluate to infinity. See #46960 for more details.
#define TF_LITE_MICRO_EXPECT_NEAR(x, y, epsilon)                              \
  do {                                                                        \
    auto vx = (x);                                                            \
    auto vy = (y);                                                            \
    auto delta = ((vx) > (vy)) ? ((vx) - (vy)) : ((vy) - (vx));               \
    if (vx != vy && delta > epsilon) {                                        \
      MicroPrintf(#x " (%f) near " #y " (%f) failed at %s:%d",                \
                  static_cast<double>(vx), static_cast<double>(vy), __FILE__, \
                  __LINE__);                                                  \
      micro_test::did_test_fail = true;                                       \
    }                                                                         \
  } while (false)

#define TF_LITE_MICRO_EXPECT_GT(x, y)                                  \
  do {                                                                 \
    if ((x) <= (y)) {                                                  \
      MicroPrintf(#x " > " #y " failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                                \
    }                                                                  \
  } while (false)

#define TF_LITE_MICRO_EXPECT_LT(x, y)                                  \
  do {                                                                 \
    if ((x) >= (y)) {                                                  \
      MicroPrintf(#x " < " #y " failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                                \
    }                                                                  \
  } while (false)

#define TF_LITE_MICRO_EXPECT_GE(x, y)                                   \
  do {                                                                  \
    if ((x) < (y)) {                                                    \
      MicroPrintf(#x " >= " #y " failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                                 \
    }                                                                   \
  } while (false)

#define TF_LITE_MICRO_EXPECT_LE(x, y)                                   \
  do {                                                                  \
    if ((x) > (y)) {                                                    \
      MicroPrintf(#x " <= " #y " failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                                 \
    }                                                                   \
  } while (false)

#define TF_LITE_MICRO_EXPECT_TRUE(x)                                       \
  do {                                                                     \
    if (!(x)) {                                                            \
      MicroPrintf(#x " was not true failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                                    \
    }                                                                      \
  } while (false)

#define TF_LITE_MICRO_EXPECT_FALSE(x)                                       \
  do {                                                                      \
    if (x) {                                                                \
      MicroPrintf(#x " was not false failed at %s:%d", __FILE__, __LINE__); \
      micro_test::did_test_fail = true;                                     \
    }                                                                       \
  } while (false)

#define TF_LITE_MICRO_FAIL(msg)                       \
  do {                                                \
    MicroPrintf("FAIL: %s", msg, __FILE__, __LINE__); \
    micro_test::did_test_fail = true;                 \
  } while (false)

#define TF_LITE_MICRO_EXPECT_STRING_EQ(string1, string2)                     \
  do {                                                                       \
    for (int i = 0; string1[i] != '\0' && string2[i] != '\0'; i++) {         \
      if (string1[i] != string2[i]) {                                        \
        MicroPrintf("FAIL: %s did not match %s", string1, string2, __FILE__, \
                    __LINE__);                                               \
        micro_test::did_test_fail = true;                                    \
      }                                                                      \
    }                                                                        \
  } while (false)

#endif  // TENSORFLOW_LITE_MICRO_TESTING_MICRO_TEST_H_

redpajama_set_name: RedPajamaGithub


text:
"""Everything needed for being able to create a virtual filesystem."""
import typing
from abc import ABC, abstractmethod, abstractproperty
from pathlib import Path

from operating_system import FakeOperatingSystem, FakeUnix, FakeWindows
from fakeuser import FakeUser, Root

class FakeFileLikeObject(ABC):
    """I am what's common between a file, a directory, a symlink and a mount."""
    def __init__(self, path: Path,
                 mode: int = 0o777,
                 uid: int = -1,
                 gid: int = -1):
        self.path = path
        self.uid = uid
        self.gid = gid
        self.mode = mode

    @property
    def parent(self) -> Path:
        """Return this file-like object's parent."""
        return self.path.parent

    @property
    def name(self) -> str:
        """Return this file-like object's name"""
        return self.path.absolute().name

class FakeFile(FakeFileLikeObject):
    """I mock a file"""
    pass

class FakeDirectory(FakeFileLikeObject):
    """I mock a directory."""
    def parts(self) -> typing.List[Path]:
        """returns the parts the directory is made of"""
        path_so_far = Path()
        for part in self.path.parts:
            path_so_far = path_so_far.joinpath(part)
            yield path_so_far

class AbstractFilesystem(ABC):
    # pylint: disable=missing-docstring
    @abstractmethod
    def has_directory(self, path: Path) -> bool:
        pass

    @abstractmethod
    def has_file(self, path: Path) -> bool:
        pass

    @abstractmethod
    def has(self, path: Path) -> bool:
        pass

    @abstractmethod
    def mkdir(self, path: Path, mode: int):
        pass

    @abstractmethod
    def makedirs(self, path: Path, mode: int, exist_ok: bool):
        pass

    @abstractmethod
    def listdir(self, path: Path) -> typing.Iterator[FakeFileLikeObject]:
        pass

    @abstractmethod
    def chown(self, path: Path, uid: int, gid: int):
        pass

    @abstractmethod
    def chmod(self, path: Path, mode: int):
        pass

    @abstractmethod
    def rmdir(self, path: Path):
        pass

    @abstractmethod
    def remove(self, path: Path):
        pass

    @abstractmethod
    def rename(self, src: Path, dst: Path):
        pass

    @abstractproperty
    def user(self) -> FakeUser:
        pass

    @abstractmethod
    def set_user(self, user: FakeUser):
        pass

    @abstractproperty
    def effective_user(self) -> FakeUser:
        pass

    @abstractmethod
    def access(self, path: Path, mode: int, effective_ids: bool):
        pass

class FakeFilesystem(AbstractFilesystem):
    """I mock the behaviour of an entire filesystem."""
    def __init__(self,
                 directories=None,
                 files=None,
                 operating_system: FakeOperatingSystem = None,
                 user: FakeUser = None):

        self.directories = directories or list()
        self.files = files or list()
        self._user = user or Root()
        self._effective_user = self._user.clone()
        self.operating_system = operating_system or FakeUnix()

    def __getitem__(self, path: Path) -> FakeFileLikeObject:
        if isinstance(path, str):
            path = Path(path)

        for file_object in self:
            if file_object.path.absolute() == path.absolute():
                return file_object

        raise FileNotFoundError(path)

    def __iter__(self) -> typing.Iterator[FakeFileLikeObject]:
        return iter(self.directories + self.files)

    @property
    def user(self):
        return self._user

    @property
    def curdir(self):
        """Return a path representing the current directory."""
        return Path(".")

    def has(self, path) -> bool:
        """Whether or not path already exists"""
        return self.has_directory(path) or self.has_file(path)

    def mkdir(self, path: Path, mode: int = 0o777):
        """Create an empty directory."""
        if self.has(path):
            raise FileExistsError

        if (path.parent != self.curdir and
                path.parent != path and not self.has(path.parent)):
            raise FileNotFoundError

        self.directories.append(FakeDirectory(path,
                                              mode,
                                              uid=self.user.uid,
                                              gid=self.user.gid)
                               )

    def makedirs(self, path: Path, mode: int = 0o777, exist_ok=False):
        """Recursively make path to a directory."""
        if self.has(path) and not exist_ok:
            raise OSError(path)

        for part in FakeDirectory(path).parts():
            if self.has_file(part):
                raise FileExistsError

            if not self.has_directory(part):
                self.mkdir(part, mode)

    def has_directory(self, path: Path) -> bool:
        """Whether or not such a directory exists."""
        return path.absolute() in (d.path.absolute() for d in self.directories)

    def has_file(self, path: Path) -> bool:
        """Whether or not such a file exists."""
        return path.absolute() in (f.path.absolute() for f in self.files)

    def listdir(self, path: Path) -> typing.Iterator[FakeFileLikeObject]:
        """List all files in a directory"""
        for file_object in self:
            if file_object.parent.absolute() == path.absolute():
                yield file_object

    def chown(self, path: Path, uid: int = -1, gid: int = -1):
        """Change the ownership of a file."""
        if uid != -1:
            self[path].uid = uid

        if gid != -1:
            self[path].gid = gid

    def chmod(self, path: Path, mode: int):
        """Chnage the mode of a file."""
        if not isinstance(mode, int):
            raise TypeError(mode)

        self[path].mode = mode

    def rmdir(self, path: Path):
        """Remove a directory."""
        if self.has_file(path):
            raise NotADirectoryError(path)

        if not self.has_directory(path):
            raise FileNotFoundError(path)

        if list(self.listdir(path)):
            raise OSError(path)

        for directory in self.directories:
            if directory.path.absolute() == path.absolute():
                self.directories.remove(directory)

    def remove(self, path: Path):
        """Remove a file."""
        if self.has_directory(path):
            raise IsADirectoryError(path)

        if not self.has_file(path):
            raise FileNotFoundError(path)

        for file in self.files:
            if file.path.absolute() == path.absolute():
                self.files.remove(file)

    def rename(self, src: Path, dst: Path):
        """Rename a file."""
        if src == dst:
            return

        if self.has_directory(dst):
            raise FileExistsError(dst)

        if isinstance(self.operating_system, FakeWindows) and self.has(dst):
            raise FileExistsError(dst)

        self[src].path = dst

        for file_object in self:
            if src in file_object.path.parents:
                file_object.path = dst / file_object.path.relative_to(src)

    def access(self, path: Path, mode: int, effective_ids: bool):
        """Test access for a file object."""
        if mode == 0:
            return self.has(path)

        user = self.user if not effective_ids else self.effective_user
        return user.can_access(self[path], action_mask=mode)

    def set_user(self, user: FakeUser):
        """Set the user."""
        self._user = user

    @property
    def effective_user(self) -> FakeUser:
        """Return the effective user.

        Note that effective users exist so there will be an answer to os's
        functionality regarding effective uids and gids."""
        return self._effective_user

class FakeFilesystemWithPermissions(AbstractFilesystem):
    """A filesystem decorator implementing user permissions.

    Attributes:
        filesystem (FakeFilesystem): encapsulated file system.
    """
    def __init__(self, filesystem: AbstractFilesystem):
        self.filesystem = filesystem

    def __getitem__(self, item):
        return self.filesystem[item]

    def __iter__(self):
        return iter(self.filesystem)

    def chown(self, path: Path, uid: int = -1, gid: int = -1):
        if not self.user.can_write(self[path]):
            raise PermissionError(path)

        return self.filesystem.chown(path=path, uid=uid, gid=gid)

    def chmod(self, path: Path, mode: int):
        if not self.user.can_write(self[path]):
            raise PermissionError(path)

        return self.filesystem.chmod(path=path, mode=mode)

    def mkdir(self, path: Path, mode: int = 0o777):
        if self.has_directory(path.parent) and not self.user.can_write(
                self[path.parent]):
            raise PermissionError(path.parent)

        return self.filesystem.mkdir(path=path, mode=mode)

    def listdir(self, path: Path):
        if not self.user.can_execute(self[path]):
            raise PermissionError(path)

        return self.filesystem.listdir(path=path)

    def rmdir(self, path: Path):
        if not self.user.can_write(self[path]):
            raise PermissionError(path)

        return self.filesystem.rmdir(path=path)

    def remove(self, path: Path):
        if not self.user.can_write(self[path]):
            raise PermissionError(path)

        return self.filesystem.remove(path=path)

    def rename(self, src: Path, dst: Path):
        if not self.user.can_write(self[src]):
            raise PermissionError(src)

        if self.has_directory(dst.parent) and not self.user.can_write(
                self[dst.parent]):
            raise PermissionError(dst)

        return self.filesystem.rename(src=src, dst=dst)

    def has(self, path: Path) -> bool:
        return self.filesystem.has(path=path)

    def makedirs(self, path: Path, mode: int = 0o777, exist_ok: bool = False):
        return self.filesystem.makedirs(path=path, mode=mode, exist_ok=exist_ok)

    @property
    def user(self):
        return self.filesystem.user

    def has_directory(self, path: Path) -> bool:
        return self.filesystem.has_directory(path=path)

    def has_file(self, path: Path) -> bool:
        return self.filesystem.has_file(path=path)

    def access(self, path: Path, mode: int, effective_ids: bool):
        return self.filesystem.access(path=path,
                                      mode=mode,
                                      effective_ids=effective_ids)

    def set_user(self, user: FakeUser):
        return self.filesystem.set_user(user)

    @property
    def effective_user(self) -> FakeUser:
        return self.filesystem.effective_user


text:
from abc import ABCMeta, abstractmethod

class ARPAParser(metaclass=ABCMeta):
    @abstractmethod
    def __init__(self, model):  # pragma: no cover
        pass

    @abstractmethod
    def parse(self, fp):  # pragma: no cover
        pass


text:
package iso20022

// Party that provides services to investors relating to financial products.
type Intermediary35 struct {

	// Unique and unambiguous identifier of the intermediary.
	Identification *PartyIdentification70Choice `xml:"Id"`

	// Business relationship between two entities; one entity is the account owner, the other entity is the account servicer.
	Account *Account20 `xml:"Acct,omitempty"`

	// Function performed by the intermediary.
	Role *Role4Choice `xml:"Role,omitempty"`
}

func (i *Intermediary35) AddIdentification() *PartyIdentification70Choice {
	i.Identification = new(PartyIdentification70Choice)
	return i.Identification
}

func (i *Intermediary35) AddAccount() *Account20 {
	i.Account = new(Account20)
	return i.Account
}

func (i *Intermediary35) AddRole() *Role4Choice {
	i.Role = new(Role4Choice)
	return i.Role
}


text:
/*
 * NBest.cc --
 *	N-best hypotheses and lists
 *
 */

#ifndef lint
static char Copyright[] = "Copyright (c) 1995-2010 SRI International.  All Rights Reserved.";
static char RcsId[] = "@(#)$Header: /home/srilm/devel/lm/src/RCS/NBest.cc,v 1.75 2010/06/02 06:22:48 stolcke Exp $";
#endif

#ifdef PRE_ISO_CXX
# include <iostream.h>
#else
# include <iostream>
using namespace std;
#endif
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>

#include "NBest.h"
#include "WordAlign.h"
#include "Bleu.h"
#include "MultiwordVocab.h"	// for MultiwordSeparator

#include "Array.cc"
#ifdef INSTANTIATE_TEMPLATES
INSTANTIATE_ARRAY(NBestHyp);
#endif

#define DEBUG_PRINT_RANK	1

const char *phoneSeparator = ":";	 // used for phones & phoneDurs strings
const NBestTimestamp frameLength = 0.01f; // quantization unit of word timemarks

/*
 * N-best word backtrace information
 */

const unsigned phoneStringLength = 100;

NBestWordInfo::NBestWordInfo()
    : word(Vocab_None), phones(0), phoneDurs(0),
      wordPosterior(0.0), transPosterior(0.0)
{
    // make acoustic info invalid by default
    invalidate();
}

NBestWordInfo::~NBestWordInfo()
{
    if (phones) free(phones);
    if (phoneDurs) free(phoneDurs);
}

NBestWordInfo &
NBestWordInfo::operator= (const NBestWordInfo &other)
{
    if (&other == this) {
	return *this;
    }

    if (phones) free(phones);
    if (phoneDurs) free(phoneDurs);

    word = other.word;
    start = other.start;
    duration = other.duration;
    acousticScore = other.acousticScore;
    languageScore = other.languageScore;

    if (!other.phones) {
	phones = 0;
    } else {
	phones = strdup(other.phones);
	assert(phones != 0);
    }

    if (!other.phoneDurs) {
	phoneDurs = 0;
    } else {
	phoneDurs = strdup(other.phoneDurs);
	assert(phoneDurs != 0);
    }

    wordPosterior = other.wordPosterior;
    transPosterior = other.transPosterior;

    return *this;
}

void
NBestWordInfo::write(File &file)
{
    fprintf(file, "%lg %lg %lg %lg %s %s",
			(double)start, (double)duration,
			(double)acousticScore, (double)languageScore,
			phones ? phones : phoneSeparator,
			phoneDurs ? phoneDurs : phoneSeparator);
}

Boolean
NBestWordInfo::parse(const char *s)
{
    double sTime, dur, aScore, lScore;
    char phs[phoneStringLength], phDurs[phoneStringLength];

    if (sscanf(s, "%lg %lg %lg %lg %100s %100s",
			&sTime, &dur, &aScore, &lScore, phs, phDurs) != 6)
    {
	return false;
    } else {
	start = sTime;
	duration = dur;
	acousticScore = aScore;
	languageScore = lScore;

	if (strcmp(phs, phoneSeparator) == 0) {
	    phones = 0;
	} else {
	    phones = strdup(phs);
	    assert(phones != 0);
	}

	if (strcmp(phDurs, phoneSeparator) == 0) {
	    phoneDurs = 0;
	} else {
	    phoneDurs = strdup(phDurs);
	    assert(phoneDurs != 0);
	}

	return true;
    }
}

void
NBestWordInfo::invalidate()
{
    duration = (NBestTimestamp)HUGE_VAL;
}

Boolean
NBestWordInfo::valid() const
{
    return (duration != (NBestTimestamp)HUGE_VAL);
}

void
NBestWordInfo::merge(const NBestWordInfo &other)
{
    /*
     * let the "other" word information supercede our own if it has
     * higher duration-normalized acoustic likelihood
     */
    if (other.acousticScore/other.duration > acousticScore/duration)
    {
	*this = other;
    }
}

/*
 * Utility functions for arrays of NBestWordInfo
 *	(analogous to VocabIndex * functions)
 */

unsigned
NBestWordInfo::length(const NBestWordInfo *words)
{
    unsigned len = 0;

    while (words[len].word != Vocab_None) len++;
    return len;
}

NBestWordInfo *
NBestWordInfo::copy(NBestWordInfo *to, const NBestWordInfo *from)
{
    unsigned i;
    for (i = 0; from[i].word != Vocab_None; i ++) {
        to[i] = from[i];
    }
    to[i] = from[i];

    return to;
}

/*
 * Extract VocabIndex string from NBestWordInfo array
 */
VocabIndex *
NBestWordInfo::copy(VocabIndex *to, const NBestWordInfo *from)
{
    unsigned i;
    for (i = 0; from[i].word != Vocab_None; i ++) {
	to[i] = from[i].word;
    }
    to[i] = Vocab_None;

    return to;
}

unsigned
LHash_hashKey(const NBestWordInfo *key, unsigned maxBits)
{
    unsigned i = 0;

    /*
     * Incorporate start time into hash key
     */
    if (key[0].valid()) {
    	i = (unsigned)key[0].start;
    }

    /*
     * The rationale here is similar to LHash_hashKey(unsigned),
     * except that we shift more to preserve more of the typical number of
     * bits in a VocabIndex.  The value was optimized to encoding 3 words
     * at a time (trigrams).
     */
    for (; key->word != Vocab_None; key ++) {
	i += (i << 12) + key->word;
    }
    return LHash_hashKey(i, maxBits);
}

const NBestWordInfo *
Map_copyKey(const NBestWordInfo *key)
{
    NBestWordInfo *copy = new NBestWordInfo[NBestWordInfo::length(key) + 1];
    assert(copy != 0);

    unsigned i;
    for (i = 0; key[i].word != Vocab_None; i ++) {
	copy[i] = key[i];
    }
    copy[i] = key[i];

    return copy;
}

void
Map_freeKey(const NBestWordInfo *key)
{
    delete [] (NBestWordInfo *)key;
}

/*
 * Two ngram keys are different if
 *	- their lengths differ, or
 *	- their start or end times (if defined) differ, or
 *	- their words differ
 */
Boolean
LHash_equalKey(const NBestWordInfo *key1, const NBestWordInfo *key2)
{
    unsigned len1 = NBestWordInfo::length(key1);
    unsigned len2 = NBestWordInfo::length(key2);

    if (len1 > 0 && len2 > 0) {
	if (len1 != len2 ||
	    key1[0].valid() != key2[0].valid() ||
	    (key1[0].valid() && key1[0].start != key2[0].start) ||
	    key1[len1-1].valid() != key2[len1-1].valid() ||
	    (key1[len1-1].valid() && key1[len1-1].start+key1[len1-1].duration !=
				     key2[len1-1].start+key2[len1-1].duration))
	{
	    return false;
	}
    }

    for (unsigned i = 0; i < len1; i ++) {
	if (key1[i].word != key2[i].word) {
	    return false;
	}
    }

    return true;
}

static inline int
sign(NBestTimestamp x)
{
    if (x < 0.0) {
    	return -1;
    } else if (x > 0) {
    	return 1;
    } else {
    	return 0;
    }
}

/*
 * Two ngram keys are sorted
 *	- first, by their start times
 *	- second, by their end times
 *	- last, by their words
 */
int
SArray_compareKey(const NBestWordInfo *key1, const NBestWordInfo *key2)
{
    unsigned len1 = NBestWordInfo::length(key1);
    unsigned len2 = NBestWordInfo::length(key2);

    if (len1 > 0 && len2 > 0) {
	if (key1[0].valid() != key2[0].valid()) {
	    return key1[0].valid() ? -1 : 1;
	}

	if (key1[len1-1].valid() != key2[len2-1].valid()) {
	    return key1[len1-1].valid() ? -1 : 1;
	}

	if (key1[0].valid()) {
	    NBestTimestamp diff = key1[0].start - key2[0].start;

	    if (diff != 0) {
		return sign(diff);	/* start times differ */
	    }
	}

	if (key1[len1-1].valid()) {
	    NBestTimestamp diff = (key1[len1-1].start + key1[len1-1].duration) -
	    			  (key2[len2-1].start + key2[len2-1].duration);

	    if (diff != 0) {
		return sign(diff);	/* end times differ */
	    }
	}
    }

    for (unsigned i = 0; ; i++) {
	if (key1[i].word == Vocab_None) {
	    if (key2[i].word == Vocab_None) {
		return 0;
	    } else {
		return -1;      /* key1 is shorter */
	    }
	} else {
	    if (key2[i].word == Vocab_None) {
		return 1;       /* key2 is shorter */
	    } else {
		int comp = SArray_compareKey(key1[i].word, key2[i].word);
		if (comp != 0) {
		    return comp;        /* words differ at pos i */
		}
	    }
	}
    }
    /*NOTREACHED*/
}

/*
 * N-Best hypotheses
 */

NBestHyp::NBestHyp()
{
    words = 0;
    wordInfo = 0;
    acousticScore = languageScore = totalScore = 0.0;
    posterior = 0.0;
    numWords = 0;
    numErrors = 0.0;
    rank = 0;
    bleuCount = 0;
    closestRefLeng = 0;
}

NBestHyp::~NBestHyp()
{
    delete [] words;
    delete [] wordInfo;
    delete bleuCount;
}

NBestHyp &
NBestHyp::operator= (const NBestHyp &other)
{
    // cerr << "warning: NBestHyp::operator= called\n";

    if (&other == this) {
	return *this;
    }

    delete [] words;
    delete [] wordInfo;
    delete bleuCount;

    acousticScore = other.acousticScore;
    languageScore = other.languageScore;
    totalScore = other.totalScore;

    numWords = other.numWords;
    posterior = other.posterior;
    numErrors = other.numErrors;
    rank = other.rank;

    if (other.bleuCount) {
        bleuCount = new BleuCount;
        *bleuCount = *other.bleuCount;
    } else
        bleuCount = 0;

    closestRefLeng = other.closestRefLeng;

    if (other.words) {
	unsigned actualNumWords = Vocab::length(other.words) + 1;

	words = new VocabIndex[actualNumWords];
	assert(words != 0);

	for (unsigned i = 0; i < actualNumWords; i++) {
	    words[i] = other.words[i];
	}

	if (other.wordInfo) {
	    wordInfo = new NBestWordInfo[actualNumWords];
	    assert(wordInfo != 0);

	    for (unsigned i = 0; i < actualNumWords; i++) {
		wordInfo[i] = other.wordInfo[i];
	    }
	} else {
	    wordInfo = 0;
	}

    } else {
	words = 0;
	wordInfo = 0;
    }

    return *this;
}

/*
 * N-Best Hypotheses
 */

static Boolean
addPhones(char *old, const char *ph, Boolean reversed = false)
{
    unsigned oldLen = strlen(old);
    unsigned newLen = strlen(ph);

    if (oldLen + 1 + newLen + 1 > phoneStringLength) {
	return false;
    } else if (reversed) {
	if (oldLen > 0) {
	    memmove(&old[newLen + 1], old, oldLen + 1);
	}
	strcpy(old, ph);
	if (oldLen > 0) {
	    old[newLen] = phoneSeparator[0];
	}
    } else {
	if (oldLen > 0) {
	    old[oldLen ++] = phoneSeparator[0];
	}
	strcpy(&old[oldLen], ph);
    }

    return true;
}

Boolean
NBestHyp::parse(char *line, Vocab &vocab, unsigned decipherFormat,
		LogP acousticOffset, const char *multiChar, Boolean backtrace)
{
    const unsigned maxFieldsPerLine = 11 * maxWordsPerLine + 4;
			    /* NBestList2.0 format uses 11 fields per word */

    static VocabString wstrings[maxFieldsPerLine];
    static VocabString justWords[maxFieldsPerLine + 1];
    Array<NBestWordInfo> backtraceInfo;

    unsigned actualNumWords =
		Vocab::parseWords(line, wstrings, maxFieldsPerLine);

    if (actualNumWords == maxFieldsPerLine) {
	cerr << "more than " << maxFieldsPerLine << " fields per line\n";
	return false;
    }

    /*
     * We don't do multiword splitting with backtraces -- that would require
     * a dictionary (see external split-nbest-words script).
     */
    if (backtrace) {
	multiChar = 0;
    }

    /*
     * We accept three formats for N-best hyps.
     * - The Decipher NBestList1.0 format, which has one combined bytelog score
     *	 in parens preceding the hyp.
     * - The Decipher NBestList2.0 format, where each word is followed by
     *	  ( st: <starttime> et: <endtime> g: <grammar_score> a: <ac_score> )
     * - Our own format, which has acoustic score, LM score, and number of
     *   words followed by the hyp.
     * If (decipherFormat > 0) only the specified Decipher format is accepted.
     */

    if (decipherFormat == 1 ||
	(decipherFormat == 0 && wstrings[0][0] == '('))
    {
	/*
	 * These formats don't support backtrace info
	 */
	backtrace = false;

	actualNumWords --;

	if (actualNumWords > maxWordsPerLine) {
	    cerr << "more than " << maxWordsPerLine << " words in hyp\n";
	    return false;
	}

	/*
	 * Parse the first word as a score (in parens)
	 */
	double score;

	if (sscanf(wstrings[0], "(%lf)", &score) != 1)
	{
	    cerr << "bad Decipher score: " << wstrings[0] << endl;
	    return false;
	}

	/*
	 * Save score
	 */
	totalScore = acousticScore = BytelogToLogP(score);
	languageScore = 0.0;

	/*
	 * Note: numWords includes pauses, consistent with the way the
	 * recognizer applies word transition weights.  Elimination of pauses
	 * is the job of LM rescoring.
	 */
	numWords = actualNumWords;

	Vocab::copy(justWords, &wstrings[1]);

    } else if (decipherFormat == 2) {
	if ((actualNumWords - 1) % 11) {
	    cerr << "badly formatted hyp\n";
	    return false;
	}

	unsigned numTokens = (actualNumWords - 1)/11;

	if (numTokens > maxWordsPerLine) {
	    cerr << "more than " << maxWordsPerLine << " tokens in hyp\n";
	    return false;
	}

	/*
	 * Parse the first word as a score (in parens)
	 */
	double score;

	if (sscanf(wstrings[0], "(%lf)", &score) != 1)
	{
	    cerr << "bad Decipher score: " << wstrings[0] << endl;
	    return false;
	}

	/*
	 * Parse remaining line into words and scores
	 *	skip over phone and state backtrace tokens, which can be
	 *	identified by noting that their times are contained within
	 *	the word duration.
	 */
	Bytelog acScore = 0;
	Bytelog lmScore = 0;

	NBestTimestamp prevEndTime = -1.0;	/* end time of last token */
	NBestTimestamp prevPhoneStart = 0.0;
	NBestWordInfo *prevWordInfo = 0;

	char phones[phoneStringLength];
	char phoneDurs[phoneStringLength];

	actualNumWords = 0;
	for (unsigned i = 0; i < numTokens; i ++) {

	    const char *token = wstrings[1 + 11 * i];
	    NBestTimestamp startTime = atof(wstrings[1 + 11 * i + 3]);
	    NBestTimestamp endTime = atof(wstrings[1 + 11 * i + 5]);

	    /*
	     * Check if this token refers to an HMM state, i.e., if
	     * it matches the pattern /-[0-9]$/.
	     * XXX: because of a bug in Decipher we need to perform this
	     * check even if we're scanning for word tokens.
	     */
	    const char *hyphen = strrchr(token, '-');
	    Boolean isStateToken = hyphen != 0 &&
				hyphen[1] >= '0' && hyphen[1] <= '9' &&
				hyphen[2] == '\0';

	    if (startTime > prevEndTime && !isStateToken) {
		int acWordScore = atol(wstrings[1 + 11 * i + 9]);
		int lmWordScore = atol(wstrings[1 + 11 * i + 7]);

		justWords[actualNumWords] = token;

		if (backtrace) {
		    /*
		     * save pronunciation info for previous word
		     */
		    if (prevWordInfo) {
			prevWordInfo->phones = strdup(phones);
			assert(prevWordInfo->phones != 0);

			prevWordInfo->phoneDurs = strdup(phoneDurs);
			assert(prevWordInfo->phoneDurs != 0);
		    }

		    NBestWordInfo winfo;
		    winfo.word = Vocab_None;
		    winfo.start = startTime;
		    /*
		     * NB: "et" in nbest backtrace is actually the START time
		     * of the last frame
		     */
		    winfo.duration = endTime - startTime + frameLength;
		    winfo.acousticScore = BytelogToLogP(acWordScore);
		    winfo.languageScore = BytelogToLogP(lmWordScore);
		    winfo.phones = winfo.phoneDurs = 0;

		    backtraceInfo[actualNumWords] = winfo;

		    /*
		     * prepare for collecting phone backtrace info
		     */
		    prevWordInfo = &backtraceInfo[actualNumWords];
		    phones[0] = phoneDurs[0] = '\0';
		}

		acScore += acWordScore;
		lmScore += lmWordScore;

		actualNumWords ++;

		prevEndTime = endTime;
	    } else {
		/*
		 * check if this token refers to an HMM state, i.e., if
		 * if matches the pattern /-[0-9]$/
		 */
		if (isStateToken) {
		    continue;
		}

		/*
		 * A Decipher phone token: if we're extracting backtrace
		 * information, * get phone identity and duration and store
		 * in word Info.
		 * The format of Decipher context-dep phone token is:
		 *    leftcontext '[' phonelabel '_' diacritic ']' rightcontext
		 * Everything except the phonelabel is optional.
		 */
		if (prevWordInfo) {
		    const char *lbracket = strchr(token, '[');
		    const char *phone = lbracket ? lbracket + 1 : token;
		    char *rbracket = (char *)strrchr(phone, ']');
		    if (rbracket) *rbracket = '\0';
		    char *subscript = (char *)strrchr(phone, '_');
		    if (subscript) *subscript = '\0';
		    addPhones(phones, phone, startTime < prevPhoneStart);

		    char phoneDur[20];
		    sprintf(phoneDur, "%d",
			    (int)((endTime - startTime)/frameLength + 0.5) + 1);
		    addPhones(phoneDurs, phoneDur, startTime < prevPhoneStart);

		    prevPhoneStart = startTime;
		}
	    }
	}

	if (backtrace) {
	    /*
	     * save pronunciation info for last word
	     */
	    if (prevWordInfo) {
		prevWordInfo->phones = strdup(phones);
		assert(prevWordInfo->phones != 0);

		prevWordInfo->phoneDurs = strdup(phoneDurs);
		assert(prevWordInfo->phoneDurs != 0);
	    }
	}

	justWords[actualNumWords] = 0;

	/*
	 * Save scores
	 */
	totalScore = BytelogToLogP(score);
	acousticScore = BytelogToLogP(acScore);
	languageScore = BytelogToLogP(lmScore);
	numWords = actualNumWords;

	/*
	if (score != acScore + lmScore) {
	    cerr << "acoustic and language model scores don't add up ("
		 << acScore << " + " << lmScore << " != " << score << ")\n";
	}
	*/

    } else {
	actualNumWords -= 3;

	if (actualNumWords > maxWordsPerLine) {
	    cerr << "more than " << maxWordsPerLine << " words in hyp\n";
	    return false;
	}

	/*
	 * Parse the first three columns as numbers
	 */
	if (!parseLogP(wstrings[0], acousticScore)) {
	    cerr << "bad acoustic score: " << wstrings[0] << endl;
	    return false;
	}
	if (!parseLogP(wstrings[1], languageScore)) {
	    cerr << "bad LM score: " << wstrings[1] << endl;
	    return false;
	}
	if (!stringToCount(wstrings[2], numWords)) {
	    cerr << "bad word count: " << wstrings[2] << endl;
	    return false;
	}

	/*
	 * Set the total score to the acoustic score so
	 * decipherFix() with a null language model leaves everything
	 * unchanged.
	 */
	totalScore = acousticScore;

	Vocab::copy(justWords, &wstrings[3]);
    }

    /*
     * Apply acoustic normalization in effect
     */
    acousticScore -= acousticOffset;
    totalScore -= acousticOffset;

    /*
     * Adjust number of words for multiwords if appropriate
     */
    if (multiChar) {
	for (unsigned j = 0; justWords[j] != 0; j ++) {
	    const char *cp = justWords[j];

	    for (cp = strchr(cp, *multiChar);
		 cp != 0;
		 cp = strchr(cp + 1, *multiChar))
	    {
		actualNumWords ++;
	    }
	}
    }

    /*
     * Copy words to nbest list
     */
    delete [] words;
    words = new VocabIndex[actualNumWords + 1];
    assert(words != 0);

    Boolean unkIsWord = vocab.unkIsWord();

    /*
     * Map word strings to indices
     */
    if (!multiChar) {
	if (unkIsWord) {
	    vocab.getIndices(justWords, words, actualNumWords + 1,
							    vocab.unkIndex());
	} else {
	    vocab.addWords(justWords, words, actualNumWords + 1);
	}

	if (decipherFormat == 2 && backtrace) {
	    delete [] wordInfo;
	    wordInfo = new NBestWordInfo[actualNumWords + 1];

	    for (unsigned j = 0; j < actualNumWords; j ++) {
		wordInfo[j] = backtraceInfo[j];
		wordInfo[j].word = words[j];
	    }
	    wordInfo[actualNumWords].word = Vocab_None;
	} else {
	    wordInfo = 0;
	}
    } else {
	unsigned i = 0;
	for (unsigned j = 0; justWords[j] != 0; j ++) {
	    char *start = (char *)justWords[j];
	    char *cp;

	    while ((cp = strchr(start, *multiChar))) {
		*cp = '\0';
		words[i++] =
		    unkIsWord ? vocab.getIndex(start, vocab.unkIndex())
			      : vocab.addWord(start);
		*cp = *multiChar;
		start = cp + 1;
	    }

	    words[i++] =
		unkIsWord ? vocab.getIndex(start, vocab.unkIndex())
			  : vocab.addWord(start);
	}
	words[i] = Vocab_None;
    }

    return true;
}

void
NBestHyp::write(File &file, Vocab &vocab, Boolean decipherFormat,
						LogP acousticOffset)
{
    if (decipherFormat) {
	fprintf(file, "(%d)", (int)LogPtoBytelog(totalScore + acousticOffset));
    } else {
	fprintf(file, "%g %g %lu", acousticScore + acousticOffset,
				      languageScore, (unsigned long)numWords);
    }

    for (unsigned i = 0; words[i] != Vocab_None; i++) {
	/*
	 * Write backtrace information if known and Decipher format is desired
	 */
	if (decipherFormat && wordInfo) {
	    fprintf(file, " %s ( st: %.2f et: %.2f g: %d a: %d )",
			   vocab.getWord(wordInfo[i].word),
			   wordInfo[i].start,
			   wordInfo[i].start+wordInfo[i].duration - frameLength,
			   (int)LogPtoBytelog(wordInfo[i].languageScore),
			   (int)LogPtoBytelog(wordInfo[i].acousticScore));
	} else {
	    fprintf(file, " %s", vocab.getWord(words[i]));
	}
    }

    fprintf(file, "\n");
}

void
NBestHyp::rescore(LM &lm, double lmScale, double wtScale)
{
    TextStats stats;

    /*
     * LM score is recomputed,
     * numWords is set to take non-word tokens into account
     */
    languageScore = weightLogP(lmScale, lm.sentenceProb(words, stats));
    numWords = (Count)stats.numWords;

    /*
     * Note: In the face of zero probaility words we do NOT
     * set the LM probability to zero.  These cases typically
     * reflect a vocabulary mismatch between the rescoring LM
     * and the recognizer, and it is more useful to rescore based on
     * the known words alone.  The warning hopefull will cause
     * someone to asssess the problem.
     */
    if (stats.zeroProbs > 0) {
	cerr << "warning: hyp contains zero prob words: "
	     << (lm.vocab.use(), words) << endl;
    }

    if (stats.numOOVs > 0) {
	cerr << "warning: hyp contains OOV words: "
	     << (lm.vocab.use(), words) << endl;
    }

    totalScore = acousticScore +
			    languageScore +
			    wtScale * numWords;
}

void
NBestHyp::reweight(double lmScale, double wtScale, double amScale)
{
    totalScore = weightLogP(amScale, acousticScore) +
			    weightLogP(lmScale, languageScore) +
			    wtScale * numWords;
}

void
NBestHyp::decipherFix(LM &lm, double lmScale, double wtScale)
{
    TextStats stats;

    /*
     * LM score is recomputed,
     * numWords is set to take non-word tokens into account
     */
    languageScore = weightLogP(lmScale, lm.sentenceProb(words, stats));
    numWords = (Count)stats.numWords;

    /*
     * Arguably a bug, but Decipher actually applies WTW to pauses.
     * So we have to do the same when subtracting the non-acoustic
     * scores below.
     */
    unsigned numAllWords = Vocab::length(words);

    if (stats.zeroProbs > 0) {
	cerr << "warning: hyp contains zero prob words: "
	     << (lm.vocab.use(), words) << endl;
	languageScore = LogP_Zero;
    }

    if (stats.numOOVs > 0) {
	cerr << "warning: hyp contains OOV words: "
	     << (lm.vocab.use(), words) << endl;
	languageScore = LogP_Zero;
    }

    acousticScore = totalScore -
			    languageScore -
			    wtScale * numAllWords;
}

/*
 * N-Best lists
 */

unsigned NBestList::initialSize = 100;

NBestList::NBestList(Vocab &vocab, unsigned maxSize,
				    Boolean multiwords, Boolean backtrace)
    : vocab(vocab), acousticOffset(0.0),
      hypList(0, initialSize), _numHyps(0), maxSize(maxSize),
      multiChar(0), backtrace(backtrace)
{
    if (multiwords) {
    	multiChar = MultiwordSeparator;
    }
}

// enable multiwords if multiChar != 0
NBestList::NBestList(Vocab &vocab, unsigned maxSize,
				const char *multiChar, Boolean backtrace)
    : vocab(vocab), acousticOffset(0.0),
      hypList(0, initialSize), _numHyps(0), maxSize(maxSize),
      multiChar(multiChar), backtrace(backtrace)
{
}

/*
 * Compute memory usage
 */
void
NBestList::memStats(MemStats &stats)
{
    stats.total += sizeof(*this) - sizeof(hypList);
    hypList.memStats(stats);

    /*
     * Add space taken up by hyp strings
     */
    for (unsigned h = 0; h < _numHyps; h++) {
	unsigned numWords = Vocab::length(hypList[h].words);
	stats.total += (numWords + 1) * sizeof(VocabIndex);
	if (hypList[h].wordInfo) {
	    stats.total += (numWords + 1) * sizeof(NBestWordInfo);
	}
    }
}

static int
compareHyps(const void *h1, const void *h2)
{
    LogP score1 = ((NBestHyp *)h1)->totalScore;
    LogP score2 = ((NBestHyp *)h2)->totalScore;

    return score1 > score2 ? -1 :
		score1 < score2 ? 1 : 0;
}

void
NBestList::sortHyps()
{
    /*
     * Sort the underlying array in place, in order of descending scores
     */
    qsort(hypList.data(), _numHyps, sizeof(NBestHyp), compareHyps);
}

extern double
computeBleu(unsigned n, unsigned correct[], unsigned total[],
            unsigned length, unsigned rlength);

void
NBestList::sortHypsBySentenceBleu(unsigned order)
{
    // compute sentence bleu
    unsigned total [MAX_BLEU_NGRAM];
    unsigned correct [MAX_BLEU_NGRAM];

    for (unsigned i = 0; i < _numHyps; i++) {
        NBestHyp & h = hypList[i];

        int t = h.numWords;
        for (unsigned k = 0; k < order; k++) {
            total[k] = t;
            correct[k] = h.bleuCount->correct[k];
            if (t > 0) t --;
        }

        double bleu = computeBleu(order, correct, total, h.numWords, h.closestRefLeng);
        h.totalScore = bleu;
    }

    sortHyps();
}

float
NBestList::sortHypsByErrorRate()
{
    if (_numHyps == 0) return 0;

    for (unsigned i = 0; i < _numHyps; i++) {
        NBestHyp & h = hypList[i];
        h.totalScore = -h.numErrors;
    }

    sortHyps();
    return hypList[0].numErrors;
}

Boolean
NBestList::read(File &file)
{
    char *line = file.getline();
    unsigned decipherFormat = 0;

    /*
     * If the first line contains the Decipher magic string
     * we enforce Decipher format for the entire N-best list.
     */
    if (line != 0) {
	if (strncmp(line, nbest1Magic, sizeof(nbest1Magic) - 1) == 0) {
	    decipherFormat = 1;
	    line = file.getline();
	} else if (strncmp(line, nbest2Magic, sizeof(nbest2Magic) - 1) == 0) {
	    decipherFormat = 2;
	    line = file.getline();
	}
    }

    unsigned int howmany = 0;

    while (line && (maxSize == 0 || howmany < maxSize)) {
	if (! hypList[howmany].parse(line, vocab, decipherFormat,
					acousticOffset, multiChar, backtrace))
	{
	    file.position() << "bad n-best hyp\n";
	    return false;
	}

	hypList[howmany].rank = howmany;

	howmany ++;

	line = file.getline();
    }

    _numHyps = howmany;

    return true;
}

Boolean
NBestList::write(File &file, Boolean decipherFormat, unsigned numHyps)
{
    if (decipherFormat) {
	fprintf(file, "%s\n", backtrace ? nbest2Magic : nbest1Magic);
    }

    for (unsigned h = 0;
	 h < _numHyps && (numHyps == 0 || h < numHyps);
	 h++)
    {
	hypList[h].write(file, vocab, decipherFormat, acousticOffset);
    }

    return true;
}

/*
 * Recompute total scores by recomputing LM scores and adding them to the
 * acoustic scores including a word transition penalty.
 */
void
NBestList::rescoreHyps(LM &lm, double lmScale, double wtScale)
{
    for (unsigned h = 0; h < _numHyps; h++) {
	hypList[h].rescore(lm, lmScale, wtScale);
    }
}

/*
 * Recompute total hyp scores using new scaling constants.
 */
void
NBestList::reweightHyps(double lmScale, double wtScale, double amScale)
{
    for (unsigned h = 0; h < _numHyps; h++) {
	hypList[h].reweight(lmScale, wtScale, amScale);
    }
}

/*
 * Compute posterior probabilities
 */
void
NBestList::computePosteriors(double lmScale, double wtScale,
					    double postScale, double amScale)
{
    /*
     * First compute the numerators for the posteriors
     */
    LogP2 totalNumerator = LogP_Zero;
    LogP scoreOffset;

    unsigned h;
    for (h = 0; h < _numHyps; h++) {
	NBestHyp &hyp = hypList[h];

	/*
	 * This way of computing the total score differs from
	 * hyp.reweight() in that we're scaling back the acoustic
	 * scores, rather than scaling up the LM scores.
	 *
	 * Store the score back into the nbest list so we can
	 * sort on it later.
	 *
	 * The posterior weight is a parameter that controls the
	 * peakedness of the posterior distribution.
	 *
	 * As a special case, if all weights are zero, we compute the
	 * posterios directly from the stored aggregate scores.
	 */
	LogP totalScore;

	if (amScale == 0.0 && lmScale == 0.0 && wtScale == 0.0) {
	    totalScore = hyp.totalScore / postScale;
	} else {
	    totalScore = (weightLogP(amScale, hyp.acousticScore) +
				weightLogP(lmScale, hyp.languageScore) +
				wtScale * hyp.numWords) /
			     postScale;
	}

	/*
	 * To prevent underflow when converting LogP's to Prob's, we
	 * subtract off the LogP of the first hyp.
	 * This is equivalent to a constant factor on all Prob's, which
	 * cancels in the normalization.
	 */
	if (h == 0) {
	    scoreOffset = totalScore;
	    totalScore = 0.0;
	} else {
	    totalScore -= scoreOffset;
	}

	/*
	 * temporarily store unnormalized log posterior in hyp
	 */
	hyp.posterior = totalScore;

	totalNumerator = AddLogP(totalNumerator, hyp.posterior);
    }

    /*
     * Normalize posteriors
     */
    for (h = 0; h < _numHyps; h++) {
	NBestHyp &hyp = hypList[h];

	hyp.posterior = LogPtoProb(hyp.posterior - totalNumerator);
    }
}

/*
 * Recompute acoustic scores by subtracting recognizer LM scores
 * from totals.
 */
void
NBestList::decipherFix(LM &lm, double lmScale, double wtScale)
{
    for (unsigned h = 0; h < _numHyps; h++) {
	hypList[h].decipherFix(lm, lmScale, wtScale);
    }
}

/*
 * Remove noise and pause words from hyps
 */
void
NBestList::removeNoise(LM &lm)
{
    NBestWordInfo endOfHyp;
    endOfHyp.word = Vocab_None;

    for (unsigned h = 0; h < _numHyps; h++) {
	lm.removeNoise(hypList[h].words);

	NBestWordInfo *wordInfo = hypList[h].wordInfo;

	// remove corresponding tokens from wordInfo array
	if (wordInfo) {
	    unsigned from, to;

	    for (from = 0, to = 0; wordInfo[from].word != Vocab_None; from ++) {
		if (wordInfo[from].word != vocab.pauseIndex() &&
		    !lm.noiseVocab.getWord(wordInfo[from].word))
		{
		    wordInfo[to++] = wordInfo[from];
		}
	    }
	    wordInfo[to] = endOfHyp;
	}
    }
}

/*
 * Normalize acoustic scores so that maximum is 0
 */
void
NBestList::acousticNorm()
{
    unsigned h;
    LogP maxScore;

    /*
     * Find maximum acoustic score
     */
    for (h = 0; h < _numHyps; h++) {
	if (h == 0 || hypList[h].acousticScore > maxScore) {
	    maxScore = hypList[h].acousticScore;
	}
    }

    /*
     * Normalize all scores
     */
    for (h = 0; h < _numHyps; h++) {
	hypList[h].acousticScore -= maxScore;
	hypList[h].totalScore -= maxScore;
    }

    acousticOffset = maxScore;
}

/*
 * Restore acoustic scores to their un-normalized values
 */
void
NBestList::acousticDenorm()
{
    for (unsigned h = 0; h < _numHyps; h++) {
	hypList[h].acousticScore += acousticOffset;
	hypList[h].totalScore -= acousticOffset;
    }

    acousticOffset = 0.0;
}

/*
 * Compute minimal word error of all hyps in the list.
 * As a side-effect the error counts on all nbest hyps are updated.
 * If weight != 0, the error counts are set to the old counts plus the
 * computed new counts times the given weight.
 */
unsigned
NBestList::wordError(const VocabIndex *words,
		     unsigned &sub, unsigned &ins, unsigned &del, float weight)
{
    unsigned minErr = (unsigned)(-1);

    for (unsigned h = 0; h < _numHyps; h++) {
	unsigned s, i, d;
	unsigned werr = ::wordError(hypList[h].words, words, s, i, d);

	if (h == 0 || werr < minErr) {
	    minErr = werr;
	    sub = s;
	    ins = i;
	    del = d;
	}

	if (weight == 0.0) {
	    hypList[h].numErrors = (float)werr;
	} else {
	    hypList[h].numErrors += weight * werr;
	}
    }

    if (_numHyps == 0) {
	/*
	 * If the n-best lists is empty we count all reference words as deleted.
	 */
	minErr = del = Vocab::length(words);
	sub = 0;
	ins = 0;
    }

    return minErr;
}

/*
 * Return hyp with minimum expected word error
 */
double
NBestList::minimizeWordError(VocabIndex *words, unsigned length,
				double &subs, double &inss, double &dels,
				unsigned maxRescore, Prob postPrune)
{
    /*
     * Compute expected word errors
     */
    double bestError;
    unsigned bestHyp;

    unsigned howmany = (maxRescore > 0) ? maxRescore : _numHyps;
    if (howmany > _numHyps) {
	howmany = _numHyps;
    }

    for (unsigned i = 0; i < howmany; i ++) {
	NBestHyp &hyp = getHyp(i);

	double totalErrors = 0.0;
	double totalSubs = 0.0;
	double totalInss = 0.0;
	double totalDels = 0.0;
	Prob totalPost = 0.0;

	for (unsigned j = 0; j < _numHyps; j ++) {
	    NBestHyp &otherHyp = getHyp(j);

	    if (i != j) {
		unsigned sub, ins, del;
		totalErrors += otherHyp.posterior *
			::wordError(hyp.words, otherHyp.words, sub, ins, del);
		totalSubs += otherHyp.posterior * sub;
		totalInss += otherHyp.posterior * ins;
		totalDels += otherHyp.posterior * del;
	    }

	    /*
	     * Optimization: if the partial accumulated error exceeds the
	     * current best error then this cannot be a new best.
	     */
	    if (i > 0 && totalErrors > bestError) {
		break;
	    }

	    /*
	     * Ignore hyps whose cummulative posterior mass is below threshold
	     */
	    totalPost += otherHyp.posterior;
	    if (postPrune > 0.0 && totalPost > 1.0 - postPrune) {
		break;
	    }
	}

	if (i == 0 || totalErrors < bestError) {
	    bestHyp = i;
	    bestError = totalErrors;
	    subs = totalSubs;
	    inss = totalInss;
	    dels = totalDels;
	}
    }

    if (debug(DEBUG_PRINT_RANK)) {
	cerr << "best hyp = " << bestHyp
	     << " post = " << getHyp(bestHyp).posterior
	     << " wer = " << bestError << endl;
    }

    if (howmany > 0) {
	for (unsigned j = 0; j < length; j ++) {
	    words[j] = getHyp(bestHyp).words[j];

	    if (words[j] == Vocab_None) break;
	}

	return bestError;
    } else {
	if (length > 0) {
	    words[0] = Vocab_None;
	}

	return 0.0;
    }
}


text:
package com.eNic.Screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.eNic.GameWorld.GameRenderer;
import com.eNic.GameWorld.GameWorld;
import com.eNic.Helpers.InputHandler;

public class GameScreen implements Screen {

    private GameWorld world;
    private GameRenderer renderer;
    private float runTime;

    // This is the constructor, not the class declaration
    public GameScreen() {

	float screenWidth = Gdx.graphics.getWidth();
	float screenHeight = Gdx.graphics.getHeight();
	float gameWidth = 480;
	float gameHeight = screenHeight / (screenWidth / gameWidth);

	world = new GameWorld();
	Gdx.input.setInputProcessor(new InputHandler(world, screenWidth
		/ gameWidth, screenHeight / gameHeight));
	renderer = new GameRenderer(world, (int) gameWidth, (int) gameHeight);
	world.setRenderer(renderer);
    }

    @Override
    public void render(float delta) {
	runTime += delta;
	world.update(delta);
	renderer.render(delta, runTime);
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void show() {
    }

    @Override
    public void hide() {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
    }

}


text:
package org.omg.CosTransactions;

/**
* org/omg/CosTransactions/RecoveryCoordinatorHolder.java .
* Error reading Messages File.
* Error reading Messages File.
* Thursday, January 14, 2010 1:08:59 AM PST
*/

public final class RecoveryCoordinatorHolder implements org.omg.CORBA.portable.Streamable
{
  public org.omg.CosTransactions.RecoveryCoordinator value = null;

  public RecoveryCoordinatorHolder ()
  {
  }

  public RecoveryCoordinatorHolder (org.omg.CosTransactions.RecoveryCoordinator initialValue)
  {
    value = initialValue;
  }

  public void _read (org.omg.CORBA.portable.InputStream i)
  {
    value = org.omg.CosTransactions.RecoveryCoordinatorHelper.read (i);
  }

  public void _write (org.omg.CORBA.portable.OutputStream o)
  {
    org.omg.CosTransactions.RecoveryCoordinatorHelper.write (o, value);
  }

  public org.omg.CORBA.TypeCode _type ()
  {
    return org.omg.CosTransactions.RecoveryCoordinatorHelper.type ();
  }

}


text:
package org.apache.ibatis.ibator.api.dom.java;

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

/**
 * @author Jeff Butler
 */
public class Parameter {
    private String name;
    private FullyQualifiedJavaType type;

    private List<String> annotations;

    public Parameter(FullyQualifiedJavaType type, String name) {
        super();
        this.name = name;
        this.type = type;
        annotations = new ArrayList<String>();
    }

    public Parameter(FullyQualifiedJavaType type, String name, String annotation) {
        this(type, name);
        addAnnotation(annotation);
    }

    /**
     * @return Returns the name.
     */
    public String getName() {
        return name;
    }
    /**
     * @return Returns the type.
     */
    public FullyQualifiedJavaType getType() {
        return type;
    }

    public List<String> getAnnotations() {
        return annotations;
    }

    public void addAnnotation(String annotation) {
        annotations.add(annotation);
    }

    public String getFormattedContent() {
        StringBuilder sb = new StringBuilder();

        for (String annotation : annotations) {
            sb.append(annotation);
            sb.append(' ');
        }

        sb.append(type.getShortName());
        sb.append(' ');
        sb.append(name);

        return sb.toString();
    }

    @Override
    public String toString() {
        return getFormattedContent();
    }
}


text:
package bbuzz

// TODO
trait RedisPubsubTweets extends TweetProvider{
  def tweets: TweetObservable = ???
}


text:
package org.apache.jackrabbit.mongomk.impl.command;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.jackrabbit.mk.model.tree.DiffBuilder;
import org.apache.jackrabbit.mk.model.tree.NodeState;
import org.apache.jackrabbit.mongomk.api.command.Command;
import org.apache.jackrabbit.mongomk.api.model.Commit;
import org.apache.jackrabbit.mongomk.api.model.Node;
import org.apache.jackrabbit.mongomk.impl.MongoNodeStore;
import org.apache.jackrabbit.mongomk.impl.action.FetchCommitAction;
import org.apache.jackrabbit.mongomk.impl.action.FetchCommitsAction;
import org.apache.jackrabbit.mongomk.impl.action.FetchHeadRevisionIdAction;
import org.apache.jackrabbit.mongomk.impl.json.JsopParser;
import org.apache.jackrabbit.mongomk.impl.json.NormalizingJsopHandler;
import org.apache.jackrabbit.mongomk.impl.model.CommitBuilder;
import org.apache.jackrabbit.mongomk.impl.model.MongoCommit;
import org.apache.jackrabbit.mongomk.impl.model.NodeImpl;
import org.apache.jackrabbit.mongomk.impl.model.tree.MongoNodeDelta;
import org.apache.jackrabbit.mongomk.impl.model.tree.MongoNodeDelta.Conflict;
import org.apache.jackrabbit.mongomk.impl.model.tree.MongoNodeState;
import org.apache.jackrabbit.mongomk.impl.model.tree.SimpleMongoNodeStore;
import org.apache.jackrabbit.mongomk.util.MongoUtil;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A {@code Command} for {@code MongoMicroKernel#merge(String, String)}
 */
public class MergeCommand extends BaseCommand<String> {

    private static final Logger LOG = LoggerFactory.getLogger(MergeCommand.class);

    private final String branchRevisionId;
    private final String message;

    /**
     * Constructs a {@code MergeCommandMongo}
     *
     * @param nodeStore Node store.
     * @param branchRevisionId Branch revision id.
     * @param message Merge message.
     */
    public MergeCommand(MongoNodeStore nodeStore, String branchRevisionId,
            String message) {
        super(nodeStore);
        this.branchRevisionId = branchRevisionId;
        this.message = message;
    }

    @Override
    public String execute() throws Exception {
        MongoCommit commit = new FetchCommitAction(nodeStore,
                MongoUtil.toMongoRepresentation(branchRevisionId)).execute();
        String branchId = commit.getBranchId();
        if (branchId == null) {
            throw new Exception("Can only merge a private branch commit");
        }

        long rootNodeId = commit.getRevisionId();

        FetchHeadRevisionIdAction query2 = new FetchHeadRevisionIdAction(nodeStore);
        long currentHead = query2.execute();

        long branchRootId = Long.parseLong(branchId.substring(0, branchId.indexOf("-")));

        Commit newCommit;
        String diff = getNonConflictingCommitsDiff(Math.max(currentHead, commit.getRevisionId()),
                branchRootId, branchId);
        if (diff != null) {
            newCommit = CommitBuilder.build("/", diff.toString(),
                    MongoUtil.fromMongoRepresentation(currentHead), message);
        } else {
            Node ourRoot = getNode("/", rootNodeId, branchId);

            // Merge changes, if any, from trunk to branch.
            Node currentHeadNode = getNode("/", currentHead);
            if (currentHead != branchRootId) {
                ourRoot = mergeNodes(ourRoot, currentHeadNode, branchRootId);
            }

            diff = new DiffBuilder(MongoUtil.wrap(currentHeadNode),
                    MongoUtil.wrap(ourRoot), "/", -1,
                    new SimpleMongoNodeStore(), "").build();

            if (diff.isEmpty()) {
                LOG.debug("Merge of empty branch {} with differing content hashes encountered, " +
                        "ignore and keep current head {}", branchRevisionId, currentHead);
                return MongoUtil.fromMongoRepresentation(currentHead);
            }

            newCommit = CommitBuilder.build("", diff,
                    MongoUtil.fromMongoRepresentation(currentHead), message);
        }

        Command<Long> command = new CommitCommandNew(nodeStore, newCommit);
        long revision = command.execute();
        return MongoUtil.fromMongoRepresentation(revision);
    }

    /**
     * Checks whether there have been no conflicting commits on trunk since the
     * branch was created and if so, returns the branch diff to be applied against
     * trunk. Otherwise, it returns null.
     *
     * @param currentHead
     * @param branchRootId
     * @param branchId
     * @return
     */
    private String getNonConflictingCommitsDiff(long currentHead, long branchRootId, String branchId) {
        FetchCommitsAction action = new FetchCommitsAction(nodeStore, branchRootId + 1, currentHead);
        List<MongoCommit> commits = action.execute();

        Set<String> affectedPathsBranch = new HashSet<String>();
        Set<String> affectedPathsTrunk = new HashSet<String>();
        StringBuilder diff = new StringBuilder();

        for (int i = commits.size() - 1; i >= 0; i--) {
            MongoCommit commit = commits.get(i);
            Set<String> affectedPaths = commit.getAffectedPaths();
            for (String affectedPath : affectedPaths) {
                if (branchId.equals(commit.getBranchId())) {
                    if (affectedPathsTrunk.contains(affectedPath)) {
                        return null;
                    }
                    affectedPathsBranch.add(affectedPath);
                } else if (commit.getBranchId() == null){
                    if (affectedPathsBranch.contains(affectedPath)) {
                        return null;
                    }
                    affectedPathsTrunk.add(affectedPath);
                }
            }
            if (branchId.equals(commit.getBranchId())) {
                try {
                    diff.append(normalizeDiff(commit.getPath(), commit.getDiff()));
                } catch (Exception e) {
                    LOG.error("Normalization error", e);
                }
            }
        }
        return diff.length() > 0 ? diff.toString() : null;
    }

    /**
     * Normalizes a JSOP diff by appending the path to all pathStrings of the
     * operations.
     *
     * @param path the root path of the diff.
     * @param diff the JSOP diff.
     * @return the JSOP diff based on an empty root path.
     */
    private String normalizeDiff(String path, String diff) throws Exception {
        NormalizingJsopHandler handler = new NormalizingJsopHandler();
        new JsopParser(path, diff, handler).parse();
        return handler.getDiff();
    }

    private NodeImpl mergeNodes(Node ourRoot, Node theirRoot,
            Long commonAncestorRevisionId) throws Exception {

        Node baseRoot = getNode("/", commonAncestorRevisionId);
        Node theirRootCopy = copy(theirRoot);

        // Recursively merge 'our' changes with 'their' changes...
        return mergeNode(baseRoot, ourRoot, theirRootCopy, "/");
    }

    private NodeImpl mergeNode(Node baseNode, Node ourNode, Node theirNode,
            String path) throws Exception {
        MongoNodeDelta theirChanges = new MongoNodeDelta(new SimpleMongoNodeStore(),
                MongoUtil.wrap(baseNode), MongoUtil.wrap(theirNode));
        MongoNodeDelta ourChanges = new MongoNodeDelta(new SimpleMongoNodeStore(),
                MongoUtil.wrap(baseNode), MongoUtil.wrap(ourNode));

        NodeImpl stagedNode = (NodeImpl)theirNode; //new NodeImpl(path);

        // Apply our changes.
        stagedNode.getProperties().putAll(ourChanges.getAddedProperties());
        stagedNode.getProperties().putAll(ourChanges.getChangedProperties());
        for (String name : ourChanges.getRemovedProperties().keySet()) {
            stagedNode.getProperties().remove(name);
        }

        for (Map.Entry<String, NodeState> entry : ourChanges.getAddedChildNodes().entrySet()) {
            MongoNodeState nodeState = (MongoNodeState)entry.getValue();
            stagedNode.addChildNodeEntry(nodeState.unwrap());
        }
        for (Map.Entry<String, NodeState> entry : ourChanges.getChangedChildNodes().entrySet()) {
            if (!theirChanges.getChangedChildNodes().containsKey(entry.getKey())) {
                MongoNodeState nodeState = (MongoNodeState)entry.getValue();
                stagedNode.addChildNodeEntry(nodeState.unwrap());
            }
        }
        for (String name : ourChanges.getRemovedChildNodes().keySet()) {
            stagedNode.removeChildNodeEntry(name);
        }

        List<Conflict> conflicts = theirChanges.listConflicts(ourChanges);
        // resolve/report merge conflicts
        for (Conflict conflict : conflicts) {
            String conflictName = conflict.getName();
            String conflictPath = PathUtils.concat(path, conflictName);
            switch (conflict.getType()) {
                case PROPERTY_VALUE_CONFLICT:
                    throw new Exception(
                            "concurrent modification of property " + conflictPath
                                    + " with conflicting values: \""
                                    + ourNode.getProperties().get(conflictName)
                                    + "\", \""
                                    + theirNode.getProperties().get(conflictName));

                case NODE_CONTENT_CONFLICT: {
                    if (ourChanges.getChangedChildNodes().containsKey(conflictName)) {
                        // modified subtrees
                        Node baseChild = baseNode.getChildNodeEntry(conflictName);
                        Node ourChild = ourNode.getChildNodeEntry(conflictName);
                        Node theirChild = theirNode.getChildNodeEntry(conflictName);
                        // merge the dirty subtrees recursively
                        mergeNode(baseChild, ourChild, theirChild, PathUtils.concat(path, conflictName));
                    } else {
                        // todo handle/merge colliding node creation
                        throw new Exception("colliding concurrent node creation: " + conflictPath);
                    }
                    break;
                }

                case REMOVED_DIRTY_PROPERTY_CONFLICT:
                    stagedNode.getProperties().remove(conflictName);
                    break;

                case REMOVED_DIRTY_NODE_CONFLICT:
                    //stagedNode.remove(conflictName);
                    stagedNode.removeChildNodeEntry(conflictName);
                    break;
            }

        }
        return stagedNode;
    }

    private Node getNode(String path, long revisionId) throws Exception {
        return getNode(path, revisionId, null);
    }

    private Node getNode(String path, long revisionId, String branchId) throws Exception {
        GetNodesCommandNew command = new GetNodesCommandNew(nodeStore, path, revisionId);
        command.setBranchId(branchId);
        return command.execute();
    }

    private NodeImpl copy(Node node) {
        NodeImpl copy = new NodeImpl(node.getPath());
        copy.setRevisionId(node.getRevisionId());
        for (Map.Entry<String, String> entry : node.getProperties().entrySet()) {
            copy.addProperty(entry.getKey(), entry.getValue());
        }
        for (Iterator<Node> it = node.getChildNodeEntries(0, -1); it.hasNext(); ) {
            Node child = it.next();
            copy.addChildNodeEntry(copy(child));
        }
        return copy;
    }

}


text:
package javax.xml.ws.spi;

import java.lang.annotation.Documented;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.WebServiceRef;
import javax.xml.ws.WebServiceRefs;
import javax.xml.ws.RespectBinding;
import javax.xml.ws.soap.Addressing;
import javax.xml.ws.soap.MTOM;

/**
 * Annotation used to identify other annotations
 * as a WebServiceFeature.
 *

 * Each WebServiceFeature annotation annotated with
 * this annotation MUST contain an
 * enabled property of type
 * boolean with a default value of true.
 *

 * JAX-WS defines the following
 * WebServiceFeature annotations (Addressing,
 * MTOM, RespectBinding), however, an implementation
 * may define vendors specific annotations for other features.
 *

 * Annotations annotated with WebServiceFeatureAnnotation MUST
 * have the same @Target of {@link WebServiceRef} annotation, so that the resulting
 * feature annotation can be used in conjunction with the {@link WebServiceRef}
 * annotation if necessary.
 *

 * If a JAX-WS implementation encounters an annotation annotated
 * with the WebServiceFeatureAnnotation that it does not
 * recognize/support an error MUST be given.
 *

 *
 * @see Addressing
 * @see MTOM
 * @see RespectBinding
 *
 * @since JAX-WS 2.1
 */
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WebServiceFeatureAnnotation {
    /**
     * Unique identifier for the WebServiceFeature.  This
     * identifier MUST be unique across all implementations
     * of JAX-WS.
     */
    String id();

    /**
     * The WebServiceFeature bean that is associated
     * with the WebServiceFeature annotation
     */
    Class<? extends WebServiceFeature> bean();
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Loader;

use Psr\Container\ContainerInterface;

/**
 * ClosureContainer helps with lazily loading dependencies.
 *
 * This class is provided for easy of use, it should not be used
 * directly within your own code.
 *
 * @internal
 */
final class ClosureContainer implements ContainerInterface
{
    private $factories;
    private $values = [];

    /**
     * @param \Closure[]|array $factories
     */
    public function __construct(array $factories)
    {
        $this->factories = $factories;
    }

    /**
     * {@inheritdoc}
     */
    public function has($id): bool
    {
        return isset($this->factories[$id]);
    }

    /**
     * {@inheritdoc}
     */
    public function get($id)
    {
        if (!isset($this->factories[$id])) {
            throw new ServiceNotFoundException($id);
        }

        if (true !== $factory = $this->factories[$id]) {
            $this->factories[$id] = true;
            $this->values[$id] = $factory();
        }

        return $this->values[$id];
    }
}


text:
=head1 NAME

mbtget - Simple perl script for make some modbus transaction from the command line.

=head1 DESCRIPTION

Modbus is a standard serial communication protocol used to interconnect industrial
PLC (and a lot of other things). This module gives you access to TCP and RTU
version of this protocol, through the MBclient object.

You can have a look at http://en.wikipedia.org/wiki/Modbus for details.

=head1 INSTALL

You can install this module from:

GitHub:

    git clone https://github.com/sourceperl/mbtget.git
    cd mbtget
    perl Makefile.PL
    make
    sudo make install

=head1 DEPENDENCIES

This script requires no other module or librarie.

It's pure Perl code without any extension.

=head1 USAGE

=head2 read mbtget help

    pi@raspberrypi ~ $ mbtget -h

=head2 read a word data at address 1000 on modbus server 127.0.0.1

    pi@raspberrypi ~ $ mbtget -a 1000 127.0.0.1

    values:
    1 (ad 01000): 52544

=head2 read 10 words data at address 1000 on modbus server plc-1.domaine.net

    pi@raspberrypi ~ $ mbtget -n 10 -a 1000 plc-1.domaine.net

    values:
    1 (ad 01000): 52544
    2 (ad 01001): 33619
    3 (ad 01002): 61010
    4 (ad 01003): 11878
    5 (ad 01004): 60142
    6 (ad 01005): 21714
    7 (ad 01006): 14182
    8 (ad 01007): 64342
    9 (ad 01008): 18511
    10 (ad 01009): 59909

=head2 write a word value of 333 at address 1000 on modbus server 127.0.0.1 with dump mode active

    pi@raspberrypi ~ $ mbtget -w6 333 -a 1000 -d 127.0.0.1
    Tx
    [10 01 00 00 00 06 01] 06 03 E8 01 4D
    Rx
    [10 01 00 00 00 06 01] 06 03 E8 01 4D

    word write ok

=head1 BUGS

Thanks to report issues at https://github.com/sourceperl/mbtget/issues

=head1 AUTHOR

Loic Lefebvre, E<lt>lle@cpan.orgE<gt>

=head1 COPYRIGHT & LICENSE

Copyright 2014 Loic Lefebvre

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
package pashkinmv.gse.components;

import pashkinmv.gse.api.GSettingsFactory;
import pashkinmv.gse.model.Value;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.util.logging.Logger;

public class ValuePanel extends JPanel {
    private static final Logger LOGGER = Logger.getLogger(ValuePanel.class.getName());
    private final JTextArea textArea = new JTextArea();
    private final JButton saveButton = new JButton("Save");
    private final JButton resetButton = new JButton("Reset");
    private final JLabel rangeLabel = new JLabel();

    private Value value;

    public ValuePanel() {
        super(new BorderLayout());

        saveButton.addActionListener(action -> GSettingsFactory.get().set(new Value(value.getKey(), textArea.getText(), value.getRange(), value.getWritable())));
        resetButton.addActionListener(action -> {
            final Value newValue = GSettingsFactory.get().reset(value.getKey());

            textArea.setText(newValue.getValue());
        });
        rangeLabel.setBorder(new EmptyBorder(10, 10, 10, 10));

        final JPanel buttonPanel = new JPanel();

        buttonPanel.add(saveButton);
        buttonPanel.add(resetButton);

        add(rangeLabel, BorderLayout.NORTH);
        add(new JScrollPane(textArea));
        add(buttonPanel, BorderLayout.SOUTH);

        setValue(null);
    }

    public void setValue(Value value) {
        this.value = value;
        this.textArea.setText(value != null ? value.getValue() : "");
        this.rangeLabel.setText(value != null ? ("Type: " + getRangeAsType(value.getRange())) : null);

        this.textArea.setEditable(value != null && value.getWritable());
        this.saveButton.setEnabled(value != null && value.getWritable());
        this.resetButton.setEnabled(value != null && value.getWritable());
    }

    private String getRangeAsType(String range) {
        if (range.startsWith("range i ") || range.startsWith("range u ")) {
            return range.replaceAll("range . (.+) (.+)", "Integer [$1..$2]");
        }

        switch (range) {
            case "enum":
                return "Enum";
            case "type a(ss)":
                return "a(ss)";
            case "type a{ss}":
                return "a{ss}";
            case "type a{si}":
                return "a{si}";
            case "type as":
                return "as";
            case "type b":
                return "Boolean";
            case "type d":
                return "Double [2.2250738585072014e-308..1.7976931348623157e+308]";
            case "type i":
                return "Integer [-2147483648..2147483647]";
            case "type o":
                return "o";
            case "type s":
                return "String";
            case "type u":
                return "Integer [0..4294967295]";
            default:
                LOGGER.warning(String.format("Unknown type: %s for schema %s and key %s", range, value.getKey().getSchema().getCode(), value.getKey().getCode()));
                return range;
        }
    }
}