text:
from argparse import Namespace

from fairseq.dataclass.utils import gen_parser_from_dataclass
from fairseq.optim import FairseqOptimizer

class FairseqLRScheduler(object):
    def __init__(self, cfg, optimizer):
        super().__init__()
        if optimizer is not None and not isinstance(optimizer, FairseqOptimizer):
            raise ValueError("optimizer must be an instance of FairseqOptimizer")
        self.cfg = cfg
        self.optimizer = optimizer
        self.best = None

    @classmethod
    def add_args(cls, parser):
        """Add arguments to the parser for this LR scheduler."""
        dc = getattr(cls, "__dataclass", None)
        if dc is not None:
            gen_parser_from_dataclass(parser, dc())

    def state_dict(self):
        """Return the LR scheduler state dict."""
        return {"best": self.best}

    def load_state_dict(self, state_dict):
        """Load an LR scheduler state dict."""
        self.best = state_dict["best"]

    def step_begin_epoch(self, epoch):
        """Update the learning rate at the beginning of the given epoch."""
        pass

    def step(self, epoch, val_loss=None):
        """Update the learning rate at the end of the given epoch."""
        if val_loss is not None:
            if self.best is None:
                self.best = val_loss
            else:
                self.best = min(self.best, val_loss)

    def step_update(self, num_updates):
        """Update the learning rate after each update."""
        return self.optimizer.get_lr()

class LegacyFairseqLRScheduler(FairseqLRScheduler):
    def __init__(self, args: Namespace, optimizer):
        if not isinstance(optimizer, FairseqOptimizer):
            raise ValueError("optimizer must be an instance of FairseqOptimizer")
        self.args = args
        self.optimizer = optimizer
        self.best = None


text:
require 'fog'
require 'json'
require 'rest_client'
require 'base64'

# create a connection to the provisioned Provider
class FogCalls
  def initialize (provider, credential_path, region)
    if provider.downcase == 'AWS'.downcase
      Fog.credentials_path = "#{credential_path}"
      @conn = Fog::Compute.new(:provider  => 'AWS', :region => region)

    elsif provider.downcase == 'Rackspace'.downcase
      Fog.credentials_path = "#{credential_path}"
      @conn = Fog::Compute.new(:provider  => 'Rackspace')

    else
     # add additional providers for your specific env
     raise "#{provider} is not a supported provider. [AWS|Rackspace]"
    end
  end

  # grab attributes for all running instances
  # IPs and other attributes are provider specific
  def get_public_ips(provider)
    servers = {}
    @conn.servers.all.each do |srv|
      if provider.downcase == 'AWS'.downcase
        if srv.state == 'running'
          # more attributes are available for specific report tuning
          # check fog documentation: http://rubydoc.info/gems/fog/1.8.0
          servers[srv.public_ip_address] = ["#{srv.attributes[:dns_name]}",
                                            "#{srv.attributes[:id]}",
                                            "#{srv.attributes[:tags]['Name']}"]
        end

      elsif provider.downcase == 'Rackspace'.downcase
        if srv.state == 'ACTIVE'
          # more attributes are available for specific report tuning
          # check fog documentation: http://rubydoc.info/gems/fog/1.8.0
          servers[srv.attributes[:addresses]['public'][0]] = ["#{srv.attributes[:name]}",
                                                              "#{srv.attributes[:id]}"]
        end
      else
        raise "#{provider} is not a supported provider. [AWS|Rackspace]"
      end
    end
    return servers
  end
end

# create a connection to Halo API
class APICalls
  def initialize (portal, key_id, key_secret)
    @portal = "#{portal}"

    begin
      # get a API authorization token
      url = "/oauth/access_token?grant_type=client_credentials"
      base64str = Base64.encode64("#{key_id}:#{key_secret}")

      resp = RestClient.post("https://#{@portal}/#{url}", '', {:"Authorization" => "Basic #{base64str}"})
      data = JSON.parse(resp)
      @token = data['access_token']

    rescue => e
      puts "ERROR: #{e}"
    end
  end

  # return the GET response to the provided URL
  def get(url)
    begin
      @resp = RestClient.get("https://#{@portal}/v1/#{url}", {:"Authorization" => "Bearer #{@token}",
                              :"Content-type" => "application/json"}){ |response, request, result, &block|
      if (200..499).include? response.code
        return response
      else
        response.return!(request, result, &block)
      end
      }
    rescue => e
      puts "ERROR: #{e}"
    end
  end
end

# arrays containing provider and Halo IP addresses
# that will be diff'd to see what servers do not
# have Halo installed
provider_ips = []
halo_ips = []

# Define providers, credential_paths and regions (if applicable) your servers
# reside. add/update this based on your environment
# example format for the file defined as credential_path:
# :default:
#     :aws_access_key_id:     ABC123ABC123ABC123AB
#     :aws_secret_access_key: ABC123ABC123ABC123ABC123ABC123ABC123ABC1
# or
# :default:
#     :rackspace_username:  user_name
#     :rackspace_api_key:   ABC123ABC123ABC123ABC123ABC123ABC123ABC1
providers = { "AWS" => ["/path/to/fog_aws", ['us-west-1', 'us-east-1']],
              "Rackspace" => ["/path/to/fog_rackspace", ['N/A']]}

# Pass in portal, key_id, key_secret to setup API session
# key_id/key_secret can be created from portal.cloudpassage.com
# Settings > Site Administration > API Keys
# At least a read-only key is required
@api = APICalls.new("api.cloudpassage.com", 'abc123abc', 'abc123abc123abc123abc123abc123ab')

# grab all active servers and parse out their connecting IP address.
# this is their public IP address, which will match the providers
resp = @api.get("/servers")
if resp.code.to_int == 200
  data = JSON.parse(resp)
  data['servers'].each do |srv|
    halo_ips << srv['connecting_ip_address']
  end
else
  puts "ERROR: #{resp}"
  exit
end

# loop through providers to get running server attributes
providers.each do |prod|
  cloud_provider = prod[0]
  credential_path = prod[1][0]

  # loop through each region
  prod[1][1].each do |r|
    cloud_region = r
    # for each provider/region, grab the srv.public_ip_address
    # for "running" or "ACTIVE" servers
    @fog = FogCalls.new(cloud_provider, credential_path, cloud_region)
    running_srvs = @fog.get_public_ips(cloud_provider)
    running_srvs.each do |ip|
      diff = []
      provider_ips << ip[0]
      # check to see if it's a server w/out a corresponding
      # Halo IP. Print out identifying attributes
      diff = provider_ips - halo_ips
      if not diff.empty?
        puts "Halo is not installed on: #{cloud_provider}, #{ip}"
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
$urlpatch = (strpos($_SERVER['DOCUMENT_ROOT'], 'xampp') == true)?'/dimli':'';
if(!defined('MAIN_DIR')){define('MAIN_DIR',$_SERVER['DOCUMENT_ROOT'].$urlpatch);}
require_once(MAIN_DIR.'/_php/_config/session.php');
require_once(MAIN_DIR.'/_php/_config/connection.php');
require_once(MAIN_DIR.'/_php/_config/functions.php');
confirm_logged_in();
require_priv('priv_catalog');

$museum = 	$mysqli->real_escape_string(trim($_POST['data']['museum']));
$address = 	$mysqli->real_escape_string(trim($_POST['data']['address']));
$city = 		$mysqli->real_escape_string(trim($_POST['data']['city']));
$state = 	$mysqli->real_escape_string(trim($_POST['data']['state']));
$zip = 		$mysqli->real_escape_string(trim($_POST['data']['zip']));
$region = 	$mysqli->real_escape_string(trim($_POST['data']['region']));
$country = 	$mysqli->real_escape_string(trim($_POST['data']['country']));
$phone = 	$mysqli->real_escape_string(trim($_POST['data']['phone']));
$website = 	$mysqli->real_escape_string(trim($_POST['data']['website']));
$images = 	$mysqli->real_escape_string(trim($_POST['data']['images']));

$sql = "INSERT INTO dimli.repository
			SET museum = 	'{$museum}',
				address = 	'{$address}',
				city = 		'{$city}',
				state = 	'{$state}',
				zip = 		'{$zip}',
				region = 	'{$region}',
				country = 	'{$country}',
				phone = 	'{$phone}',
				website = 	'{$website}',
				images = 	'{$images}' ";

$result = db_query($mysqli, $sql);

if ($result)
{ ?>

	<script>

		msg(['Repository successfully created','<?php echo $museum;?>'], 'success');

	</script>

<?php
}

// Clear new repository array
$_SESSION['newRepositoryDetails'] = array();

// Debugging
// echo '<pre>'.print_r($_POST['data']).'</pre>';
?>


text:
package org.apache.flume.source.http;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.nio.charset.UnsupportedCharsetException;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import junit.framework.Assert;
import org.apache.flume.Event;
import org.apache.flume.event.JSONEvent;
import org.junit.Before;
import org.junit.Test;

/**
 *
 */
public class TestJSONHandler {

  HTTPSourceHandler handler;

  @Before
  public void setUp() {
    handler = new JSONHandler();
  }

  @Test
  public void testMultipleEvents() throws Exception {
    String json = "[{\"headers\":{\"a\": \"b\"},\"body\": \"random_body\"},"
            + "{\"headers\":{\"e\": \"f\"},\"body\": \"random_body2\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(),"UTF-8"));
    e = deserialized.get(1);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("random_body2", new String(e.getBody(),"UTF-8"));

  }

  @Test
  public void testMultipleEventsUTF16() throws Exception {
    String json = "[{\"headers\":{\"a\": \"b\"},\"body\": \"random_body\"},"
            + "{\"headers\":{\"e\": \"f\"},\"body\": \"random_body2\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json, "UTF-16");
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(), "UTF-16"));
    e = deserialized.get(1);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("random_body2", new String(e.getBody(), "UTF-16"));

  }

  @Test
  public void testMultipleEventsUTF32() throws Exception {
    String json = "[{\"headers\":{\"a\": \"b\"},\"body\": \"random_body\"},"
            + "{\"headers\":{\"e\": \"f\"},\"body\": \"random_body2\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json, "UTF-32");
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(), "UTF-32"));
    e = deserialized.get(1);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("random_body2", new String(e.getBody(), "UTF-32"));
  }

  @Test
  public void testMultipleEventsUTF8() throws Exception {
    String json = "[{\"headers\":{\"a\": \"b\"},\"body\": \"random_body\"},"
            + "{\"headers\":{\"e\": \"f\"},\"body\": \"random_body2\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json, "UTF-8");
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(), "UTF-8"));
    e = deserialized.get(1);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("random_body2", new String(e.getBody(), "UTF-8"));

  }

  @Test
  public void testEscapedJSON() throws Exception {
    //JSON allows escaping double quotes to add it in the data.
    String json = "[{\"headers\":{\"a\": \"b\"}},"
            + "{\"headers\":{\"e\": \"f\"},\"body\": \"rand\\\"om_body2\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertTrue(e.getBody().length == 0);
    e = deserialized.get(1);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("rand\"om_body2", new String(e.getBody(),"UTF-8"));
  }

  @Test
  public void testNoBody() throws Exception {
    String json = "[{\"headers\" : {\"a\": \"b\"}},"
            + "{\"headers\" : {\"e\": \"f\"},\"body\": \"random_body2\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertTrue(e.getBody().length == 0);
    e = deserialized.get(1);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("random_body2", new String(e.getBody(),"UTF-8"));
  }

  @Test
  public void testSingleHTMLEvent() throws Exception {
    String json = "[{\"headers\": {\"a\": \"b\"},"
            + "\"body\": \"test\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("test",
            new String(e.getBody(),"UTF-8"));
  }

  @Test
  public void testSingleEvent() throws Exception {
    String json = "[{\"headers\" : {\"a\": \"b\"},\"body\": \"random_body\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(),"UTF-8"));
  }

  @Test(expected = HTTPBadRequestException.class)
  public void testBadEvent() throws Exception {
    String json = "{[\"a\": \"b\"],\"body\": \"random_body\"}";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    handler.getEvents(req);
    Assert.fail();
  }

  @Test(expected = UnsupportedCharsetException.class)
  public void testError() throws Exception {
    String json = "[{\"headers\" : {\"a\": \"b\"},\"body\": \"random_body\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json, "ISO-8859-1");
    handler.getEvents(req);
    Assert.fail();
  }

  @Test
  public void testSingleEventInArray() throws Exception {
    String json = "[{\"headers\": {\"a\": \"b\"},\"body\": \"random_body\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(),"UTF-8"));
  }

  @Test
  public void testMultipleLargeEvents() throws Exception {
    String json = "[{\"headers\" : {\"a\": \"b\", \"a2\": \"b2\","
            + "\"a3\": \"b3\",\"a4\": \"b4\"},\"body\": \"random_body\"},"
            + "{\"headers\" :{\"e\": \"f\",\"e2\": \"f2\","
            + "\"e3\": \"f3\",\"e4\": \"f4\",\"e5\": \"f5\"},"
            + "\"body\": \"random_body2\"},"
            + "{\"headers\" :{\"q1\": \"b\",\"q2\": \"b2\",\"q3\": \"b3\",\"q4\": \"b4\"},"
            + "\"body\": \"random_bodyq\"}]";
    HttpServletRequest req = new FlumeHttpServletRequestWrapper(json);
    List<Event> deserialized = handler.getEvents(req);
    Event e = deserialized.get(0);
    Assert.assertNotNull(e);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("b2", e.getHeaders().get("a2"));
    Assert.assertEquals("b3", e.getHeaders().get("a3"));
    Assert.assertEquals("b4", e.getHeaders().get("a4"));
    Assert.assertEquals("random_body", new String(e.getBody(),"UTF-8"));
    e = deserialized.get(1);
    Assert.assertNotNull(e);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("f2", e.getHeaders().get("e2"));
    Assert.assertEquals("f3", e.getHeaders().get("e3"));
    Assert.assertEquals("f4", e.getHeaders().get("e4"));
    Assert.assertEquals("f5", e.getHeaders().get("e5"));
    Assert.assertEquals("random_body2", new String(e.getBody(),"UTF-8"));
    e = deserialized.get(2);
    Assert.assertNotNull(e);
    Assert.assertEquals("b", e.getHeaders().get("q1"));
    Assert.assertEquals("b2", e.getHeaders().get("q2"));
    Assert.assertEquals("b3", e.getHeaders().get("q3"));
    Assert.assertEquals("b4", e.getHeaders().get("q4"));
    Assert.assertEquals("random_bodyq", new String(e.getBody(),"UTF-8"));

  }

  @Test
  public void testDeserializarion() throws Exception {
    Type listType = new TypeToken<List<JSONEvent>>() {
    }.getType();
    List<JSONEvent> events = Lists.newArrayList();
    Random rand = new Random();
    for (int i = 1; i < 10; i++) {
      Map<String, String> input = Maps.newHashMap();
      for (int j = 1; j < 10; j++) {
        input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i));
      }
      JSONEvent e = new JSONEvent();
      e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8"));
      e.setHeaders(input);
      events.add(e);
    }
    Gson gson = new Gson();
    List<Event> deserialized = handler.getEvents(
            new FlumeHttpServletRequestWrapper(gson.toJson(events, listType)));
    int i = 0;
    for (Event e : deserialized) {
      Event current = events.get(i++);
      Assert.assertEquals(new String(current.getBody(),"UTF-8"),
              new String(e.getBody(),"UTF-8"));
      Assert.assertEquals(current.getHeaders(), e.getHeaders());
    }
  }
}


text:
package com.quirkygaming.reflectionlib;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.quirkygaming.errorlib.ErrorHandler;

class ReflUtil {

	static <Ex extends Exception> AnonymousObject instantiate(Class<?> clazz, ErrorHandler<Ex> eh, Object... parameters) throws Ex {
		try {
			Object o;
			if (parameters.length == 0) {
				o = clazz.newInstance();
			} else {
				Constructor<?> c;
				Class<?>[] classes = getClassesFromParams(parameters);
				c = clazz.getConstructor(classes);
				o = c.newInstance(parameters);
			}
			return new AnonymousObject(o);

		} catch (IllegalAccessException e) {
			eh.handle(e);
		} catch (InstantiationException e) {
			eh.handle(e);
		} catch (NoSuchMethodException e) {
			eh.handle(e);
		} catch (SecurityException e) {
			eh.handle(e);
		} catch (IllegalArgumentException e) {
			eh.handle(e);
		} catch (InvocationTargetException e) {
			eh.handle(e);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	static <T, Ex extends Exception> T getField(Class<?> clazz, Object o, ErrorHandler<Ex> eh, String fieldName) throws Ex {
		try {
			Field m = clazz.getField(fieldName);
			return (T) m.get(o);
		} catch (IllegalArgumentException e) {
			eh.handle(e);
		} catch (IllegalAccessException e) {
			eh.handle(e);
		} catch (ClassCastException e) {
			eh.handle(e);
		} catch (NoSuchFieldException e) {
			eh.handle(e);
		} catch (SecurityException e) {
			eh.handle(e);
		}
		return null;
	}

	static <Ex extends Exception> void setField(Class<?> clazz, Object o, ErrorHandler<Ex> eh, String fieldName, Object value) throws Ex {
		try {
			Field m = clazz.getField(fieldName);
			if (value != null && value instanceof AnonymousObject) {
				value = ((AnonymousObject)value).o;
			}
			m.set(o, value);
		} catch (IllegalArgumentException e) {
			eh.handle(e);
		} catch (IllegalAccessException e) {
			eh.handle(e);
		} catch (ClassCastException e) {
			eh.handle(e);
		} catch (NoSuchFieldException e) {
			eh.handle(e);
		} catch (SecurityException e) {
			eh.handle(e);
		}
	}

	@SuppressWarnings("unchecked")
	static <Ex extends Exception, T> T invoke(Class<?> clazz, Object o, ErrorHandler<Ex> eh, String methodName, Object... parameters) throws Ex {
		try {
			Method m = null;
			Class<?>[] classes = getClassesFromParams(parameters);
			try {
				m = clazz.getMethod(methodName, classes);
			} catch (NoSuchMethodException e) {
				nextMethod: for (Method match : clazz.getDeclaredMethods()) {
					if (match.getName().equals(methodName) && match.getParameterTypes().length == classes.length) {
						for (int i = 0; i < classes.length; i++) {
							Class<?>[] params = match.getParameterTypes();
							if (! (classes[i] == null || params[i].isAssignableFrom(classes[i])) ) {
								continue nextMethod;
							}
						}
						m = match;
						break;
					}
				}
				if (m == null) throw e;
			}
			return (T) m.invoke(o, parameters);
		} catch (IllegalAccessException e) {
			eh.handle(e);
		} catch (ClassCastException e) {
			eh.handle(e);
		} catch (NoSuchMethodException e) {
			eh.handle(e);
		} catch (SecurityException e) {
			eh.handle(e);
		} catch (IllegalArgumentException e) {
			eh.handle(e);
		} catch (InvocationTargetException e) {
			eh.handle(e);
		}
		return null;
	}

	static Class<?>[] getClassesFromParams(Object[] params) {
		Class<?>[] classes = new Class<?>[params.length];
		for (int i = 0; i < params.length; i++) {
			Object param = params[i];
			if (param == null) {
				classes[i] = null;//TODO correct???
				continue;
			} else if (param instanceof AnonymousObject) {
				param = ((AnonymousObject)param).getObject();
				params[i] = param;
			}
			classes[i] = param.getClass();
		}
		return classes;
	}
}


text:
package com.communote.server.model.config;

/**
 * This class holds constants of attributes and associations of the entity
 * LdapSearchBaseDefinition.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public class LdapSearchBaseDefinitionConstants {

    public final static String CLASS_NAME = LdapSearchBaseDefinitionImpl.class.getName();

    public final static String SEARCHBASE = "searchBase";

    public final static String SEARCHSUBTREE = "searchSubtree";

    public final static String ID = "id";

}


text:
<?php
/**
 * User: nikk
 * Date: 6/19/13
 * Time: 4:29 PM
 */

namespace Ps\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="Ps\AppBundle\Repository\RegularEventRepository")
 * @ORM\Table(name="regular_event")
 */
class RegularEvent
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="regularEvents")
     * @ORM\JoinColumn(name="organizer_id", referencedColumnName="id", nullable=false)
     */
    private $organizer;

    /**
     * @ORM\ManyToOne(targetEntity="Place", inversedBy="regularEvents")
     * @ORM\JoinColumn(name="place_id", referencedColumnName="id", nullable=false)
     */
    private $place;

    /**
     * @ORM\ManyToOne(targetEntity="EventPrivacy", inversedBy="regularEvents")
     * @ORM\JoinColumn(name="privacy_id", referencedColumnName="id", nullable=false)
     */
    private $privacy;

    /**
     * @ORM\ManyToOne(targetEntity="Sport", inversedBy="regularEvents")
     * @ORM\JoinColumn(name="sport_id", referencedColumnName="id", nullable=false)
     */
    private $sport;

    /**
     * @ORM\ManyToOne(targetEntity="EventState", inversedBy="regularEvents")
     * @ORM\JoinColumn(name="state_id", referencedColumnName="id", nullable=false)
     */
    private $state;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @ORM\Column(type="string", length=3, nullable=false)
     */
    private $dayStart;

    /**
     * @ORM\Column(type="string", length=5, nullable=false)
     */
    private $timeStart;

    /**
     * @ORM\Column(type="string", length=3, nullable=false)
     */
    private $dayEnd;

    /**
     * @ORM\Column(type="string", length=5, nullable=false)
     */
    private $timeEnd;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $memberLimit;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return RegularEvent
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set dayStart
     *
     * @param string $dayStart
     * @return RegularEvent
     */
    public function setDayStart($dayStart)
    {
        $this->dayStart = $dayStart;

        return $this;
    }

    /**
     * Get dayStart
     *
     * @return string
     */
    public function getDayStart()
    {
        return $this->dayStart;
    }

    /**
     * Set timeStart
     *
     * @param string $timeStart
     * @return RegularEvent
     */
    public function setTimeStart($timeStart)
    {
        $this->timeStart = $timeStart;

        return $this;
    }

    /**
     * Get timeStart
     *
     * @return string
     */
    public function getTimeStart()
    {
        return $this->timeStart;
    }

    /**
     * Set dayEnd
     *
     * @param string $dayEnd
     * @return RegularEvent
     */
    public function setDayEnd($dayEnd)
    {
        $this->dayEnd = $dayEnd;

        return $this;
    }

    /**
     * Get dayEnd
     *
     * @return string
     */
    public function getDayEnd()
    {
        return $this->dayEnd;
    }

    /**
     * Set timeEnd
     *
     * @param string $timeEnd
     * @return RegularEvent
     */
    public function setTimeEnd($timeEnd)
    {
        $this->timeEnd = $timeEnd;

        return $this;
    }

    /**
     * Get timeEnd
     *
     * @return string
     */
    public function getTimeEnd()
    {
        return $this->timeEnd;
    }

    /**
     * Set organizer
     *
     * @param User $organizer
     * @return RegularEvent
     */
    public function setOrganizer(User $organizer)
    {
        $this->organizer = $organizer;

        return $this;
    }

    /**
     * Get organizer
     *
     * @return User
     */
    public function getOrganizer()
    {
        return $this->organizer;
    }

    /**
     * Set place
     *
     * @param Place $place
     * @return RegularEvent
     */
    public function setPlace(Place $place)
    {
        $this->place = $place;

        return $this;
    }

    /**
     * Get place
     *
     * @return Place
     */
    public function getPlace()
    {
        return $this->place;
    }

    /**
     * Set memberLimit
     *
     * @param integer $memberLimit
     * @return RegularEvent
     */
    public function setMemberLimit($memberLimit)
    {
        $this->memberLimit = $memberLimit;

        return $this;
    }

    /**
     * Get memberLimit
     *
     * @return integer
     */
    public function getMemberLimit()
    {
        return $this->memberLimit;
    }

    /**
     * Set privacy
     *
     * @param EventPrivacy $privacy
     * @return RegularEvent
     */
    public function setPrivacy(EventPrivacy $privacy)
    {
        $this->privacy = $privacy;

        return $this;
    }

    /**
     * Get privacy
     *
     * @return EventPrivacy
     */
    public function getPrivacy()
    {
        return $this->privacy;
    }

    /**
     * Set sport
     *
     * @param Sport $sport
     * @return RegularEvent
     */
    public function setSport(Sport $sport)
    {
        $this->sport = $sport;

        return $this;
    }

    /**
     * Get sport
     *
     * @return Sport
     */
    public function getSport()
    {
        return $this->sport;
    }

    /**
     * @param EventState $state
     *
     * @return RegularEvent
     */
    public function setState(EventState $state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * @return EventState
     */
    public function getState()
    {
        return $this->state;
    }
}


text:
static int prof_counter = 0;   // cycles 0..1023 and prints profile info at every 0

static unsigned long long
    operations = 0,             // # of operations in total
    creations = 0,              // # of hash map creations
    capCountSum = 0,            // the highest count seen on deletion
    destroys = 0,               // # of hash map destructions
    node_creations = 0,         // # of nodes created
    node_destroys = 0,          // # of nodes deleted
    totbucks = 0,               // total number of buckets created
    totemptybucks = 0,          // total number of empty buckets (even after destruction)
    totpopbucks = 0,            // total number of populated buckets (1 or more)
    totcollbucks = 0,           // total number of buckets with > 1 node
    totfinds = 0,               // total number of bucket find ops
    totsets = 0,                // total number of set operations
    totgets = 0,                // total number of get operations
    totdels = 0,                // total number of delete operations
    totreplaces = 0,            // total number of replacements (i.e. sets for pre-existing keys)
    totcolls = 0,               // total number of collisions (insertions into populated buckets)
    totsetcolls = 0,            // total number of collisions on set ops
    totgetcolls = 0,            // total number of collisions on get ops
    topbucksize = 0,            // biggest observed bucket size (in nodes)
    cstring_hashgens = 0,       // number of c string hash generations
    cstring_hashcomps = 0;      // number of c string hash comparisons

#define BS_TRACK_CAP 8
static unsigned long long buckets_sized[BS_TRACK_CAP] = {0};
#define reg_buck_insert(bucket) do { \
            PDSize bsize = PDArrayGetCount(bucket);\
            PDSize bscapped = bsize > BS_TRACK_CAP-1 ? BS_TRACK_CAP-1 : bsize;\
            if (bsize > 0) {\
                totcolls++; \
                totcollbucks += bsize == 1;\
                if (bsize + 1 > topbucksize) topbucksize = bsize + 1; \
                buckets_sized[bscapped]--; \
            }\
            buckets_sized[bscapped+1]++; \
        } while(0)

#define reg_buck_delete(bucket) do {\
            PDSize bsize = PDArrayGetCount(bucket);\
            if (bsize > BS_TRACK_CAP-1) bsize = BS_TRACK_CAP-1;\
            PDAssert(bsize > 0); \
            buckets_sized[bsize]--;\
            buckets_sized[bsize-1]++;\
        } while(0)

static inline void prof_report()
{
    printf("                     HASH MAP PROFILING\n"
           "=================================================================================================\n"
           "total operation count : %10llu\n"
           "average count / dict  : %10lf\n"
           "creations  : %10llu   destroys   : %10llu\n"
           "nodes      : %10llu              : %10llu\n"
           "bucket sum : %10llu   top sized  : %10llu\n"
           "   empty   : %10llu   populated  : %10llu  w/ collisions : %10llu\n"
           "set ops    : %10llu   get ops    : %10llu     deletions  : %10llu\n"
           "find ops   : %10llu   replace ops: %10llu\n"
           "C string g : %10llu   C string c : %10llu\n"
           "collisions : %10llu\n"
           "   on set  : %10llu   on get     : %10llu\n"
           "collision ratio : %f\n"
           "   set collisions : %f   get/del collisions : %f\n"
           , operations
           , (double)capCountSum / (double)destroys
           , creations, destroys
           , node_creations, node_destroys
           , totbucks, topbucksize
           , totemptybucks, totpopbucks, totcollbucks
           , totsets, totgets, totdels
           , totfinds, totreplaces
           , cstring_hashgens, cstring_hashcomps
           , totcolls
           , totsetcolls, totgetcolls
           , (float)totcolls / (float)(totsets + totgets + totdels)
           , (float)totsetcolls / (float)totsets, (float)totgetcolls / (float)(totgets+totdels));
    printf("bucket sizes:\n"
           "        0        1        2        3        4        5        6        7+\n");
    for (PDSize i = 0; i < BS_TRACK_CAP; i++) {
        printf(" %8llu", buckets_sized[i]);
    }
    printf("\n"
           "=================================================================================================\n");
}

#   define  prof(args...) do {\
                args;\
                if (!(prof_counter = (prof_counter + 1) & prof_ctr_mask))\
                prof_report();\
            } while(0)
#else
#   define reg_buck_insert(bucket)
#   define reg_buck_delete(bucket)
#   define prof(args...)
#   define prof_report()
#endif

void PDDictionaryDestroy(PDDictionaryRef hm)
{
    prof(capCountSum += hm->maxCount);
    prof(destroys++);

#ifdef PD_SUPPORT_CRYPTO
    PDRelease(hm->ci);
#endif
    free(hm->buckets);
    PDRelease(hm->populated);
}

static inline PDSize PDHashGeneratorCString(const char *key)
{
    prof(cstring_hashgens++);
    // from http://c.learncodethehardway.org/book/ex37.html
    size_t len = strlen(key);
    PDSize hash = 0;
    PDSize i = 0;

    for(hash = i = 0; i < len; ++i) {
        hash += key[i];
        hash += (hash << 10);
        hash ^= (hash >> 6);
    }

    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);

    return hash;
}

#ifdef PDHM_PROF
static inline int PDHashComparatorCString(const char *key1, const char *key2)
{
    prof(cstring_hashcomps++);
    return strcmp(key1, key2);
}
#else
#   define PDHashComparatorCString  strcmp
#endif

#define PD_HASHMAP_DEFAULT_BUCKETS  64

PDDictionaryRef _PDDictionaryCreateWithSettings(PDSize bucketc)
{
    prof(creations++; totbucks += bucketc; totemptybucks += bucketc);
    PDDictionaryRef hm = PDAllocTyped(PDInstanceTypeDict, sizeof(struct PDDictionary), PDDictionaryDestroy, false);
    hm->count = 0;
    prof(hm->maxCount = 0);
    hm->bucketc = bucketc;   // 128 (0b10000000)
    hm->bucketm = bucketc-1; // 127 (0b01111111)
    hm->buckets = calloc(sizeof(PDArrayRef), hm->bucketc);
    hm->populated = PDArrayCreateWithCapacity(bucketc);
    hm->ci = NULL;
    return hm;
}

PDDictionaryRef PDDictionaryCreateWithBucketCount(PDSize bucketCount)
{
    if (bucketCount < 16) bucketCount = 16;
    PDAssert(bucketCount < 1 << 24); // crash = absurd bucket count (over 16777216)
    PDSize bits = ceilf(log2f(bucketCount)); // ceil(log2(100)) == ceil(6.6438) == 7
    PDSize bucketc = 1 << bits; // 1 << 7 == 128
    return _PDDictionaryCreateWithSettings(bucketc);
}

PDDictionaryRef PDDictionaryCreate()
{
    return _PDDictionaryCreateWithSettings(PD_HASHMAP_DEFAULT_BUCKETS);
}

PDDictionaryRef PDDictionaryCreateWithComplex(pd_stack stack)
{
    PDDictionaryRef hm = _PDDictionaryCreateWithSettings(PD_HASHMAP_DEFAULT_BUCKETS);
    PDDictionaryAddEntriesFromComplex(hm, stack);
    return hm;
}

PDDictionaryRef PDDictionaryCreateWithKeyValueDefinition(const void **defs)
{
    PDDictionaryRef hm = _PDDictionaryCreateWithSettings(PD_HASHMAP_DEFAULT_BUCKETS);

    PDInteger i = 0;
    char *key;
    void *val;
    while (defs[i]) {
        key = (char *)defs[i++];
        val = (void *)defs[i++];
        PDDictionarySet(hm, key, val);
    }
    return hm;
}

void PDDictionaryAddEntriesFromComplex(PDDictionaryRef hm, pd_stack stack)
{
    if (stack == NULL) {
        // empty dictionary
        return;
    }

    // this may be an entry that is a dictionary inside another dictionary; if so, we should see something like

    if (PDIdentifies(stack->info, PD_DE)) {
        stack = stack->prev->prev->info;
    }

    // we may have the DICT identifier
    if (PDIdentifies(stack->info, PD_DICT)) {
        if (stack->prev->prev == NULL)
            stack = NULL;
        else
            stack = stack->prev->prev->info;
    }

    pd_stack s = stack;
    pd_stack entry;

    pd_stack_set_global_preserve_flag(true);
    while (s) {
        entry = as(pd_stack, s->info)->prev;

        // entry must be a string; it's the key value
        char *key = entry->info;
        entry = entry->prev;
        if (entry->type == PD_STACK_STRING) {
            PDDictionarySet(hm, key, PDStringCreate(strdup(entry->info), strlen(entry->info)));
        } else {
            entry = entry->info;
            pd_stack_set_global_preserve_flag(true);
            void *v = PDInstanceCreateFromComplex(&entry);
            pd_stack_set_global_preserve_flag(false);
#ifdef PD_SUPPORT_CRYPTO
            if (v && hm->ci) (*PDInstanceCryptoExchanges[PDResolve(v)])(v, hm->ci, true);
#endif
            PDDictionarySet(hm, key, v);
            PDRelease(v);
        }
        s = s->prev;
    }
    pd_stack_set_global_preserve_flag(false);
}

static void PDDictionaryNodeDestroy(PDDictionaryNodeRef n)
{
    PDRelease(n->data);
    free(n->key);
    prof(node_destroys++);
}

static inline PDDictionaryNodeRef PDDictionaryNodeCreate(PDSize hash, char *key, void *data)
{
    prof(node_creations++);
    PDDictionaryNodeRef n = PDAlloc(sizeof(struct PDDictionaryNode), PDDictionaryNodeDestroy, false);
    n->hash = hash;
    n->key = key; // owned! freed on node destruction!
    n->data = PDRetain(data);
    return n;
}

static inline PDArrayRef PDDictionaryFindBucket(PDDictionaryRef hm, const char *key, PDSize hash, PDBool create, PDInteger *outIndex)
{
    prof(totfinds++);
    PDSize bucketIndex = hash & hm->bucketm;

    PDArrayRef bucket = hm->buckets[bucketIndex];
    *outIndex = -1;

    if (NULL == bucket) {
        if (! create) return NULL;
        prof(totemptybucks--; totpopbucks++); // when a bucket is asked to be created, it means it will be non-empty and populated, so we prof that here
        bucket = PDArrayCreateWithCapacity(4);
        hm->buckets[bucketIndex] = bucket;
        PDArrayAppend(hm->populated, bucket);
        PDRelease(bucket);
    } else {
        PDDictionaryNodeRef node;
        PDInteger len = PDArrayGetCount(bucket);
        for (PDInteger i = 0; i < len; i++) {
            node = PDArrayGetElement(bucket, i);
            if (node->hash == hash && !PDHashComparatorCString(key, node->key)) {
                *outIndex = i;
                break;
            }
            prof(if (create) totsetcolls++; else totgetcolls++);
        }
    }

    return bucket;
}

void PDDictionarySet(PDDictionaryRef hm, const char *key, void *value)
{
    PDAssert(key != NULL);  // crash = key is NULL; this is not allowed
    PDAssert(value != NULL); // crash = value is NULL; use delete to remove keys

#ifdef PD_SUPPORT_CRYPTO
    if (hm->ci) PDInstanceCryptoExchanges[PDResolve(value)](value, hm->ci, false);
#endif

    prof(operations++);
    prof(totsets++);
    PDSize hash = PDHashGeneratorCString(key);
    PDInteger nodeIndex;
    PDArrayRef bucket = PDDictionaryFindBucket(hm, key, hash, true, &nodeIndex);
    PDAssert(bucket != NULL);

    if (nodeIndex != -1) {
        prof(totreplaces++);
        PDDictionaryNodeRef node = PDArrayGetElement(bucket, nodeIndex);
        PDRetain(value);
        PDRelease(node->data);
        node->data = value;
    } else {
        reg_buck_insert(bucket);
        hm->count++;
        prof(if (hm->count > hm->maxCount) hm->maxCount = hm->count);
        PDDictionaryNodeRef node = PDDictionaryNodeCreate(hash, strdup(key), value);
        PDArrayAppend(bucket, node);
        PDRelease(node);
    }
}

void *PDDictionaryGet(PDDictionaryRef hm, const char *key)
{
    PDAssert(hm);
    prof(operations++);
    prof(totgets++);
    PDSize hash = PDHashGeneratorCString(key);
    PDInteger nodeIndex;
    PDArrayRef bucket = PDDictionaryFindBucket(hm, key, hash, false, &nodeIndex);
    return nodeIndex > -1 ? ((PDDictionaryNodeRef)PDArrayGetElement(bucket, nodeIndex))->data : NULL;
}

void *PDDictionaryGetTyped(PDDictionaryRef dictionary, const char *key, PDInstanceType type)
{
    void *v = PDDictionaryGet(dictionary, key);
    return v && PDResolve(v) == type ? v : NULL;
}

void PDDictionaryDelete(PDDictionaryRef hm, const char *key)
{
    prof(operations++);
    prof(totdels++);
    PDSize hash = PDHashGeneratorCString(key);
    PDInteger nodeIndex;
    PDArrayRef bucket = PDDictionaryFindBucket(hm, key, hash, false, &nodeIndex);
    if (! bucket || nodeIndex == -1) return;
    reg_buck_delete(bucket);
    hm->count--;
    PDArrayDeleteAtIndex(bucket, nodeIndex);
}

void PDDictionaryClear(PDDictionaryRef hm)
{
    prof(operations++);
    PDInteger blen = PDArrayGetCount(hm->populated);
    for (PDInteger i = 0; i < blen; i++) {
        PDArrayRef bucket = PDArrayGetElement(hm->populated, i);
        PDArrayClear(bucket);
    }
    hm->count = 0;
}

PDSize PDDictionaryGetCount(PDDictionaryRef hm)
{
    return hm->count;
}

void PDDictionaryIterate(PDDictionaryRef hm, PDHashIterator it, void *ui)
{
    PDBool shouldStop = false;
    PDInteger blen = PDArrayGetCount(hm->populated);
    for (PDInteger i = 0; i < blen; i++) {
        PDArrayRef bucket = PDArrayGetElement(hm->populated, i);
        PDInteger len = PDArrayGetCount(bucket);
        for (PDInteger j = 0; j < len; j++) {
            PDDictionaryNodeRef node = PDArrayGetElement(bucket, j);
            it(node->key, node->data, ui, &shouldStop);
            if (shouldStop) return;
        }
    }
}

typedef struct hm_keygetter {
    int i;
    char **res;
} hm_keygetter;

typedef struct hm_printer {
    char **bv, **buf;
    PDInteger *cap;
    PDInteger *offs;
} hm_printer;

void pd_hm_getkeys(char *key, void *val, hm_keygetter *userInfo, PDBool *shouldStop)
{
    userInfo->res[userInfo->i++] = key;
}

void pd_hm_print(char *key, void *val, hm_printer *p, PDBool *shouldStop)
{
    char *bv;
    PDInteger *cap = p->cap;

    char **buf = p->buf;
    PDInteger offs = *p->offs;

    PDInteger klen = strlen(key);
    PDInstancePrinterRequire(klen + 10, klen + 10);
    bv = *buf;
    bv[offs++] = '/';
    strcpy(&bv[offs], key);
    offs += klen;
    bv[offs++] = ' ';
    PDInstanceType it = PDResolve(val);
    if (it == PDInstanceTypeString) {
        PDStringRef str = val;
        PDStringType st = PDStringGetType(str);
        if (st == PDStringTypeBinary || st == PDStringTypeEscaped)  {
            str = PDAutorelease(PDStringCreateFromStringWithType(str, PDStringTypeEscaped, true, false));
        }
        offs = PDInstancePrinters[PDInstanceTypeString](str, buf, offs, cap);
    } else offs = PDInstancePrinters[PDResolve(val)](val, buf, offs, cap);
    PDInstancePrinterRequire(4, 4);
    bv = *buf;
    bv[offs++] = ' ';

    *p->bv = bv;
    *p->offs = offs;

//    printf("\t%s: %s\n", key, val);
}

void PDDictionaryPopulateKeys(PDDictionaryRef hm, char **keys)
{
    hm_keygetter kg;
    kg.i = 0;
    kg.res = keys;
    PDDictionaryIterate(hm, (PDHashIterator)pd_hm_getkeys, &kg);
}

char *PDDictionaryToString(PDDictionaryRef hm, PDInteger *outLength)
{
    PDInteger cap = 6 + 20 * hm->count;
    char *str = malloc(cap);
    PDInteger len = PDDictionaryPrinter(hm, &str, 0, &cap);
    if (outLength) *outLength = len;
    return str;
}

void PDDictionaryPrint(PDDictionaryRef hm)
{
    char *str = PDDictionaryToString(hm, NULL);
    puts(str);
    free(str);
}

PDInteger PDDictionaryPrinter(void *inst, char **buf, PDInteger offs, PDInteger *cap)
{
    hm_printer p;
    PDInstancePrinterInit(PDDictionaryRef, 0, 1);
    PDInteger len = 6 + 20 * i->count;
    PDInstancePrinterRequire(len, len);
    char *bv = *buf;
    bv[offs++] = '<';
    bv[offs++] = '<';
    bv[offs++] = ' ';

    p.buf = buf;
    p.cap = cap;

    p.bv = &bv;
    p.offs = &offs;

    PDDictionaryIterate(i, (PDHashIterator)pd_hm_print, &p);

    bv[offs++] = '>';
    bv[offs++] = '>';
    bv[offs] = 0;
    return offs;
}

#ifdef PD_SUPPORT_CRYPTO

void pd_hm_encrypt(void *key, void *val, PDCryptoInstanceRef ci, PDBool *shouldStop)
{
    (*PDInstanceCryptoExchanges[PDResolve(val)])(val, ci, false);
}

void PDDictionaryAttachCrypto(PDDictionaryRef hm, pd_crypto crypto, PDInteger objectID, PDInteger genNumber)
{
    hm->ci = PDCryptoInstanceCreate(crypto, objectID, genNumber);
    PDDictionaryIterate(hm, (PDHashIterator)pd_hm_encrypt, hm->ci);
}

void PDDictionaryAttachCryptoInstance(PDDictionaryRef hm, PDCryptoInstanceRef ci, PDBool encrypted)
{
    hm->ci = PDRetain(ci);
    PDDictionaryIterate(hm, (PDHashIterator)pd_hm_encrypt, hm->ci);
}

#endif


text:
package standard

import (
	G "github.com/ionous/sashimi/game"
	. "github.com/ionous/sashimi/script"
	. "github.com/ionous/sashimi/standard/live"
	"github.com/ionous/sashimi/util/lang"
)

func init() {
	AddScript(func(s *Script) {
		// "Represents a machine or contrivance of some kind which can be switched on or off."

		// FIX: having problems with a lack of parts
		s.The("objects",
			AreEither("operable").Or("inoperable").Usually("inoperable"))

		s.The("props",
			Called("devices"),
			AreEither("switched off").Or("switched on"))

		s.The("devices",
			When("printing name text").
				Always(func(g G.Play) {
					text := ArticleName(g, "device", func(device G.IObject) (status string) {
						if device.Is("operable") {
							if device.Is("switched on") {
								status = "switched on"
							} else {
								status = "switched off"
							}
						}
						return status
					})
					text = lang.Capitalize(text)
					g.Say(text)
					g.StopHere()
				}))

		s.The("props", Can("report inoperable").And("reporting inoperable").RequiresNothing(),
			To("report inoperable", func(g G.Play) {
				g.Say("It's inoperable.")
			}))

		//
		// Turn on, fix: was "prop", now "object" to handle outlet actors :(
		//
		s.The("actors",
			Can("switch it on").And("switching it on").RequiresOne("object"),
			To("switch it on", func(g G.Play) { ReflectToTarget(g, "report switched on") }))

		s.The("objects",
			Can("report switched on").And("reporting switched on").RequiresOne("actor"),
			To("report switched on", func(g G.Play) {
				device, actor := g.The("action.source"), g.The("actor")
				if !device.Is("operable") {
					device.Go("report inoperable")
				} else {
					if device.Is("switched on") {
						device.Go("report already on", actor)
					} else {
						device.IsNow("switched on")
						device.Go("report now on", actor)
					}
				}
			}),
			Can("report already on").And("reporting already on").RequiresOne("actor"),
			To("report already on", func(g G.Play) {
				g.Say("It's already switched on.")
			}),
			Can("report now on").And("reporting now on").RequiresOne("actor"),
			To("report now on", func(g G.Play) {
				device := g.The("device")
				g.Say("Now the", device.Text("Name"), "is on.")
			}))

		//
		// Turn off
		//
		s.The("actors",
			Can("switch it off").And("switching it off").RequiresOne("prop"),
			To("switch it off", func(g G.Play) { ReflectToTarget(g, "report switch off") }))

		s.The("devices",
			Can("report switch off").And("reporting switch off").RequiresNothing(),
			To("report switch off", func(g G.Play) {
				device, actor := g.The("device"), g.The("actor")
				if device.Is("switched off") {
					device.Go("report already off", actor)
				} else {
					device.IsNow("switched off")
					device.Go("report now off", actor)
				}
			}),
			Can("report already off").And("reporting already off").RequiresOne("actor"),
			To("report already off", func(g G.Play) {
				g.Say("It's already off.") //[regarding the noun]?
			}),
			Can("report now off").And("reporting now off").RequiresOne("actor"),
			To("report now off", func(g G.Play) {
				device, _ := g.The("device"), g.The("actor")
				g.Say("Now the", device.Text("Name"), "is off.")
			}))

		// understandings:
		// note: inform has "template matching" here --
		// "switch [something switched on]" as switching off.
		// FIX:  inform's  "understand" has many meanings, but i think itd be better here
		// maybe: s.Understand.Or.As; Understand().WhenMatching("").Or()
		s.Execute("switch it on",
			Matching("switch|turn on {{something}}").
				Or("switch {{something}} on"))

		s.Execute("switch it off",
			Matching("turn|switch off {{something}}").
				Or("turn|switch {{something}} off"))
	})
}


text:
package com.polymathiccoder.avempace.meta.model;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;

import com.polymathiccoder.avempace.config.Region;
import com.polymathiccoder.avempace.meta.annotation.Entity;
import com.polymathiccoder.avempace.meta.annotation.Table;
import com.polymathiccoder.avempace.meta.model.validation.MetaModelValidationException;

@AutoProperty
public final class TypeMapping {
// Fields
	private final Class<?> annotatedType;

	private Region primaryRegion;
	private Set<Region> secondaryRegions;
	private boolean propagatedAcrossAllRegions;

	private String tableName;
	private long readCapacityUnits;
	private long writeCapacityUnits;

// Life cycle
	private TypeMapping(final Class<?> annotatedType) {
		this.annotatedType = annotatedType;
	}

	// Factories
	public static TypeMapping generateForType(final Class<?> type) {
		TypeMapping typeMapping = new TypeMapping(type);

		// Construct
		for (final Annotation annotation : type.getAnnotations()) {
			processTableAnnotation(typeMapping, annotation);
			processEntityAnnotation(typeMapping, annotation);
		}

		// Validate
		try {
			validate(typeMapping);
		} catch (MetaModelValidationException metaModelValidationException) {
			//TODO Handle better
			throw new IllegalStateException();
		}

		return typeMapping;
	}

	// Helpers
	private static boolean processTableAnnotation(final TypeMapping typeMapping, final Annotation annotation) {
		boolean processed = false;
		if (annotation instanceof Table) {
			final Table tableAnnotation = (Table) annotation;

			typeMapping.tableName = tableAnnotation.name();
			typeMapping.readCapacityUnits = tableAnnotation.readCapacityUnits();
			typeMapping.writeCapacityUnits = tableAnnotation.writeCapacityUnits();

			processed = true;
		}
		return processed;
	}

	private static boolean processEntityAnnotation(final TypeMapping typeMapping, final Annotation annotation) {
		boolean processed = false;
		if (annotation instanceof Entity) {
			final Entity entityAnnotation = (Entity) annotation;

			typeMapping.primaryRegion = entityAnnotation.primaryRegion();
			typeMapping.secondaryRegions = new HashSet<>(Arrays.asList(entityAnnotation.secondaryRegions()));
			typeMapping.propagatedAcrossAllRegions = entityAnnotation.propagatedAcrossAllRegions();

			processed = true;
		}
		return processed;
	}

	private static void validate(final TypeMapping typeMapping) throws MetaModelValidationException {
		//TODO Implement
	}

	// Accessors and mutators
	public Class<?> getAnnotatedType() { return annotatedType; }

	public Region getPrimaryRegion() { return primaryRegion; }

	public Set<Region> getSecondaryRegions() { return secondaryRegions; }

	public boolean isPropagatedAcrossAllRegions() { return propagatedAcrossAllRegions; }

	public String getTableName() { return tableName; }

	public long getReadCapacityUnits() { return readCapacityUnits; }

	public long getWriteCapacityUnits() { return writeCapacityUnits; }

	// Common methods
	@Override
	public boolean equals(final Object other) { return Pojomatic.equals(this, other); }
	@Override
	public int hashCode() { return Pojomatic.hashCode(this); }
	@Override
	public String toString() { return Pojomatic.toString(this); }
}


text:
<?php

namespace Helthe\Component\Chronos;

use Helthe\Component\Chronos\Job\JobInterface;

/**
 * Programmatic cron job scheduler.
 *
 * @author Carl Alexander <carlalexander@helthe.co>
 */
class CronJobScheduler
{
    /**
     * @var array
     */
    private $jobs;

    /**
     * Constructor.
     *
     * @param array $jobs
     */
    public function __construct(array $jobs = array())
    {
        $this->jobs = array();

        foreach ($jobs as $job) {
            $this->add($job);
        }
    }

    /**
     * Add job to the scheduler.
     *
     * @param JobInterface $job
     */
    public function add(JobInterface $job)
    {
        $this->jobs[] = $job;
    }

    /**
     * Run all the jobs that are due now.
     */
    public function runJobs()
    {
        foreach ($this->jobs as $job) {
            if ($job->isDue()) {
                $job->run();
            }
        }
    }
}


text:
package com.mokalab.simplesqlitetest;

import android.app.Application;

import com.mokalab.simplesqlitelibrary.DatabaseController;
import com.mokalab.simplesqlitelibrary.DatabaseHelper;
import com.mokalab.simplesqlitelibrary.IDatabase;

/**
 * Created by work on 2014-06-12.
 */
public class SampleApplication extends Application {

    @Override
    public void onCreate() {

        super.onCreate();
        initialize();
    }

    private void initialize() {

        initializeDb();
    }

    /**
     * How to use and initialize your Application Database
     * using SimpleSqliteLibrary api.
     */
    private void initializeDb() {

        IDatabase db = new SampleDatabase();
        DatabaseHelper helper = new DatabaseHelper(this, db);
        DatabaseController.initialize(helper);
    }
}


text:
/**
 *
 */
package com.bbs.services.blog.impl;

import java.io.Serializable;

import com.bbs.dao.blog.ManageBlogDao;
import com.bbs.dao.blog.impl.ManageBlogDaoImpl;
import com.bbs.entity.blog.Blog;
import com.bbs.services.blog.ManageBlogServices;
import com.bbs.utils.PageUtils;

/**
 * ÏîÄ¿Ãû³Æ£ºBBS
 * ÀàÃû³Æ£ºManagerServicesBlogImpl
 * ÀàÃèÊö£º
 * ´´½¨ÈË£ºÌ³×Ó
 * ´´½¨Ê±¼ä£º2016Äê4ÔÂ2ÈÕ ÏÂÎç4:27:33
 * ÐÞ¸ÄÈË£ºTanLiu
 * ÐÞ¸Äʱ¼ä£º2016Äê4ÔÂ2ÈÕ ÏÂÎç4:27:33
 * Ð޸ı¸×¢£º
 * @version
 */
public class ManagerServicesBlogImpl implements ManageBlogServices {

	ManageBlogDao managerBlogDao=new ManageBlogDaoImpl();

	@Override
	public void deleteBlog(Serializable id) {
		managerBlogDao.deleteBlog(id);
	}

	@Override
	public PageUtils<Blog> findPartBlot(PageUtils<Blog> pageUtils) {
		return managerBlogDao.findPartBlot(pageUtils);
	}

	@Override
	public PageUtils<Blog> findByTitle(PageUtils<Blog> pageUtils, String query) {
		// TODO Auto-generated method stub
		return managerBlogDao.findByTitle(pageUtils,query);
	}

}


text:
package com.hisun.loganalysis.spark.kafka;

import org.apache.spark.api.java.JavaSparkContext;
import org.slf4j.LoggerFactory;

public abstract class AbstractProcessor implements Processor {

	private transient org.slf4j.Logger logger = LoggerFactory.getLogger(AbstractProcessor.class);

	public AbstractProcessor() {
	}

	public Object doProcess(JavaSparkContext context, boolean async) throws Exception {

		Object ret = null;

		try {

			before(context);

			if(async) {
				ret = processAsAsync(context);
			}else {
				ret = process(context);
			}

			after(context);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return ret;
	}
}


text:
- Getting Started
  - [Introduction](/)
  - [Screens](screens.md)
  - [API](API.md)
  - [Contribute](CONTRIBUTE.md)
  - [Contribute-kr](CONTRIBUTE-kr.md)
  - [Examples](examples.md)
  - [History](HISTORY.md)


text:
CGovernanceObjectVoteFile::CGovernanceObjectVoteFile()
    : nMemoryVotes(0),
      listVotes(),
      mapVoteIndex()
{}

CGovernanceObjectVoteFile::CGovernanceObjectVoteFile(const CGovernanceObjectVoteFile& other)
    : nMemoryVotes(other.nMemoryVotes),
      listVotes(other.listVotes),
      mapVoteIndex()
{
    RebuildIndex();
}

void CGovernanceObjectVoteFile::AddVote(const CGovernanceVote& vote)
{
    uint256 nHash = vote.GetHash();
    // make sure to never add/update already known votes
    if (HasVote(nHash))
        return;
    listVotes.push_front(vote);
    mapVoteIndex.emplace(nHash, listVotes.begin());
    ++nMemoryVotes;
}

bool CGovernanceObjectVoteFile::HasVote(const uint256& nHash) const
{
    return mapVoteIndex.find(nHash) != mapVoteIndex.end();
}

bool CGovernanceObjectVoteFile::SerializeVoteToStream(const uint256& nHash, CDataStream& ss) const
{
    vote_m_cit it = mapVoteIndex.find(nHash);
    if(it == mapVoteIndex.end()) {
        return false;
    }
    ss << *(it->second);
    return true;
}

std::vector<CGovernanceVote> CGovernanceObjectVoteFile::GetVotes() const
{
    std::vector<CGovernanceVote> vecResult;
    for(vote_l_cit it = listVotes.begin(); it != listVotes.end(); ++it) {
        vecResult.push_back(*it);
    }
    return vecResult;
}

void CGovernanceObjectVoteFile::RemoveVotesFromMasternode(const COutPoint& outpointMasternode)
{
    vote_l_it it = listVotes.begin();
    while(it != listVotes.end()) {
        if(it->GetMasternodeOutpoint() == outpointMasternode) {
            --nMemoryVotes;
            mapVoteIndex.erase(it->GetHash());
            listVotes.erase(it++);
        }
        else {
            ++it;
        }
    }
}

void CGovernanceObjectVoteFile::RebuildIndex()
{
    mapVoteIndex.clear();
    nMemoryVotes = 0;
    vote_l_it it = listVotes.begin();
    while(it != listVotes.end()) {
        CGovernanceVote& vote = *it;
        uint256 nHash = vote.GetHash();
        if(mapVoteIndex.find(nHash) == mapVoteIndex.end()) {
            mapVoteIndex[nHash] = it;
            ++nMemoryVotes;
            ++it;
        }
        else {
            listVotes.erase(it++);
        }
    }
}


text:
Interface gráfica com a execução de vários algoritmos da disciplina de Grafos.

O programa inclui uma MainWindow, com a opção de execução de vários algoritmos de grafos.


text:
import json
import os
from builder.network_builder import Network

class Generator:

    def __init__(self):
        self.best_accuracy = 0
        self.best_accuracy_logdir = None
        self.best_network_spec = None

    def get_best_spec (self, logdir):
        # get all netswork.json
        for subdir, dirs, files in os.walk(str(logdir)):
            for file in files:
                # filter
                if file == 'network.json':
                    file_loc = os.path.join(subdir, file)
                    #read current network.json
                    with open(file_loc, 'r') as fp:
                        n_spec = json.loads( fp.read() )
                        if('results' in n_spec ):
                            if(self.best_accuracy < n_spec['results']['accuracy']):
                                self.best_accuracy = n_spec['results']['accuracy']
                                self.best_accuracy_logdir = file_loc
                                self.best_network_spec = n_spec

        #self._write_to_logdir(logdir=logdir, n_spec=self.best_network_spec)
        return self.best_network_spec

    def _write_to_logdir(self, logdir, n_spec):
        file_loc = os.path.join(logdir, 'Best_Network.json')
        with open(file_loc, 'w') as fp:
            fp.write(str(n_spec))

def main():
            base_logdir = 'log'
            output_logdir = base_logdir + '/best/'

            generator = Generator()
            json_network_spec = generator.get_best_spec(logdir = base_logdir)
            print('best Network: ' + str(json_network_spec))

            # workaround
            json_network_spec['logdir'] = output_logdir

            network = Network(json.dumps(json_network_spec))
            network.evaluate(get_weights=True)

            print('Finished')

main()


text:
.. -*- coding: utf-8 -*-
.. URL: https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/
.. SOURCE: https://github.com/docker/docker/blob/master/docs/userguide/networking/default_network/dockerlinks.md
   doc version: 1.12
      https://github.com/docker/docker/commits/master/docs/userguide/networking/default_network/dockerlinks.md
.. check date: 2016/06/14
.. Commits on Feb 2, 2016 6f863cfa18f30d1df2f1f81b2b4f456dee2a73b8
.. ---------------------------------------------------------------------------

.. Legacy container links

.. _legacy-container-links:

========================================
コンテナ・リンク機能(古い機能)
========================================

.. sidebar:: 目次

   .. contents::
       :depth: 3
       :local:

.. The information in this section explains legacy container links within the Docker default `bridge` network which is created automatically when you install Docker.

ここでは古い機能であるコンテナ・リンクについて説明します。
これは Docker のデフォルトである ``bridge`` ネットワーク内にあるもので、この ``bridge`` ネットワークは Docker をインストールした際に自動的に生成されます。

.. Before the [Docker networks feature](/engine/userguide/networking/index.md), you could use the
   Docker link feature to allow containers to discover each other and securely
   transfer information about one container to another container. With the
   introduction of the Docker networks feature, you can still create links but they
   behave differently between default `bridge` network and
   [user defined networks](/engine/userguide/networking/work-with-networks.md#linking-containers-in-user-defined-networks).

:doc:`Docker のネットワーク機能 </engine/userguide/networking/index>` が提供される以前は、Docker のリンク機能によって複数のコンテナが互いを検出し、一方から他方への情報送信を安全に行うようにしていました。
Docker のネットワーク機能が導入されてからも、リンクを生成することはできます。
ただしデフォルトの ``bridge`` ネットワークであるか、:ref:`ユーザ定義のネットワーク <linking-containers-in-user-defined-networks>` であるかによって、その動作は異なることになります。

.. This section briefly discusses connecting via a network port and then goes into
   detail on container linking in default `bridge` network.

この節においてはネットワークポートを通じてネットワークに接続する方法を簡単に説明した上で、デフォルトの ``bridge`` ネットワーク内でのコンテナ・リンクを行う方法へ進んでいきます。

.. >**Warning**:
   >The `--link` flag is a deprecated legacy feature of Docker. It may eventually
   be removed. Unless you absolutely need to continue using it, we recommend that you use
   user-defined networks to facilitate communication between two containers instead of using
   `--link`. One feature that user-defined networks do not support that you can do
   with `--link` is sharing environmental variables between containers. However,
   you can use other mechanisms such as volumes to share environment variables
   between containers in a more controlled way.
   {:.warning}

.. warning::

   Docker の ``--link`` フラグは過去の機能です。
   そのうちに削除されるかもしれません。
   この機能を確実に必要としているのでなければ ``--link`` を使わず、2 つのコンテナ間の通信を実現するユーザ定義のネットワークを利用することをお勧めします。
   ``--link`` に存在していて、ユーザ定義のネットワークにない機能は、コンテナ間で環境変数を共有できる機能です。
   ただしボリュームのような別の機能を使えば、コンテナ間での環境変数の共有は、より制御しやすく利用できます。

.. ## Connect using network port mapping

.. _connect-using-network-port-mapping:

ネットワーク・ポート・マッピングを利用した接続
===============================================

.. Let's say you used this command to run a simple Python Flask application:

以下のコマンドによって Python Flask アプリケーションを起動しているとします。

..  $ docker run -d -P training/webapp python app.py
.. code-block:: bash

   $ docker run -d -P training/webapp python app.py

.. > **Note**:
   > Containers have an internal network and an IP address.
   > Docker can have a variety of network configurations. You can see more
   > information on Docker networking [here](/engine/userguide/networking/index.md).
.. note::

   コンテナには内部ネットワークと IP アドレスがあります。
   そして Docker にはさまざまなネットワーク設定方法があります。
   Docker のネットワーク機能の詳細は :doc:`こちら </engine/userguide/networking/index>` を参照してください。

.. When that container was created, the `-P` flag was used to automatically map
   any network port inside it to a random high port within an *ephemeral port
   range* on your Docker host. Next, when `docker ps` was run, you saw that port
   5000 in the container was bound to port 49155 on the host.

このコンテナの生成時には ``-P`` フラグが指定されているので、コンテナ内部のネットワークポートはすべて、Docker ホスト上の「エフェメラルポート」範囲内にあるランダムな高位ポートに自動的に割り当てられます。
その後に ``docker ps`` を実行すれば、コンテナ内の 5000 番ポートが、ホスト上の 49155 番ポートに割り当てられているのがわかります。

..  $ docker ps nostalgic_morse

    CONTAINER ID  IMAGE                   COMMAND       CREATED        STATUS        PORTS                    NAMES
    bc533791f3f5  training/webapp:latest  python app.py 5 seconds ago  Up 2 seconds  0.0.0.0:49155->5000/tcp  nostalgic_morse

.. code-block:: bash

   $ docker ps nostalgic_morse

   CONTAINER ID  IMAGE                   COMMAND       CREATED        STATUS        PORTS                    NAMES
   bc533791f3f5  training/webapp:latest  python app.py 5 seconds ago  Up 2 seconds  0.0.0.0:49155->5000/tcp  nostalgic_morse

.. You also saw how you can bind a container's ports to a specific port using
   the `-p` flag. Here port 80 of the host is mapped to port 5000 of the
   container:

またコンテナのポートを特定のポートに割り当てるには ``-p`` フラグを使えばよいことも、すでに見てきました。
以下はホストの 80 番ポートを、コンテナの 5000 番ポートに割り当てます。

..  $ docker run -d -p 80:5000 training/webapp python app.py

.. code-block:: bash

   $ docker run -d -p 80:5000 training/webapp python app.py

.. And you saw why this isn't such a great idea because it constrains you to
   only one container on that specific port.

ただしこれはあまり良い方法でないのは、すでにお分かりでしょう。
これでは、特定のポートを指定できるのが、ただ一つのコンテナでしかないからです。

.. Instead, you may specify a range of host ports to bind a container port to
   that is different than the default *ephemeral port range*:

上とは違って、コンテナ・ポートに対して、ホストのポート範囲を指定することができます。
この範囲は「エフェメラル・ポート」の範囲とは異なるものです。

..  $ docker run -d -p 8000-9000:5000 training/webapp python app.py

.. code-block:: bash

   $ docker run -d -p 8000-9000:5000 training/webapp python app.py

.. This would bind port 5000 in the container to a randomly available port
   between 8000 and 9000 on the host.

これによるとコンテナの 5000 番ポートは、ホスト上の 8000 から 9000 の中で利用可能なポートがランダムに選び出されます。

.. There are also a few other ways you can configure the `-p` flag. By
   default the `-p` flag will bind the specified port to all interfaces on
   the host machine. But you can also specify a binding to a specific
   interface, for example only to the `localhost`.

``-p`` フラグの設定方法には他にもいくつかあります。
デフォルトにおいて ``-p`` フラグは、ホストマシン上のすべてのインターフェースに対して、指定されたポートを割り当てます。
しかし特定のインターフェースに対しての割り当てを行うこともできます。
たとえば以下は ``loalhost`` にのみ割り当てる例です。

..  $ docker run -d -p 127.0.0.1:80:5000 training/webapp python app.py
.. code-block:: bash

   $ docker run -d -p 127.0.0.1:80:5000 training/webapp python app.py

.. This would bind port 5000 inside the container to port 80 on the
   `localhost` or `127.0.0.1` interface on the host machine.

上はコンテナ内の 5000 番ポートを、ホストマシン上の 80 番ポートに割り当てますが、これが行われるのは ``localhost`` つまり ``127.0.0.1`` インターフェースに対してのみです。

.. Or, to bind port 5000 of the container to a dynamic port but only on the
   `localhost`, you could use:

コンテナ内の 5000 番ポートを ``localhost`` 上の動的ポートに割り当てるなら、以下のようにします。

..  $ docker run -d -p 127.0.0.1::5000 training/webapp python app.py
.. code-block:: bash

   $ docker run -d -p 127.0.0.1::5000 training/webapp python app.py

.. You can also bind UDP ports by adding a trailing /udp. For example:

また、UDP ポートを割り当てたい場合は、最後に ``/udp`` を追加します。例えば、次のように実行します。

.. code-block:: bash

   $ docker run -d -p 127.0.0.1:80:5000/udp training/webapp python app.py

.. You also learned about the useful `docker port` shortcut which showed us the
   current port bindings. This is also useful for showing you specific port
   configurations. For example, if you've bound the container port to the
   `localhost` on the host machine, then the `docker port` output will reflect that.

便利なコマンド ``docker port`` についてはこれまでにも使ってきました。
これによって現時点でのポート割り当ての状況がすぐにわかります。
また特定のポートがどのように設定されているかがわかります。
たとえばコンテナの特定のポートを、ホストマシンの ``localhost`` に割り当てていたとします。
``docker port`` コマンドの出力には、そのことが示されます。

..  $ docker port nostalgic_morse 5000

    127.0.0.1:49155
.. code-block:: bash

   $ docker port nostalgic_morse 5000

   127.0.0.1:49155

.. > **Note**:
   > The `-p` flag can be used multiple times to configure multiple ports.
.. note::

   ``-p`` フラグは複数個の指定が可能であり、これにより複数ポートの指定を行うことができます。

.. ## Connect with the linking system

.. _connect-with-the-linking-system:

リンク・システムを用いた接続
==============================

.. > **Note**:
   > This section covers the legacy link feature in the default `bridge` network.
   > Please refer to [linking containers in user-defined networks](/engine/userguide/networking/work-with-networks.md#linking-containers-in-user-defined-networks)
   > for more information on links in user-defined networks.
.. note::

   この節ではデフォルトの ``bridge`` ネットワーク内の古い機能であるリンク機能について説明します。
   ユーザ定義ネットワーク上のリンクに関しては :ref:`ユーザ定義ネットワークでのコンテナのリンク <linking-containers-in-user-defined-networks>` を参照してください。

.. Network port mappings are not the only way Docker containers can connect to one
   another. Docker also has a linking system that allows you to link multiple
   containers together and send connection information from one to another. When
   containers are linked, information about a source container can be sent to a
   recipient container. This allows the recipient to see selected data describing
   aspects of the source container.

Docker コンテナを別のコンテナと接続させるのは、ネットワークのポート割り当てだけが唯一の方法ではありません。
Docker にはリンクシステム(linking system)があります。
このシステムにより複数のコンテナは互いにリンクすることが可能となり、接続情報をやり取りできるようになります。
複数のコンテナがリンクされていると、1 つのコンテナの情報を別のコンテナに送信することが可能です。
つまり情報を受け取る側のコンテナは、情報元のコンテナに関する情報の中から、必要な情報を取り出して見ることができます。

.. ### The importance of naming

.. _the-importance-of-naming:

名前づけの重要性
--------------------

.. To establish links, Docker relies on the names of your containers.
   You've already seen that each container you create has an automatically
   created name; indeed you've become familiar with our old friend
   `nostalgic_morse` during this guide. You can also name containers
   yourself. This naming provides two useful functions:

Docker がリンクを確立するためには、コンテナの名前が重要になります。
これまでコンテナを生成した際には、各コンテナに自動的に名前がつけられることを見てきました。
実際にここまでの説明においては、おなじみの ``nostalgic_morse`` という名前を用いています。
コンテナの名前は自由につけることができます。
名前をつけることによって、以下の 2 点が得られます。

.. 1. It can be useful to name containers that do specific functions in a way
      that makes it easier for you to remember them, for example naming a
      container containing a web application `web`.

1. コンテナが実現する特定の機能に合わせて、それを表わす名称にしておくと覚えやすく便利です。
   たとえばウェブ・アプリケーションを含んだコンテナには ``web`` という名前をつけます。

.. 2. It provides Docker with a reference point that allows it to refer to other
      containers, for example, you can specify to link the container `web` to container `db`.

2. 名前は、他のコンテナから参照させるための参照名となります。
   たとえば ``web`` コンテナからのリンクとして、``db`` という名前の別のコンテナを指定することができます。

.. You can name your container by using the `--name` flag, for example:

たとえば以下のようにして ``--name`` フラグを使ってコンテナに名前をつけることができます。

..  $ docker run -d -P --name web training/webapp python app.py
.. code-block:: bash

   $ docker run -d -P --name web training/webapp python app.py

.. This launches a new container and uses the `--name` flag to
   name the container `web`. You can see the container's name using the
   `docker ps` command.

上のコマンドは、新規にコンテナを起動させ、``--name`` フラグの情報からコンテナに ``web`` という名前をつけます。
``docker ps`` コマンドによってコンテナ名を確認することができます。

..  $ docker ps -l

    CONTAINER ID  IMAGE                  COMMAND        CREATED       STATUS       PORTS                    NAMES
    aed84ee21bde  training/webapp:latest python app.py  12 hours ago  Up 2 seconds 0.0.0.0:49154->5000/tcp  web
.. code-block:: bash

   $ docker ps -l

   CONTAINER ID  IMAGE                  COMMAND        CREATED       STATUS       PORTS                    NAMES
   aed84ee21bde  training/webapp:latest python app.py  12 hours ago  Up 2 seconds 0.0.0.0:49154->5000/tcp  web

.. You can also use `docker inspect` to return the container's name.

``docker inspect`` の結果からも、コンテナ名を得ることができます。

.. > **Note**:
   > Container names have to be unique. That means you can only call
   > one container `web`. If you want to re-use a container name you must delete
   > the old container (with `docker rm`) before you can create a new
   > container with the same name. As an alternative you can use the `--rm`
   > flag with the `docker run` command. This will delete the container
   > immediately after it is stopped.
.. note::

   コンテナ名は一意である必要があります。
   つまり ``web`` と呼ぶことができるコンテナは 1 つだけということです。
   コンテナ名を再利用したい場合は、それまでの古いコンテナを(``docker container rm`` を使って)削除する必要があります。
   その後であれば、同一名のコンテナを生成して利用することができます。
   これとは別に ``docker run`` の ``--rm`` フラグを利用する方法もあります。
   この方法ではそれまでのコンテナが停止され、すぐに削除されます。

.. ## Communication across links

.. _communication-across-links:

リンク間の通信
====================

.. Links allow containers to discover each other and securely transfer information
   about one container to another container. When you set up a link, you create a
   conduit between a source container and a recipient container. The recipient can
   then access select data about the source. To create a link, you use the `--link`
   flag. First, create a new container, this time one containing a database.

リンク機能によって複数のコンテナが互いを検出し、一方から他方への情報送信を安全に行うことができます。
リンク機能を設定すると、情報発信元のコンテナと受信先のコンテナの間に経路が生成されます。
そして受信先コンテナは、発信元コンテナに関する情報を選び出してアクセスできるようになります。
リンクの生成には `--link` フラグを使います。
そこで以下では、まず新たなコンテナを生成します。
今回はデータベースを含むコンテナーです。

..  $ docker run -d --name db training/postgres
.. code-block:: bash

   $ docker run -d --name db training/postgres

.. This creates a new container called `db` from the `training/postgres`
   image, which contains a PostgreSQL database.

上のコマンドは、PostgreSQL データベースを含む ``training/postgres`` イメージから ``db`` という新規のコンテナを生成します。

.. Now, you need to delete the `web` container you created previously so you can replace it
   with a linked one:

先ほど生成した ``web`` コンテナは、リンクされた状態のコンテナとするために、いったんここで削除する必要があります。

..  $ docker rm -f web
.. code-block:: bash

   $ docker rm -f web

.. Now, create a new `web` container and link it with your `db` container.

新たな ``web`` コンテナを生成して ``db`` コンテナにリンクします。

..  $ docker run -d -P --name web --link db:db training/webapp python app.py
.. code-block:: bash

   $ docker run -d -P --name web --link db:db training/webapp python app.py

.. This will link the new `web` container with the `db` container you created
   earlier. The `--link` flag takes the form:

これにより、新しい ``web`` コンテナが、直前に生成した ``db`` コンテナにリンクされます。
``--link`` フラグは以下のような書式です。

..  --link <name or id>:alias
.. code-block:: bash

   --link <name または id>:alias

.. Where `name` is the name of the container we're linking to and `alias` is an
   alias for the link name. You'll see how that alias gets used shortly.
   The `--link` flag also takes the form:

ここで ``name`` はリンクするコンテナの名前を指定します。
また ``alias`` はリンク名に対するエイリアス名の定義です。
このエイリアス名は簡単に利用することができます。
``--link`` フラグは以下の書式でも構いません。

..	--link <name or id>
.. code-block:: bash

   --link <name または id>

.. In which case the alias will match the name. You could have written the previous
   example as:

この場合、エイリアスはリンク名そのものになります。
先ほどの実行例は、以下のようにすることもできます。

..  $ docker run -d -P --name web --link db training/webapp python app.py
.. code-block:: bash

   $ docker run -d -P --name web --link db training/webapp python app.py

.. Next, inspect your linked containers with `docker inspect`:

次にリンクしたコンテナを ``docker inspect`` によって確認してみます。

..  {% raw %}
    $ docker inspect -f "{{ .HostConfig.Links }}" web

    [/db:/web/db]
    {% endraw %}
.. code-block:: bash

   $ docker inspect -f "{{ .HostConfig.Links }}" web

   [/db:/web/db]

.. You can see that the `web` container is now linked to the `db` container
   `web/db`. Which allows it to access information about the `db` container.

``web`` コンテナが ``db`` コンテナにリンクされ ``web/db`` となっているのがわかります。
これにより ``db`` コンテナに関する情報にアクセスできるようになりました。

.. So what does linking the containers actually do? You've learned that a link allows a
   source container to provide information about itself to a recipient container. In
   our example, the recipient, `web`, can access information about the source `db`. To do
   this, Docker creates a secure tunnel between the containers that doesn't need to
   expose any ports externally on the container; you'll note when we started the
   `db` container we did not use either the `-P` or `-p` flags. That's a big benefit of
   linking: we don't need to expose the source container, here the PostgreSQL database, to
   the network.

コンテナのリンク機能は実際には何をしているでしょう?
リンクを使うと、情報発信元となるコンテナそのものの情報を、受信先コンテナに提供できるということを、すでに学びました。
上の例においては情報を受け取るコンテナが ``web`` であり、情報元となる ``db`` の情報にアクセスできるというものです。
Docker はこのとき、コンテナ間にセキュアなトンネルを作り出します。
そこではコンテナから外部に向けてポートを公開する必要がないようにしています。
そもそも ``db`` コンテナを起動する際には、``-P`` フラグも ``-p`` フラグも使っていませんでした。
これこそがリンクシステムの優れたところです。
情報元となるコンテナ、つまり上の例では PostgreSQL データベースを、ネットワーク上に公開していなくても構わないということです。

.. Docker exposes connectivity information for the source container to the
   recipient container in two ways:

情報元のコンテナから受信先のコンテナに公開される接続情報は、以下の 2 つの手段を通じて受け渡されます。

.. * Environment variables,
   * Updating the `/etc/hosts` file.

* 環境変数
* ``/etc/hosts`` ファイルの更新

.. ### Environment variables

.. _environment-variables:

環境変数
----------

.. Docker creates several environment variables when you link containers. Docker
   automatically creates environment variables in the target container based on
   the `--link` parameters. It will also expose all environment variables
   originating from Docker from the source container. These include variables from:

コンテナをリンクすると、環境変数が数種類作り出されます。
Docker は ``--link`` パラメータに基づいて、対象とするコンテナ上に自動的に環境変数を作り出すものです。
また発信元コンテナからは、Docker がもともと提供している環境変数もすべて公開されています。
そういった環境変数は以下に基づくものです。

.. * the `ENV` commands in the source container's Dockerfile
   * the `-e`, `--env`, and `--env-file` options on the `docker run`
   command when the source container is started

* 情報元のコンテナにおける Dockerfile に記述された ``ENV`` コマンド
* 情報元のコンテナを ``docker run`` によって起動する際の、``-e``, ``--env``, ``--env-file`` オプション

.. These environment variables enable programmatic discovery from within the
   target container of information related to the source container.

このような環境変数があることによって、発信元コンテナに関する情報を、目的としているコンテナ内部においてプログラムレベルで検出できるようになります。

.. > **Warning**:
   > It is important to understand that *all* environment variables originating
   > from Docker within a container are made available to *any* container
   > that links to it. This could have serious security implications if sensitive
   > data is stored in them.
   {:.warning}
.. warning::

   コンテナ内の環境変数のうち Docker がもともと提供している環境変数はすべて、リンクしているどのコンテナからも利用可能である点を、十分に留意しておいてください。
   その環境変数の中に重要な機密情報が含まれていたら、重大なセキュリティ問題にもなります。

.. Docker sets an `<alias>_NAME` environment variable for each target container
   listed in the `--link` parameter. For example, if a new container called
   `web` is linked to a database container called `db` via `--link db:webdb`,
   then Docker creates a `WEBDB_NAME=/web/webdb` variable in the `web` container.

``--link`` パラメータに指定されたコンテナに対しては、``<alias>_NAME`` という名前の環境変数が定義されます。
たとえば ``web`` という名前の新たなコンテナが、``--link db:webdb`` という指定を通じてデータベースコンテナ ``db`` にリンクしているとします。
このとき ``web`` コンテナ内には ``WEBDB_NAME=/web/webdb`` という環境変数が生成されます。

.. Docker also defines a set of environment variables for each port exposed by the
   source container. Each variable has a unique prefix in the form:

さらに情報発信元となるコンテナが公開しているポートに対しても、環境変数が定義されます。
各変数には一意なプリフィックスがつけられます。

``<name>_PORT_<port>_<protocol>``

.. The components in this prefix are:

プリフィックスは以下のものから構成されます。

.. * the alias `<name>` specified in the `--link` parameter (for example, `webdb`)
   * the `<port>` number exposed
   * a `<protocol>` which is either TCP or UDP

* ``<name>``: ``--link`` パラメータによって指定されたエイリアス名。
  (たとえば ``webdb``)
* ``<port>``: 公開されているポート番号。
* ``<protocol>``: TCP、 UDP いずれかのプロトコル。

.. Docker uses this prefix format to define three distinct environment variables:

このプリフィックスの書式から、以下の 3 つの環境変数が定義されます。

.. * The `prefix_ADDR` variable contains the IP Address from the URL, for
   example `WEBDB_PORT_5432_TCP_ADDR=172.17.0.82`.
   * The `prefix_PORT` variable contains just the port number from the URL for
   example `WEBDB_PORT_5432_TCP_PORT=5432`.
   * The `prefix_PROTO` variable contains just the protocol from the URL for
   example `WEBDB_PORT_5432_TCP_PROTO=tcp`.

* ``prefix_ADDR`` 変数: URL に対する IP アドレス。
  たとえば ``WEBDB_PORT_5432_TCP_ADDR=172.17.0.82`` など。
* ``prefix_PORT`` 変数: URL に対するポート番号。
  たとえば ``WEBDB_PORT_5432_TCP_PORT=5432`` など。
* ``prefix_PROTO`` 変数: URL に対するプロトコル。
  たとえば ``WEBDB_PORT_5432_TCP_PROTO=tcp`` など。

.. If the container exposes multiple ports, an environment variable set is
   defined for each one. This means, for example, if a container exposes 4 ports
   that Docker creates 12 environment variables, 3 for each port.

コンテナが複数ポートを公開している場合は、個々のポートに対して環境変数が定義されます。
これはたとえば、コンテナが 4 つのポートを公開していたとすると、1 つのポートに対して 3 つの環境変数、つまり全部で 12 個の環境変数が定義されることになります。

.. Additionally, Docker creates an environment variable called `<alias>_PORT`.
   This variable contains the URL of the source container's first exposed port.
   The 'first' port is defined as the exposed port with the lowest number.
   For example, consider the `WEBDB_PORT=tcp://172.17.0.82:5432` variable. If
   that port is used for both tcp and udp, then the tcp one is specified.

さらに ``<alias>_PORT`` という環境変数も生成されます。
この変数には、発信元コンテナの一番初めの公開ポートを用いた URL が定義されます。
この「一番初めの」というのは、公開ポート番号の中で最も小さなものを指します。
たとえば ``WEBDB_PORT=tcp://172.17.0.82:5432`` という変数があったとして、このポートが tcp、udp の双方で利用されている場合、tcp が設定されます。

.. Finally, Docker also exposes each Docker originated environment variable
   from the source container as an environment variable in the target. For each
   variable Docker creates an `<alias>_ENV_<name>` variable in the target
   container. The variable's value is set to the value Docker used when it
   started the source container.

最後に、発信元コンテナにおいて Docker が元から定義している環境変数が、対象とするコンテナ上の環境変数として公開されます。
各変数に対しては、対象コンテナ上に ``<alias>_ENV_<name>`` という変数が生成されます。
この変数の値は、発信元コンテナが起動する際に、Docker が利用した値が設定されます。

.. Returning back to our database example, you can run the `env`
   command to list the specified container's environment variables.

データベースの例に戻ります。
``env`` コマンドを実行して、指定するコンテナ上の環境変数を一覧表示してみます。

.. ```
       $ docker run --rm --name web2 --link db:db training/webapp env

       . . .
       DB_NAME=/web2/db
       DB_PORT=tcp://172.17.0.5:5432
       DB_PORT_5432_TCP=tcp://172.17.0.5:5432
       DB_PORT_5432_TCP_PROTO=tcp
       DB_PORT_5432_TCP_PORT=5432
       DB_PORT_5432_TCP_ADDR=172.17.0.5
       . . .
   ```
.. code-block:: bash

   $ docker run --rm --name web2 --link db:db training/webapp env

   . . .
   DB_NAME=/web2/db
   DB_PORT=tcp://172.17.0.5:5432
   DB_PORT_5432_TCP=tcp://172.17.0.5:5432
   DB_PORT_5432_TCP_PROTO=tcp
   DB_PORT_5432_TCP_PORT=5432
   DB_PORT_5432_TCP_ADDR=172.17.0.5
   . . .

.. You can see that Docker has created a series of environment variables with
   useful information about the source `db` container. Each variable is prefixed
   with
   `DB_`, which is populated from the `alias` you specified above. If the `alias`
   were `db1`, the variables would be prefixed with `DB1_`. You can use these
   environment variables to configure your applications to connect to the database
   on the `db` container. The connection will be secure and private; only the
   linked `web` container will be able to talk to the `db` container.

この出力から、情報元である ``db`` コンテナに関して必要となる情報が、環境変数としていくつも生成されているのがわかります。
各環境変数には ``DB_`` というプリフィックスがつけられていて、これは上で指定した ``alias`` から命名されたものです。
``alias`` を ``db1`` としていたら、環境変数のプリフィックスは ``DB1_`` になっていたはずです。
この環境変数を使えば、``db`` コンテナ上にあるデータベースに、アプリケーションから接続する設定を行うことができます。
その際の接続はセキュアでありプライベートなものです。
そしてリンクしている ``web`` コンテナだけが、``db`` コンテナとの通信を行うことができます。

.. ### Important notes on Docker environment variables

.. _important-notes-on-docker-environment-variables:

Docker 環境変数に関する重要事項
----------------------------------------

.. Unlike host entries in the [`/etc/hosts` file](#updating-the-etchosts-file),
   IP addresses stored in the environment variables are not automatically updated
   if the source container is restarted. We recommend using the host entries in
   `/etc/hosts` to resolve the IP address of linked containers.

``/etc/hosts`` :ref:`ファイル <updating-the-etchosts-file>` におけるホストの設定とは違って、環境変数内に保存された IP アドレスは、発信元のコンテナが再起動されたときに自動的に更新されません。
リンクされたコンテナの IP アドレスを取得するためには、``/etc/hosts`` に設定することをお勧めします。

.. These environment variables are only set for the first process in the
   container. Some daemons, such as `sshd`, will scrub them when spawning shells
   for connection.

こういった環境変数の設定は、そのコンテナの初期処理段階でのみ行われます。
デーモンの中には ``sshd`` などのように、接続を実現するために起動するシェルにおいて、そのような変数を破棄するものもあります。

.. ### Updating the `/etc/hosts` file

.. _updating-the-etchosts-file:

``/etc/hosts`` ファイルの更新
------------------------------

.. In addition to the environment variables, Docker adds a host entry for the
   source container to the `/etc/hosts` file. Here's an entry for the `web`
   container:

環境変数とは別に Docker は、発信元コンテナを示すホスト設定を ``/etc/hosts`` ファイルに加えます。
以下は ``web`` コンテナに対するホスト設定の例です。

..  $ docker run -t -i --rm --link db:webdb training/webapp /bin/bash

    root@aed84ee21bde:/opt/webapp# cat /etc/hosts

    172.17.0.7  aed84ee21bde
    . . .
    172.17.0.5  webdb 6e5cdeb2d300 db
.. code-block:: bash

   $ docker run -t -i --rm --link db:webdb training/webapp /bin/bash

   root@aed84ee21bde:/opt/webapp# cat /etc/hosts

   172.17.0.7  aed84ee21bde
   . . .
   172.17.0.5  webdb 6e5cdeb2d300 db

.. You can see two relevant host entries. The first is an entry for the `web`
   container that uses the Container ID as a host name. The second entry uses the
   link alias to reference the IP address of the `db` container. In addition to
   the alias you provide, the linked container's name--if unique from the alias
   provided to the `--link` parameter--and the linked container's hostname will
   also be added in `/etc/hosts` for the linked container's IP address. You can ping
   that host now via any of these entries:

上においては、関連する 2 つの設定を見ることができます。
1 つめは ``web`` コンテナに対する設定であり、ホスト名としてコンテナ ID が用いられています。
2 つめの設定では、``db`` コンテナの IP アドレスを参照する、リンク機能のエイリアスを用いています。
エイリアス名の他に、リンクされたコンテナ名も追加されています。
そして ``--link`` パラメータによって指定されたエイリアスとホスト名が異なっていれば、このホスト名も、``/etc/hosts`` 内のリンクされたコンテナの IP アドレスに対して追加されます。
設定項目の要素のどれを使っても ping を実行することができます。

..  root@aed84ee21bde:/opt/webapp# apt-get install -yqq inetutils-ping

    root@aed84ee21bde:/opt/webapp# ping webdb

    PING webdb (172.17.0.5): 48 data bytes
    56 bytes from 172.17.0.5: icmp_seq=0 ttl=64 time=0.267 ms
    56 bytes from 172.17.0.5: icmp_seq=1 ttl=64 time=0.250 ms
    56 bytes from 172.17.0.5: icmp_seq=2 ttl=64 time=0.256 ms
.. code-block:: bash

   root@aed84ee21bde:/opt/webapp# apt-get install -yqq inetutils-ping

   root@aed84ee21bde:/opt/webapp# ping webdb

   PING webdb (172.17.0.5): 48 data bytes
   56 bytes from 172.17.0.5: icmp_seq=0 ttl=64 time=0.267 ms
   56 bytes from 172.17.0.5: icmp_seq=1 ttl=64 time=0.250 ms
   56 bytes from 172.17.0.5: icmp_seq=2 ttl=64 time=0.256 ms

.. > **Note**:
   > In the example, you'll note you had to install `ping` because it was not included
   > in the container initially.
.. note::

   ここに示す例においては ``ping`` をインストールしています。
   このコンテナの初期状態ではインストールされていないためです。

.. Here, you used the `ping` command to ping the `db` container using its host entry,
   which resolves to `172.17.0.5`. You can use this host entry to configure an application
   to make use of your `db` container.

上では ``db`` コンテナに対しての ``ping`` コマンド実行において、``/etc/hosts`` の設定項目を利用しました。
そしてそれは ``172.17.0.5`` であることがわかりました。
このように ``/etc/hosts`` の設定項目を用いてアプリケーションを設定すれば、``db`` コンテナを利用することができます。

.. > **Note**:
   > You can link multiple recipient containers to a single source. For
   > example, you could have multiple (differently named) web containers attached to your
   >`db` container.
.. note::

   情報発信元となる 1 つのコンテナに対して、受信先となるコンテナを複数リンクすることができます。
   たとえば複数の(名前の異なる)ウェブ・コンテナを ``db`` コンテナにリンクすることもできます。

.. If you restart the source container, the linked containers `/etc/hosts` files
   will be automatically updated with the source container's new IP address,
   allowing linked communication to continue.

情報発信元となるコンテナを再起動すると、リンクされたコンテナ内の ``/etc/hosts`` ファイルは自動的に更新されて、発信元コンテナの新たな IP アドレスが設定されます。
こうしてリンクされた通信状態が維持されます。

..  $ docker restart db

    db

    $ docker run -t -i --rm --link db:db training/webapp /bin/bash

    root@aed84ee21bde:/opt/webapp# cat /etc/hosts

    172.17.0.7  aed84ee21bde
    . . .
    172.17.0.9  db
.. code-block:: bash

   $ docker restart db

   db

   $ docker run -t -i --rm --link db:db training/webapp /bin/bash

   root@aed84ee21bde:/opt/webapp# cat /etc/hosts

   172.17.0.7  aed84ee21bde
   . . .
   172.17.0.9  db

.. Related information

.. seealso::

   Legacy container links
      https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/


text:
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///                                                                                ///
///     MIT License                                                                                ///
///                                                                                ///
///     Copyright (c) 2016 Raphaël Ernaelsten (@RaphErnaelsten)                                                                                ///
///                                                                                ///
///     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,                  ///
///     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.                                                                                ///
///                                                                                ///
///     PLEASE CONSIDER CREDITING AURA IN YOUR PROJECTS. IF RELEVANT, USE THE UNMODIFIED LOGO PROVIDED IN THE "LICENSE" FOLDER.                                 ///
///                                                                                ///
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

using UnityEngine;

namespace AuraAPI
{
    /// <summary>
    /// Collection of settings defining the computation of the volumetric data
    /// </summary>
    public struct FrustumSettingsParameters
    {
        #region Public Members
        /// <summary>
        /// Enables the computation of volumes
        /// </summary>
        public bool enableVolumes;
        /// <summary>
        /// Enables the computation of volumes' texture mask
        /// </summary>
        public bool enableVolumesTextureMask;
        /// <summary>
        /// Enables the computation of volumes' noise mask
        /// </summary>
        public bool enableVolumesNoiseMask;
        /// <summary>
        /// Enables the computation of directional lights
        /// </summary>
        public bool enableDirectionalLights;
        /// <summary>
        /// Enables the computation of directional lights' shadow
        /// </summary>
        public bool enableDirectionalLightsShadows;
        /// <summary>
        /// Enables the computation of spot lights
        /// </summary>
        public bool enableSpotLights;
        /// <summary>
        /// Enables the computation of spot lights' shadow
        /// </summary>
        public bool enableSpotLightsShadows;
        /// <summary>
        /// Enables the computation of point lights
        /// </summary>
        public bool enablePointLights;
        /// <summary>
        /// Enables the computation of point lights' shadow
        /// </summary>
        public bool enablePointLightsShadows;
        /// <summary>
        /// Enables the computation of lights' cookie
        /// </summary>
        public bool enableLightsCookies;
        /// <summary>
        /// Enables depth occlusion culling
        /// </summary>
        public bool enableOcclusionCulling;
        /// <summary>
        /// The accuracy of the occlusion search
        /// </summary>
        public OcclusionCullingAccuracyEnum occlusionCullingAccuracy;
        /// <summary>
        /// Enables temporal reprojection
        /// </summary>
        public bool enableTemporalReprojection;
        /// <summary>
        /// Amount of reprojection with the previous frame
        /// </summary>
        [Range(0, 1)]
        public float temporalReprojectionFactor;
        /// <summary>
        /// The resolution of the frustum grid
        /// </summary>
        public Vector3Int resolution;
        /// <summary>
        /// The maximum distance where the volumetric data will be computed
        /// </summary>
        public float farClipPlaneDistance;
        #endregion

        #region Functions
        /// <summary>
        /// Initializes the struct to default values
        /// </summary>
        public void Init()
        {
            enableVolumes = true;
            enableVolumesTextureMask = true;
            enableVolumesNoiseMask = true;
            enableDirectionalLights = true;
            enableDirectionalLightsShadows = true;
            enableSpotLights = true;
            enableSpotLightsShadows = true;
            enablePointLights = true;
            enablePointLightsShadows = true;
            enableLightsCookies = true;
            enableOcclusionCulling = true;
            enableTemporalReprojection = true;
            temporalReprojectionFactor = 0.9f;
            resolution = new Vector3Int(160, 90, 128);
            farClipPlaneDistance = 25.0f;
        }
        #endregion
    }
}