text:
package co.cask.coopr.test.client.rest;

import co.cask.common.http.exception.HttpFailureException;
import co.cask.coopr.Entities;
import co.cask.coopr.client.PluginClient;
import co.cask.coopr.provisioner.plugin.ResourceMeta;
import co.cask.coopr.provisioner.plugin.ResourceStatus;
import co.cask.coopr.spec.plugin.AutomatorType;
import co.cask.coopr.spec.plugin.ProviderType;
import co.cask.coopr.test.client.ClientTest;
import co.cask.coopr.test.client.ClientTestEntities;
import com.google.common.collect.Sets;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PluginRestClientTest extends ClientTest {

  private static final String AUTOMATOR_TYPE_CHEF_NAME = "chef-solo";
  private static final String PROVIDER_TYPE_JOYENT_NAME = "joyent";

  private PluginClient pluginClient;

  @Before
  public void setUpt() throws Exception {
    pluginClient = superadminCientManager.getPluginClient();
  }

  @Test
  public void testGetAllAutomatorTypes() throws IOException {
    List<AutomatorType> result = pluginClient.getAllAutomatorTypes();
    Assert.assertEquals(3, result.size());
    Assert.assertTrue(result.contains(Entities.AutomatorTypeExample.CHEF));
    Assert.assertTrue(result.contains(Entities.AutomatorTypeExample.PUPPET));
    Assert.assertTrue(result.contains(Entities.AutomatorTypeExample.SHELL));
  }

  @Test
  public void testGetAutomatorTypes() throws IOException {
    AutomatorType result = pluginClient.getAutomatorType(AUTOMATOR_TYPE_CHEF_NAME);
    Assert.assertEquals(Entities.AutomatorTypeExample.CHEF, result);
  }

  @Test
  public void testGetAutomatorTypesNotExist() throws IOException {
    try {
      pluginClient.getAutomatorType("test");
      Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
      Assert.assertEquals(HttpStatus.SC_NOT_FOUND, e.getStatusCode());
    }
  }

  @Test
  public void testGetAutomatorTypeResources() throws IOException {
    Map<String, Set<ResourceMeta>> result =
      pluginClient.getAutomatorTypeResources(AUTOMATOR_TYPE_CHEF_NAME,
                                             ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                             ResourceStatus.ACTIVE);
    Assert.assertEquals(2, result.size());
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.HADOOP_RESOURCE_META_V1,
                                        ClientTestEntities.HADOOP_RESOURCE_META_V2), result.get("hadoop"));
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.KAFKA_RESOURCE_META), result.get("kafka"));
  }

  @Test
  public void testStageAutomatorTypeResource() throws IOException {
    pluginClient.stageAutomatorTypeResource(AUTOMATOR_TYPE_CHEF_NAME,
                                            ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                            ClientTestEntities.HADOOP_RESOURCE_META_V2.getName(),
                                            String.valueOf(ClientTestEntities.HADOOP_RESOURCE_META_V2.getVersion()));
  }

  @Test
  public void testStageAutomatorTypeResourceUnknownVersion() throws IOException {
    try {
      pluginClient.stageAutomatorTypeResource(AUTOMATOR_TYPE_CHEF_NAME,
                                              ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                              ClientTestEntities.KAFKA_RESOURCE_META.getName(), String.valueOf(5));
      Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
      Assert.assertEquals(HttpStatus.SC_NOT_FOUND, e.getStatusCode());
    }
  }

  @Test
  public void testRecallAutomatorTypeResource() throws IOException {
    pluginClient.recallAutomatorTypeResource(AUTOMATOR_TYPE_CHEF_NAME,
                                             ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                             ClientTestEntities.HADOOP_RESOURCE_META_V1.getName(),
                                             String.valueOf(ClientTestEntities.HADOOP_RESOURCE_META_V1.getVersion()));
  }

  @Test
  public void testRecallAutomatorTypeResourceUnknownResource() throws IOException {
    try {
      pluginClient.recallAutomatorTypeResource(AUTOMATOR_TYPE_CHEF_NAME,
                                               ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(), "test",
                                               String.valueOf(1));
      Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
      Assert.assertEquals(HttpStatus.SC_NOT_FOUND, e.getStatusCode());
    }
  }

  @Test
  public void testDeleteAutomatorTypeResource() throws IOException {
    Map<String, Set<ResourceMeta>> result
      = pluginClient.getAutomatorTypeResources(AUTOMATOR_TYPE_CHEF_NAME,
                                               ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                               ResourceStatus.INACTIVE);
    Assert.assertEquals(1, result.size());
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.MYSQL_RESOURCE_META), result.get("mysql"));

    pluginClient.deleteAutomatorTypeResourceVersion(AUTOMATOR_TYPE_CHEF_NAME,
                                                    ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                                    ClientTestEntities.MYSQL_RESOURCE_META.getName(),
                                                    String.valueOf(ClientTestEntities.MYSQL_RESOURCE_META
                                                                     .getVersion()));

    result = pluginClient.getAutomatorTypeResources(AUTOMATOR_TYPE_CHEF_NAME,
                                                    ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                                    ResourceStatus.INACTIVE);
    Assert.assertEquals(0, result.size());
  }

  @Test
  public void testDeleteAutomatorTypeResourceActive() throws IOException {
    Map<String, Set<ResourceMeta>> result
      = pluginClient.getAutomatorTypeResources(AUTOMATOR_TYPE_CHEF_NAME,
                                               ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                               ResourceStatus.ACTIVE);
    Assert.assertEquals(2, result.size());
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.HADOOP_RESOURCE_META_V1,
                                        ClientTestEntities.HADOOP_RESOURCE_META_V2), result.get("hadoop"));
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.KAFKA_RESOURCE_META), result.get("kafka"));

    try {
      pluginClient.deleteAutomatorTypeResourceVersion(AUTOMATOR_TYPE_CHEF_NAME,
                                                      ClientTestEntities.COOKBOOKS_RESOURCE_TYPE.getTypeName(),
                                                      ClientTestEntities.HADOOP_RESOURCE_META_V1.getName(),
                                                      String.valueOf(ClientTestEntities.HADOOP_RESOURCE_META_V1
                                                                       .getVersion()));
      Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
      Assert.assertEquals(HttpStatus.SC_CONFLICT, e.getStatusCode());
    }
  }

  @Test
  public void testGetAllProviderTypes() throws IOException {
    List<ProviderType> result = pluginClient.getAllProviderTypes();
    Assert.assertEquals(2, result.size());
    Assert.assertTrue(result.contains(Entities.ProviderTypeExample.JOYENT));
    Assert.assertTrue(result.contains(Entities.ProviderTypeExample.RACKSPACE));
  }

  @Test
  public void testGetProviderTypes() throws IOException {
    ProviderType result = pluginClient.getProviderType(PROVIDER_TYPE_JOYENT_NAME);
    Assert.assertEquals(Entities.ProviderTypeExample.JOYENT, result);
  }

  @Test
  public void testGetProviderTypesNotExist() throws IOException {
    try {
      pluginClient.getProviderType("test");
      Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
      Assert.assertEquals(HttpStatus.SC_NOT_FOUND, e.getStatusCode());
    }
  }

  @Test
  public void testProviderTypeResources() throws IOException {
    Map<String, Set<ResourceMeta>> result = pluginClient.getProviderTypeResources(PROVIDER_TYPE_JOYENT_NAME,
                                                ClientTestEntities.KEYS_RESOURCE_TYPE.getTypeName(),
                                                ResourceStatus.ACTIVE);
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.DEV_KEY_RESOURCE_META_V1,
                                        ClientTestEntities.DEV_KEY_RESOURCE_META_V2), result.get("dev"));
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.RESEARCH_KEY_RESOURCE_META), result.get("research"));
  }

  @Test
  public void testGetProviderTypeResourcesUnknownResource() throws IOException {
    try {
      pluginClient.getProviderTypeResources(PROVIDER_TYPE_JOYENT_NAME,
                                                  "test", ResourceStatus.ACTIVE);
      Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
      Assert.assertEquals(HttpStatus.SC_NOT_FOUND, e.getStatusCode());
    }
  }

  @Test
  public void stageProviderTypeResourceSuccessTest() throws IOException {
    pluginClient.stageProviderTypeResource(PROVIDER_TYPE_JOYENT_NAME,
                                           ClientTestEntities.KEYS_RESOURCE_TYPE.getTypeName(),
                                           ClientTestEntities.DEV_KEY_RESOURCE_META_V1.getName(),
                                           String.valueOf(ClientTestEntities.DEV_KEY_RESOURCE_META_V1.getVersion()));
  }

  @Test
  public void recallProviderTypeResourceSuccessTest() throws IOException {
    pluginClient.recallProviderTypeResource(PROVIDER_TYPE_JOYENT_NAME,
                                            ClientTestEntities.KEYS_RESOURCE_TYPE.getTypeName(),
                                            ClientTestEntities.RESEARCH_KEY_RESOURCE_META.getName(),
                                            String.valueOf(ClientTestEntities.RESEARCH_KEY_RESOURCE_META.getVersion()));
  }

  @Test
  public void deleteProviderTypeResourceSuccessTest() throws IOException {
    Map<String, Set<ResourceMeta>> result
      = pluginClient.getProviderTypeResources(PROVIDER_TYPE_JOYENT_NAME,
                                               ClientTestEntities.KEYS_RESOURCE_TYPE.getTypeName(),
                                               ResourceStatus.INACTIVE);
    Assert.assertEquals(1, result.size());
    Assert.assertEquals(Sets.newHashSet(ClientTestEntities.VIEW_KEY_RESOURCE_META), result.get("view"));

    pluginClient.deleteProviderTypeResourceVersion(PROVIDER_TYPE_JOYENT_NAME,
                                                    ClientTestEntities.KEYS_RESOURCE_TYPE.getTypeName(),
                                                    ClientTestEntities.VIEW_KEY_RESOURCE_META.getName(),
                                                    String.valueOf(ClientTestEntities.VIEW_KEY_RESOURCE_META
                                                                     .getVersion()));

    result = pluginClient.getProviderTypeResources(PROVIDER_TYPE_JOYENT_NAME,
                                                    ClientTestEntities.KEYS_RESOURCE_TYPE.getTypeName(),
                                                    ResourceStatus.INACTIVE);
    Assert.assertEquals(0, result.size());
  }
}


text:
using System;
using System.Collections.Generic;
using System.Web.Http;
using NewsMonitor.API.ConsoleHost.Models.ArticleModel;
using NewsMonitor.API.ConsoleHost.Models.ArticleModel.ArticleSearchResult;

namespace NewsMonitor.API.ConsoleHost.Controllers
{
    [RoutePrefix("articles")]
    public class ArticlesController : ApiController
    {
        private readonly List<ArticleModel> _articles = new List<ArticleModel>
        {
            new ArticleModel
            {
                Id = 0,
                Date = new DateTime(2010, 11, 10),
                Title = "Some title 0",
                Keyword = "keyword 0",
                Text = "Some text"
            },
            new ArticleModel
            {
                Id = 1,
                Date = new DateTime(2011, 6, 21),
                Title = "Title 1",
                Keyword = "keyword 1",
                Text = "Another text"
            }
        };

        [HttpGet]
        [Route("{id:int}")]
        public ArticleModel GetArticle(int id)
        {
            return _articles[id];
        }

        [HttpGet]
        [Route("search")]
        public ArticleSearchResult FindArticle(int? year, int? month, int? day,
            string title, string keyword)
        {
            var result = new ArticleSearchResult
            {
                TotalCount = 1
            };
            return result;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package isolate

import (
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"sort"
	"strings"

	"chromium.googlesource.com/infra/swarming/client-go/internal/common"
)

import . "chromium.googlesource.com/infra/swarming/client-go/internal/types"

type ConfigValueOfKey struct {
	Value   string
	IsBound bool
}

func (c *ConfigValueOfKey) Set(value string) {
	c.Value = value
	c.IsBound = true
}

type ConfigName []ConfigValueOfKey

func compareConfigNames(lhs, rhs ConfigName) int {
	// Bound value is less than unbound one.
	assert(len(lhs) == len(rhs))
	for k, l := range lhs {
		r := rhs[k]
		if l.IsBound && r.IsBound {
			if l.Value < r.Value {
				return -1
			} else if l.Value > r.Value {
				return 1
			}
		} else if l.IsBound {
			return -1
		} else if r.IsBound {
			return 1
		}
	}
	return 0
}

func (c *ConfigName) Equals(o ConfigName) bool {
	return reflect.DeepEqual(c, o)
}

type ConfigPair struct {
	Key   ConfigName
	Value ConfigSettings
}

type ConfigPairs []ConfigPair

func (c ConfigPairs) Len() int {
	return len(c)
}

func (c ConfigPairs) Less(i, j int) bool {
	// Compare only bounded values of .key
	lhs, rhs := c[i].Key, c[j].Key
	return compareConfigNames(lhs, rhs) < 0
}

func (c ConfigPairs) Swap(i, j int) {
	c[i], c[j] = c[j], c[i]
}

// Config Represents a processed .isolate file.
//
//  Stores the file in a processed way, split by configuration.
//
//  At this point, we don't know all the possibilities. So mount a partial view
//  that we have.
//
//  This class doesn't hold isolate_dir, since it is dependent on the final
//  configuration selected. It is implicitly dependent on which .isolate defines
//  the 'command' that will take effect.
type Configs struct {
	FileComment []byte
	// Contains names only; the order is same as in ByConfig.
	ConfigVariables []string
	// Since Go doesn't allow slices as map keys, this is stored a list of (config_key, config_value).
	// The config key are lists of values of vars in the same order as ConfigSettings.
	ByConfig []ConfigPair
	// TODO(tandrii): maybe re-invent the hashing wheel here fo faster lookups by key?
}

func (c *Configs) Init(fileComment []byte, configVariables []string) {
	c.FileComment = fileComment
	assert(sort.IsSorted(sort.StringSlice(c.ConfigVariables)))
	c.ConfigVariables = configVariables
	c.ByConfig = []ConfigPair{}
}

// GetConfig returns all configs that matches this config as a single ConfigSettings.
//
// Returns an empty ConfigSettings if none apply.
func (c *Configs) GetConfig(configName ConfigName) (ConfigSettings, error) {
	out := ConfigSettings{}
	// Order ByConfig according to compareConfigNames function.
	sort.Sort(ConfigPairs(c.ByConfig))
	for _, pair := range c.ByConfig {
		ok := true
		for i, confValueOfKey := range configName {
			if pair.Key[i].IsBound && pair.Key[i] != confValueOfKey {
				ok = false
				break
			}
		}
		if ok {
			var err error
			if out, err = out.Union(pair.Value); err != nil {
				return out, err
			}
		}
	}
	return out, nil
}

// GetExactConfig returns ConfigSettings for exactly given configName key.
// This func exists because ByConfig is not a map.
func (c *Configs) GetExactConfig(key ConfigName) (ConfigSettings, bool) {
	for _, kv := range c.ByConfig {
		if kv.Key.Equals(key) {
			return kv.Value, true
		}
	}
	return ConfigSettings{}, false
}

// SetConfig sets the ConfigSettings for this key.
//
// The key is a tuple of bounded or unbounded variables. The global variable
// is the key where all values are unbounded.
func (c *Configs) SetConfig(key ConfigName, value ConfigSettings) {
	assert(len(key) == len(c.ConfigVariables))
	_, exists := c.GetExactConfig(key)
	assert(!exists)
	c.ByConfig = append(c.ByConfig, ConfigPair{key, value})
}

// Union returns a new Configs instance, the union of variables from self and rhs.
//
// Uses lhs.file_comment if available, otherwise rhs.file_comment.
// It keeps config_variables sorted in the output.
func (lhs *Configs) Union(rhs Configs) (Configs, error) {
	// Merge the keys of config_variables for each Configs instances. All the new
	// variables will become unbounded. This requires realigning the keys.
	out := Configs{}
	if len(lhs.FileComment) == 0 {
		out.Init(rhs.FileComment, lhs.getConfigVarsUnion(rhs))
	} else {
		out.Init(lhs.FileComment, lhs.getConfigVarsUnion(rhs))
	}

	ByConfig := ConfigPairs(append(
		lhs.expandConfigVariables(out.ConfigVariables),
		rhs.expandConfigVariables(out.ConfigVariables)...))
	if len(ByConfig) == 0 {
		return out, nil
	}
	// Take union of ConfigSettings with the same ConfigName (key).
	sort.Sort(ByConfig)
	last := ByConfig[0]
	for _, curr := range ByConfig[1:] {
		if compareConfigNames(last.Key, curr.Key) == 0 {
			var err error
			if last.Value, err = last.Value.Union(curr.Value); err != nil {
				return out, err
			}
		} else {
			out.SetConfig(last.Key, last.Value)
			last = curr
		}
	}
	out.SetConfig(last.Key, last.Value)
	return out, nil
}

// getConfigVarsUnion returns a sorted set of union of ConfigVariables of two Configs.
func (lhs *Configs) getConfigVarsUnion(rhs Configs) []string {
	varSet := append([]string{}, lhs.ConfigVariables...)
	varSet = append(varSet, rhs.ConfigVariables...)
	if len(varSet) == 0 {
		return varSet
	}
	sort.Strings(varSet)
	unique := varSet[:1]
	last := unique[0]
	for _, cur := range varSet[1:] {
		if cur == last {
			continue
		}
		unique = append(unique, cur)
		last = cur
	}
	return unique
}

// expandConfigVariables returns new ByConfig value.
func (c *Configs) expandConfigVariables(newConfigVars []string) []ConfigPair {
	// Get mapping from old config vars list to new one.
	mapping := make([]int, len(newConfigVars))
	i := 0
	for n, nk := range newConfigVars {
		if i == len(c.ConfigVariables) || c.ConfigVariables[i] > nk {
			mapping[n] = -1
		} else if c.ConfigVariables[i] == nk {
			mapping[n] = i
			i++
		} else {
			// Must never happens because newConfigVars and c.configVariables are sorted ASC,
			// and newConfigVars contain c.configVariables as a subset.
			assert(c.ConfigVariables[i] >= nk)
		}
	}
	// Expands ConfigName to match newConfigVars.
	getNewConfigName := func(old ConfigName) ConfigName {
		var out ConfigName = make([]ConfigValueOfKey, len(mapping))
		for i, m := range mapping {
			if m != -1 {
				out[i] = old[m]
			}
		}
		return out
	}
	// Compute new ByConfig.
	out := make([]ConfigPair, len(c.ByConfig))
	for i, kv := range c.ByConfig {
		out[i] = ConfigPair{getNewConfigName(kv.Key), kv.Value}
	}
	return out
}

// ConfigSettings Represents the dependency variables for a single build configuration.
//
//  The structure is immutable.
//
//  .command and .isolate_dir describe how to run the command. .isolate_dir uses
//      the OS' native path separator. It must be an absolute path, it's the path
//      where to start the command from.
//  .files is the list of dependencies. The items use '/' as a path separator.
//  .read_only describe how to map the files.
type ConfigSettings struct {
	Files      []string
	Command    []string
	ReadOnly   int
	IsolateDir string
}

func (c *ConfigSettings) Init(values ParsedIsolate, isolateDir string) {
	if isolateDir == "" {
		// It must be an empty object if isolate_dir is not set.
		assert(values.IsEmpty(), values)
	} else {
		assert(filepath.IsAbs(isolateDir))
	}
	c.IsolateDir = isolateDir
	c.Files = values.Files
	sort.Strings(c.Files)
	c.Command = values.Command
	c.ReadOnly = values.ReadOnly
}

// Union merges two config settings together into a new instance.
//
// A new instance is not created and self or rhs is returned if the other
// object is the empty object.
//
// self has priority over rhs for .command. Use the same .isolate_dir as the
// one having a .command.
//
// Dependencies listed in rhs are patch adjusted ONLY if they don't start with
// a path variable, e.g. the characters '<('.
func (lhs *ConfigSettings) Union(rhs ConfigSettings) (ConfigSettings, error) {
	// When an object has .isolate_dir == "", it means it is the empty object.
	if lhs.IsolateDir == "" {
		return rhs, nil
	}
	if rhs.IsolateDir == "" {
		return *lhs, nil
	}

	if common.IsWin32() {
		assert(strings.ToLower(lhs.IsolateDir) == strings.ToLower(rhs.IsolateDir))
	}

	// Takes the difference between the two isolate_dir. Note that while
	// isolate_dir is in native path case, all other references are in posix.
	var useRhs bool
	var command []string
	if len(lhs.Command) > 0 {
		useRhs = false
		command = lhs.Command
	} else if len(rhs.Command) > 0 {
		useRhs = true
		command = rhs.Command
	} else {
		// If self doesn't define any file, use rhs.
		useRhs = len(lhs.Files) == 0
	}

	readOnly := rhs.ReadOnly
	if lhs.ReadOnly != -1 {
		readOnly = lhs.ReadOnly
	}

	lRelCwd, rRelCwd := lhs.IsolateDir, rhs.IsolateDir
	lFiles, rFiles := lhs.Files, rhs.Files
	if useRhs {
		// Rebase files in rhs.
		lRelCwd, rRelCwd = rhs.IsolateDir, lhs.IsolateDir
		lFiles, rFiles = rhs.Files, lhs.Files
	}

	var result ConfigSettings

	rebasePath, err := filepath.Rel(rRelCwd, lRelCwd)
	if err != nil {
		return result, err
	}
	rebasePath = strings.Replace(rebasePath, string(os.PathSeparator), "/", 0)

	files := make([]string, len(lFiles)+len(rFiles))
	copy(files, lFiles)
	for i, f := range rFiles {
		// Rebase item.
		if !(strings.HasPrefix(f, "<(") || rebasePath == ".") {
			f = common.PosixpathJoin(rebasePath, f)
		}
		files[i+len(lFiles)] = f
	}
	sort.Strings(files)
	result.Init(ParsedIsolate{command, files, readOnly}, lRelCwd)
	return result, nil
}

type UntypedIsolate struct {
	dict interface{}
}

func (p *UntypedIsolate) IsEmpty() bool {
	if p.dict == nil {
		return true
	}
	if m, ok := p.dict.(map[string]interface{}); ok {
		return len(m) == 0
	}
	return false
}

type ParsedIsolate struct {
	Command []string `json:"command"`
	Files   []string `json:"files"`
	// TODO(tandrii): read_only has 1 as default, according to specs.
	// Python-isolate also uses None as undefined, this code uses -1.
	// Golang's default is currently just 0.
	ReadOnly int `json:"read_only"`
}

func (p *ParsedIsolate) IsEmpty() bool {
	return len(p.Command) == 0 && len(p.Files) == 0
}

// LoadIsolateAsConfig parses one .isolate file and returns a Configs instance.
//
//  Arguments:
//    isolate_dir: only used to load relative includes so it doesn't depend on
//                 cwd.
//    value: is the loaded dictionary that was defined in the gyp file.
//    file_comment: comments found at the top of the file so it can be preserved.
//
//  The expected format is strict, anything diverting from the format below will result in error:
//  {
//    'includes': [
//      'foo.isolate',
//    ],
//    'conditions': [
//      ['OS=="vms" and foo=42', {
//        'variables': {
//          'command': [
//            ...
//          ],
//          'files': [
//            ...
//          ],
//          'read_only': 0,
//        },
//      }],
//      ...
//    ],
//    'variables': {
//      ...
//    },
//  }
func LoadIsolateAsConfig(isolateDir string, content []byte, fileComment []byte) (Configs, error) {
	var isolate Configs
	// TODO: can we parse this without Python?
	err := common.ExecPyHelperTyped(&isolate, "load_isolate_as_config", content, isolateDir)
	isolate.FileComment = fileComment
	return isolate, err
}

// LoadIsolateForConfig loads the .isolate file and returns the information unprocessed but
// filtered for the specific OS.
//
// Returns:
// tuple of command, dependencies, read_only flag, isolate_dir.
// The dependencies are fixed to use os.path.sep.
func LoadIsolateForConfig(isolateDir string, content []byte, configVariables KeyVars) (
	[]string, []string, int, string, error) {
	// Load the .isolate file, process its conditions, retrieve the command and dependencies.
	isolate, err := LoadIsolateAsConfig(isolateDir, content, nil)
	if err != nil {
		return nil, nil, -1, "", err
	}
	configName, err := computeConfigName(isolate, configVariables)
	if err != nil {
		return nil, nil, -1, "", err
	}
	// A configuration is to be created with all the combinations of free variables.
	config, err := isolate.GetConfig(configName)
	if err != nil {
		return nil, nil, -1, "", err
	}
	dependencies := make([]string, len(config.Files))
	for i, f := range config.Files {
		dependencies[i] = strings.Replace(f, "/", string(os.PathSeparator), -1)
	}
	return config.Command, dependencies, config.ReadOnly, config.IsolateDir, nil
}

func computeConfigName(isolate Configs, configVariables KeyVars) (ConfigName, error) {
	out := []ConfigValueOfKey{}
	missingVars := []string{}
	for _, variable := range isolate.ConfigVariables {
		if value, ok := configVariables[variable]; ok {
			out = append(out, ConfigValueOfKey{value, true})
		} else {
			missingVars = append(missingVars, variable)
		}
	}
	if len(missingVars) > 0 {
		sort.Strings(missingVars)
		return ConfigName{}, fmt.Errorf("These configuration variables were missing from the command line: %v",
			missingVars)
	}
	return ConfigName(out), nil
}


text:
/**
 * An object tracking all artefacts. Artefacts are registered by the id of
 * the item. To get an array, just use `Object.values(P.artefacts)` or call
 * `P.allArtefacts()`.
 *
 * @private
 * @type {Object}
 */
P.artefacts = {}

/**
 * @name Artefact
 * @class The main artefact class
 * @memberOf P
 */
P.Artefact = paper.Base.extend(/** @lends Artefact */{

	/**
	 * @private
	 * @type {String}
	 */
	_class: 'Artefact',

	/**
	 * Constructor
	 */
	initialize: function(item) {
		this.item = item;
		this.item.data._artefact = this;
		this.animation = undefined;
		this.shadow = undefined;
		this.selected = false;

		// Register artefact by id
		P.artefacts[item.id] = this
	},

	/**
	 * Show the bounding box of the current artefact
	 *
	 * @return {Artefact} This artefact
	 * @instance
	 */
	showBoundingBox: function() {
		if(!this.bbox) this.drawBoundingBox();
		this.bbox.visible = true;
		return this;
	},

	/**
	 * Hide the bounding box
	 *
	 * @return {Artefact} This artefact
	 * @instance
	 */
	hideBoundingBox: function() {
		if(this.bbox) this.bbox.visible = false;
		return this;
	},

	/**
	 * Completely remove the bounding box of this artefact
	 *
	 * @return {Artefact} This artefact
	 * @instance
	 */
	removeBoundingBox: function() {
		this.hideBoundingBox();
		if(this.bbox) this.bbox.remove();
		this.bbox = undefined;
		return this;
	},

	/**
	 * Draw the bounding box of the artefact.
	 *
	 * This function relies on the `_drawBoundingBox` in one of the inheriting
	 * classes {@link Artefact.Rectangle}, {@link Artefact.Circle} or {@link Artefact.Group},
	 * which actually generates the handles, border and shadow element.
	 *
	 * @return {Aftefact} This artefact
	 * @instance
	 */
	drawBoundingBox: function() {
		if(!this._drawBoundingBox) {
			console.log('ERROR!')
			return
		}

		// Clean up
		this.removeBoundingBox();

		var parts = this._drawBoundingBox();
		this.shadow = parts.shadow;
		this.shadow.fillColor = P.mainColor;
		this.shadow.opacity = 0.1;
		this.shadow.name = 'shadow'
		delete this.shadow.data._artefact

		var border = parts.border;
		border.name = 'border';
		border.strokeColor = P.mainColor;

		var children = [parts.border].concat(parts.handles).concat([this.shadow]);
		this.bbox = new paper.Group(children);
		this.bbox.parent = this.item.parent;
		this.bbox.pivot = this.shadow.bounds.center;

		// TODO: this.bbox.data._item?
		this.bbox.data._artefact = this;
		this.bbox.name = 'bbox';

		this.item.insertBelow(this.bbox);
	},

	/**
	 * Generate a handle object
	 *
	 * @private
	 * @param  {Point} position The position for the handle
	 * @return {Path}
	 */
	_getHandle: function(position) {
		var handle = new paper.Path.Circle({
			center: position,
			radius: 4,
			strokeColor: P.mainColor,
			fillColor: 'white'
		})

		handle.on('mouseenter', function() {
			this.fillColor = P.mainColor
		})

		handle.on('mouseleave', function() {
			this.fillColor = 'white'
		})

		handle.name = 'handle'

		return handle
	},

	/**
	 * @summary Test if this Artefact is selected
	 * @return {Boolean}
	 * @instance
	 */
	isSelected: function() {
		return this.selected == true;
	},

	/**
	 * Select the current artefact. If an artefact is selected, the bounding box and
	 * animation handles, if they exist, are shown.
	 *
	 * @return {Artefact}
	 * @instance
	 */
	select: function() {
		if(!this.isSelected()) {
			this.showBoundingBox();
			if(this.hasAnimation()) this.getAnimation().drawHandles();
			this.selected = true;
		}
		return this;
	},

	/**
	 * Deselect this artefact. Removes the bounding box and animation handles.
	 *
	 * @return {Artefact}
	 * @instance
	 */
	deselect: function() {
		this.hideBoundingBox();
		this.item.strokeColor = undefined;
		this.item.dashArray = undefined;
		if(this.hasAnimation())
			this.getAnimation().removeHandles();
		this.selected = false;
		return this;
	},

	/**
	 * Animate the artefact. This adds an {@link Animation} object of a certain type to the
	 * artefact.
	 *
	 * @param  {String} type       The type of animation, e.g. 'bounce' or 'rotate'.
	 * @param  {Object} properties Properties for this animation. The shape of this object
	 * differs across types of animations.
	 * @return {Animation}         The animation object
	 * @instance
	 */
	animate: function(type, properties) {
		this.removeAnimation()

		var anim = new P.Animation(this, type, properties);
		this.anim = anim;
		return this.anim;
	},

	/**
	 * Completely removes the animation from this artefact, if any exists.
	 * @return {undefined}
	 * @instance
	 */
	removeAnimation: function() {
		if(!this.hasAnimation()) return;
		this.getAnimation().remove()
		this.anim = undefined;
	},

	/**
	 * Get the animation object.
	 *
	 * @return {Animation} The animation object, an instance of {@link Animation}.
	 * @instance
	 */
	getAnimation: function() {
		return this.anim;
	},

	/**
	 * Test if this artefact has an animation.
	 *
	 * @param  {Boolean|String} [type=false] If `type` is specified, it also checks
	 * if the animation is of the given type
	 * @return {Boolean}
	 * @instance
	 */
	hasAnimation: function(type) {
		if(!this.getAnimation()) return false;
		if(type) return this.getAnimation().type == type;
		return true;
	},

	/**
	 * Test if this artefact is currently animating, that is, if the animation is active.
	 *
	 * @return {Boolean}
	 * @instance
	 */
	isAnimating: function() {
		return this.hasAnimation() ? this.getAnimation().isActive() : false;
	},

	/**
	 * Get the so called 'shadow bounds'. The *shadow* object is the heart of
	 * the bounding box and has the same shape as the Artefact. The shadow (and
	 * bounding box) stay in place when the artefact is animated. In this way,
	 * the shadow provides a way to find out the exact dimensions of an artefact
	 * if the animation would be removed, without ever having to stop the
	 * animation. The bounds of the shadow are thus of special importance.
	 *
	 * For groups, the shadow bounds are computed recursively, by combining the
	 * shadow bounds of children up to a certain depth.
	 *
	 * @param  {Number} [depth=1] How deep the recursion should go; only used
	 * when computing the bounds of a {@link Artefact.Group}.
	 * @return {paper.Rectangle} The bounds
	 * @instance
	 */
	getShadowBounds: function(depth=1) {
		return this.shadow ? this.shadow.bounds : false;
	},

	/**
	 * Transform this item. The transformation will also be applied to the
	 * bounding box and the animation (handles). In this way, the artefact always
	 * moves as a single unit.
	 *
	 * @param  {paper.Matrix} matrix The transformation Matrix
	 * @return {Artefact}
	 * @instance
	 */
	transform: function(matrix) {
		this.item.transform(matrix);
		if(this.bbox) this.bbox.transform(matrix);
		if(this.hasAnimation()) this.getAnimation().transform(matrix);
		return this;
	},

	/**
	 * Move the item by a specified distance. Internally, the {@link Artefact.transform}
	 * method is used.
	 *
	 * @param  {paper.Point} delta The distance by which the item should be moved.
	 * @return {Artefact}
	 * @instance
	 */
	move: function(delta) {
		var matrix = new paper.Matrix().translate(delta);
		this.transform(matrix);
		return this;
	},

	/**
	 * Destroy this artefact
	 *
	 * @return {}
	 * @instance
	 */
	destroy: function() {
		this.deselect();
		if(this.bbox) {
			this.bbox.remove();
			delete this.bbox;
		}

		this.removeAnimation();

		// Remove the item the very end!
		this.item.remove();
		delete P.artefacts[this.id];
	},

	/**
	 * Restore this artefact. After destroying the artefact, a reference to it
	 * might still exist. In that case, `restore` can be called to, yes, restore
	 * the artefact. This is typically used in undo/redo settings.
	 *
	 * @return {Artefact}
	 * @instance
	 */
	restore: function() {
		paper.project.activeLayer.addChild(this.item);
		if(this.hasAnimation()) this.getAnimation().start;
		P.artefacts[this.id] = this;
		return this;
	},

	/**
	 * Clone the artefact. This should result in a deep copy, with no references
	 * to the original artefact. Paper items, bounding boxes, animations, all
	 * should be copied.
	 *
	 * @param  {Boolean|Artefact} [copy=false] If a copy is given, the current item
	 * is not cloned, but the copy is further updated to mirror the current artefact.
	 * @return {Artefact} A clone of the original artefact.
	 * @instance
	 */
	clone: function(copy=false) {

		// Construct new copy
		var Class = this.className ? P.Artefact[this.className] : P.Artefact;
		var copy = copy || new Class(this.item.clone());

		// Clone bounding box
		copy.bbox = this.bbox.clone();
		copy.bbox.name = 'bbox';
		copy.bbox.data._artefact = copy;

		// Update names of children of bbox
		for(var i=0; i<copy.bbox.children.length; i++){
			var child = copy.bbox.children[i];
			if(child.name) child.name = child.name.replace(' 1', '')
		}
		copy.shadow = copy.bbox.children['shadow'];
		copy.shadow.getBounds()

		// Clone animation
		if(this.hasAnimation()) {
			var anim = this.getAnimation();
			var props = anim.cloneProperties();
			copy.animate(anim.type, props);
			copy.getAnimation().start();
		}

		// Select and return
		copy.selected = false;
		this.deselect();
		copy.select();

		return copy;
	},

	/**
	 * Test if this artefact is a {@link Artefact.Rectangle}
	 * @return {Boolean}
	 * @instance
	 */
	isRectangle: function() {
		return this instanceof P.Artefact.Rectangle;
	},

	/**
	 * Test if this artefact is a {@link Artefact.Circle}
	 * @return {Boolean} [description]
	 * @instance
	 */
	isCircle: function() {
		return this instanceof P.Artefact.Circle;
	},

	/**
	 * Manipulate the artefact using an {@link paper.ToolEvent}. The behaviour
	 * is different for different artefacts and overridden by inheriting classes.
	 *
	 * @param  {paper.ToolEvent} event
	 * @param  {paper.Item} handle The handle hit by the event
	 * @return {}
	 * @instance
	 */
	manipulate: function(event, handle) {},

	bringToFront: function() {
		this.item.bringToFront();
	},

	sendToBack: function() {
		this.item.sendToBack();
	}

})

/**
 * @name Rectangle
 * @class A rectangular Artefact. Yes, really just a rectangle.
 * @memberOf P.Artefact
 */
P.Artefact.Rectangle = P.Artefact.extend(/** @lends Artefact.Rectangle */{

	_class: 'Rectangle',

	/**
	 * Constructor
	 * @param  {paper.Item|args} args Either a rectangular paper.Item or arguments
	 * that can be passed to the paper.Path.Rectangle constructor.
	 * @return {}
	 */
	initialize: function(args) {
		var item;
		if(args instanceof paper.Item) {
			item = args;
		} else{
			item = new paper.Path.Rectangle(args);
		}
		P.Artefact.apply(this, [item]);
	},

	/**
	 * Draws the bounding box for a rectangular artefact.
	 * @private
	 */
	_drawBoundingBox: function() {
		var handles = [];
		var shadow = this.item.clone();

		// The border of the bounding box (expanded slightly)
		var border = new paper.Path.Rectangle(shadow.bounds.expand(12))

		// Name the segments
		var self = this;
		var names = ['bottomLeft', 'topLeft', 'topRight', 'bottomRight'];
		var handles = this.item.segments.map(function(segment){

			// Find the name of this segment
			var name = names.filter(function(name) {
				var position = shadow.bounds[name];
				return segment.point.equals(position);
			})[0];

			// Create the handle
			var position = border.bounds[name];
			var handle = self._getHandle(position);
			handle.name = 'handle:' + name;
			segment.name = name;

			return handle
		});

		return {
			shadow: shadow,
			handles: handles,
			border: border
		}
	},

	/**
	 * @private
	 * @param  {ToolEvent} event
	 * @param  {Item} handle [description]
	 */
	manipulate: function(event, handle) {
		if(this.isAnimating()) return false;

		var index, segments, adjacents, sameX, sameY, newWidth, newHeight, deltaX, deltaY;
		var itemIndex = this.item.index;
		// Get segment corresponding to the handle, and segments adjacent to that
		index = handle.parent.children.indexOf(handle) - 1;
		segment = this.item.segments[index];
		adjacents = this._getAdjacentSegments(segment);
		sameX = adjacents.sameX;
		sameY = adjacents.sameY;

		// Move segments
		// To do: this is still a bit buggy... You sometimes get crosses, or the
		// rectangle is essentially removed. Could the problem be in getAdjacentSegments ?
		newWidth  = Math.abs(segment.point.x - (sameY.point.x + event.delta.x));
		newHeight = Math.abs(segment.point.y - (sameX.point.y + event.delta.y));
		deltaX = (newWidth <= 3) ? 0 : event.delta.x;
		deltaY = (newHeight <= 3) ? 0 : event.delta.y;
		sameX.point   = sameX.point.add([deltaX, 0]);
		sameY.point   = sameY.point.add([0, deltaY]);
		segment.point = segment.point.add([deltaX, deltaY]);

		// Update bounding box
		this.drawBoundingBox();

		// Keep the item at the same 'vertical' position
		this.item.parent.insertChild(itemIndex, this.item);

		// Color selected handle
		// Todo: doesn't work when flipping a rectangle, but at least the code is
		// simple and readable again.
		var newHandle = this.bbox.children[handle.name];
		newHandle.fillColor = P.mainColor;
	},

	/**
	* Get the adjacent segments of a given segment on a rectangle
	* @private
	* @param  {Segment} segment
	* @return {Object} Object containing the segment with the same X
	* and the one with the same Y coordinate.
	*/
	_getAdjacentSegments: function(segment) {
		var adjacents = {
			'bottomRight': 	{ sameX: 'topRight', 		sameY: 'bottomLeft'},
			'bottomLeft': 	{ sameX: 'topLeft', 		sameY: 'bottomRight'},
			'topLeft': 			{ sameX: 'bottomLeft', 	sameY: 'topRight'},
			'topRight': 		{ sameX: 'bottomRight', sameY: 'topLeft'},
		}[segment.name];

		// Store all segments by name
		var segmentsByName = {}
		for(var i=0; i<segment.path.segments.length; i++) {
			var segm = segment.path.segments[i];
			segmentsByName[segm.name] = segm;
		}

		return {
			sameX: segmentsByName[adjacents.sameX],
			sameY: segmentsByName[adjacents.sameY],
		}
	}

});

/**
 * @name Circle
 * @class  A circular Artefact.
 * @memberOf P.Artefact
 */
P.Artefact.Circle = P.Artefact.extend(/** @lends Artefact.Circle */{
	_class: 'Circle',

	initialize: function(args) {
		var item;
		if(args instanceof paper.Item) {
			item = args;
		} else {
			item = new paper.Path.Circle(arguments[0], arguments[1] );
		}
		P.Artefact.apply(this, [item])
	},

	_drawBoundingBox: function() {
		var shadow = this.item.clone();
		var radius = (this.item.bounds.width + 12) / 2
		var center = this.item.position
		var border = new paper.Path.Circle(this.item.position, radius)
		var handle = this._getHandle([center.x + radius, center.y])
		return {
			shadow: shadow,
			handles: [handle],
			border: border
		};
	},

	manipulate: function(event, handle) {
		if(this.isAnimating()) return false;
		var item = this.item;
		var index = item.index;
		var center = item.position,
					radius = item.bounds.width,
					newRadius = event.point.subtract(center).length * 2 - 6,
					scaleFactor = newRadius/radius;
		item.scale(scaleFactor);
		this.drawBoundingBox();

		// Keep the item at the same 'vertical' position
		item.parent.insertChild(index, item);

		// Color the selected handle
		var newHandle = this.bbox.children[1];
		newHandle.fillColor = P.mainColor;
	}

})

/**
 * @name Group
 * @class The group Artefact is an artefact consisting of several others.
 * It is really just a group with some added niceties.
 * @memberOf P.Artefact
 */
P.Artefact.Group = P.Artefact.extend(/** @lends Artefact.Group */{
	_class: 'Group',

	initialize: function(artefacts) {

		var items = artefacts.map(function(a) { return a.item });
		var group = new paper.Group(items);
		P.Artefact.apply(this, [group]);

		this.children = artefacts;
		this.item.transformContent = false;
		var bounds = this.getShadowBounds(0);
		group.pivot = new paper.Point(bounds.center);

		// Select only the group!
		this.children.mmap('deselect');
	},

	/**
	 * Override the default clone method
	 *
	 * @private
	 * @return {Artefact.Group}
	 */
	clone: function clone() {
		this.deselect();
		var clonedChildren = this.children.mmap('clone').mmap('deselect')
		var	copy = new P.Artefact.Group(clonedChildren);
		clone.base.call(this, copy);
		copy.item.transform(this.item.matrix)
		return copy
	},

	/**
	 * Override the default getShadowBounds. Instead, compute the shadow bounds,
	 * by recursively combining the shadow bounds of children.
	 *
	 * @private
	 * @param  {Number} [depth=1] How deep the recursion should go
	 * @return {paper.Rectangle}
	 */
	getShadowBounds: function(depth) {
		var depth = depth || 1;
		// Get the shadow bounds only up to a certain depth
		if(this.shadow && depth == 0){
			return this.shadow.bounds
		}

		// For groups we combine all shadow bounds
		var bounds;
		for(var i=0; i<this.children.length;i++){
			var child = this.children[i];
			var childBounds = child.getShadowBounds(depth-1);
			bounds = bounds ? bounds.unite(childBounds) : childBounds;
		}
		return bounds
	},

	/**
	 * Draw bounding box around the group
	 * @private
	 */
	_drawBoundingBox: function() {
		// The item's shadow
		var bounds = this.getShadowBounds();
		var shadow = new paper.Path.Rectangle(bounds);
		shadow.transform(this.item.matrix)

		// The border of the bounding box (expanded slightly)
		var border = new paper.Path.Rectangle(shadow.bounds.expand(12))
		border.dashArray = [5,2];

		// Handles
		var self = this;
		var handles = border.segments.map(function(segment) {
			return self._getHandle(segment.point);
		})

		return {
			shadow: shadow,
			handles: handles,
			border: border
		}
	},

	/**
	 * Manipulate the group, that is, scale it.
	 *
	 * @private
	 * @param {paper.ToolEvent} event
	 * @param {paper.Item} handle
	 */
	manipulate: function(event, handle) {
		if(this.isAnimating()) return false;

		var index = this.item.index,
				bounds = this.item.bounds,
				center = this.item.position,
				width = bounds.width,
				height = bounds.height,
				diag = Math.sqrt(width*width + height*height),
				newDiag = event.point.subtract(center).length * 2 - 6,
				scaleFactor = newDiag/diag;

		this.item.scale(scaleFactor);

		// Update the selection box
		this.drawBoundingBox();

		// Keep the item at the same 'vertical' position
		this.item.parent.insertChild(index, this.item);

		// Color selected handle
		if(this.bbox.children[handle.name])
			this.bbox.children[handle.name].fillColor = P.mainColor;
	},

	/**
	 * Ungroup. Destroys the group and inserts the children Artefact at the
	 * same position in the layer.
	 *
	 * @return {Artefact[]} Artefacts
	 */
	ungroup: function() {
		// Reinstert parent items
		var childItems = this.children.map(function(child){ return child.item });
		var parent = this.item.parent ? this.item.parent : paper.project.activeLayer;
		parent.insertChildren(this.item.index, childItems);

		// Stop the animation, to get the actual transformation of the group
		if(this.hasAnimation()) this.animation.stop();
		var matrix = this.item.matrix;
		this.children.map(function(child) {

			// The children of groups are not transformed untill
			// we ungroup them!
			child.bbox.visible=true
			child.transform(matrix);

			// Reset the bounding box
			if(child.isAnimating()) {
				child.animation.stop();
				child.drawBoundingBox();
				child.animation.start();
			} else {
				child.drawBoundingBox();
			}

		});

		// Remove and reset
		this.destroy(false);
		return this.children;
	},

	/**
	 * Override the default destroy
	 * @param  {Boolean} [destroyChildren=true] Destroy the children as well?
	 * @return {}
	 */
	destroy: function destroy(destroyChildren=false) {
		if(destroyChildren) this.children.mmap('destroy');
		destroy.base.call(this);
	}
})


text:
<?php

/**
 * $Header: /home/ppcvs/paypal_php_sdk/Log/mcal.php,v 1.1 2006/02/19 08:22:29 dennis Exp $
 * $Horde: horde/lib/Log/mcal.php,v 1.2 2000/06/28 21:36:13 jon Exp $
 *
 * @version $Revision: 1.1 $
 * @package Log
 */

/**
 * The Log_mcal class is a concrete implementation of the Log::
 * abstract class which sends messages to a local or remote calendar
 * store accessed through MCAL.
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @since Horde 1.3
 * @since Log 1.0
 * @package Log
 */
class Log_mcal extends Log
{
    /**
     * holding the calendar specification to connect to.
     * @var string
     * @access private
     */
    var $_calendar = '{localhost/mstore}';

    /**
     * holding the username to use.
     * @var string
     * @access private
     */
    var $_username = '';

    /**
     * holding the password to use.
     * @var string
     * @access private
     */
    var $_password = '';

    /**
     * holding the options to pass to the calendar stream.
     * @var integer
     * @access private
     */
    var $_options = 0;

    /**
     * ResourceID of the MCAL stream.
     * @var string
     * @access private
     */
    var $_stream = '';

    /**
     * Integer holding the log facility to use.
     * @var string
     * @access private
     */
    var $_name = LOG_SYSLOG;

    /**
     * Constructs a new Log_mcal object.
     *
     * @param string $name     The category to use for our events.
     * @param string $ident    The identity string.
     * @param array  $conf     The configuration array.
     * @param int    $level    Log messages up to and including this level.
     * @access public
     */
    function Log_mcal($name, $ident = '', $conf = array(),
                      $level = PEAR_LOG_DEBUG)
    {
        $this->_id = md5(microtime());
        $this->_name = $name;
        $this->_ident = $ident;
        $this->_mask = Log::UPTO($level);
        $this->_calendar = $conf['calendar'];
        $this->_username = $conf['username'];
        $this->_password = $conf['password'];
        $this->_options = $conf['options'];
    }

    /**
     * Opens a calendar stream, if it has not already been
     * opened. This is implicitly called by log(), if necessary.
     * @access public
     */
    function open()
    {
        if (!$this->_opened) {
            $this->_stream = mcal_open($this->_calendar, $this->_username,
                $this->_password, $this->_options);
            $this->_opened = true;
        }

        return $this->_opened;
    }

    /**
     * Closes the calendar stream, if it is open.
     * @access public
     */
    function close()
    {
        if ($this->_opened) {
            mcal_close($this->_stream);
            $this->_opened = false;
        }

        return ($this->_opened === false);
    }

    /**
     * Logs $message and associated information to the currently open
     * calendar stream. Calls open() if necessary. Also passes the
     * message along to any Log_observer instances that are observing
     * this Log.
     *
     * @param mixed  $message  String or object containing the message to log.
     * @param string $priority The priority of the message. Valid
     *                  values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT,
     *                  PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING,
     *                  PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG.
     * @return boolean  True on success or false on failure.
     * @access public
     */
    function log($message, $priority = null)
    {
        /* If a priority hasn't been specified, use the default value. */
        if ($priority === null) {
            $priority = $this->_priority;
        }

        /* Abort early if the priority is above the maximum logging level. */
        if (!$this->_isMasked($priority)) {
            return false;
        }

        /* If the connection isn't open and can't be opened, return failure. */
        if (!$this->_opened && !$this->open()) {
            return false;
        }

        /* Extract the string representation of the message. */
        $message = $this->_extractMessage($message);

        $date_str = date('Y:n:j:G:i:s');
        $dates = explode(':', $date_str);

        mcal_event_init($this->_stream);
        mcal_event_set_title($this->_stream, $this->_ident);
        mcal_event_set_category($this->_stream, $this->_name);
        mcal_event_set_description($this->_stream, $message);
        mcal_event_add_attribute($this->_stream, 'priority', $priority);
        mcal_event_set_start($this->_stream, $dates[0], $dates[1], $dates[2],
            $dates[3], $dates[4], $dates[5]);
        mcal_event_set_end($this->_stream, $dates[0], $dates[1], $dates[2],
            $dates[3], $dates[4], $dates[5]);
        mcal_append_event($this->_stream);

        $this->_announce(array('priority' => $priority, 'message' => $message));

        return true;
    }

}


text:
"""Hyperparameter configuration for centralized training."""

import collections
import itertools

from typing import List, Mapping, Union

from absl import flags
import numpy as np

from generalization.experiments import config_utils

flags.DEFINE_enum('task', None, [
    'stackoverflow_word', 'cifar100_image', 'emnist_character',
    'shakespeare_character'
], 'Which task to perform training on.')
flags.DEFINE_boolean('emnist_character_only_digits', False,
                     'Whether to use digits-only version of EMNIST.')
flags.DEFINE_string('sql_database', None,
                    'Directory for SQL database, if applicable')

FLAGS = flags.FLAGS

def define_parameters() -> List[Mapping[str, Union[str, int, float]]]:
  """Returns a list of dicts of parameters defining the experiment grid."""
  # Base hyperparameters grid for all experiments

  # Define task-specific hyperparameter flags
  if FLAGS.task == 'cifar100_image':
    task_grid = collections.OrderedDict(  # pylint: disable=unused-variable
        task=['cifar100_image'],
        cifar100_image_num_classes=[10],
        sql_database=[FLAGS.sql_database],
        train_val_ratio_intra_client=[4],  # Required
        unpart_clients_proportion=[0.2],  # Required
        cifar100_image_resnet_layers=[18],
        num_epochs=[200],
        # decay_epochs=[60],
        centralized_shuffle_buffer_size=[50000],
        # lr_decay=[0.2],
        centralized_learning_rate=np.logspace(-2.5, -0.5, num=5),
        # part_clients_subsampling_rate=np.logspace(-1.0, -0.0, num=3),
        batch_size=[50],
    )
    sgd_grid = collections.OrderedDict(
        centralized_optimizer=['sgd'],
        centralized_sgd_momentum=[0.9],
    )
    optimizer_grids = [sgd_grid]
  elif FLAGS.task == 'emnist_character':
    if FLAGS.emnist_character_only_digits:
      task_grid = collections.OrderedDict(
          task=['emnist_character'],
          emnist_character_model=['cnn'],
          emnist_character_only_digits=[True],
          unpart_clients_proportion=[0.2],
          part_clients_subsampling_rate=[0.1],
          centralized_shuffle_buffer_size=[100000],
          centralized_learning_rate=np.logspace(-3.0, -1.0, num=5),
          num_epochs=[200],
          # decay_epochs=[6],
          # lr_decay=[0.2],
          batch_size=[50],
      )
    else:
      task_grid = collections.OrderedDict(
          task=['emnist_character'],
          sql_database=[FLAGS.sql_database],
          emnist_character_model=['cnn'],
          emnist_character_only_digits=[False],
          emnist_character_merge_case=[False],
          unpart_clients_proportion=[0.2],  # Required
          # train_val_ratio_intra_client=[4],  # Required
          num_epochs=[200],
          # decay_epochs=[6],
          # lr_decay=[0.1],
          centralized_shuffle_buffer_size=[100000],
          part_clients_subsampling_rate=[0.1],
          centralized_learning_rate=np.logspace(-3.0, -1.0, num=5),
          batch_size=[50],
      )
    sgd_grid = collections.OrderedDict(
        centralized_optimizer=['sgd'],
        centralized_sgd_momentum=[0.9],
    )
    optimizer_grids = [sgd_grid]

  elif FLAGS.task == 'stackoverflow_word':
    task_grid = collections.OrderedDict(  # pylint: disable=unused-variable
        task=['stackoverflow_word'],
        train_val_ratio_intra_client=[4],  # Required
        part_clients_subsampling_rate=np.logspace(-3.0, -1.0, num=5),
        num_epochs=[100],
        decay_epochs=[30],
        lr_decay=[0.1],
        centralized_shuffle_buffer_size=[100000],
        centralized_learning_rate=np.logspace(-2.5, -0.5, num=5),
        batch_size=[500],
        part_clients_per_eval=[500],
        unpart_clients_per_eval=[500],
        test_clients_for_eval=[500],
        max_elements_per_client=[1000])

    adam_grid = collections.OrderedDict(  # pylint: disable=unused-variable
        centralized_optimizer=['adam'],
        centralized_adam_epsilon=[1e-4],
    )
    optimizer_grids = [adam_grid]
  elif FLAGS.task == 'shakespeare_character':
    task_grid = collections.OrderedDict(
        task=['shakespeare_character'],
        unpart_clients_proportion=[0.2],  # Required
        num_epochs=[30],
        centralized_shuffle_buffer_size=[20000],
        centralized_learning_rate=np.logspace(-3.0, -1.0, num=5),
        batch_size=[20])
    adam_grid = collections.OrderedDict(  # pylint: disable=unused-variable
        centralized_optimizer=['adam'],
        centralized_adam_epsilon=[1e-4],
    )
    optimizer_grids = [adam_grid]
  else:
    raise ValueError('Invalid task name.')

  # Define optimizer-specific grids
  all_grids = []
  for opt_grid in optimizer_grids:
    all_grids.append(config_utils.hyper_grid({
        **task_grid,
        **opt_grid,
    }))

  return list(itertools.chain.from_iterable(all_grids))


text:
#pragma once

namespace juce
{

/**
    Represents traversal paths from master blocks and any connected blocks.

    @tags{Blocks}
*/
class BlockGraph
{
public:
    /** Creates a BlockGraph object from a BlockTopology with an optional filter function. This
        will build a block graph of traversal paths for each master.
    */
    BlockGraph (const BlockTopology topology, std::function<bool (Block::Ptr block)> filter = nullptr);
    BlockGraph (BlockGraph&&);

    using BlockTraversalPaths = Array<Block::Array, CriticalSection>;

    /** Get traversal paths for each master block in a topology */
    BlockTraversalPaths getTraversalPaths() const;

    /** Get traversal path for a specific master block in a topology */
    Block::Array getTraversalPathFromMaster (Block::Ptr masterBlock) const;

    /** Gets a string representation of all traversal paths */
    String asString() const;

private:
    void buildGraph();
    Block::Array buildPathFromMaster (Block::Ptr masterBlock);
    void addAllConnectedToArray (Block::Ptr startBlock, Block::Array& store);
    bool shouldIncludeBlock (Block::Ptr block) const;

    BlockTraversalPaths traversalPaths; // one path for each master block
    BlockTopology topology;
    std::function<bool (Block::Ptr)> filter;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockGraph)
};

} // namespace juce


text:
/* $Id: cmd-capture-pane.c,v 1.1.1.2 2011/08/17 18:40:04 jmmv Exp $ */

/*
 * Copyright (c) 2009 Jonathan Alvarado <radobobo@users.sourceforge.net>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>

#include <stdlib.h>
#include <string.h>

#include "tmux.h"

/*
 * Write the entire contents of a pane to a buffer.
 */

int	cmd_capture_pane_exec(struct cmd *, struct cmd_ctx *);

const struct cmd_entry cmd_capture_pane_entry = {
	"capture-pane", "capturep",
	"b:E:S:t:", 0, 0,
	"[-b buffer-index] [-E end-line] [-S start-line] [-t target-pane]",
	0,
	NULL,
	NULL,
	cmd_capture_pane_exec
};

int
cmd_capture_pane_exec(struct cmd *self, struct cmd_ctx *ctx)
{
	struct args		*args = self->args;
	struct window_pane	*wp;
	char 			*buf, *line, *cause;
	struct screen		*s;
	struct grid		*gd;
	int			 buffer, n;
	u_int			 i, limit, top, bottom, tmp;
	size_t         		 len, linelen;

	if (cmd_find_pane(ctx, args_get(args, 't'), NULL, &wp) == NULL)
		return (-1);
	s = &wp->base;
	gd = s->grid;

	buf = NULL;
	len = 0;

	n = args_strtonum(args, 'S', SHRT_MIN, SHRT_MAX, &cause);
	if (cause != NULL) {
		top = gd->hsize;
		xfree(cause);
	} else if (n < 0 && (u_int) -n > gd->hsize)
		top = 0;
	else
		top = gd->hsize + n;
	if (top > gd->hsize + gd->sy - 1)
		top = gd->hsize + gd->sy - 1;

	n = args_strtonum(args, 'E', SHRT_MIN, SHRT_MAX, &cause);
	if (cause != NULL) {
		bottom = gd->hsize + gd->sy - 1;
		xfree(cause);
	} else if (n < 0 && (u_int) -n > gd->hsize)
		bottom = 0;
	else
		bottom = gd->hsize + n;
	if (bottom > gd->hsize + gd->sy - 1)
		bottom = gd->hsize + gd->sy - 1;

	if (bottom < top) {
		tmp = bottom;
		bottom = top;
		top = tmp;
	}

	for (i = top; i <= bottom; i++) {
	       line = grid_string_cells(s->grid, 0, i, screen_size_x(s));
	       linelen = strlen(line);

	       buf = xrealloc(buf, 1, len + linelen + 1);
	       memcpy(buf + len, line, linelen);
	       len += linelen;
	       buf[len++] = '\n';

	       xfree(line);
	}

	limit = options_get_number(&global_options, "buffer-limit");

	if (!args_has(args, 'b')) {
		paste_add(&global_buffers, buf, len, limit);
		return (0);
	}

	buffer = args_strtonum(args, 'b', 0, INT_MAX, &cause);
	if (cause != NULL) {
		ctx->error(ctx, "buffer %s", cause);
		xfree(cause);
		return (-1);
	}

	if (paste_replace(&global_buffers, buffer, buf, len) != 0) {
		ctx->error(ctx, "no buffer %d", buffer);
		xfree(buf);
		return (-1);
	}

	return (0);
}


text:
package com.eagleoj.web.entity;

/**
 * @author Smith
 **/
public class TagEntity {

    private Integer tid;

    private String name;

    private Integer used;

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getUsed() {
        return used;
    }

    public void setUsed(Integer used) {
        this.used = used;
    }
}


text:
div.smMap {
    z-index: 0;
    padding: 0px!important;
    margin: 0px!important;
  //  cursor: default;
    cursor: url("../images/cursors/Pan.cur"),default;
    border:1px solid #3473b7;
}

div.smMapViewport {
    text-align: left;
}

div.smLayerDiv {
   -moz-user-select: none;
}

.smLayerGoogleCopyright {
    left: 2px;
    bottom: 2px;
}
.smLayerGooglePoweredBy {
    left: 2px;
    bottom: 15px;
}
.smControlAttribution {
    font-size: smaller;
    right: 3px;
    bottom: 0.5em;
    position: absolute;
    display: block;
}
.smControlScale {
    right: 3px;
    bottom: 3em;
    display: block;
    position: absolute;
    font-size: smaller;
}
.smControlScaleLine {
   display: block;
   position: absolute;
   left: 10px;
   bottom: 15px;
   font-size: xx-small;
}
.smControlScaleLineBottom {
   border: solid 2px black;
   border-bottom: none;
   margin-top:-2px;
   text-align: center;
}
.smControlScaleLineTop {
   border: solid 2px black;
   border-top: none;
   text-align: center;
}

.smControlPermalink {
    right: 3px;
    bottom: 1.5em;
    display: block;
    position: absolute;
    font-size: smaller;
}

div.smControlMousePosition {
    bottom: 0em;
    right: 3px;
    display: block;
    position: absolute;
    font-family: Arial;
    font-size: smaller;
}

.smControlOverviewMapContainer {
    position: absolute;
    bottom: 0px;
    right: 0px;
	background-color: #e5f3ff;
}

.smControlOverviewMapElement {
	border-left:1px solid #3473b7;
	border-top:1px solid #3473b7;
	padding-top: 4px;
	padding-left: 4px;
}

.smControlOverviewMapMinimizeButton {
    right: 0px;
    bottom: 1px;
    cursor: pointer;
}

.smControlOverviewMapMaximizeButton {
    right: 0px;
    bottom: 1px;
    cursor: pointer;
}

.smControlOverviewMapExtentRectangle {
    overflow: hidden;
    /*background-image:url(../../image/blank.gif);*/
    border: 1px solid red;
	background:#69F;
	filter:alpha(opacity=50);/* IE */
	-moz-opacity:0.5;/* Moz + FF */
	opacity: 0.5; /* 支持CSS3的浏览器(FF 1.5也支持)*/
}
.smControlOverviewMapRectReplacement {
    overflow: hidden;
    cursor: url("../images/cursors/PanDown.cur"),move;
    background-image: url(../images/overview_replacement.gif);
    background-repeat: no-repeat;
    background-position: center;
}

.smLayerGeoRSSDescription {
    float:left;
    width:100%;
    overflow:auto;
    font-size:1.0em;
}
.smLayerGeoRSSClose {
    float:right;
    color:gray;
    font-size:1.2em;
    margin-right:6px;
    font-family:sans-serif;
}
.smLayerGeoRSSTitle {
    float:left;font-size:1.2em;
}

.smPopupContent {
    padding:5px;
    overflow: auto;
}

.smHandlerBoxZoomBox {
    border: 2px solid red;
    position: absolute;
    background-color: white;
    opacity: 0.50;
    font-size: 1px;
    filter: alpha(opacity=50);
}
.smHandlerBoxSelectFeature {
    border: 2px solid blue;
    position: absolute;
    background-color: white;
    opacity: 0.50;
    font-size: 1px;
    filter: alpha(opacity=50);
}

.smPopupCloseBox {
  background: url("../images/close.gif") no-repeat;
  cursor: pointer;
}

.smFramedCloudPopupContent {
    padding: 5px;
    overflow: auto;
}

.smImageLoadError {
    background-color: pink;
    opacity: 0.5;
    filter: alpha(opacity=50); /* IE */
	display: none;
}

/**
 * Cursor styles
 */
 .smDefault {
     cursor: default;
 }
.smCursorWait {
    cursor: wait;
}
.smDragDown {
    cursor: url("../images/cursors/PanDown.cur"),move;
}
.smDragDownCanvas {
    cursor: move;
}
.smDragUp {
    cursor: url("../images/cursors/Pan.cur"),auto;
}

.smCursorPointer {
    cursor: pointer;
}

.smDrawBox {
    cursor: crosshair;
}
.smControlDragFeatureOver {
    /*cursor: move;*/
}
.smControlDragFeatureActive.smControlDragFeatureOver.smDragDown {
   /* cursor: -moz-grabbing;*/
}

/**
 * Layer switcher
 */
.smControlLayerSwitcher {
    position: absolute;
    top: 25px;
    right: 0px;
    width: 20em;
    font-family: sans-serif;
    font-weight: bold;
    margin-top: 3px;
    margin-left: 3px;
    margin-bottom: 3px;
    font-size: smaller;
    color: white;
    background-color: transparent;
    cursor: default;
}

.smControlLayerSwitcher .layersDiv {
    padding-top: 5px;
    padding-left: 10px;
    padding-bottom: 5px;
    background-color: darkblue;
    width: 100%;
    height: 100%;
}
/*白色样式下*/
.smControlLayerSwitcher .layersDivWhite {
    padding-top: 5px;
    padding-left: 10px;
    padding-bottom: 5px;
    background-color: darkblue;
    width: 100%;
    height: 100%;
}

.smControlLayerSwitcher .layersDiv .baseLbl,
.smControlLayerSwitcher .layersDiv .dataLbl {
    margin-top: 3px;
    margin-left: 3px;
    margin-bottom: 3px;
}

.smControlLayerSwitcher .layersDiv .baseLayersDiv,
.smControlLayerSwitcher .layersDiv .dataLayersDiv {
    padding-left: 3px;
}

.smControlLayerSwitcher .maximizeDiv,
.smControlLayerSwitcher .minimizeDiv {
    top: 0px;
    right: 0px;
    text-align: left;
    cursor: pointer;
}
.smControlLayerSwitcher .maximizeDiv{
    border: 3px solid #a5c8ec;
}

.smControlLayerSwitcher .maximizeDivWhite{
    top: 0px;
    right: 0px;
    cursor: pointer;
}

div.smControlLayerSwitcher {
    position: absolute;
    top: 50px;
    right: 0px;
    width: 171px;
    font-family: sans-serif;
    font-weight: bold;
    margin: 0px 3px 3px;
    font-size: smaller;
    font-size: 13px;
    color: #4083c2;
    background-color: transparent;
    border: 3px solid #a5c8ec;
}
div.smControlLayerSwitcher div.layersDiv {
    padding-top: 25px;
    padding-left: 5px;
    padding-bottom: 5px;
    background-color: #FFFFFF;
    width: 166px;
    height: 100%;
}
div.smControlLayerSwitcher div.layersDivWhite {
    padding-top: 10px;
    padding-left: 5px;
    padding-bottom: 10px;
    background-color: #FFFFFF;
    width: 166px;
    height: 100%;
    color: #565656;
    box-shadow:0px 0px 3px #ababab;
    border:1px solid #d7d7d7;
    border-radius:4px;
}

.layerSwitcherHR{
    width: 95%;
}

input.inputElem {
    width: 14px;
    height:14px;
    margin-left: 3px;
    margin-right:4px;
    margin-bottom: 4px;
    margin-top: 4px;
    vertical-align: middle;
    border: 0px;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 0%,0%;
    cursor: pointer;
}
span.labelSpan {
    margin-left: 5px;
    padding-bottom: 3px;
    padding-top: 3px;
    height:20px;
    vertical-align: middle;
}
div.minimizeDiv .layerSwitcherContent{
    position: absolute;
    padding: 2px 40px;
}

/**
 * Animations
 */

.smLayerDiv .smTileImage {
    -webkit-transition: opacity 0.2s linear;
    -moz-transition: opacity 0.2s linear;
    -o-transition: opacity 0.2s linear;
    transition: opacity 0.2s linear;
}

#popwin img{
    max-width: none;
}
/**
*绘制矩形框
*/
.qByBoundsBoxDiv {
    background-color: #304DBE;
    border: 2px solid #060abe;
    opacity: 0.3;
}


text:
@interface  SMTurnstileTests()
@property (nonatomic) NSInteger returnCoinsCounter;
@property (nonatomic) BOOL isWorkTime;

@end

@implementation SMTurnstileTests
@synthesize returnCoinsCounter = _returnCoinsCounter;
@synthesize isWorkTime = _isWorkTime;

-(void)returnCoin{
    self.returnCoinsCounter++;
}

-(void)greenLightOn{

}

-(void)redLightOn{

}

-(void)testTurnstileWithDecision{
    //Create structure
    __weak id weakSelf = self;
    //strong ref to monitor object
    SMMonitorNSLog *nsLogMonitor =[[SMMonitorNSLog alloc] initWithSmName:@"Turnstile"];
    SMStateMachine *sm = [[SMStateMachine alloc] init];
    sm.globalExecuteIn = self; //execute all selectors on self object
    //log to NSLog
    sm.monitor = nsLogMonitor;
    SMState *opened = [sm createState:@"open"];
    SMState *closed = [sm createState:@"closed"];
    SMDecision *isWorkTime = [sm createDecision:@"isWorkTime" withPredicateBoolBlock:^(){
       return [weakSelf isWorkTime];
    }];
    sm.initialState = closed;
    [opened setEntrySelector:@selector(greenLightOn)];
    [closed setEntrySelector:@selector(redLightOn)];
    [sm transitionFrom:closed to:isWorkTime forEvent:@"coin"];
    [sm trueTransitionFrom:isWorkTime to:opened];
    [sm falseTransitionFrom:isWorkTime to:closed withSel:@selector(returnCoin)];
    [sm transitionFrom:opened to:closed forEvent:@"pass"];
    [sm transitionFrom:opened to:closed forEvent:@"timeout"];
    [sm transitionFrom:opened to:opened forEvent:@"coin" withSel:@selector(returnCoin)];
    [sm validate];

    //Usage
    self.isWorkTime = NO;
    self.returnCoinsCounter = 0;
    [sm post:@"coin"];
    STAssertEquals(1, self.returnCoinsCounter, nil);
    self.isWorkTime = YES;
    [sm post:@"coin"];
    STAssertEquals(1, self.returnCoinsCounter, nil);
    [sm post:@"coin"];
    STAssertEquals(2, self.returnCoinsCounter, nil);
}

@end


text:
ape - a productive environment
==============================

.. image:: https://travis-ci.org/henzk/ape.svg?branch=master
    :target: https://travis-ci.org/henzk/ape

.. epigraph::

    ``ape`` is a make/rake/ant/fab-like system with support for FOSD.

``ape`` is short for "A Productive Environment". It provides a way to organize tasks in feature modules.
Feature modules can introduce new tasks and refine tasks that have been introduced by other features.

Tasks are defined as simple python functions. ``ape`` makes these task functions available from the command line
and provides usage information by extracting the functions' docstrings.

``ape`` can be used to manage software product lines(SPL). SPLs are placed in containers that contain their features and products.

Documentation: http://ape.readthedocs.org/

License: MIT


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS110-2015S: Introduction to Computing
% Copyright 2015 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS110-2015S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def \topDirectory {.}
\def \texDirectory {\topDirectory/src/main/tex}

\documentclass[12pt,letterpaper,twoside]{article}
\usepackage{\texDirectory/template/style/directives}
\usepackage{\texDirectory/template/style/assignment}
\input{\texDirectory/template/config}

\begin{document}

\doc{title}{Solution to Assignment 4}
\doc{date-pub}{Apr 06, 2015 at 00:00 AM}
\doc{date-due}{Apr 16, 2015 at 5:30 PM}
\doc{points}{8}

\prepare{header}

\section*{Question 1}

Back to Dalton Brothers! Develop a simple class \texttt{Brother.java} and its data memebrs and methods as you think best fits this program. Neglecting their original heights, write a program \texttt{Daltons3.java} that uses the \texttt{Brother.java} class to sort Joe, William, Jack and Averell after getting their heights from the user. The program should output names of the brothers in ascending order of their heights as specified.

\begin{figure}[H]\centering
\includegraphics{\texDirectory/template/images/daltons.png}
\end{figure}

\subsection*{Solution}

\begin{enumerate}
\item Class \texttt{Brother.java}

\lstset{language=java,tabsize=2}
\begin{lstlisting}
public class Brother {
	public double height;
	public String name;
	public Brother(String hisName, double hisHeight) {
		height = hisHeight;
		name = hisName;
	}
	public Brother() {
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
\end{lstlisting}

\item Class \texttt{DaltonsSort.java}
\lstset{language=java,tabsize=2}
\begin{lstlisting}
import java.util.Scanner;
public class DaltonsSort {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		// Let's start with what we know: Names of brothers.
		String[] broNames = {"Joe", "William", "Jack", "Averell"};
		// Now that we can treat these brothers as humans (objects) not just variables,
		// Let's declare an array of objects and put all brothers in it.
		Brother[] bros = new Brother[broNames.length];
		// Now we can give identity to each brother by setting its name
		for (int i = 0; i < bros.length; i++){
			System.out.print("What is the height of " + broNames[i] + "? ");
			int height = input.nextInt();
			bros[i] = new Brother(broNames[i], height);
		}
		// So far, we have four brothers with different names and different heights
		// Let's ask user the sorting order
		System.out.print("In which order do you want to sort the Daltons [ASC, DESC]? ");
		String orderName = input.next();
		boolean orderAsc = orderName.equals("ASC") ? true : false;
		// Now we have all we want. Let's close the Scanner object then.
		input.close();
		// Time for sorting.
		for (int j = 0; j < bros.length; j++) {
			int minIndex = j;
			double min = Double.MAX_VALUE;
			for (int i = j; i < bros.length; i++) {
				if (bros[i].height < min) {
					min = bros[i].height;
					minIndex = i;
				}
			}
			if (j != minIndex) {
				Brother temp = new Brother();
				temp = bros[j];
				bros[j] = bros[minIndex];
				bros[minIndex] = temp;
			}
		}
		// Print names
		for (int i = 0; i < bros.length; i++) {
			System.out.println(orderAsc ? bros[i].getName() : bros[bros.length-1-i].getName());
		}
	}
}
\end{lstlisting}
\end{enumerate}

\section*{Question 2}

A student recently found a scrap of paper in MBTA Red line train on which the following code was written. Without modifying the code, develop a class \texttt{Elevator.java} to be used by this program.
\lstset{language=java,tabsize=2}
\begin{lstlisting}
public class ElevatorTest {
	public static void main(String[] args) {
		Elevator.currentLevel(); //outputs current floor
		Elevator.go(2); //moves the elevator two floors up
		Elevator.currentLevel();
	}
}
\end{lstlisting}

\subsection*{Solution}

Class \texttt{Elevator.java}
\lstset{language=java}
\begin{lstlisting}
public class Elevator {
	private static int floor;
	private final static int limitUp = 10;
	private final static int limitDown = -2;
	private Elevator() { floor = 0; }
	protected static void go(int level) {
		int dest = floor + level;
		if (dest <= limitUp && dest >= limitDown) {
			floor += level;
		}
		else {
			System.out.println("Impossible!");
		}
	}
	protected static void currentLevel() {
		System.out.println("Elevator is at floor "+floor);
	}
}
\end{lstlisting}

\section*{Question 3}

Objective is to simulate a circle-shaped pond with 100 meters radius, in which there are initially 100 salmons and one shark. As sharks and salmons know swimming, they continually wander around the pond. It's all about survival! To avoid starving to death, the shark must eat. To avoid extinction, salmons reproduce. Contrary to what it seems however, the shark has a very poor fate. If it doesn't eat for too long it will sadly die. If it manages to eat all the salmons and there are no more to eat, it won't be able to escape his destiny either. It's not about survival then. It's all about time!
\begin{figure}[H]\centering
\includegraphics[width=8cm,height=5cm]{\texDirectory/template/images/pond.png}
\end{figure}

Write a program \texttt{Simulation.java} that determines how many days the shark will live. Develop classes \texttt{Fish.java}, \texttt{Salmon.java}, \texttt{Shark.java} and \texttt{Pond.java} with their class members as you think best fits this program. Use the following assumptions.
\begin{itemize}[itemsep=1mm] \parskip=0pt \parsep=0pt
\item[] Fish are initially positioned randomly in the pond.
\item[] Fish move randomly in the pond.
\item[] Salmons move 10 meter per hour.
\item[] Salmons reproduce every day.
\item[] Salmons don't age and don't need to eat.
\item[] Salmons won't die unless they are eaten.
\item[] The shark moves 40 meters per hour in one direction.
\item[] The shark cannot eat while it's moving.
\item[] The shark is always hungry and never loses interest in eating.
\item[] The shark swallows all salmons within its 20 meters of proximity in a blink of an eye.
\item[] The shark dies if it does not eat in three days.
\item[] The shark is initially well fed.
\end{itemize}

\subsection*{Solution}

\begin{enumerate}
\item Class \texttt{Simulation.java}
\lstset{language=java, tabsize=2}
\begin{lstlisting}
import java.util.ArrayList;
public class Simulation {
	public static void main(String[] args) {
		initialize();
		while (shark.getHunger() < 3 * 24) {
			nextHour();
			eat();
			if (time % 24 == 0) {
				reproduce();
			}
			showStatistics();
		}
	}
	private static ArrayList<Salmon> salmons;
	private static Shark shark;
	private static int time = 0;
	// setup 100 salmons and 1 shark in Pond
	private static void initialize() {
		System.out.println("Initalizing Pond...");
		salmons = new ArrayList<Salmon>(101);
		for (int i = 0; i < 100; i++) {
			Salmon salmon = new Salmon();
			salmons.add(salmon);
		}
		shark = new Shark();
		System.out.println("Pond Initialized.");
	}
	// move all salmons and the shark
	private static void nextHour() {
		for (int i = 0; i < salmons.size(); i++) {
			salmons.get(i).move();
		}
		shark.move();
		time++;
	}
	// check if it's time to eat
	private static void eat() {
		double[] posShark = shark.getPosition();
		double[] posSalmon = new double[2];
		double dist;
		for (int i = salmons.size() - 1; i >= 0; i--) {
			posSalmon = salmons.get(i).getPosition();
			dist = Math.sqrt(Math.pow(posShark[0] - posSalmon[0], 2) + Math.pow(posShark[1] - posSalmon[1], 2));
			if (dist < shark.getRange()) {
				salmons.remove(i);
				shark.eat();
			}
		}
	}
	private static void reproduce() {
		int num = salmons.size();
		for (int i = 0; i < num; i++) {
			Salmon salmon = new Salmon(salmons.get(i).getPosition());
			salmons.add(salmon);
		}
	}
	private static void showStatistics() {
		System.out.printf("Time: %d\n", time);
		System.out.printf("Fish: %d\n", salmons.size());
		System.out.println();
	}
}
\end{lstlisting}
\item Class \texttt{Pond.java}
\lstset{language=java, tabsize=2}
\begin{lstlisting}
public class Pond {
	// Fields
	private static double radius = 100;
	// Instantiation should be forbidden
	private Pond() {}
	// Since radius of pond is fixed, setter for radius is not needed
	public static double getRadius() {
		return radius;
	}
}
\end{lstlisting}
\item Class \texttt{Fish.java}
\lstset{language=java, tabsize=2}
\begin{lstlisting}
public class Fish {
	// fields
	private static int numFish = 0;
	// attributes
	private double posRho;
	private double posAng;
	private double speed;
	// methods
	public void move() {
		double oldX = posRho * Math.cos(posAng);
		double oldY = posRho * Math.sin(posAng);
		while (true) {
			double theta = Math.random() * 2 * Math.PI;
			double newX = oldX + speed*Math.cos(theta);
			double newY = oldY + speed*Math.sin(theta);
			double newRho = Math.sqrt(Math.pow(newX,2) + Math.pow(newY,2));
			if (newRho < Pond.getRadius()) {
				posRho = newRho;
				posAng = Math.atan2(newY, newX);
				break;
			}
		}
	}
	// constructor
	public Fish() {
		posRho = Math.random() * Pond.getRadius();
		posAng = Math.random() * 2 * Math.PI;
		numFish++;
	}
	public Fish(double[] position) {
		posRho = Math.sqrt(Math.pow(position[0], 2) + Math.pow(position[1], 2));
		posAng = Math.atan2(position[1], position[0]);
		numFish++;
	}
	// getter and setter for position
	public void setSpeed(double speed) {
		this.speed = speed;
	}
	public static int getNumFish() {
		return numFish;
	}
	public double[] getPosition() {
		double[] position = new double[2];
		position[0] = posRho * Math.cos(posAng);
		position[1] = posRho * Math.sin(posAng);
		return position;
	}
}
\end{lstlisting}
\item Class \texttt{Salmon.java}
\lstset{language=java, tabsize=2}
\begin{lstlisting}
public class Salmon extends Fish {
	private static int numSalmons = 0;
	public Salmon() {
		super();
		setSpeed(10);
		numSalmons++;
	}
	public Salmon(double[] position) {
		super(position);
		setSpeed(10);
		numSalmons++;
	}
	public static int getNumSalmons() {
		return numSalmons;
	}
}
\end{lstlisting}
\item Class \texttt{Shark.java}
\lstset{language=java, tabsize=2}
\begin{lstlisting}
public class Shark extends Fish{
	private static int numSharks = 0;
	private int hunger = 0;
	private double range = 20;
	public Shark() {
		super();
		setSpeed(40);
		numSharks++;
	}
	public void move() {
		super.move();
		hunger++;
	}
	public static int getNumSharks() {
		return numSharks;
	}
	public int getHunger() {
		return hunger;
	}
	public void eat() {
		hunger = 0;
	}
	public double getRange() {
		return range;
	}
}
\end{lstlisting}
\end{enumerate}

\end{document}


text:
#region License

// SLNTools
// Copyright (c) 2009
// by Christian Warren
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#endregion

using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace CWDev.SLNTools.Core.Merge
{
    public class DifferenceHashList : KeyedCollection<ElementIdentifier, Difference>
    {
        public DifferenceHashList()
        {
        }

        public DifferenceHashList(IEnumerable<Difference> items)
        {
            AddRange(items);
        }

        protected override ElementIdentifier GetKeyForItem(Difference item)
        {
            return item.Identifier;
        }

        public void AddRange(IEnumerable<Difference> items)
        {
            if (items != null)
            {
                foreach (var item in items)
                {
                    Add(item);
                }
            }
        }
    }
}


text:
//
//  NSStringAddition.h
//  Created by Devin Ross on 10/26/09.
//

@import Foundation;

/** Additional functionality for `NSString`.  */
@interface NSString (TKCategory)

/** Returns `YES` if a string is a valid email address, otherwise `NO`.
 @return True if the string is formatted properly as an email address.
 */
@property (nonatomic, getter=isEmail, readonly) BOOL email;

/** Returns a `NSString` that removes blank space from the start and end of string.
 @return A stripped string.
 */
@property (nonatomic, readonly, copy) NSString *stripWhitespace;

/** Returns a `NSString` that removes blank space and new lines from the start and end of string.
 @return A stripped string.
 */
@property (nonatomic, readonly, copy) NSString *stripWhitepspaceAndNewlines;

/** Returns a `NSString` that is URL friendly.
 @return A URL encoded string.
 */
@property (nonatomic, readonly, copy) NSString *URLEncode;

/** Returns a `NSString` that properly replaces HTML specific character sequences.
 @return An escaped HTML string.
 */
@property (nonatomic, readonly, copy) NSString *escapeHTML;

/** Returns a `NSString` that properly formats text for HTML.
 @return An unescaped HTML string.
 */
@property (nonatomic, readonly, copy) NSString *unescapeHTML;

/** Returns a `NSString` that removes HTML elements.
 @return Returns a string without the HTML elements.
 */
@property (nonatomic, readonly, copy) NSString *stringByRemovingHTML;

/** Returns an MD5 string of from the given `NSString`.
 @return A MD5 string.
 */
@property (nonatomic, readonly, copy) NSString *md5sum;

/** Returns `YES` is a string has the substring, otherwise `NO`.
 @param substring The substring.
 @return `YES` if the substring is contained in the string, otherwise `NO`.
 */
- (BOOL) hasString:(NSString*)substring;

/** Returns the length of the string minus the whitespace characters.
 @return Returns the length of the string minus the whitespace characters.
 */
@property (nonatomic, readonly) NSUInteger lengthWithoutWhitespace;

/** Returns a string without the whitespace characters.
 @return Returns a string without the whitespace characters.
 */
@property (nonatomic, readonly) NSString *stringWithoutWhitespace;

/* Returns a string with the first word in each sentence as capitalized. */
@property (nonatomic, readonly, copy) NSString *capitalizeSentence;

/** Returns the credit card type based on the first for digits of the card number.
 @return A credit card company name if the number matches a company otherwise nil.
 */
@property (nonatomic, readonly, copy) NSString *creditCardType;

/** Returns YES if the card number passes the Luhn algorithm. No spaces in the card number.
 @return Returns YES if the card is a valid credit card number, otherwise NO.
 */
@property (nonatomic, getter=isValidCreditCardNumber, readonly) BOOL validCreditCardNumber;

/** Returns a formatted phone number. So it'd transform a string 18005555555 would be 1-800-555-5555.
 @param deleteLastChar Remove the last character from the string.
 @return Returns an `NSString` that transform a string of numbers into a string human readable phone number.
 */
- (NSString*) formattedPhoneNumberWithLastCharacterRemoved:(BOOL)deleteLastChar;

- (NSString*) formattedPhoneNumberWithLastCharacterRemoved:(BOOL)deleteLastChar limit:(NSInteger)limit;

@end


text:
Template['chatbox'].helpers({
    'messages' : function () {
        var userId = Meteor.userId();
        console.log(Meteor.userId());
        return getMessage(userId);

    },

    'isUserMessage': function (type) {
        return type === "user"
    },

    'isMentorMessage': function (type) {
        return type === "mentor"
    },

    'isSiteMessage': function (type) {
        return type === "site"
    },

    getCurrentUserName: function(){
        var userFullName = Meteor.users.findOne({_id: Meteor.user()._id}).profile.full_name;
        return userFullName;
    },

    getCurrentUserProfilePicture: function(){
        var photo = Meteor.users.findOne({_id: Meteor.user()._id}).profile.profilePicture;
        return photo;
    },

    checkMeteorUser: function () {
        return Meteor.user();
    }
});

Template['chatbox'].events({

    "submit form": function(event) {
        event.preventDefault();
        var body = event.target.message.value;
        var to = 'dyGw39BywKb8DiZqn';
        event.target.message.value = "";
        Meteor.call('insertMessage', body, to);
        console.log("Message sent");
    },
    "click #user" : function(event){
        event.preventDefault();
        var userId= event.currentTarget.innerText;
        Meteor.call('insertMessage', userId);
        Session.set("user",userId);
        console.log(userId);
    },

    "click #backward": function(){
        Session.set('backwardPressed', 1);
    }
});

function getUniqueUsers(){
    var data = Messages.find({},{fields:{from:1}}).fetch();
    //TODO::optimize it later, group by should be changed to uniq.
    var groupedDates = _.groupBy(_.pluck(data, 'from'));
    var array = [];
    _.each(_.values(groupedDates), function(dates) {
       array.push (dates[0]);
    });
    return array;
}

function getMessage(userId){
    setTimeout(function() {
        $('#chat_box').scrollTop($('#chat_box')[0].scrollHeight);
    }, 50);
    if(Meteor.user()) {
        var message = Messages.find({$or: [{to: userId}, {from: userId}]}).fetch();
        return message;
    }else{
        return null;
    }
}

Session.set('backwardPressed', null);


text:
import {
	PerspectiveCamera,
	Quaternion,
	Vector3
} from '../../three.module.js'

/**
 * peppers ghost effect based on http://www.instructables.com/id/Reflective-Prism/?ALLSTEPS
 */

class PeppersGhostEffect {

	constructor( renderer ) {

		const scope = this;

		scope.cameraDistance = 15;
		scope.reflectFromAbove = false;

		// Internals
		let _halfWidth, _width, _height;

		const _cameraF = new PerspectiveCamera(); //front
		const _cameraB = new PerspectiveCamera(); //back
		const _cameraL = new PerspectiveCamera(); //left
		const _cameraR = new PerspectiveCamera(); //right

		const _position = new Vector3();
		const _quaternion = new Quaternion();
		const _scale = new Vector3();

		// Initialization
		renderer.autoClear = false;

		this.setSize = function ( width, height ) {

			_halfWidth = width / 2;
			if ( width < height ) {

				_width = width / 3;
				_height = width / 3;

			} else {

				_width = height / 3;
				_height = height / 3;

			}

			renderer.setSize( width, height );

		};

		this.render = function ( scene, camera ) {

			scene.updateMatrixWorld();

			if ( camera.parent === null ) camera.updateMatrixWorld();

			camera.matrixWorld.decompose( _position, _quaternion, _scale );

			// front
			_cameraF.position.copy( _position );
			_cameraF.quaternion.copy( _quaternion );
			_cameraF.translateZ( scope.cameraDistance );
			_cameraF.lookAt( scene.position );

			// back
			_cameraB.position.copy( _position );
			_cameraB.quaternion.copy( _quaternion );
			_cameraB.translateZ( - ( scope.cameraDistance ) );
			_cameraB.lookAt( scene.position );
			_cameraB.rotation.z += 180 * ( Math.PI / 180 );

			// left
			_cameraL.position.copy( _position );
			_cameraL.quaternion.copy( _quaternion );
			_cameraL.translateX( - ( scope.cameraDistance ) );
			_cameraL.lookAt( scene.position );
			_cameraL.rotation.x += 90 * ( Math.PI / 180 );

			// right
			_cameraR.position.copy( _position );
			_cameraR.quaternion.copy( _quaternion );
			_cameraR.translateX( scope.cameraDistance );
			_cameraR.lookAt( scene.position );
			_cameraR.rotation.x += 90 * ( Math.PI / 180 );

			renderer.clear();
			renderer.setScissorTest( true );

			renderer.setScissor( _halfWidth - ( _width / 2 ), ( _height * 2 ), _width, _height );
			renderer.setViewport( _halfWidth - ( _width / 2 ), ( _height * 2 ), _width, _height );

			if ( scope.reflectFromAbove ) {

				renderer.render( scene, _cameraB );

			} else {

				renderer.render( scene, _cameraF );

			}

			renderer.setScissor( _halfWidth - ( _width / 2 ), 0, _width, _height );
			renderer.setViewport( _halfWidth - ( _width / 2 ), 0, _width, _height );

			if ( scope.reflectFromAbove ) {

				renderer.render( scene, _cameraF );

			} else {

				renderer.render( scene, _cameraB );

			}

			renderer.setScissor( _halfWidth - ( _width / 2 ) - _width, _height, _width, _height );
			renderer.setViewport( _halfWidth - ( _width / 2 ) - _width, _height, _width, _height );

			if ( scope.reflectFromAbove ) {

				renderer.render( scene, _cameraR );

			} else {

				renderer.render( scene, _cameraL );

			}

			renderer.setScissor( _halfWidth + ( _width / 2 ), _height, _width, _height );
			renderer.setViewport( _halfWidth + ( _width / 2 ), _height, _width, _height );

			if ( scope.reflectFromAbove ) {

				renderer.render( scene, _cameraL );

			} else {

				renderer.render( scene, _cameraR );

			}

			renderer.setScissorTest( false );

		};

	}

}

export { PeppersGhostEffect };


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 64: 10 (1956)

#### Original name
Sorosporium arthraxonis S. Ahmad

### Remarks
null


text:
require 'ooor/services'
require 'active_support/configurable'
require 'active_support/core_ext/hash/slice'

module Ooor
  class Session
    include ActiveSupport::Configurable
    include Transport

    attr_accessor :web_session, :id, :models

    def common(); @common_service ||= CommonService.new(self); end
    def db(); @db_service ||= DbService.new(self); end
    def object(); @object_service ||= ObjectService.new(self); end
    def report(); @report_service ||= ReportService.new(self); end

    def initialize(config, web_session, id)
      set_config(_config(config))
      Object.const_set(config[:scope_prefix], Module.new) if config[:scope_prefix]
      @models = {}
      @local_context = {}
      @web_session = web_session || {}
      @id = id || web_session[:session_id]
    end

    def set_config(configuration)
      configuration.each do |k, v|
        config.send "#{k}=", v
      end
    end

    # a part of the config that will be mixed in the context of each session
    def connection_session
      HashWithIndifferentAccess.new(config[:connection_session] || {})
    end

    def [](key)
      self[key]
    end

    def []=(key, value)
      self[key] = value
    end

    def global_login(options)
      config.merge!(options.symbolize_keys)
      load_models(config[:models], options[:reload])
    end

    def with_context(context)
      @local_context = context
      yield
      @local_context = {}
    end

    def session_context(context={})
      connection_session.merge(web_session.slice('lang', 'tz')).merge(@local_context).merge(context) # not just lang and tz?
    end

    def const_get(model_key, lang=nil);
      if config[:aliases]
        if lang && alias_data = config[:aliases][lang]
          openerp_model = alias_data[model_key] || model_key
        elsif alias_data = config[:aliases][connection_session['lang'] || :en_US]
          openerp_model = alias_data[model_key] || model_key
        else
          openerp_model = model_key
        end
      else
        openerp_model = model_key
      end
      define_openerp_model(model: openerp_model, scope_prefix: config[:scope_prefix], generate_constants: config[:generate_constants])
    end

    def[](model_key) #TODO invert: define method here and use []
      const_get(model_key)
    end

    def load_models(model_names=config[:models], reload=config[:reload])
      helper_paths.each do |dir|
        ::Dir[dir].each { |file| require file }
      end
      search_domain = model_names ? [['model', 'in', model_names]] : []
      models_records = read_model_data(search_domain)
      models_records.reject {|opts| opts['model'] == '_unknown' }.each do |opts|
        options = HashWithIndifferentAccess.new(opts.merge(scope_prefix: config[:scope_prefix],
                                                           reload: reload,
                                                           generate_constants: config[:generate_constants]))
        define_openerp_model(options)
      end
    end

    def read_model_data(search_domain)
      if config[:force_xml_rpc]
        model_ids = object.object_service(:execute, "ir.model", :search, search_domain, 0, false, false, {}, false)
        models_records = object.object_service(:execute, "ir.model", :read, model_ids, ['model', 'name'])
      else
        response = object.object_service(:search_read, "ir.model", 'search_read',
                fields: ['model', 'name'],
                offset: 0,
                limit: false,
                domain: search_domain,
                sort: false,
                context: {})
        models_records = response["records"]
      end
    end

    def set_model_template!(klass, options)
      template = Ooor.model_registry.get_template(config, options[:model])
      if template
        klass.t = template
      else
        template = Ooor::ModelSchema.new
        template.openerp_model = options[:model]
        template.openerp_id = options[:id]
        template.description = options[:name]
        template.state = options[:state]
        template.many2one_associations = {}
        template.one2many_associations = {}
        template.many2many_associations = {}
        template.polymorphic_m2o_associations = {}
        template.associations_keys = []
        klass.t = template
      end
    end

    def define_openerp_model(options) #TODO param to tell if we define constants or not
      if !models[options[:model]] || options[:reload]# || !scope.const_defined?(model_class_name)
        scope_prefix = options[:scope_prefix]
        scope = scope_prefix ? Object.const_get(scope_prefix) : Object
        model_class_name = class_name_from_model_key(options[:model])
        logger.debug "registering #{model_class_name}"
        klass = Class.new(Base)
        set_model_template!(klass, options)
        klass.name = model_class_name
        klass.scope_prefix = scope_prefix
        klass.session = self
        if options[:generate_constants] && (options[:reload] || !scope.const_defined?(model_class_name))
          scope.const_set(model_class_name, klass)
        end
        (Ooor.extensions[options[:model]] || []).each do |block|
          klass.class_eval(&block)
        end
        models[options[:model]] = klass
      end
      models[options[:model]]
    end

#    def models; @models ||= {}; end

    def logger; Ooor.logger; end

    def helper_paths
      [File.dirname(__FILE__) + '/helpers/*', *config[:helper_paths]]
    end

    def class_name_from_model_key(model_key)
      model_key.split('.').collect {|name_part| name_part.capitalize}.join
    end

    private

    def _config(config)
      c = config.is_a?(String) ? Ooor.load_config(config, env) : config #TODO env, see old Connection
      HashWithIndifferentAccess.new(c)
    end

  end
end


text:
class <%= migration_name %> < ActiveRecord::Migration
  def self.up
    if <%= class_name -%>.stub_tables?
      create_table :<%= table_name %>, :primary_key=>:<%= primary_key %> do |t|
  <% for attribute in attributes
      unless attribute.name == primary_key -%>
      t.<%= attribute.type %> :<%= attribute.name %>
  <% end
  end -%>
    end
    else
      raise "DM probably needs to run a grant as it looks like #{<%= class_name -%>.table_name} doesn't exist" unless <%= class_name -%>.table_exists?
    end
  end

  def self.down
    if <%= class_name -%>.stub_tables?
      drop_table :<%= table_name %>
    end
  end
end


text:
package org.decimal4j.arithmetic;

import java.math.BigInteger;

import org.decimal4j.scale.ScaleMetrics;

/**
 * Contains methods to convert from and to {@link BigInteger}.
 */
final class BigIntegerConversion {

	/**
	 * Converts the specified big integer value to an unscaled decimal value. An exception is thrown if the value
	 * exceeds the valid Decimal range.
	 *
	 * @param scaleMetrics
	 *            the scale metrics of the result value
	 * @param value
	 *            the big integer value to convert
	 * @return the decimal value of the scale as defined by {@code ScaleMetrics}
	 * @throws IllegalArgumentException
	 *             if the value is outside of the valid Decimal range
	 */
	public static final long bigIntegerToUnscaled(ScaleMetrics scaleMetrics, BigInteger value) {
		if (value.bitLength() <= 63) {
			return LongConversion.longToUnscaled(scaleMetrics, value.longValue());
		}
		throw new IllegalArgumentException("Overflow: cannot convert " + value + " to Decimal with scale " + scaleMetrics.getScale());
	}

	// no instances
	private BigIntegerConversion() {
		super();
	}
}