text:
package com.facebook.buck.cxx;

import static com.facebook.buck.cxx.DebugSectionProperty.COMPRESSED;
import static com.facebook.buck.cxx.DebugSectionProperty.STRINGS;
import static java.nio.channels.FileChannel.MapMode.READ_WRITE;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;

import com.facebook.buck.log.Logger;
import com.facebook.buck.util.ByteBufferReplacer;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;

import javax.annotation.Nonnull;

/**
 * This sanitizer works by munging the compiler output to replace paths. Currently, this just
 * supports sanitizing the compilation directory that compilers typically embed in binaries
 * when including debug sections (e.g. using "-g" with gcc/clang inserts the compilation
 * directory in the DW_AT_comp_dir DWARF field).
 */
public class MungingDebugPathSanitizer extends DebugPathSanitizer {

  private static final DebugSectionFinder DEBUG_SECTION_FINDER = new DebugSectionFinder();
  protected final ImmutableBiMap<Path, Path> other;
  private final LoadingCache<Path, ImmutableBiMap<Path, Path>> pathCache =
      CacheBuilder
          .newBuilder()
          .softValues()
          .build(new CacheLoader<Path, ImmutableBiMap<Path, Path>>() {
            @Override
            public ImmutableBiMap<Path, Path> load(@Nonnull Path key) {
              return getAllPathsWork(key);
            }
          });

  /**
   * @param pathSize fix paths to this size for in-place replacements.
   * @param separator the path separator used to fill paths aren't of {@code pathSize} length.
   * @param compilationDirectory the desired path to replace the actual compilation directory with.
   */
  public MungingDebugPathSanitizer(
      int pathSize,
      char separator,
      Path compilationDirectory,
      ImmutableBiMap<Path, Path> other) {
    super(separator, pathSize, compilationDirectory);
    this.other = other;
  }

  @Override
  public Map<String, String> getCompilationEnvironment(
      Path workingDir,
      boolean shouldSanitize) {
    // A forced compilation directory is set in the constructor.  Now, we can't actually force
    // the compiler to embed this into the binary -- all we can do set the PWD environment to
    // variations of the actual current working directory (e.g. /actual/dir or
    // /actual/dir////).  This adjustment serves two purposes:
    //
    //   1) it makes the compiler's current-directory line directive output agree with its cwd,
    //      given by getProjectDirectoryRoot.  (If PWD and cwd are different names for the same
    //      directory, the compiler prefers PWD, but we expect cwd for DebugPathSanitizer.)
    //
    //   2) in the case where we're using post-linkd debug path replacement, we reserve room
    //      to expand the path later.
    return ImmutableMap.of(
        "PWD", shouldSanitize ?
            getExpandedPath(workingDir) :
            workingDir.toString());
  }

  @Override
  ImmutableList<String> getCompilationFlags() {
    return ImmutableList.of();
  }

  // Construct the replacer, giving the expanded current directory and the desired directory.
  // We use ASCII, since all the relevant debug standards we care about (e.g. DWARF) use it.
  @Override
  public void restoreCompilationDirectory(Path path, Path workingDir) throws IOException {
    restore(path, getCompilationDirectoryReplacer(workingDir));
  }

  /**
   * @return a {@link ByteBufferReplacer} suitable for replacing {@code workingDir} with
   *     {@code compilationDirectory}.
   */
  protected ByteBufferReplacer getCompilationDirectoryReplacer(Path workingDir) {
    return new ByteBufferReplacer(
        ImmutableMap.of(
            getExpandedPath(workingDir).getBytes(Charsets.US_ASCII),
            getExpandedPath(compilationDirectory).getBytes(Charsets.US_ASCII)));
  }

  /**
   * Run {@code replacer} on all relevant debug sections in {@code buffer}, falling back to
   * processing the entire {@code buffer} if the format is unrecognized.
   */
  private void restore(ByteBuffer buffer, ByteBufferReplacer replacer) {
    // Find the debug sections in the file represented by the buffer.
    Optional<ImmutableMap<String, DebugSection>> results = DEBUG_SECTION_FINDER.find(buffer);

    // If we were able to recognize the file format and find debug symbols, perform the
    // replacement on them.  Otherwise, just do a find-and-replace on the whole blob.
    if (results.isPresent()) {
      for (DebugSection section : results.get().values()) {
        // We can't do in-place updates on compressed debug sections.
        Preconditions.checkState(!section.properties.contains(COMPRESSED));
        if (section.properties.contains(STRINGS)) {
          replacer.replace(section.body);
        }
      }
    } else {
      replacer.replace(buffer);
    }
  }

  protected void restore(Path path, ByteBufferReplacer replacer) throws IOException {
    try (FileChannel channel = FileChannel.open(path, READ, WRITE)) {
      MappedByteBuffer buffer = channel.map(READ_WRITE, 0, channel.size());
      restore(buffer, replacer);
    }
  }

  @Override
  protected ImmutableBiMap<Path, Path> getAllPaths(Optional<Path> workingDir) {
    if (!workingDir.isPresent()) {
      return other;
    }

    try {
      return pathCache.get(workingDir.get());
    } catch (ExecutionException e) {
      Logger.get(DebugPathSanitizer.class).error(
          "Problem loading paths into cache",
          e);
      return getAllPathsWork(workingDir.get());
    }
  }

  private ImmutableBiMap<Path, Path> getAllPathsWork(Path workingDir) {
    ImmutableBiMap.Builder<Path, Path> builder = ImmutableBiMap.builder();
    builder.put(workingDir, compilationDirectory);
    builder.putAll(other);
    return builder.build();
  }
}


text:
package org.apache.solr.client.solrj.impl;

import java.io.IOException;
import java.util.List;
import org.apache.solr.client.solrj.SolrClient;

public class Http2ClusterStateProvider extends BaseHttpClusterStateProvider {
  final Http2SolrClient httpClient;
  final boolean closeClient;

  public Http2ClusterStateProvider(List<String> solrUrls, Http2SolrClient httpClient)
      throws Exception {
    this.httpClient = httpClient == null ? new Http2SolrClient.Builder().build() : httpClient;
    this.closeClient = httpClient == null;
    init(solrUrls);
  }

  @Override
  public void close() throws IOException {
    if (this.closeClient && this.httpClient != null) {
      httpClient.close();
    }
  }

  @Override
  protected SolrClient getSolrClient(String baseUrl) {
    return new Http2SolrClient.Builder(baseUrl).withHttpClient(httpClient).build();
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/video/livestream/v1/service.proto

namespace Google\Cloud\Video\LiveStream\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request message for "LivestreamService.DeleteChannel".
 *
 * Generated from protobuf message google.cloud.video.livestream.v1.DeleteChannelRequest
 */
class DeleteChannelRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The name of the channel resource, in the form of:
     * `projects/{project}/locations/{location}/channels/{channelId}`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';
    /**
     * A request ID to identify requests. Specify a unique request ID
     * so that if you must retry your request, the server will know to ignore
     * the request if it has already been completed. The server will guarantee
     * that for at least 60 minutes after the first request.
     * For example, consider a situation where you make an initial request and the
     * request times out. If you make the request again with the same request ID,
     * the server can check if original operation with the same request ID was
     * received, and if so, will ignore the second request. This prevents clients
     * from accidentally creating duplicate commitments.
     * The request ID must be a valid UUID with the exception that zero UUID is
     * not supported `(00000000-0000-0000-0000-000000000000)`.
     *
     * Generated from protobuf field string request_id = 2;
     */
    private $request_id = '';
    /**
     * If the `force` field is set to the default value of `false`, you must
     * delete all of a channel's events before you can delete the channel itself.
     * If the field is set to `true`, requests to delete a channel also delete
     * associated channel events.
     *
     * Generated from protobuf field bool force = 3;
     */
    private $force = false;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. The name of the channel resource, in the form of:
     *           `projects/{project}/locations/{location}/channels/{channelId}`.
     *     @type string $request_id
     *           A request ID to identify requests. Specify a unique request ID
     *           so that if you must retry your request, the server will know to ignore
     *           the request if it has already been completed. The server will guarantee
     *           that for at least 60 minutes after the first request.
     *           For example, consider a situation where you make an initial request and the
     *           request times out. If you make the request again with the same request ID,
     *           the server can check if original operation with the same request ID was
     *           received, and if so, will ignore the second request. This prevents clients
     *           from accidentally creating duplicate commitments.
     *           The request ID must be a valid UUID with the exception that zero UUID is
     *           not supported `(00000000-0000-0000-0000-000000000000)`.
     *     @type bool $force
     *           If the `force` field is set to the default value of `false`, you must
     *           delete all of a channel's events before you can delete the channel itself.
     *           If the field is set to `true`, requests to delete a channel also delete
     *           associated channel events.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Video\Livestream\V1\Service::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The name of the channel resource, in the form of:
     * `projects/{project}/locations/{location}/channels/{channelId}`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. The name of the channel resource, in the form of:
     * `projects/{project}/locations/{location}/channels/{channelId}`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * A request ID to identify requests. Specify a unique request ID
     * so that if you must retry your request, the server will know to ignore
     * the request if it has already been completed. The server will guarantee
     * that for at least 60 minutes after the first request.
     * For example, consider a situation where you make an initial request and the
     * request times out. If you make the request again with the same request ID,
     * the server can check if original operation with the same request ID was
     * received, and if so, will ignore the second request. This prevents clients
     * from accidentally creating duplicate commitments.
     * The request ID must be a valid UUID with the exception that zero UUID is
     * not supported `(00000000-0000-0000-0000-000000000000)`.
     *
     * Generated from protobuf field string request_id = 2;
     * @return string
     */
    public function getRequestId()
    {
        return $this->request_id;
    }

    /**
     * A request ID to identify requests. Specify a unique request ID
     * so that if you must retry your request, the server will know to ignore
     * the request if it has already been completed. The server will guarantee
     * that for at least 60 minutes after the first request.
     * For example, consider a situation where you make an initial request and the
     * request times out. If you make the request again with the same request ID,
     * the server can check if original operation with the same request ID was
     * received, and if so, will ignore the second request. This prevents clients
     * from accidentally creating duplicate commitments.
     * The request ID must be a valid UUID with the exception that zero UUID is
     * not supported `(00000000-0000-0000-0000-000000000000)`.
     *
     * Generated from protobuf field string request_id = 2;
     * @param string $var
     * @return $this
     */
    public function setRequestId($var)
    {
        GPBUtil::checkString($var, True);
        $this->request_id = $var;

        return $this;
    }

    /**
     * If the `force` field is set to the default value of `false`, you must
     * delete all of a channel's events before you can delete the channel itself.
     * If the field is set to `true`, requests to delete a channel also delete
     * associated channel events.
     *
     * Generated from protobuf field bool force = 3;
     * @return bool
     */
    public function getForce()
    {
        return $this->force;
    }

    /**
     * If the `force` field is set to the default value of `false`, you must
     * delete all of a channel's events before you can delete the channel itself.
     * If the field is set to `true`, requests to delete a channel also delete
     * associated channel events.
     *
     * Generated from protobuf field bool force = 3;
     * @param bool $var
     * @return $this
     */
    public function setForce($var)
    {
        GPBUtil::checkBool($var);
        $this->force = $var;

        return $this;
    }

}


text:
namespace HotSwapDemo.App
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using HotSwap.Contracts;
    using PluginWatcher;

    public class Program
    {
        private static readonly object VersionLock = new object();
        static ISimpleTask current;

        static void Main()
        {
            Console.WriteLine("Copy new versions into the Plugins folder, and the output below should change. Press [enter] to exit");

            IPluginWatcher<ISimpleTask> watcher = new PluginWatcher<ISimpleTask>("./Plugins");
            watcher.PluginsChanged += watcher_PluginsChanged;

            current = Latest(watcher.CurrentlyAvailable);

            Console.WriteLine("\r\nInitial startup\r\nLatest version:");
            Console.WriteLine(current.Version());

            // Here we set some state that should be maintained between versions
            current.SetGreets("Hello");

            do
            {
                while (!Console.KeyAvailable)
                {
                    Thread.Sleep(200);
                    lock (VersionLock)
                    {
                        Console.SetCursorPosition(0, 8);
                        Console.WriteLine(current.Greeting("world"));
                    }
                }
            }
            while (Console.ReadKey().Key != ConsoleKey.Enter);
        }

        /// <summary>
        /// Do a version upgrade!
        /// </summary>
        static void Upgrade(IHotSwap old, ISimpleTask latest)
        {
            lock (VersionLock)
            {
                try
                {
                    latest.SetState(old.GetState());
                    current = latest;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Can't upgrade: " + ex.Message);
                }
            }
        }

        /// <summary>
        /// Set of plugins has changed
        /// </summary>
        static void watcher_PluginsChanged(object sender, PluginsChangedEventArgs<ISimpleTask> e)
        {
            var latest = Latest(e.AvailablePlugins);
            if (latest.Version() > current.Version()) Upgrade(current, latest);
        }

        /// <summary>
        /// Get highest version available
        /// </summary>
        static ISimpleTask Latest(IEnumerable<ISimpleTask> currentlyAvailable)
        {
            var list = currentlyAvailable.ToList();
            if (!list.Any()) throw new Exception("No tasks available");
            return list.OrderBy(task => task.Version()).Last();
        }

    }
}


text:
import unittest
from item_22_helper_classes import Subject, Student, GradeBook

# tests for item 22 helper classes

class TestGradeBook(unittest.TestCase):
    """Test GradeBook class"""

    def setUp(self):
        self.book = GradeBook()

    def test_gradebook_report_grade_and_get_average_grade(self):
        """Test that we correctly report grades and get averages for students"""
        self.book.report_grade('Jim', 'Math', {'score':50, 'weight':0.3})
        self.book.report_grade('Jim', 'Math', {'score':100, 'weight':0.7})

        self.book.report_grade('Tim', 'Math', {'score':100, 'weight':0.3})
        self.book.report_grade('Tim', 'Math', {'score':100, 'weight':0.7})

        self.book.report_grade('Tim', 'Bio', {'score':20, 'weight':0.3})
        self.book.report_grade('Tim', 'Bio', {'score':100, 'weight':0.7})

        self.assertEqual(self.book.get_average_grade('Jim', 'Math'), 85)
        self.assertEqual(self.book.get_average_grade('Tim', 'Math'), 100)
        self.assertEqual(self.book.get_average_grade('Tim', 'Bio'), 76)

class TestStudent(unittest.TestCase):
    """Test Student class"""
    def setUp(self):
        self.student = Student()

    def test_report_grade_and_get_average_grade(self):
        """Test reporting and getting average is correctly computed for each subject"""
        self.student.report_grade('Math', score=50, weight=0.3)
        self.student.report_grade('Math', score=100, weight=0.7)

        #check math is correct
        self.assertEqual(self.student.get_average_grade('Math'), 85)  # 15+70 = 85

        self.student.report_grade('English', score=60, weight=0.3)
        self.student.report_grade('English', score=40, weight=0.2)
        self.student.report_grade('English', score=80, weight=0.5)

        # assert both subjects are correct
        self.assertEqual(self.student.get_average_grade('English'), 66)  # 18+8+40=66
        self.assertEqual(self.student.get_average_grade('Math'), 85)  # 15+70 = 85

class TestSubject(unittest.TestCase):
    """Test Subject class"""

    def setUp(self):
        self.subject = Subject()

    def test_report_grade_and_get_average_int(self):
        """Test grades are correctly reported and average are correctly computed"""

        # only integers
        self.subject.report_grade(100, 1)
        self.assertEqual(self.subject.get_average_grade(), 100)

        self.subject.report_grade(70, 3)
        self.assertEqual(self.subject.get_average_grade(), 77.5)  # 310/4 = 77.5

    def test_report_grade_and_get_average_float(self):
        """Test grades are correctly reported and average are correctly computed"""

        self.subject.report_grade(90, 0.3)
        self.assertEqual(self.subject.get_average_grade(), 90)

        self.subject.report_grade(60, 0.7)
        self.assertEqual(self.subject.get_average_grade(), 69)  # 42 + 27 = 69


text:
<?php
/**
 * (c) CupcakePHP: The Rapid and Tasty Development Framework.
 *
 * PHP version 5.5.12
 *
 * @author  Ge Bender <gesianbender@gmail.com>
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 * @version GIT: <git_id>
 * @link    http://cupcake.simplesys.com.br
 */

namespace Cupcake;

class DAO
{

    public $db;

    public $app;

    public $EntityRepository;

    public $ClassMetadata;

    public $name;

    public function __construct($app, $entity='')
    {
        $this->app = $app;
        $this->defineName($app, $entity);
        $this->db = $app['db'];

        if ($app['FileSystem']->classExists($this->name) === true) {
            $this->EntityRepository = $app['db']->getRepository($this->name);
            $this->ClassMetadata = $this->db->getMetadataFactory()->getMetadataFor($this->name);
        }

    }

    public function defineName($app, $entity)
    {
        $classParts = explode('\\', get_class($this));
        $class = array_pop($classParts);
        $class = str_replace('DAO', '', $class);
        if ($class !== '') {
            $this->name = $class;
        } else if ($entity !== '') {
            $this->name = $entity;
        } else {
            $this->name = $app['route']['entity'];
        }

    }

    public function listen(array $data)
    {
        $mappings = $this->ClassMetadata->getAssociationMappings();
        $model = $this->EntityRepository->find($data[$this->name]['id']);
        if ($model === null) {
            $model = $this->loadModel($data[$this->name]['id']);
        }

        foreach ($data[$this->name] as $k => $v) {
            if (isset($mappings[$k]) === true) {
                $mappedDAO = new DAO($this->app, $mappings[$k]['targetEntity']);
                $v = $mappedDAO->find($v);
            }

            $set = 'set' . ucfirst($k);
            (is_array($v) === true) ? $v = implode($model->getListSeparator(), $v) : false;
            $model->$set($v);
        }

        return $model;

    }

    public function defineAssinante($model)
    {
        if (property_exists($model, 'assinante') === true) {
            $model->setAssinante(Cookies::restore('assinante'));
        }

        return $model;

    }

    public function loadModel()
    {
        $name = $this->name;
        $model = new $name();

        return $model;

    }

    public function find($id)
    {
        $criteria = array('id' => $id);
        $result = $this->findBy($criteria);

        if (isset($result[0]) === true) {
            return $result[0];
        }

    }

    public function defineFiltroAssinante(array $criteria)
    {
        $modelName = $this->name;
        $model = new $modelName();
        if (property_exists($model, 'assinante') === true) {
            $criteria['assinante'] = (string) Cookies::restore('assinante')->getId();
        }

        return $criteria;

    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $criteria = $this->defineFiltroAssinante($criteria);
        $result = $this->EntityRepository->findBy($criteria, $orderBy, $limit, $offset);
        return $result;

    }

    public function findAll(array $criteria=array())
    {
        return $this->findBy($criteria);

    }

    public function salvar($model)
    {
        $original = $this->find($model->getId());
        if ($original === null) {
            $this->db->persist($model);
            $model = $this->defineAssinante($model);
            $this->db->merge($model);
        } else {
            $this->db->merge($model);
        }

        $this->db->flush();

    }

    public function deletar($id)
    {
        $model = $this->find($id);
        $this->db->remove($model);
        $this->db->flush();

        return true;

    }

}


text:
<?php

namespace GotChosen\SiteBundle\Controller;

use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserInterface;
use GotChosen\SiteBundle\Entity\ProfileProperty;
use GotChosen\SiteBundle\Entity\User;
use GotChosen\SiteBundle\Form\Type\RegistrationFormType;
use GotChosen\SiteBundle\Repository\UserRepository;
use GotChosen\User\UserPropertyHandler;
use GotChosen\Util\Strings;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * Class RegistrationController
 * @package GotChosen\SiteBundle\Controller
 */
class RegistrationController extends BaseController
{
    /**
     * @Route("/register", name="fos_user_registration_register")
     */
    public function registerAction(Request $request)
    {
        $currentDate = new \DateTime;
        $cutoffDate = new \DateTime("2014-10-01 00:00:00");
        if ($currentDate >= $cutoffDate)
        {
            return $this->redirectRoute('login-disabled');
        }

        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');

        /** @var UserRepository $userRepo */
        $userRepo = $this->repo('User');

        /** @var UserPropertyHandler $handler */
        $handler = $this->get('gotchosen.user_property_handler');
        $userRepo->setPropertyHandler($handler);

        /** @var User $user */
        $user = $userManager->createUser();
        $user->setEnabled(true);

        $registrationProperties = [
            'FirstName', 'LastName', 'Gender', 'BirthDay'
        ];
        $propertyRefs = $userRepo->getPropertyReferences($registrationProperties);

        $form = $this->createForm(new RegistrationFormType($propertyRefs), $user);

        $form->handleRequest($request);

        if ( $form->isValid() && $userManager->findUserByUsername($form->get('username')->getData()) ) {
            $form->get('username')->addError(new FormError('Username already taken'));
        }

        if ( $form->isValid() && $userManager->findUserByEmail($form->get('email')->getData()) ) {
            $form->get('email')->addError(new FormError('E-mail address already taken'));
        }

        if ( $form->isValid() ) {
            // e-mail confirmation stuff
            $tokenGenerator = $this->get('fos_user.util.token_generator');
            $user->setEnabled(false);
            $user->setStatus(User::STATUS_AWAITING_VERIFICATION);
            if ( null === $user->getConfirmationToken() ) {
                // Apparently the FOS Token Generator can and frequently will generate tokens
                // that are not unique. We have to make sure we're only working with tokens
                // that are not on any other user accounts.
                do {
                    $token = $tokenGenerator->generateToken();
                } while ( $userManager->findUserBy(['confirmationToken' => $token]) );

                $user->setConfirmationToken($token);
            }

            $customTarget = $request->request->get('_target');
            $this->sendConfirmationEmailMessage($user, $customTarget);

            $this->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
            $this->get('session')->save(); // workaround for issue with some session handlers, including memcached.

            $url = $this->get('router')->generate('fos_user_registration_check_email');

            // update general user fields
            $userManager->updateUser($user);

            // set notification subs
            $userRepo->installDefaultNotifications($user);

            /** @var $property ProfileProperty */
            foreach ( $propertyRefs as $propName => $property ) {
                $userRepo->setProperty($user, $propName,
                    $handler->transformToData($property, $form->get($propName)->getData()));
            }

            $this->em()->flush();

            $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
            $this->container->get('security.context')->setToken($token);

            /*
            if ( $customTarget ) {
                $response = $this->redirect($request->getUriForPath($customTarget));
            } else {
                $response = $this->redirectRoute('user_my_profile');
            }*/
            $response = $this->redirect($url);

            return $response;
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
            'form' => $form->createView(),
            'properties' => $registrationProperties,
        ));
    }

    /**
     * @Route("/register/resend/{email}", name="register_resend")
     */
    public function resendConfirmationAction($email)
    {
        $email = Strings::base64DecodeUrl($email);
        $user = $this->get('fos_user.user_manager')->findUserByEmail($email);
        if ( $user === null ) {
            throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', htmlentities($email)));
        }

        $token = $user->getConfirmationToken();
        if ( empty($token) ) {
            $user->setConfirmationToken($this->get('fos_user.util.token_generator')->generateToken());
            $this->get('fos_user.user_manager')->updateUser($user);
        }
        $this->sendConfirmationEmailMessage($user, null);

        $this->flash('success', 'The confirmation email was re-sent to ' . htmlentities($email));
        $this->get('session')->save();

        return $this->redirectRoute('fos_user_security_login');//, ['resent_confirmation' => 1]);
    }

    protected function sendConfirmationEmailMessage(User $user, $customTarget)
    {
        $params = ['token' => $user->getConfirmationToken()];
        if ( $customTarget ) {
            $params['_target'] = $customTarget;
        }
        $url = $this->generateUrl('fos_user_registration_confirm', $params, true);
        $rendered = $this->renderView('FOSUserBundle:Registration:email.txt.twig', array(
            'user' => $user,
            'confirmationUrl' =>  $url
        ));

        // Render the email, use the first line as the subject, and the rest as the body
        $renderedLines = explode("\n", trim($rendered));
        $subject = $renderedLines[0];
        $body = implode("\n", array_slice($renderedLines, 1));
        $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom('noreply@gotchosen.com', 'GotChosen - automated message, do not reply')
            ->setTo($user->getEmail())
            ->setBody($body);

        $this->get('mailer')->send($message);
    }

    /**
     * Tell the user to check his email provider
     *
     * @Route("/register/check-email", name="fos_user_registration_check_email")
     * @Method("GET")
     */
    public function checkEmailAction()
    {
        $email = $this->container->get('session')->get('fos_user_send_confirmation_email/email');
        $this->container->get('session')->remove('fos_user_send_confirmation_email/email');
        $user = $this->container->get('fos_user.user_manager')->findUserByEmail($email);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:checkEmail.html.'.$this->getEngine(), array(
            'user' => $user,
        ));
    }

    /**
     * Receive the confirmation token from user email provider, login the user
     *
     * @Route("/register/confirm/{token}", name="fos_user_registration_confirm")
     * @Method("GET")
     */
    public function confirmAction(Request $request, $token)
    {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');
        $logger = $this->get('logger');
        $clientIp = $request->getClientIp();

        $logger->error("UserConfirmation [{$clientIp}]: Hit with token: {$token}");

        $user = $userManager->findUserByConfirmationToken($token);

        if (null === $user) {
            $logger->error("UserConfirmation [{$clientIp}]: Did not find a user for the provided token.");
            $currentUser = $this->getUser();
            if ( $currentUser ) {
                $logger->error("UserConfirmation [{$clientIp}]: Found logged-in user and redirecting to profile: " . $currentUser->getUsername());
            }
            $route = $currentUser ? 'user_my_profile' : 'fos_user_security_login';
            return $this->redirectRoute($route);
        }

        $logger->error("UserConfirmation [{$clientIp}]: Found a user for the provided token: " . $user->getUsername());

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

        $user->setConfirmationToken(null);
        $user->setEnabled(true);
        $user->setStatus(User::STATUS_ACTIVE);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            //$url = $this->container->get('router')->generate('fos_user_registration_confirmed');
            //$response = new RedirectResponse($url);
            if ( $customTarget = $request->query->get('_target') ) {
                $response = $this->redirect($request->getUriForPath($customTarget));
            } else {
                $response = $this->redirectRoute('user_my_profile');
            }
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    /**
     * Tell the user his account is now confirmed
     *
     * @Route("/register/confirmed", name="fos_user_registration_confirmed")
     * @Method("GET")
     */
    public function confirmedAction()
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:confirmed.html.'.$this->getEngine(), array(
            'user' => $user,
        ));
    }

    protected function getEngine()
    {
        return $this->container->getParameter('fos_user.template.engine');
    }
}


text:
<variables>
	<category name="ZoneVolume">
		<variable name="VolumeZone1" type="integer" sysvar="VolumeZone1" />
		<variable name="VolumeZone2" type="integer" sysvar="VolumeZone2" />
		<variable name="VolumeZone3" type="integer" sysvar="VolumeZone3" />
		<variable name="VolumeZone4" type="integer" sysvar="VolumeZone4" />
		<variable name="VolumeZone5" type="integer" sysvar="VolumeZone5" />
		<variable name="VolumeZone6" type="integer" sysvar="VolumeZone6" />
		<variable name="VolumeZone7" type="integer" sysvar="VolumeZone7" />
		<variable name="VolumeZone8" type="integer" sysvar="VolumeZone8" />
	</category>
	<category name="ZonePower">
		<variable format="B:Off:On" name="PowerZone1" type="boolean" sysvar="PowerZone1" />
		<variable format="B:Off:On" name="PowerZone2" type="boolean" sysvar="PowerZone2" />
		<variable format="B:Off:On" name="PowerZone3" type="boolean" sysvar="PowerZone3" />
		<variable format="B:Off:On" name="PowerZone4" type="boolean" sysvar="PowerZone4" />
		<variable format="B:Off:On" name="PowerZone5" type="boolean" sysvar="PowerZone5" />
		<variable format="B:Off:On" name="PowerZone6" type="boolean" sysvar="PowerZone6" />
		<variable format="B:Off:On" name="PowerZone7" type="boolean" sysvar="PowerZone7" />
		<variable format="B:Off:On" name="PowerZone8" type="boolean" sysvar="PowerZone8" />
	</category>
	<category name="ZoneMute">
		<variable format="B:No:Yes" name="MuteZone1" type="boolean" sysvar="MuteZone1" />
		<variable format="B:No:Yes" name="MuteZone2" type="boolean" sysvar="MuteZone2" />
		<variable format="B:No:Yes" name="MuteZone3" type="boolean" sysvar="MuteZone3" />
		<variable format="B:No:Yes" name="MuteZone4" type="boolean" sysvar="MuteZone4" />
		<variable format="B:No:Yes" name="MuteZone5" type="boolean" sysvar="MuteZone5" />
		<variable format="B:No:Yes" name="MuteZone6" type="boolean" sysvar="MuteZone6" />
		<variable format="B:No:Yes" name="MuteZone7" type="boolean" sysvar="MuteZone7" />
		<variable format="B:No:Yes" name="MuteZone8" type="boolean" sysvar="MuteZone8" />
	</category>
</variables>


text:
/**
* \file ForceBiasedAlgorithm.h
* \author Rémi Blanc
* \date 31. July 2012
*/

#ifndef __FORCEBIASEDALGORITHM_H_
#define __FORCEBIASEDALGORITHM_H_

#include "BaseScene.h"
#include "FBMovementManager.h"

namespace psciob {

/** \brief ForceBiasedAlgorithm
*
* This is the base class for implementing the force-biased algorithm.
* This algorithm is a deterministic, collective re-arrangement method for removing overlaps between geometric objects
* From an initial collection, for each pair of intersecting objects, it proposes a displacment aiming at reducing the overlaps
* All proposal moves are composed, and applied simultaneously. The objects are slightly downscaled, and the process is iterated until
* no intersection remain.
*
* The algorithm works with a FBMovementManager to deal with different kinds of moves (translations, possibly rotations, scaling) for the various object types...
* The default FBMovementManager performs only translations
*
* This algorithm requires the scene to work with a interaction manager that deals with overlaps only.
*/

//IDEA: use a temporary scene ?? in which to perform all computations...?

//DEV: implement a structure, with one entry per object, in which to store the proposal moves, and perform the necessary compositions.
//how to store those moves??? -> matrices seem to be the most generic way.
//I could just store the parameter modifications to be applied here, and let the manager deal with this...

template<class TScene>
class ForceBiasedAlgorithm : public itk::LightObject {
public:
    /** Standard class typedefs. */
    typedef ForceBiasedAlgorithm    Self;
    typedef itk::LightObject        Superclass;
    typedef itk::SmartPointer<Self> Pointer;
    /** Run-time type information (and related methods). */
    itkTypeMacro(ForceBiasedAlgorithm, itk::LightObject);
    itkNewMacro(Self);

    typedef TScene                                     SceneType;
    static const unsigned int Dimension              = SceneType::Dimension;
    typedef typename SceneType::IDType                 IDType;
    typedef typename SceneType::ObjectTypesLibraryType ObjectTypesLibraryType;
    typedef typename SceneType::DeformableObjectType   ObjectType;
	typedef typename FBMovementManager<SceneType>      FBMovementManagerType;

	/** types of boundary effect
	* VOIDBOUNDARIES (default): scene boundaries are void, they have no effect on objects
	* SOLIDBOUNDARIES: scene boundaries are solid, and thus tend to push inwards objects that are partially outside the scene.
	* PERIODICBOUNDARIES: considering periodic boundaries, a part of an object partially outside on the right side 're-enters' the scene on the left side.
	*/
	enum BOUNDARYEFFECT { VOIDBOUNDARIES, SOLIDBOUNDARIES, PERIODICBOUNDARIES };

    /** Attach a scene to the algorithm */
    void SetScene(SceneType* scene) {
        m_scene = scene;
		for (unsigned d=0 ; d<Dimension ; d++) m_sceneWidth(d) = m_scene->GetSceneBoundingBox()(2*d+1)-m_scene->GetSceneBoundingBox()(2*d);
        m_mvtManager->SetScene(m_scene);
    }

	/** Set the Boundary effect behavior
	* \todo implement the non-void boundary conditions...
	*/
	void SetBoundaryEffectBehavior(BOUNDARYEFFECT eff) {
		m_boundaryEffectCode = eff;
	}

    /** Set a specific movement manager, this object is in charge of proposing and applying moves to the objects of the scene
    * The default manager is a FBMovementManager, one can set a specialized child instead (e.g. for managing rotations).
    */
    void SetMovementManager(FBMovementManagerType* mm) {
        m_mvtManager = mm;
        if (!m_scene) {} else { m_mvtManager->SetScene(m_scene); }
    }

    /** Get a pointer to the movement manager
    * this is useful, in particular for (re)defining specific aspects of the manager
    */
    FBMovementManagerType* GetMovementManager() { return m_mvtManager; }

    /** Set the maximum number of iterations for the method IterateUntilConvergence - default is 1e10 */
    void SetMaximumNumberOfIterations(unsigned n) {m_maxNbIteration=n;}

    /** Get the maximum number of iterations for the method IterateUntilConvergence - default is 1e10 */
    unsigned GetMaximumNumberOfIterations() { return m_maxNbIteration;}

    /** Applies a single iteration of the algorithm
	* returns false if no overlaps were present anyway.
	*/
	bool ApplyOneIteration(bool verbose = false) {
		clock_t t0=clock();
		m_proposedMoves.clear(); //make sure it starts empty.
		//initialize the moves to identity for all objects (m_proposedMoves)
		SceneObjectIterator<SceneType> objectIt(m_scene);
		for (objectIt.GoToBegin() ; !objectIt.IsAtEnd() ; ++objectIt) {
			m_proposedMoves.insert(m_proposedMoves.end(), MovePairType(objectIt.GetID(), m_scene->GetParametersOfObject(objectIt.GetID())) );
		}

		std::map<IDType, vnl_vector<double>>::iterator it;

		//this is used only for PERIODICBOUNDARIES, to avoid treating multiple time the same pair of objects...
		unsigned long pairKey, keyMult = 2*m_scene->GetNumberOfObjects();
		std::set<unsigned long> treatedPairs; //structure that stores all pairs of overlapping objects that have already been treated, using the format minid + maxid*keyMult as a key
		std::pair<std::set<unsigned long>::iterator, bool> treatedPairsInsertResp;

		//check for overlaps between objects
		//for each pair of overlapping objects, propose a move, and compose it with the existing m_proposedMoves
		m_scene->GetInteractionManager()->TurnOnInteractionManagement(); //should not be necessary... but do it just in case...
		unsigned nbOverlaps = 0;
		for (it = m_proposedMoves.begin() ; it != m_proposedMoves.end() ; ++it) {
			//look for the interactions for this object
			for (SceneType::ObjectInteractionIterator dit = m_scene->GetObject(it->first)->interactionData.begin() ; dit != m_scene->GetObject(it->first)->interactionData.end() ; dit++ , ++nbOverlaps) {
				//propose a move unilaterally for the current object, and compose it with the current proposed move
				it->second = m_mvtManager->UpdateMove( it->second, it->first, dit->first, dit->second );
				treatedPairs.insert( min(it->first,dit->first) + max(it->first,dit->first)*keyMult );
				//the second object of the pair will be treated when its turn comes
			}
		}
		if (verbose) std::cout<<"  time after processing object overlaps ("<<nbOverlaps<<"): "<<(clock()-t0)/((double)CLOCKS_PER_SEC)<<" s."<<std::endl;

		//manage boundary effects
		switch (m_boundaryEffectCode) {
			case VOIDBOUNDARIES: //nothing to do.
				break;
			case SOLIDBOUNDARIES: //translate inwards objects that are partially outside the scene
				for (it = m_proposedMoves.begin() ; it != m_proposedMoves.end() ; ++it) {
					std::vector<unsigned> intersects;
					intersects = IdentifyIntersectionBoundingBoxes_NoCheck( m_scene->GetObject(it->first)->obj->GetPhysicalBoundingBox(), m_scene->GetSceneBoundingBox() );
					for (unsigned w = 0 ; w<intersects.size() ; w++, ++nbOverlaps) it->second = m_mvtManager->UpdateMoveWithSceneWall( it->second, it->first, intersects[w] );
				}
				break;
			case PERIODICBOUNDARIES:
				//check with which border(s), if any, the object overlaps with, and update the move accordingly.
				//for each of these, add (a) temporary object(s) on the 'opposite' face(s) of the scene, and UpdateMove as usual in case of interaction
				//Furthermore, if an objects is too much outside the scene (more than half), than delete it and move it to the other side...
				struct MirroredObjectType {
					SceneType::IDType id, sourceId; //id of the mirrored object, and id of the source object.
					std::vector<unsigned> mirroredWallIds; //list of wall Ids over which the original objects reflected itself to create this object
				};
				MirroredObjectType obj;
				SceneType::DeformableObjectType::Pointer tmpObj;
				std::map<SceneType::IDType, MirroredObjectType> setMirroredObjects;

				//1: add all the 'mirrored' objects
				for (it = m_proposedMoves.begin() ; it != m_proposedMoves.end() ; ++it) {
					std::vector<unsigned> wallIds, faceIds; //ids of the walls (in [0,2*d]) and faces (in [0,d]) that the current object overlaps
					std::set<unsigned> activeFaceIds; std::pair<std::set<unsigned>::iterator,bool> facesSetInsertResp; //set of already activated faces

					std::vector<MirroredObjectType> currentMirroredObjects, previousMirroredObjects, tmpMirroredObjects;

					wallIds = IdentifyIntersectionBoundingBoxes_NoCheck( m_scene->GetObject(it->first)->obj->GetPhysicalBoundingBox(), m_scene->GetSceneBoundingBox() );
					if (wallIds.size()==0) continue; //this object is not affected by boundary conditions, just continue.

					tmpObj = m_scene->GetObject(it->first)->obj->CreateClone();
					obj.id = it->first; obj.sourceId = it->first;
					currentMirroredObjects.push_back(obj);
					vnl_vector<double> tmpParams;

					for (unsigned i=0 ; i<wallIds.size() ; i++) {
						faceIds.push_back(wallIds[i]/2);
						facesSetInsertResp = activeFaceIds.insert( faceIds.back() );
						if (facesSetInsertResp.second) { //new face: add the 'reflections' of all objects in the currentMirroredObjects
							previousMirroredObjects = currentMirroredObjects; //backup this set of objects, can be useful in some cases
							tmpMirroredObjects = currentMirroredObjects;
						}
						else {// this is the same face as in the previous iteration, but the opposite wall, only the objects in previousMirroredObjects need to be 'reflected'.
							//this case shouldn't happen often, it means the object is crossing the entire scene
							tmpMirroredObjects = previousMirroredObjects;
						}

						for (unsigned idt=0 ; idt<tmpMirroredObjects.size() ; idt++) {
							obj = tmpMirroredObjects[idt]; //set the parameters of the mirrored object, starting from the current object in the list
							tmpParams = m_scene->GetParametersOfObject(obj.id);
							if (wallIds[i] == 2*faceIds[i]) { //0 or 2 or 4, ... (first 'wall' of that 'face')
								obj.mirroredWallIds.push_back(wallIds[i]+1); tmpParams(faceIds[i]) += m_sceneWidth(faceIds[i]);
							}
							else { //1 or 3 or 5, ... (second 'wall' of that 'face')
								obj.mirroredWallIds.push_back(wallIds[i]-1); tmpParams(faceIds[i]) -= m_sceneWidth(faceIds[i]);
							}
							//add it to the scene
							tmpObj->SetParameters(tmpParams); obj.id = m_scene->AddObject( tmpObj );
							if (obj.id == 0) { continue; } //it can happen that the bounding box intersects with the border, but still the original object was fully inside the scene, so let just skip those cases...
							else {
								if ( m_scene->GetObject(obj.id)->interactionData.find( it->first ) != m_scene->GetObject(obj.id)->interactionData.end() ) { //if the mirrored object intersects the original, then remove it.
									std::cout<<"ForceBiasedAlgorithm with periodic boundary conditions: WARNING: the object 'reflection' overlaps the original object! this reflection is ignored..."<<std::endl;
									m_scene->RemoveObject( obj.id );
								}
								else { //ok, register the new mirror object
									currentMirroredObjects.push_back( obj ); setMirroredObjects[obj.id] = obj;
								}
							}
						}
					}
				}

				//2: treat all temporary objects that have been created, paying attention to intersection between 'mirrored' objects
				std::vector<unsigned> distantWallIds; bool distantCrossesSameFace; //wall ids that the distant object crosses
				std::vector<unsigned> intersectWalldIds;
				SceneType::IDType currentSourceId, distantSourceId;
				for (std::map<SceneType::IDType, MirroredObjectType>::iterator mit = setMirroredObjects.begin() ; mit != setMirroredObjects.end() ; ++mit) {
					currentSourceId = mit->second.sourceId; //source id of the current mirror-object
					// for all temporary reflections of the current object, check for intersections with other objects of the scene
					for (SceneType::ObjectInteractionIterator dit = m_scene->GetObject(mit->first)->interactionData.begin() ; dit != m_scene->GetObject(mit->first)->interactionData.end() ; dit++) {
						//check whether the distant object is a mirrored object, or an original object and get its id if so.
						std::map<SceneType::IDType, MirroredObjectType>::iterator tmpIt = setMirroredObjects.find(dit->first);
						if (tmpIt==setMirroredObjects.end()) {
							//this mirror object intersects an original object
							distantSourceId = dit->first;
						}
						else {
							//this mirror object intersects another mirror object
							distantSourceId = tmpIt->second.sourceId;
							//-> if the original objects were already intersecting, then skip this.
							if ( m_scene->GetObject(currentSourceId)->interactionData.find(distantSourceId) != m_scene->GetObject(currentSourceId)->interactionData.end() ) continue;
						}

						pairKey = min(currentSourceId,distantSourceId) + max(currentSourceId,distantSourceId)*keyMult;
						treatedPairsInsertResp = treatedPairs.insert( pairKey );

						if (treatedPairsInsertResp.second ==false) continue; //if the pair was already treated, then skip it.

						////check whether the distant object touches the border over which the current object has been 'mirrored'
						//distantWallIds = IdentifyIntersectionBoundingBoxes_NoCheck( m_scene->GetObject(dit->first)->obj->GetPhysicalBoundingBox(), m_scene->GetSceneBoundingBox() );
						//intersectWalldIds.clear();
						//std::set_intersection(mit->second.mirroredWallIds.begin(), mit->second.mirroredWallIds.end(),
						//	distantWallIds.begin(), distantWallIds.end(), std::inserter(intersectWalldIds, intersectWalldIds.end()) );
						////if so, then it has also produced a mirror object, which will intersect the source of the current mirror-object
						//if ( (!intersectWalldIds.empty()) && (currentSourceId < distantSourceId) ) continue; //this overlap was already treated via the reflections of the object distantSourceId
						//else ... move both objects (the second object may not cross the boundary, so it should be treated immediately
						++nbOverlaps;

						m_proposedMoves[currentSourceId] = m_mvtManager->UpdateMove( m_proposedMoves[currentSourceId], mit->first, dit->first, dit->second );
						m_proposedMoves[distantSourceId] = m_mvtManager->UpdateMove( m_proposedMoves[distantSourceId], dit->first, mit->first, dit->second );

					}
				}

				//3: remove all the mirror objects.
				for (std::map<SceneType::IDType, MirroredObjectType>::iterator mit = setMirroredObjects.begin() ; mit != setMirroredObjects.end() ; ++mit) m_scene->RemoveObject(mit->first);

				break;
		}
		if (verbose) std::cout<<"  time after dealing with boundary conditions: "<<(clock()-t0)/((double)CLOCKS_PER_SEC)<<" s., nb of overlaps after this step: "<<nbOverlaps<<std::endl;

		if (nbOverlaps==0) return false;

		//apply the moves
		m_scene->GetInteractionManager()->TurnOffInteractionManagement();
		unsigned nbModifs = 0;
		for (it = m_proposedMoves.begin() ; it != m_proposedMoves.end() ; ++it) {
			//downscale the objects -> compute the parameters that realizes this downscaling and apply the moves
			if (m_boundaryEffectCode==PERIODICBOUNDARIES) {
				for (unsigned i=0 ; i<Dimension ; i++) {
					if ( it->second(i) < m_scene->GetSceneBoundingBox()( 2*i ) ) { it->second(i) += m_sceneWidth(i); }
					if ( it->second(i) > m_scene->GetSceneBoundingBox()(2*i+1) ) { it->second(i) -= m_sceneWidth(i); }
				}
			}
			if (m_scene->ModifyObjectParameters( it->first, m_mvtManager->GetScaledParameters(it->first, it->second) )) nbModifs++;
		}

		m_scene->GetInteractionManager()->TurnOnInteractionManagement();
		if (verbose) std::cout<<"  total time for this iteration, after updating the interactions: "<<(clock()-t0)/((double)CLOCKS_PER_SEC)<<" s."<<std::endl;
		if (nbModifs==0) return false;
		return true;
	}

    /** Iterate until convergence
    * returns -1 if it exited after reaching the maximum number of allowed iterations
    * and 1 otherwise.
    */
    int IterateUntilConvergence(bool verbose = false) {
        if (!m_scene) throw DeformableModelException("ForceBiasedAlgorithm::IterateUntilConvergence -- the scene must be set first.");
        unsigned nbIter=0;
        int converged = 0;
        //draw the scene now
        while (converged==0) {
			if (verbose) std::cout<<"\nIteration "<<nbIter<<std::endl;
            nbIter++;
            if (nbIter>=m_maxNbIteration) { converged = -1; break; }
            if ( !ApplyOneIteration(verbose) ) converged = 1;
			if (verbose) {
				if (Dimension==2) psciob::Write2DGreyLevelRescaledImageToFile<SceneType::LabelImageType>("FB_it" + stringify(nbIter) + ".png", m_scene->GetSceneAsLabelImage());
				if (Dimension==3) {
					psciob::WriteITKImageToFile("FB_it" + stringify(nbIter) + ".nii", m_scene->GetSceneAsLabelImage());
					psciob::WriteMirrorPolyDataToFile("FB_it" + stringify(nbIter) + ".vtk", m_scene->GetSceneAsVTKPolyData());
				}
			}
        }
        return converged;
    }

protected:
	ForceBiasedAlgorithm() : m_sceneWidth(Dimension) {
        m_scene = 0;
        m_maxNbIteration = 1e10;
        m_mvtManager = FBMovementManagerType::New();
		m_boundaryEffectCode = VOIDBOUNDARIES;
    };
    ~ForceBiasedAlgorithm() {};

    typename SceneType::Pointer m_scene;
    unsigned m_maxNbIteration;
    typename FBMovementManagerType::Pointer m_mvtManager;

	vnl_vector<double> m_sceneWidth;

    //temporary storage for the proposal movements
    //it associate a vnl_vector representing the parameters of the proposed moves.
    //those are initialized, filled, and composed using the FBMovementManager
    typedef std::map<IDType, vnl_vector<double>> ProposedMovesType;
    typedef std::pair<IDType, vnl_vector<double>> MovePairType;
    std::map<IDType, vnl_vector<double>> m_proposedMoves;

	BOUNDARYEFFECT m_boundaryEffectCode;
private:
    ForceBiasedAlgorithm(const Self&);      //purposely not implemented
    const Self & operator=( const Self & ); //purposely not implemented
};

} // namespace psciob

#endif /* __FORCEBIASEDALGORITHM_H_ */


text:
package net.smartrover.skyrover.ui;

import javax.microedition.khronos.opengles.GL10;

import net.smartrover.skyrover.ui.gl.GLSprite;
import net.smartrover.skyrover.util.TextureUtils;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author OROCA SmartRover Team
 * @since  0.1
 */
public class Image extends Sprite
{
    public enum SizeParams {
        NONE,
        FILL_SCREEN,
        REPEATED
    }

    private GLSprite sprite;
    private SizeParams widthParam;
    private SizeParams heightParam;

    private boolean isInitialized;

    private boolean updateTexture;

    private Resources res;
    private int resId;

    public Image(Resources resources, int resId, Align align)
    {
        super(align);

        widthParam = SizeParams.NONE;
        heightParam = SizeParams.NONE;

        isInitialized = false;
        sprite = new GLSprite(resources, resId);
        this.res = resources;
        this.resId = resId;
    }

    @Override
    public void init(GL10 gl, int program)
    {
        sprite.init(gl, program);
        isInitialized = true;
    }

    @Override
    public void surfaceChanged(GL10 gl, int width, int height)
    {
        sprite.onSurfaceChanged(gl, width, height);

        if (widthParam == SizeParams.FILL_SCREEN) {
            sprite.setSize(width, sprite.height);
        }
        if(heightParam == SizeParams.FILL_SCREEN){
            sprite.setSize(sprite.width, height);
        }

        super.surfaceChanged(gl, width, height);
    }

    @Override
    public void surfaceChanged(Canvas canvas)
    {
        super.surfaceChanged(canvas);
    }

    private void invalidate()
    {
        updateTexture = true;
    }

    private Bitmap createBitmapToRender(boolean xRepeated, boolean yRepeated) {
        return TextureUtils.makeTexture(res, BitmapFactory.decodeResource(res, resId), surfaceWidth, surfaceHeight, true, true);
    }

    @Override
    public void draw(GL10 gl)
    {
        if (updateTexture) {
            boolean xRepated = (widthParam == SizeParams.REPEATED) ? true : false;
            boolean yRepated = (heightParam == SizeParams.REPEATED) ? true : false;

            Bitmap bitmap = createBitmapToRender(xRepated ,yRepated);
            sprite.updateTexture(res, bitmap);
            layout(surfaceWidth, surfaceHeight);

            updateTexture = false;
        }

        sprite.onDraw(gl, bounds.left, surfaceHeight - bounds.top - sprite.height);
    }

    @Override
    public void draw(Canvas canvas)
    {
        sprite.onDraw(canvas, bounds.left, bounds.top);
    }

    @Override
    public boolean onTouchEvent(View v, MotionEvent event)
    {
        return false;
    }

    @Override
    protected void onAlphaChanged(float newAlpha)
    {
        sprite.setAlpha(newAlpha);
    }

    @Override
    public boolean isInitialized()
    {
        return isInitialized;
    }

    @Override
    public void setViewAndProjectionMatrices(float[] vMatrix, float[] projMatrix)
    {
        sprite.setViewAndProjectionMatrices(vMatrix, projMatrix);
    }

    public void setBounds(Rect rect)
    {
        this.bounds = rect;
    }

    public void setPosition(int x, int y)
    {
        bounds.offsetTo(x, y);
    }

    @Override
    public int getWidth()
    {
        return sprite.width;
    }

    @Override
    public int getHeight()
    {
        return sprite.height;
    }

    public void setSizeParams(SizeParams width, SizeParams height)
    {
        widthParam = width;
        heightParam = height;

        if (width == SizeParams.REPEATED || height == SizeParams.REPEATED) {
            invalidate();
        }
    }

    @Override
    public void freeResources()
    {
        sprite.freeResources();
    }

    @Override
    public void setNeedsUpdate() {
        isInitialized = false;
    }
}


text:
import isInteger from './isInteger'

describe('isInteger', () => {
  test('returns true for primitive numbers that are integers', () => {
    expect(isInteger(0)).toBe(true)
    expect(isInteger(-1)).toBe(true)
    expect(isInteger(1)).toBe(true)
  })

  test('returns true for Number objects that are integers', () => {
    expect(isInteger(new Number(0))).toBe(true)
    expect(isInteger(new Number(-1))).toBe(true)
    expect(isInteger(new Number(1))).toBe(true)
  })

  test('returns false for primitive numbers that are not integers', () => {
    expect(isInteger(-1.2)).toBe(false)
    expect(isInteger(1.2)).toBe(false)
  })

  test('returns false for NaN', () => {
    expect(isInteger(NaN)).toBe(false)
  })

  test('returns false for Infinity', () => {
    expect(isInteger(Infinity)).toBe(false)
    expect(isInteger(-Infinity)).toBe(false)
  })

  test('returns false for MIN_VALUE', () => {
    expect(isInteger(Number.MIN_VALUE)).toBe(false)
  })

  test('returns false for string values that are string integers', () => {
    expect(isInteger('3')).toBe(false)
  })

  test('returns false for Number objects that are not integers', () => {
    expect(isInteger(new Number(-1.2))).toBe(false)
    expect(isInteger(new Number(1.2))).toBe(false)
    expect(isInteger(new Number(NaN))).toBe(false)
    expect(isInteger(new Number(Infinity))).toBe(false)
    expect(isInteger(new Number(-Infinity))).toBe(false)
  })

  test('returns false for all other values', () => {
    expect(isInteger(undefined)).toBe(false)
    expect(isInteger(null)).toBe(false)
    expect(isInteger(false)).toBe(false)
    expect(isInteger(true)).toBe(false)
    expect(isInteger('')).toBe(false)
    expect(isInteger('abc')).toBe(false)
    expect(isInteger(/abc/)).toBe(false)
    expect(isInteger([])).toBe(false)
    expect(isInteger({})).toBe(false)
    expect(isInteger(async () => {})).toBe(false)
    expect(isInteger(() => {})).toBe(false)
    expect(isInteger(function() {})).toBe(false)
    expect(isInteger(function*() {})).toBe(false)
    expect(isInteger((function*() {})())).toBe(false)
    expect(isInteger(new Array(0))).toBe(false)
    expect(isInteger(new ArrayBuffer(2))).toBe(false)
    expect(isInteger(new Boolean(false))).toBe(false)
    expect(isInteger(new Boolean(true))).toBe(false)
    expect(isInteger(new Date())).toBe(false)
    expect(isInteger(new Error())).toBe(false)
    expect(isInteger(new Promise(() => {}))).toBe(false)
    expect(isInteger(new Proxy({}, {}))).toBe(false)
    expect(isInteger(new Set())).toBe(false)
    expect(isInteger(new String())).toBe(false)
    expect(isInteger(new String(''))).toBe(false)
    expect(isInteger(new String('abc'))).toBe(false)
    expect(isInteger(Symbol('abc'))).toBe(false)
    expect(isInteger(new WeakMap())).toBe(false)
    expect(isInteger(new WeakSet())).toBe(false)
  })
})


text:
package org.olat.core.commons.modules.glossary;

import java.util.List;

import org.olat.core.commons.modules.glossary.morphService.MorphologicalService;

/**
 * Description:

 * Helps to get configuration settings.
 *

 * Initial Date: 23.12.2008

 *
 * @author Roman Haag, frentix GmbH, roman.haag@frentix.com
 */
public class GlossaryModule {

	private static List<MorphologicalService> morphologicalServices;

	/**
	 * @return Returns the flexionServices.
	 */
	public static List<MorphologicalService> getMorphologicalServices() {
		return morphologicalServices;
	}

	/**
	 * used by spring
	 *
	 * @param morphServices The MorphologicalService to set.
	 */
	public void setMorphologicalServices(List<MorphologicalService> morphServices) {
		morphologicalServices = morphServices;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Popups;

namespace REST_SampleCode.Controls
{
    // 摘要:
    //     指定显示消息框时要包含的按钮。
    public enum MessageBoxButton
    {
        // 摘要:
        //     仅显示"确定"按钮。
        OK = 0,
        //
        // 摘要:
        //     同时显示"确定"和"取消"按钮。
        OKCancel = 1,
    }
    // 摘要:
    //     表示对消息框的用户响应。
    public enum MessageBoxResult
    {
        // 摘要:
        //     当前未使用此值。
        None = 0,
        //
        // 摘要:
        //     用户单击了"确定"按钮。
        OK = 1,
        //
        // 摘要:
        //     用户单击了"取消"按钮或按下了 Esc。
        Cancel = 2,
        //
        // 摘要:
        //     当前未使用此值。
        Yes = 6,
        //
        // 摘要:
        //     当前未使用此值。
        No = 7,
    }

    public class MessageBox
    {
        static string okStr = "确定", cancelStr = "取消", captionStr = "提示";

        public async static Task<IUICommand> Show(string message)
        {
            MessageBox msg = new MessageBox();
            return await msg.ShowMessage(message);
        }

        public async static Task<MessageBoxResult> Show(string messageBoxText, string caption, MessageBoxButton button)
        {
            MessageBox box = new MessageBox();

            var result = await box.ShowMessage(messageBoxText, caption, MessageBoxButton.OKCancel);

            return getResult(result);
        }

        public async Task<IUICommand> ShowMessage(string message)
        {
            return await ShowMessage(message, captionStr, MessageBoxButton.OK);
        }

        public async Task<IUICommand> ShowMessage(string messageBoxText, string caption, MessageBoxButton button)
        {
            MessageDialog msg = new MessageDialog(messageBoxText, caption);

            msg.Commands.Add(new UICommand(okStr, CommandInvokedHandler));
            if (button == MessageBoxButton.OKCancel)
            {
                msg.Commands.Add(new UICommand(cancelStr, CommandInvokedHandler));
            }
            msg.DefaultCommandIndex = 1;
            msg.CancelCommandIndex = 1;
            IUICommand result = await msg.ShowAsync();
            return result;
        }

        public delegate void CompleteHandler(MessageBoxResult result);

        public CompleteHandler Complete;

        private void CommandInvokedHandler(IUICommand command)
        {
            if (Complete != null)
            {
                Complete(getResult(command));

            }
        }

        private static MessageBoxResult getResult(IUICommand command)
        {
            MessageBoxResult msgresult = MessageBoxResult.Cancel;
            if (command.Label == okStr)
            {
                msgresult = MessageBoxResult.OK;
            }
            else if (command.Label == cancelStr)
            {
                msgresult = MessageBoxResult.Cancel;
            }
            else
            {
                msgresult = MessageBoxResult.None;
            }
            return msgresult;
        }

    }
}


text:
package org.pentaho.di.job;

import org.junit.Test;
import org.pentaho.di.job.entries.helper.PersistentPropertyChangeListener;

import static junit.framework.Assert.*;

/**
 * User: RFellows
 * Date: 6/5/12
 */
public class BlockableJobConfigTest {

  @Test
  public void testAddPropertyChangeListener() throws Exception {
    BlockableJobConfig config = new BlockableJobConfig();

    PersistentPropertyChangeListener l = new PersistentPropertyChangeListener();

    // make sure it is capturing property change events
    config.addPropertyChangeListener(l);
    config.setJobEntryName("jobName1");
    assertEquals(1, l.getReceivedEvents().size());
    assertEquals(config.getJobEntryName(), l.getReceivedEvents().get(0).getNewValue());

    // remove the listener & verify that it isn't receiving events anymore
    config.removePropertyChangeListener(l);
    config.setJobEntryName("jobName2");
    assertEquals(1, l.getReceivedEvents().size()); // still 1, from the previous call
  }

  @Test
  public void testAddPropertyChangeListener_propertyName() throws Exception {
    BlockableJobConfig config = new BlockableJobConfig();

    PersistentPropertyChangeListener l = new PersistentPropertyChangeListener();

    // dummy property name, should not indicate any captured prop change
    config.addPropertyChangeListener("dummy", l);
    config.setJobEntryName("jobName0");
    assertEquals(0, l.getReceivedEvents().size());
    config.removePropertyChangeListener("dummy", l);

    // make sure it is capturing property change events
    config.addPropertyChangeListener(BlockableJobConfig.JOB_ENTRY_NAME, l);
    config.setJobEntryName("jobName1");
    assertEquals(1, l.getReceivedEvents().size());
    assertEquals(config.getJobEntryName(), l.getReceivedEvents().get(0).getNewValue());

    // remove the listener & verify that it isn't receiving events anymore
    config.removePropertyChangeListener(BlockableJobConfig.JOB_ENTRY_NAME, l);
    config.setJobEntryName("jobName2");
    assertEquals(1, l.getReceivedEvents().size()); // still 1, from the previous call
  }

  @Test
  public void testGetterAndSetter() throws Exception {
    BlockableJobConfig config = new BlockableJobConfig();
    assertNull(config.getJobEntryName());

    config.setJobEntryName("jobName");
    assertEquals("jobName", config.getJobEntryName());
  }

  @Test
  public void testClone() throws Exception {
    BlockableJobConfig configOrig = new BlockableJobConfig();
    configOrig.setJobEntryName("Test");
    BlockableJobConfig configCloned = (BlockableJobConfig) configOrig.clone();

    assertNotSame(configOrig, configCloned);
    assertEquals(configOrig, configCloned);

    configOrig.setJobEntryName("New Name");
    assertFalse(configOrig.getJobEntryName().equals(configCloned.getJobEntryName()));

  }
}


text:
layout: post
title: Setup Common Lisp Development Environment by SLIME and Emacs
category: ComputerScience
tags: [CLisp]
---

  SLIME is the "Superior Lisp Interaction Mode for Emacs".SLIME extends Emacs with support for interactive programming in Common Lisp.The Features are centered around slime-mode,an Emacs minor-mode that complements the standard lisp-mode.

## Prerequisites

- **Install a Lisp implementation**

There are lots of Lisp implementations,such as Steel Bank Common Lisp,Clozure Common Lisp.We can get a binary package of CLISP easily by:

```bash
sudo apt-get install clisp
```

- **Install Emacs**

```bash
sudo apt-get install emacs24
```

- **Install SLIME**

Get a duplication of SLIME from here,and put it in a location with whole permission.

## Configure the Emacs

Start Emacs and open ~/.emacs (if not exists,create one).Configure SLIME as below:

```elisp
(add-to-list 'load-path "/path/to/slime")
(require 'slime-autoloads)
(setq inferior-lisp-program "/usr/bin/clisp")
```

## Usage

Start Emacs,input M-x slime and just have fun with Common Lisp!

You can also binding a shortcut for SLIME,just adding:

```elisp
(global-set-key (kbd "C-x j") 'slime)
```

## Shortcuts binding in official documents

**Key bindings**

C-h k <key> describe-key "What does this key do?"

Describes current function bound to <key> for focus buffer.

C-h b describe-bindings "Exactly what bindings are available?"

Lists the current key-bindings for the focus buffer.

C-h m describe-mode "Tell me all about this mode"

Shows all the available major mode keys, then the minor mode keys, for the modes of the focus buffer.

C-h l view-lossage "Woah, what key chord did I just do?"

Shows you the literal sequence of keys you've pressed in order.

**Evaluation commands**

C-x C-e

M-x slime-eval-last-expression

Evaluate the expression before point and show the result in the echo area.

C-M-x

M-x slime-eval-defun

Evaluate the current toplevel form and show the result in the echo area. 'C-M-x'treats 'defvar' expressions specially. Normally, evaluating a 'defvar' expressiondoes nothing if the variable it defines already has a value. But 'C-M-x' un-conditionally resets the variable to the initial value specified in the 'defvar'expression. This special feature is convenient for debugging Lisp programs.If C-M-x or C-x C-e is given a numeric argument, it inserts the value into the currentbuffer, rather than displaying it in the echo area.

C-c :

M-x slime-interactive-eval

Evaluate an expression read from the minibuffer.

C-c C-r

M-x slime-eval-region

Evaluate the region.

C-c C-p

M-x slime-pprint-eval-last-expression

Evaluate the expression before point and pretty-print the result in a fresh buffer.

C-c E

M-x slime-edit-value

Edit the value of a setf-able form in a new buffer '*Edit <form>*'. The value isinserted into a temporary buffer for editing and then set in Lisp when committedwith C-c C-c.

C-x M-e

M-x slime-eval-last-expression-display-output

Display the output buffer and evaluate the expression preceding point. This is useful if the expression writes something to the output stream.

C-c C-u

M-x slime-undefine-function

Undefine the function, with fmakunbound, for the symbol at point.

**Compilation commands**

SLIME has fancy commands for compiling functions, files, and packages. The fancy part is
that notes and warnings offered by the Lisp compiler are intercepted and annotated directly
onto the corresponding expressions in the Lisp source buffer. (Give it a try to see what this
means.)

C-c C-c

M-x slime-compile-defun

Compile the top-level form at point. The region blinks shortly to give some
feedback which part was chosen.
With (positive) prefix argument the form is compiled with maximal debug set-
tings (C-u C-c C-c). With negative prefix argument it is compiled for speed
(M-- C-c C-c). If a numeric argument is passed set debug or speed settings to
it depending on its sign.
The code for the region is executed after compilation. In principle, the command
writes the region to a file, compiles that file, and loads the resulting code.

C-c C-k

M-x slime-compile-and-load-file

Compile and load the current buffer's source file. If the compilation step fails,
the file is not loaded. It's not always easy to tell whether the compilation failed:
occasionally you may end up in the debugger during the load step.
With (positive) prefix argument the file is compiled with maximal debug set-
tings (C-u C-c C-k). With negative prefix argument it is compiled for speed
(M-- C-c C-k). If a numeric argument is passed set debug or speed settings to
it depending on its sign.

C-c M-k

M-x slime-compile-file

Compile (but don't load) the current buffer's source file.

C-c C-l

M-x slime-load-file

Load a Lisp file. This command uses the Common Lisp LOAD function.

M-x slime-compile-region

Compile the selected region.
The annotations are indicated as underlining on source forms. The compiler message
associated with an annotation can be read either by placing the mouse over the text or with
the selection commands below.

M-n

M-x slime-next-note

Move the point to the next compiler note and displays the note.

M-p

M-x slime-previous-note

Move the point to the previous compiler note and displays the note.

C-c M-c

M-x slime-remove-notes

Remove all annotations from the buffer.

C-x '

M-x next-error

Visit the next-error message. This is not actually a SLIME command but SLIME
creates a hidden buffer so that most of the Compilation mode commands (See
Info file 'emacs', node 'Compilation Mode') work similarly for Lisp as for batch
compilers.