text:
"""
Helper interface and functions for higher level plugin module getter methods.

Plugin configuration dictionaries take the following general format:

    {
        "type": "name",
        "impl_name": {
            "param1": "val1",
            "param2": "val2",
            ...
        },
        "other_impl": {
            ...
        },
        ... (etc.)
    }

"""

import abc
import collections
import importlib
import logging
import os
import re
import sys

# Template for checking validity of sub-module files
VALID_MODULE_FILE_RE = re.compile("^[a-zA-Z]\w*(?:\.py)?$")

# Template for checking validity of module attributes
VALUE_ATTRIBUTE_RE = re.compile("^[a-zA-Z]\w*$")

OS_ENV_PATH_SEP = (sys.platform == "win32" and ';') or ':'

class NotUsableError (Exception):
    """
    Exception thrown when a pluggable class is constructed but does not report
    as usable.
    """

class Pluggable (object):
    """
    Interface for classes that have plugin implementations
    """

    @classmethod
    @abc.abstractmethod
    def is_usable(cls):
        """
        Check whether this class is available for use.

        Since certain plugin implementations may require additional dependencies
        that may not yet be available on the system, this method should check
        for those dependencies and return a boolean saying if the implementation
        is usable.

        NOTES:
            - This should be a class method
            - When an implementation is deemed not usable, this should emit a
                warning detailing why the implementation is not available for
                use.

        :return: Boolean determination of whether this implementation is usable.
        :rtype: bool

        """
        raise NotImplementedError("is_usable class-method not implemented for "
                                  "class '%s'" % cls.__name__)

    def __init__(self):
        if not self.is_usable():
            raise NotUsableError("Implementation class '%s' is not currently "
                                 "usable." % self.__class__.__name__)

def get_plugins(base_module_str, internal_dir, dir_env_var, helper_var,
                baseclass_type, warn=True, reload_modules=False):
    """
    Discover and return classes found in the SMQTK internal plugin directory and
    any additional directories specified via an environment variable.

    In order to specify additional out-of-SMQTK python modules containing
    base-class implementations, additions to the given environment variable must
    be made. Entries must be separated by either a ';' (for windows) or ':' (for
    everything else). This is the same as for the PATH environment variable on
    your platform. Entries should be paths to importable modules containing
    attributes for potential import.

    We look for module attributes that start with an alphanumeric character ('_'
    prefixed attributes are hidden from import by this function).

    We required that the base class that we are checking for also descends from
    the ``Pluggable`` interface defined above. This allows us to check if a
    loaded class ``is_usable``.

    Within a module we first look for a helper variable by the name provided,
    which can either be a single class object or an iterable of class objects,
    to be specifically exported. If the variable is set to None, we skip that
    module and do not import anything. If the variable is not present, we look
    at attributes defined in that module for classes that descend from the given
    base class type. If none of the above are found, or if an exception occurs,
    the module is skipped.

    :param base_module_str: SMQTK internal string module path in which internal
        plugin modules are located.
    :type base_module_str: str

    :param internal_dir: Directory path to where SMQTK internal plugin modules
        are located.
    :type internal_dir: str

    :param dir_env_var: String name of an environment variable to look for that
        may optionally define additional directory paths to search for modules
        that may implement additional child classes of the base type.
    :type dir_env_var: str

    :param helper_var: Name of the expected module helper attribute.
    :type helper_var: str

    :param baseclass_type: Class type that discovered classes should descend
        from (inherit from).
    :type baseclass_type: type

    :param warn: If we should warn about module import failures.
    :type warn: bool

    :param reload_modules: Explicitly reload discovered modules from source
        instead of taking a potentially cached version of the module.
    :type reload_modules: bool

    :return: Map of discovered class objects descending from type
        ``baseclass_type`` and ``smqtk.utils.plugin.Pluggable`` whose keys are
        the string names of the class types.
    :rtype: dict of (str, type)

    """
    log = logging.getLogger('.'.join([__name__,
                                      "getPlugins[%s]" % base_module_str]))

    if not issubclass(baseclass_type, Pluggable):
        raise ValueError("Required base-class must descend from the Pluggable "
                         "interface!")

    # List of module paths to check for valid sub-classes.
    #: :type: list[str]
    module_paths = []

    # modules nested under internal module
    log.debug("Finding internal modules...")
    for filename in os.listdir(internal_dir):
        if VALID_MODULE_FILE_RE.match(filename):
            module_name = os.path.splitext(filename)[0]
            log.debug("-- %s", module_name)
            module_paths.append('.'.join([base_module_str, module_name]))
    log.debug("Internal modules to search: %s", module_paths)

    # modules from env variable
    log.debug("Extracting env var module paths")
    log.debug("-- path sep: %s", OS_ENV_PATH_SEP)
    if dir_env_var in os.environ:
        env_var_module_paths = os.environ[dir_env_var].split(OS_ENV_PATH_SEP)
        # strip out empty strings
        env_var_module_paths = [p for p in env_var_module_paths if p]
        log.debug("Additional module paths specified in env var: %s",
                  env_var_module_paths)
        module_paths.extend(env_var_module_paths)
    else:
        log.debug("No paths added from environment.")

    log.debug("Getting plugins for module '%s'", base_module_str)
    class_map = {}
    for module_path in module_paths:
        log.debug("Examining module: %s", module_path)
        # We want any exception this might throw to continue up. If a module
        # in the directory is not importable, the user should know.
        try:
            module = importlib.import_module(module_path)
        except Exception, ex:
            if warn:
                log.warn("[%s] Failed to import module due to exception: "
                         "(%s) %s",
                         module_path, ex.__class__.__name__, str(ex))
            continue
        if reload_modules:
            # Invoke reload in case the module changed between imports.
            module = reload(module)
            if module is None:
                raise RuntimeError("[%s] Failed to reload"
                                   % module_path)

        # Find valid classes in the discovered module by:
        classes = []
        if hasattr(module, helper_var):
            # Looking for magic variable for import guidance
            classes = getattr(module, helper_var)
            if classes is None:
                log.debug("[%s] Helper is None-valued, skipping module",
                          module_path)
                classes = []
            elif (isinstance(classes, collections.Iterable) and
                  not isinstance(classes, basestring)):
                classes = list(classes)
                log.debug("[%s] Loaded list of %d class types via helper",
                          module_path, len(classes))
            elif issubclass(classes, baseclass_type):
                log.debug("[%s] Loaded class type: %s",
                          module_path, classes.__name__)
                classes = [classes]
            else:
                raise RuntimeError("[%s] Helper variable set to an invalid "
                                   "value: %s", module_path, classes)
        else:
            # Scan module valid attributes for classes that descend from the
            # given base-class.
            for attr_name in dir(module):
                if VALUE_ATTRIBUTE_RE.match(attr_name):
                    log.debug("[%s] Checking attribute '%s'", module_path,
                              attr_name)
                    attr = getattr(module, attr_name)
                    if isinstance(attr, type) and \
                            attr is not baseclass_type and \
                            issubclass(attr, baseclass_type):
                        log.debug("[%s] -- Discovered subclass: %s",
                                  module_path, attr.__name__)
                        classes.append(attr)

        # Check the validity of the discovered class types
        for cls in classes:
            # check that all class types in iterable are types and
            # are subclasses of the given base-type and plugin interface
            if not (isinstance(cls, type) and
                    cls is not baseclass_type and
                    issubclass(cls, baseclass_type)):
                raise RuntimeError("[%s] Found element in list "
                                   "that is not a class or does "
                                   "not descend from required base "
                                   "class '%s': %s"
                                   % (module_path,
                                      baseclass_type.__name__,
                                      cls))
            # Check if the algorithm reports being usable
            elif not cls.is_usable():
                log.debug('[%s] Class type "%s" reported not usable '
                          '(skipping).',
                          module_path, cls.__name__)
            else:
                # Otherwise add it to the output mapping
                class_map[cls.__name__] = cls

    return class_map

def make_config(plugin_getter):
    """
    Generated configuration dictionary for the given plugin getter method (which
    returns a dictionary of labels to class types)

    A types parameters, as listed, at the construction parameters for that type.
    Default values are inserted where possible, otherwise None values are
    used.

    :param plugin_getter: Function that returns a dictionary mapping labels to
        class types.
    :type plugin_getter: () -> dict[str, type]

    :return: Base configuration dictionary with an empty ``type`` field, and
        containing the types and initialization parameter specification for all
        implementation types available from the provided getter method.
    :rtype: dict[str, object]

    """
    d = {"type": None}
    for label, cls in plugin_getter().iteritems():
        # noinspection PyUnresolvedReferences
        d[label] = cls.get_default_config()
    return d

def to_plugin_config(cp_inst):
    """
    Helper method that transforms the configuration dictionary gotten from the
    passed Configurable-subclass instance into the standard multi-plugin
    configuration dictionary format (see above).

    This result of this function would be compatible with being passed to the
    ``from_plugin_config`` function, given the appropriate plugin-getter method.

    TL;DR: This wraps the instance's ``get_config`` return in a certain way
           that's compatible with ``from_plugin_config``.

    :param cp_inst: Instance of a Configurable-subclass.
    :type cp_inst: Configurable

    :return: Plugin-format configuration dictionary.
    :rtype: dict

    """
    name = cp_inst.__class__.__name__
    return {
        "type": name,
        name: cp_inst.get_config()
    }

def from_plugin_config(config, plugin_getter, *args):
    """
    Helper method for instantiating an instance of a class available via the
    provided ``plugin_getter`` function given the plugin configuration
    dictionary ``config``.

    :raises KeyError: There was no ``type`` field to inspect, or there was no
        parameter specification for the specified ``type``.
    :raises TypeError: Insufficient/incorrect initialization parameters were
        specified for the specified ``type``'s constructor.

    :param config: Configuration dictionary to draw from.
    :type config: dict

    :param plugin_getter: Function that returns a dictionary mapping labels to
        class types.
    :type plugin_getter: () -> dict[str, type]

    :param args: Additional argument to be passed to the ``from_config`` method
        on the configured class type.

    :return: Instance of the configured class type as found in the given
        ``plugin_getter``.
    :rtype: smqtk.utils.Configurable

    """
    t = config['type']
    cls = plugin_getter()[t]
    try:
        # noinspection PyUnresolvedReferences
        return cls.from_config(config[t], *args)
    except TypeError, ex:
        raise TypeError(cls.__name__ + '.' + ex.message)


text:
package org.apache.tomcat.websocket.server;

import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.net.SocketWrapperBase;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.Transformation;
import org.apache.tomcat.websocket.WsFrameBase;
import org.apache.tomcat.websocket.WsIOException;
import org.apache.tomcat.websocket.WsSession;

public class WsFrameServer extends WsFrameBase {

    private static final Log log = LogFactory.getLog(WsFrameServer.class);
    private static final StringManager sm = StringManager.getManager(WsFrameServer.class);

    private final SocketWrapperBase<?> socketWrapper;
    private final ClassLoader applicationClassLoader;

    public WsFrameServer(SocketWrapperBase<?> socketWrapper, WsSession wsSession,
            Transformation transformation, ClassLoader applicationClassLoader) {
        super(wsSession, transformation);
        this.socketWrapper = socketWrapper;
        this.applicationClassLoader = applicationClassLoader;
    }

    /**
     * Called when there is data in the ServletInputStream to process.
     *
     * @throws IOException if an I/O error occurs while processing the available
     *                     data
     */
    public void onDataAvailable() throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("wsFrameServer.onDataAvailable");
        }
        while (isOpen()) {
            // Fill up the input buffer with as much data as we can
            inputBuffer.mark();
            inputBuffer.position(inputBuffer.limit()).limit(inputBuffer.capacity());
            int read = socketWrapper.read(false, inputBuffer);
            inputBuffer.limit(inputBuffer.position()).reset();
            if (read < 0) {
                throw new EOFException();
            } else if (read == 0) {
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("wsFrameServer.bytesRead", Integer.toString(read)));
            }
            processInputBuffer();
        }
    }

    @Override
    protected boolean isMasked() {
        // Data is from the client so it should be masked
        return true;
    }

    @Override
    protected Transformation getTransformation() {
        // Overridden to make it visible to other classes in this package
        return super.getTransformation();
    }

    @Override
    protected boolean isOpen() {
        // Overridden to make it visible to other classes in this package
        return super.isOpen();
    }

    @Override
    protected Log getLog() {
        return log;
    }

    @Override
    protected void sendMessageText(boolean last) throws WsIOException {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(applicationClassLoader);
            super.sendMessageText(last);
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }

    @Override
    protected void sendMessageBinary(ByteBuffer msg, boolean last) throws WsIOException {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(applicationClassLoader);
            super.sendMessageBinary(msg, last);
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.ajah.job.task;

import java.io.Serializable;

import lombok.Data;

import com.ajah.util.FromStringable;
import com.ajah.util.ToStringable;

/**
 * A wrapper around a String for typesafe {@link JobTask} IDs.
 *
 * @author Eric F. Savage <code@efsavage.com>
 *
 */
@Data
public class JobTaskId implements Serializable, ToStringable, FromStringable, Comparable<JobTaskId> {

	private final String id;

	/**
	 * Simple string constructor.
	 *
	 * @param id
	 *            UID of item, cannot be null.
	 */
	public JobTaskId(final String id) {
		this.id = id;
	}

	/**
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(final JobTaskId other) {
		return this.id.compareTo(other.getId());
	}

	/**
	 * Returns the String passed into the constructor.
	 *
	 * @return The String passed into the constructor.
	 */
	public String getId() {
		return this.id;
	}

	/**
	 * Returns the String passed into the constructor.
	 */
	@Override
	public String toString() {
		return this.id;
	}

}


text:
<?php

namespace Lexik\Bundle\TranslationBundle\Model;

use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Lexik\Bundle\TranslationBundle\Manager\TranslationInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * This class represent a trans unit which contain translations for a given domain and key.
 *
 * @author Cédric Girard <c.girard@lexik.fr>
 */
abstract class TransUnit
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     */
    protected $key;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     */
    protected $domain;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @Assert\NotBlank()
     */
    protected $translations;

    /**
     * @var \DateTime
     */
    protected $createdAt;

    /**
     * @var \DateTime
     */
    protected $updatedAt;

    /**
     * Construct.
     */
    public function __construct()
    {
        $this->domain = 'messages';
        $this->translations = new ArrayCollection();
    }

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

    /**
     * Set key name
     *
     * @param string $key
     */
    public function setKey($key)
    {
        $this->key = $key;
    }

    /**
     * Get key name
     *
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Set domain
     *
     * @param string $domain
     */
    public function setDomain($domain)
    {
        $this->domain = $domain;
    }

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

    /**
     * Add translations
     *
     * @param \Lexik\Bundle\TranslationBundle\Model\Translation $translations
     */
    public function addTranslation(\Lexik\Bundle\TranslationBundle\Model\Translation $translation)
    {
        $this->translations[] = $translation;
    }

    /**
     * Remove translations
     *
     * @param \Lexik\Bundle\TranslationBundle\Model\Translation $translations
     */
    public function removeTranslation(\Lexik\Bundle\TranslationBundle\Model\Translation $translation)
    {
        $this->translations->removeElement($translation);
    }

    /**
     * Get translations
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTranslations()
    {
        return $this->translations;
    }

    /**
     * Return true if this object has a translation for the given locale.
     *
     * @param string $locale
     * @return boolean
     */
    public function hasTranslation($locale)
    {
        return null !== $this->getTranslation($locale);
    }

    /**
     * Return the content of translation for the given locale.
     *
     * @param string $locale
     * @return \Lexik\Bundle\TranslationBundle\Model\Translation
     */
    public function getTranslation($locale)
    {
        foreach ($this->getTranslations() as $translation) {
            if ($translation->getLocale() == $locale) {
                return $translation;
            }
        }

        return null;
    }

    /**
     * Set translations collection
     *
     * @param Collection $collection
     */
    public function setTranslations(Collection $collection)
    {
        $this->translations = new ArrayCollection();

        foreach ($collection as $translation) {
            $this->addTranslation($translation);
        }
    }

    /**
     * Return transaltions with  not blank content.
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function filterNotBlankTranslations()
    {
        return $this->getTranslations()->filter(function (TranslationInterface $translation) {
            $content = $translation->getContent();
            return !empty($content);
        });
    }

    /**
     * Return false if at least one translation without content.
     *
     * @return bool
     */
    public function validForBlankTranslations()
    {
        foreach ($this->getTranslations() as $translation) {
            if (empty($translation->getContent())) {
                return false;
            }
        }

        return true;
    }

    /**
     * Get createdAt
     *
     * @return datetime $createdAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Get updatedAt
     *
     * @return datetime $updatedAt
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}


text:
// Copyright 2010-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include <stddef.h>

/**
 * @brief Enable early entropy source for RNG
 *
 * Uses the SAR ADC to feed entropy into the HWRNG. The ADC is put
 * into a test mode that reads the 1.1V internal reference source and
 * feeds the LSB of data into the HWRNG.
 *
 * Can also be used from app code early during operation, if entropy
 * is required before WiFi stack is initialised. Call this function
 * from app code only if WiFi/BT are not yet enabled and I2S and SAR
 * ADC are not in use.
 *
 * Call bootloader_random_disable() when done.
 */
void bootloader_random_enable(void);

/**
 * @brief Disable early entropy source for RNG
 *
 * Disables SAR ADC source and resets the I2S hardware.
 *
 */
void bootloader_random_disable(void);

/**
 * @brief Fill buffer with 'length' random bytes
 *
 * @param buffer Pointer to buffer
 * @param length This many bytes of random data will be copied to buffer
 */
void bootloader_fill_random(void *buffer, size_t length);


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index — cage 0.1a1 documentation</title>
    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="#" />
    <link rel="search" title="Search" href="search.html" />

  <link rel="stylesheet" href="_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Index

 A
 | B
 | C
 | D
 | E
 | F
 | G
 | I
 | L
 | N
 | O
 | P
 | R
 | S
 | T
 | U
 | V

A

add_dock() (cage.core.OccupiedCage method)

add_site() (cage.core.Facet method)

add_structure() (cage.study.Study method)

add_task() (cage.study.Study method)

analyze_cation_energies() (cage.landscape.LandscapeAnalyzer method)

angle_between() (in module cage.landscape)

(in module cage.utils)

angle_to_normal() (cage.core.Facet method)

anion_center (cage.core.Cage attribute)

append() (cage.core.Cage method)

as_dict() (cage.core.Facet method)

(cage.landscape.Landscape method)

(cage.landscape.LandscapeAnalyzer method)

B

barrier (cage.path.Path attribute)

barrier_analysis() (in module cage.cli.commands.analyze)

C

Cage (class in cage.core)

cage (module), [1]

cage.cli (module)

cage.cli.commands (module)

cage.cli.commands.analyze (module)

cage.cli.commands.setup (module)

cage.cli.commands.util (module)

cage.core (module)

cage.landscape (module)

cage.path (module)

cage.study (module)

cage.tests (module)

cage.tests.test_landscape (module)

cage.utils (module)

CATIONS (cage.core.OccupiedCage attribute)

center (cage.core.Facet attribute)

(cage.landscape.Landscape attribute)

center() (cage.core.Cage method)

(cage.core.OccupiedCage method)

chainsetup() (in module cage.cli.commands.setup)

change_center() (cage.landscape.Landscape method)

change_software() (cage.study.Study method)

check_calculation() (in module cage.cli.commands.util)

classify_by_composition() (in module cage.study)

copy() (cage.core.Cage method)

(cage.core.Facet method)

coulomb_potential() (in module cage.cli.commands.analyze)

create_sphere() (cage.landscape.Landscape class method)

D

data (cage.landscape.LandscapeAnalyzer attribute)

datapoints (cage.landscape.LandscapeAnalyzer attribute)

distance() (in module cage.utils)

docks (cage.core.OccupiedCage attribute)

docksetup() (in module cage.cli.commands.setup)

E

energies (cage.path.Path attribute)

energy() (in module cage.cli.commands.util)

extend_by_rotation() (cage.landscape.Landscape method)

extend_by_translation() (cage.landscape.Landscape method)

extend_from_point() (cage.landscape.Landscape method)

F

Facet (class in cage.core)

facets (cage.core.Cage attribute)

(cage.core.OccupiedCage attribute)

find_closest_facet() (cage.core.Cage method)

find_constraints() (in module cage.cli.commands.setup)

find_facet_links() (cage.core.Cage method)

find_farthest_facet() (cage.core.Cage method)

find_noneq_chain_links() (cage.core.Cage method)

find_noneq_facet_chain() (cage.core.Cage method)

find_noneq_facets() (cage.core.Cage method)

find_surface_facets() (cage.core.Cage method)

(cage.core.OccupiedCage method)

flip() (cage.path.Path method)

flip_coordinates() (cage.landscape.LandscapeAnalyzer method)

flip_normal() (cage.core.Facet method)

from_cage_and_facets() (cage.core.OccupiedCage class method)

from_data() (cage.landscape.LandscapeAnalyzer class method)

from_dict() (cage.core.Facet class method)

(cage.landscape.LandscapeAnalyzer class method)

from_file() (cage.core.Facet class method)

(cage.landscape.Landscape class method)

(cage.landscape.LandscapeAnalyzer class method)

(cage.path.Path class method)

from_molecule() (cage.core.Cage class method)

from_poscar() (cage.core.Cage class method)

(cage.core.OccupiedCage class method)

from_str() (cage.core.Facet class method)

from_string() (cage.landscape.LandscapeAnalyzer class method)

from_vertices() (cage.landscape.Landscape class method)

G

gather_landscape() (in module cage.cli.commands.util)

geo() (in module cage.cli.commands.util)

get_distance() (cage.core.Facet method)

get_normal_intersection() (cage.core.Facet method)

I

insert() (cage.core.Cage method)

is_equivalent() (cage.core.Facet method)

L

Landscape (class in cage.landscape)

landscape_analysis() (in module cage.cli.commands.analyze)

LandscapeAnalyzer (class in cage.landscape)

N

nebsetup() (in module cage.cli.commands.setup)

normal (cage.core.Facet attribute)

O

OccupiedCage (class in cage.core)

optimize() (in module cage.cli.commands.setup)

P

Path (class in cage.path)

pathsetup() (in module cage.cli.commands.setup)

perpendicular_part() (in module cage.landscape)

plot_energies() (cage.landscape.LandscapeAnalyzer method)

(cage.path.Path method)

plot_images() (in module cage.cli.commands.setup)

plot_landscape() (in module cage.cli.commands.analyze)

pointgroup (cage.core.Cage attribute)

points (cage.landscape.Landscape attribute)

process_output() (in module cage.cli.commands.util)

R

reconstruct_chain() (in module cage.cli.commands.analyze)

redefine_origin() (cage.core.Cage method)

(cage.core.Facet method)

reference() (in module cage.cli.commands.analyze)

(in module cage.cli.commands.setup)

remove_surface_facet() (cage.core.OccupiedCage method)

rotation_matrix() (in module cage.landscape)

S

schoenflies_to_hm() (in module cage.utils)

search_and_reboot() (in module cage.cli.commands.util)

set_energies() (cage.path.Path method)

set_up_edge_landscape() (in module cage.cli.commands.setup)

set_up_facet_list() (cage.core.Cage method)

set_up_input() (cage.study.Study method)

set_up_lattice() (in module cage.cli.commands.setup)

set_up_molecules() (in module cage.cli.commands.setup)

set_up_neb() (cage.path.Path method)

site_center() (in module cage.utils)

site_collections (cage.path.Path attribute)

sites (cage.core.Facet attribute)

software (cage.landscape.LandscapeAnalyzer attribute)

(cage.study.Study attribute)

sphere_analysis() (in module cage.cli.commands.analyze)

spheresetup() (in module cage.cli.commands.setup)

structures (cage.study.Study attribute)

Study (class in cage.study)

symmops (cage.core.Cage attribute)

T

tasks (cage.study.Study attribute)

Test_LandscapeAnalyzer() (in module cage.tests.test_landscape)

to() (cage.core.Facet method)

(cage.landscape.LandscapeAnalyzer method)

to_poscar() (cage.core.Cage method)

twocat_chainsetup() (in module cage.cli.commands.setup)

U

unit_vector() (in module cage.landscape)

(in module cage.utils)

V

visualize_facets() (cage.core.Cage method)

(in module cage.cli.commands.util)

cage

Navigation

Contents:

Introduction

Tutorial

Related Topics

Documentation overview

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2017, Marnik Bercx.

      |
      Powered by Sphinx 1.8.2
      & Alabaster 0.7.12


text:
package org.apache.karaf.cave.deployer.service.command;

import org.apache.karaf.cave.deployer.DeployerService;
import org.apache.karaf.cave.deployer.service.command.completers.ConnectionCompleter;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;

@Service
@Command(scope = "cave", name = "deployer-bundle-install", description = "Install a bundle on a remote instance")
public class BundleInstallCommand implements Action {

    @Reference
    private DeployerService deployer;

    @Argument(index = 0, name = "The connection to use", required = true, multiValued = false)
    @Completion(ConnectionCompleter.class)
    String connection;

    @Argument(index = 1, name = "The URL of the bundle to deploy", required = true, multiValued = false)
    String bundle;

    @Override
    public Object execute() throws Exception {
        deployer.installBundle(bundle, connection);
        return null;
    }
}


text:
package org.zstack.test.lb;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.query.QueryOp;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.network.service.lb.*;
import org.zstack.network.service.vip.VipInventory;
import org.zstack.network.service.vip.VipVO;
import org.zstack.network.service.virtualrouter.APIQueryVirtualRouterVmMsg;
import org.zstack.network.service.virtualrouter.APIQueryVirtualRouterVmReply;
import org.zstack.network.service.virtualrouter.VirtualRouterConstant;
import org.zstack.network.service.virtualrouter.lb.VirtualRouterLoadBalancerBackend.LbTO;
import org.zstack.network.service.virtualrouter.lb.VirtualRouterLoadBalancerBackend.RefreshLbCmd;
import org.zstack.simulator.appliancevm.ApplianceVmSimulatorConfig;
import org.zstack.simulator.virtualrouter.VirtualRouterSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;

/**
 * @author frank
 *

 *         1. create a lb
 *

 *         confirm lb are created successfully
 *

 *         2. delete the lb
 *

 *         confirm all related resources deleted
 *

 *         3. create a new lb
 *

 *         confirm the vip is locked
 *

 *         4. delete the new lb
 *

 *         confirm the vip is unlocked
 *

 *         5. query the vr
 *

 *         confirm the result is right
 */
public class TestVirtualRouterLb {
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;
    VirtualRouterSimulatorConfig vconfig;
    ApplianceVmSimulatorConfig aconfig;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/lb/TestVirtualRouterLb.xml", con);
        deployer.addSpringConfig("VirtualRouter.xml");
        deployer.addSpringConfig("VirtualRouterSimulator.xml");
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.addSpringConfig("vip.xml");
        deployer.addSpringConfig("lb.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        vconfig = loader.getComponent(VirtualRouterSimulatorConfig.class);
        aconfig = loader.getComponent(ApplianceVmSimulatorConfig.class);
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
        session = api.loginAsAdmin();
    }

    @Test
    public void test() throws ApiSenderException {
        LoadBalancerInventory lb = deployer.loadBalancers.get("lb");
        LoadBalancerVO lbvo = dbf.findByUuid(lb.getUuid(), LoadBalancerVO.class);
        Assert.assertNotNull(lbvo);
        Assert.assertNotNull(lbvo.getProviderType());
        Assert.assertFalse(lbvo.getListeners().isEmpty());
        Assert.assertFalse(lbvo.getListeners().iterator().next().getVmNicRefs().isEmpty());

        VipVO vip = dbf.findByUuid(lbvo.getVipUuid(), VipVO.class);
        Assert.assertNotNull(vip);
        Assert.assertEquals(LoadBalancerConstants.LB_NETWORK_SERVICE_TYPE_STRING, vip.getUseFor());
        Assert.assertEquals(VirtualRouterConstant.VIRTUAL_ROUTER_PROVIDER_TYPE, vip.getServiceProvider());
        Assert.assertFalse(vconfig.vips.isEmpty());

        Assert.assertFalse(vconfig.refreshLbCmds.isEmpty());
        RefreshLbCmd cmd = vconfig.refreshLbCmds.get(0);
        Assert.assertFalse(cmd.getLbs().isEmpty());
        LbTO to = cmd.getLbs().get(0);
        LoadBalancerListenerVO l = lbvo.getListeners().iterator().next();
        Assert.assertEquals(l.getProtocol(), to.getMode());
        Assert.assertEquals(l.getInstancePort(), to.getInstancePort());
        Assert.assertEquals(l.getLoadBalancerPort(), to.getLoadBalancerPort());

        Assert.assertEquals(vip.getIp(), to.getVip());

        L3NetworkInventory gnw = deployer.l3Networks.get("GuestNetwork");
        VmInstanceInventory vm = deployer.vms.get("TestVm");
        VmNicInventory nic = vm.findNic(gnw.getUuid());
        Assert.assertFalse(to.getNicIps().isEmpty());
        String nicIp = to.getNicIps().get(0);
        Assert.assertEquals(nic.getIp(), nicIp);

        api.deleteLoadBalancer(lb.getUuid(), null);
        Assert.assertEquals(0, dbf.count(LoadBalancerVO.class));
        Assert.assertEquals(0, dbf.count(LoadBalancerListenerVO.class));
        Assert.assertEquals(0, dbf.count(LoadBalancerListenerVmNicRefVO.class));
        vip = dbf.findByUuid(lbvo.getVipUuid(), VipVO.class);
        Assert.assertNull(vip.getUseFor());

        L3NetworkInventory pubNw = deployer.l3Networks.get("PublicNetwork");
        VipInventory vip1 = api.acquireIp(pubNw.getUuid());
        LoadBalancerInventory lb2 = api.createLoadBalancer("lb2", vip1.getUuid(), null, null);
        VipVO vip1vo = dbf.findByUuid(vip1.getUuid(), VipVO.class);
        Assert.assertEquals(LoadBalancerConstants.LB_NETWORK_SERVICE_TYPE_STRING, vip1vo.getUseFor());

        api.deleteLoadBalancer(lb2.getUuid(), null);
        vip1vo = dbf.findByUuid(vip1.getUuid(), VipVO.class);
        Assert.assertNull(vip1vo.getUseFor());
        Assert.assertFalse(dbf.isExist(lb2.getUuid(), LoadBalancerVO.class));

        APIQueryVirtualRouterVmMsg msg = new APIQueryVirtualRouterVmMsg();
        msg.addQueryCondition("__systemTag__", QueryOp.EQ, "role::LoadBalancer");
        APIQueryVirtualRouterVmReply r = api.query(msg, APIQueryVirtualRouterVmReply.class);
        Assert.assertEquals(1, r.getInventories().size());
    }
}


text:
// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import ParseTreeTransformer from 'ParseTreeTransformer.js';
import {
  ArrayPattern,
  BindingElement,
  BindingIdentifier,
  FormalParameterList,
  ObjectPattern,
  ObjectPatternField,
  RestParameter,
  SpreadPatternElement
} from '../syntax/trees/ParseTrees.js';
import EQUAL from '../syntax/TokenType.js';
import {
  IDENTIFIER_EXPRESSION,
  SPREAD_PATTERN_ELEMENT
} from '../syntax/trees/ParseTreeType.js';

/**
 * @fileoverview This transformer is used by the parser to transform a
 * CoverFormals tree into a FormalParameterList tree.
 */

/**
 * Error class used to signal that the transformation to a valid
 * FormalParameterList cannot be done.
 */
export class CoverFormalsTransformerError extends Error {}

export class CoverFormalsTransformer extends ParseTreeTransformer {
  constructor() {
    this.isValid = true;
    this.inArrayPattern_ = false;
  }

  transformCoverFormals(tree) {
    var expressions = this.transformList(tree.expressions);
    return new FormalParameterList(tree.location, expressions);
  }

  transformIdentifierExpression(tree) {
    return new BindingElement(tree.location,
        new BindingIdentifier(tree.location, tree.identifierToken),
        null);
  }

  transformBinaryOperator(tree) {
    if (tree.operator.type !== EQUAL)
      throw new CoverFormalsTransformerError();

    var bindingElement = this.transformAny(tree.left);
    return new BindingElement(tree.location,
                              bindingElement.binding,
                              tree.right);
  }

  transformArrayLiteralExpression(tree) {
    // We need to distinguish '...' at top level vs inside array patterns.
    var wasInArrayPattern = this.inArrayPattern_;
    this.inArrayPattern_ = true;
    var elements = this.transformList(tree.elements);
    this.inArrayPattern_ = wasInArrayPattern;

    // In expression context '...' can occur in any array position, but in
    // patterns it can only occur in last position.
    var okIndex = elements.length - 1;
    for (var i = 0; i < okIndex; i++) {
      if (elements[i].type === SPREAD_PATTERN_ELEMENT)
        throw new CoverFormalsTransformerError();
    }

    return new BindingElement(tree.location,
                              new ArrayPattern(tree.location, elements),
                              null);
  }

  transformObjectLiteralExpression(tree) {
    var propertyNameAndValues = this.transformList(tree.propertyNameAndValues);

    return new BindingElement(tree.location,
        new ObjectPattern(tree.location, propertyNameAndValues), null);
  }

  transformPropertyNameAssignment(tree) {
    // TODO(arv) name is currently just a token but that will change with
    // [names].
    return new ObjectPatternField(tree.location, tree.name,
                                  this.transformAny(tree.value));
  }

  transformPropertyNameShorthand(tree) {
    return new BindingElement(tree.location,
                              new BindingIdentifier(tree.location, tree.name),
                              null);
  }

  transformSpreadExpression(tree) {
    // These only happens inside array patterns.
    if (tree.expression.type !== IDENTIFIER_EXPRESSION)
      throw new CoverFormalsTransformerError();

    var bindingIdentifier =
        new BindingIdentifier(tree.expression.location,
                              tree.expression.identifierToken);

    if (this.inArrayPattern_)
      return new SpreadPatternElement(tree.location, bindingIdentifier);
    return new RestParameter(tree.location, bindingIdentifier);
  }

  transformMissingPrimaryExpression(tree) {
    throw new AssignmentPatternTransformerError();
  }
}


text:
package com.conmigo.app;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurer;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.security.AuthenticationNameUserIdSource;

/**
 * Created by Mohamed on 5/29/2014
 */
@Configuration
@EnableSocial
public class SocialConfig implements SocialConfigurer {

	@Autowired
	private DataSource dataSource;

	@Autowired
	private ConnectionSignUp customConnection;

	@Override
	public void addConnectionFactories( final ConnectionFactoryConfigurer connectionFactoryConfigurer, final Environment environment ) {
	}

	@Override
	public UserIdSource getUserIdSource() {
		return new AuthenticationNameUserIdSource();
	}

	@Override
	public UsersConnectionRepository getUsersConnectionRepository( final ConnectionFactoryLocator connectionFactoryLocator ) {
		JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository( dataSource, connectionFactoryLocator, Encryptors.noOpText() );
		repository.setConnectionSignUp( customConnection );
		return repository;
	}
}


text:
using System;

using Internal.TypeSystem;

using Debug = System.Diagnostics.Debug;

namespace Internal.IL.Stubs
{
    /// <summary>
    /// Provides method bodies for generic System.Runtime.CompilerServices.Unsafe intrinsics.
    /// </summary>
    public static class UnsafeIntrinsics
    {
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(((MetadataType)method.OwningType).Name == "Unsafe");

            switch (method.Name)
            {
                case "AsPointer":
                    return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldarg_0, (byte)ILOpcode.conv_u, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
                case "SizeOf":
                    return EmitSizeOf(method);
                case "As":
                    return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldarg_0, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
                case "AddByteOffset":
                    return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldarg_0, (byte)ILOpcode.ldarg_1, (byte)ILOpcode.add, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
            }

            return null;
        }

        private static MethodIL EmitSizeOf(MethodDesc method)
        {
            Debug.Assert(method.Signature.IsStatic && method.Signature.Length == 0);

            TypeSystemContext context = method.Context;

            ILEmitter emit = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();
            codeStream.Emit(ILOpcode.sizeof_, emit.NewToken(context.GetSignatureVariable(0, method: true)));
            codeStream.Emit(ILOpcode.ret);
            return emit.Link(method);
        }
    }
}


text:
import fs from 'fs';
import JPEG from './image/jpeg';
import PNG from './image/png';

class PDFImage {
  static open(src, label) {
    let data;
    if (Buffer.isBuffer(src)) {
      data = src;
    } else if (src instanceof ArrayBuffer) {
      data = Buffer.from(new Uint8Array(src));
    } else {
      let match = /^data:.+;base64,(.*)$/.exec(src);
      if (match) {
        data = Buffer.from(match[1], 'base64');
      } else if (!BROWSER) {
        data = fs.readFileSync(src);
        if (!data) return;
      }
    }

    if (data[0] === 0xff && data[1] === 0xd8) {
      return new JPEG(data, label);
    }

    if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') {
      return new PNG(data, label);
    }

    throw new Error('Unknown image format.');
  }
}

export default PDFImage;


text:
<?php

class Profile_M extends MY_Model{
	protected $_table_name = 'profiles';
	protected $_primary_key = 'idProfile';
	protected $_order_by = 'profile';
	public $rules = array(
		'profile' => array(
			'field' => 'profile',
			'label' => 'Profile',
			'rules' => 'trim|required|alpha'
		),
		'description' => array(
			'field' => 'description',
			'label' => 'Description',
			'rules' => 'trim|required|alpha'
		)
	);

	function __construct(){
		parent::__construct();
	}

	public function get_new(){
		$profile = new stdClass();
		$profile->profile = '';
		$profile->description = '';
		return $profile;
	}

	public function delete ($id)
	{
		// Delete a page
		parent::delete($id);
	}
}


text:
import Path from 'path'
import uuid from 'uuid/v1'

//
// ACTION TYPES
//
const EDIT = "EDIT"
const APP_ADD = "APP_ADD"
const APP_REMOVE = "APP_REMOVE"
const EXTENSIONS_OPEN_WITH_ADD = "EXTENSIONS_OPEN_WITH_ADD"
const EXTENSIONS_OPEN_WITH_REMOVE = "EXTENSIONS_OPEN_WITH_REMOVE"
const PATH_OPEN_WITH_ADD = "PATH_OPEN_WITH_ADD"
const PATH_OPEN_WITH_REMOVE = "PATH_OPEN_WITH_REMOVE"
//
// REDUCER
//

const initialState = {
    showHidden: false,
    theme: 'dark',
    apps: [],
    extensionsOpenWith: [],
    pathsOpenWith: []
};

export default function counter(state = initialState, action = {}) {
    switch (action.type) {
        case EDIT: {
            return {
                ...initialState,
                ...state,
                ...action.properties
            }
        }
        case APP_ADD: {
            let apps = state.apps;
            if (action.appPath && apps.filter(app => app.path === action.appPath).length === 0) {
                apps.push({
                    id: uuid(),
                    path: action.appPath,
                    name: Path.basename(action.appPath)
                })
            }
            return {
                ...initialState,
                ...state,
                apps: apps
            }
        }
        case APP_REMOVE: {
            let apps = state.apps.filter(app => app.id !== action.id);
            return {
                ...initialState,
                ...state,
                apps: apps
            }
        }
        case EXTENSIONS_OPEN_WITH_ADD: {
            let extensionsOpenWith = state.extensionsOpenWith;
            if (action.extension && extensionsOpenWith.filter(x => x.extension === action.extension.extension).length === 0) {
                extensionsOpenWith.push({
                    id: uuid(),
                    extension: action.extension.extension,
                    appId: action.extension.appId
                })
            }
            return {
                ...initialState,
                ...state,
                extensionsOpenWith: extensionsOpenWith
            }
        }
        case EXTENSIONS_OPEN_WITH_REMOVE: {
            let extensionsOpenWith = state.extensionsOpenWith.filter(ext => ext.id !== action.id);
            return {
                ...initialState,
                ...state,
                extensionsOpenWith: extensionsOpenWith
            }
        }
        case PATH_OPEN_WITH_ADD: {
            let pathsOpenWith = state.pathsOpenWith;
            if (action.path && pathsOpenWith.filter(p => p.path === action.path.path).length === 0) {
                pathsOpenWith.push({
                    id: uuid(),
                    path: action.path.path,
                    appId: action.path.appId
                })
            }
            return {
                ...initialState,
                ...state,
                pathsOpenWith: pathsOpenWith
            }
        }
        case PATH_OPEN_WITH_REMOVE: {
            let pathsOpenWith = state.pathsOpenWith.filter(p => p.id !== action.id);
            return {
                ...initialState,
                ...state,
                pathsOpenWith: pathsOpenWith
            }
        }
        default:
            return state;
    }
}

//
// ACTIONS
//

export function update(properties) {
    return {
        type: EDIT,
        properties: properties
    }
}

export function appAdd(appPath) {
    return {
        type: APP_ADD,
        appPath: appPath
    }
}

export function appRemove(appId) {
    return {
        type: APP_REMOVE,
        id: appId
    }
}

export function extensionsOpenWithAdd(extension) {
    return {
        type: EXTENSIONS_OPEN_WITH_ADD,
        extension: extension
    }
}

export function extensionsOpenWithRemove(extId) {
    return {
        type: EXTENSIONS_OPEN_WITH_REMOVE,
        id: extId
    }
}

export function pathsOpenWithAdd(path) {
    return {
        type: PATH_OPEN_WITH_ADD,
        path: path
    }
}

export function pathsOpenWithRemove(pathId) {
    return {
        type: PATH_OPEN_WITH_REMOVE,
        id: pathId
    }
}


text:
{-# LANGUAGE FlexibleInstances #-}

module Geordi.Param ( Param (..) ) where
import qualified Data.Text.Lazy as T

readMay :: Read a => String -> Maybe a
readMay s = case [x | (x,t) <- reads s, ("","") <- lex t] of
               [x] -> Just x
               _ -> Nothing

class Param a where
  render :: a -> T.Text
  parse  :: T.Text -> Maybe a

instance Param T.Text where
  render = id
  parse = Just

instance Param Int where
  render = T.pack . show
  parse  = readMay . T.unpack

instance Param Bool where
  render = T.pack . show
  parse  = readMay . T.unpack

instance Param [Char] where
  render = T.pack
  parse  = Just . T.unpack


text:
--------------------------------
--  Adds a SpriteFrame to a Animation.

-- The frame will be added with one "delay unit".
-- @function [parent=#Animation] addSpriteFrame
-- @param self
-- @param #cc.SpriteFrame frame

--------------------------------
--  Sets whether to restore the original frame when animation finishes
-- @function [parent=#Animation] setRestoreOriginalFrame
-- @param self
-- @param #bool restoreOriginalFrame

--------------------------------
--
-- @function [parent=#Animation] clone
-- @param self
-- @return Animation#Animation ret (return value: cc.Animation)

--------------------------------
--  Gets the duration in seconds of the whole animation. It is the result of totalDelayUnits * delayPerUnit
-- @function [parent=#Animation] getDuration
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
--  Sets the array of AnimationFrames
-- @function [parent=#Animation] setFrames
-- @param self
-- @param #array_table frames

--------------------------------
--  Gets the array of AnimationFrames
-- @function [parent=#Animation] getFrames
-- @param self
-- @return array_table#array_table ret (return value: array_table)

--------------------------------
--  Sets the times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ...
-- @function [parent=#Animation] setLoops
-- @param self
-- @param #unsigned int loops

--------------------------------
--  Sets the delay in seconds of the "delay unit"
-- @function [parent=#Animation] setDelayPerUnit
-- @param self
-- @param #float delayPerUnit

--------------------------------
--  Adds a frame with an image filename. Internally it will create a SpriteFrame and it will add it.

-- The frame will be added with one "delay unit".

-- Added to facilitate the migration from v0.8 to v0.9.
-- @function [parent=#Animation] addSpriteFrameWithFile
-- @param self
-- @param #string filename

--------------------------------
--  Gets the total Delay units of the Animation.
-- @function [parent=#Animation] getTotalDelayUnits
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
--  Gets the delay in seconds of the "delay unit"
-- @function [parent=#Animation] getDelayPerUnit
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
--  Checks whether to restore the original frame when animation finishes.
-- @function [parent=#Animation] getRestoreOriginalFrame
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
--  Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it.

-- The frame will be added with one "delay unit".

-- Added to facilitate the migration from v0.8 to v0.9.
-- @function [parent=#Animation] addSpriteFrameWithTexture
-- @param self
-- @param #cc.Texture2D pobTexture
-- @param #rect_table rect

--------------------------------
-- @overload self, array_table, float, unsigned int
-- @overload self
-- @function [parent=#Animation] create
-- @param self
-- @param #array_table arrayOfAnimationFrameNames
-- @param #float delayPerUnit
-- @param #unsigned int loops
-- @return Animation#Animation ret (return value: cc.Animation)

--------------------------------
--
-- @function [parent=#Animation] createWithSpriteFrames
-- @param self
-- @param #array_table arrayOfSpriteFrameNames
-- @param #float delay
-- @param #unsigned int loops
-- @return Animation#Animation ret (return value: cc.Animation)

return nil


text:
using UnityEditor;
using UnityEngine;
using PrimitivePlus;
using System.Collections;
using System.Collections.Generic;

namespace PrimitivePlusEditor
{
	[CustomEditor(typeof(PrimitivePlusMaterial)), CanEditMultipleObjects]
	public class PrimitivePlusMaterialEditor : Editor
	{

		private void OnDisable()
		{
			Resources.UnloadUnusedAssets();
		}

		public override void OnInspectorGUI ()
		{
			GameObject[] gameObjects = Selection.gameObjects;
			List<PrimitivePlusMaterial> materials = new List<PrimitivePlusMaterial>();
			Material material = gameObjects[0].GetComponent<MeshRenderer>().sharedMaterial;

			for(int i = 0; i < gameObjects.Length; i++)
			{
				if(gameObjects[i].GetComponent<PrimitivePlusMaterial>() != null)
					materials.Add(gameObjects[i].GetComponent<PrimitivePlusMaterial>());
			}

			GUILayout.Space(10);
			GUILayout.BeginHorizontal();
			GUILayout.Space(10);
			if(materials.Count > 1 && GUILayout.Button("Share Materials", EditorStyles.miniButtonLeft))
			{
				for(int i = 0; i < materials.Count; i++)
				{
					materials[i].SetSharedMaterial(material);
				}
			}
			GUIStyle buttonStyle = (materials.Count > 1) ? EditorStyles.miniButtonRight : EditorStyles.miniButton;
			if(GUILayout.Button("New Material", buttonStyle))
			{
				for(int i = 0; i < materials.Count; i++)
				{
					materials[i].SetNewMaterial();
				}
			}
			GUILayout.Space(15);
			GUILayout.EndHorizontal();

			GUILayout.Space(10);
			GUILayout.BeginHorizontal();
			GUILayout.Space(10);
			if(GUILayout.Button("Save Material", buttonStyle))
			{
				for(int i = 0; i < materials.Count; i++)
				{
					materials[i].SetSharedMaterial(material);
				}
				string folderPath = PrimitivePlusConstants.PRIMITIVE_PLUS_RESOURCES + PrimitivePlusConstants.PRIMITIVE_PLUS_MATERIALS;

				if(!System.IO.Directory.Exists(folderPath))
				{
					System.IO.Directory.CreateDirectory(folderPath);
				}

				string newMaterialPath = AssetDatabase.GenerateUniqueAssetPath(folderPath + "NewPrimitivePlusMaterial.asset");
				AssetDatabase.CreateAsset(material, newMaterialPath);
				AssetDatabase.SaveAssets();
				AssetDatabase.Refresh();
			}
			GUILayout.Space(15);
			GUILayout.EndHorizontal();
			GUILayout.Space(10);

			GUILayout.BeginHorizontal();
			EditorGUILayout.HelpBox("NOTE: If you do not save the material, your prefab will lose the material and become magenta!", MessageType.Warning);
			GUILayout.Space(10);
			GUILayout.EndHorizontal();
		}
	}
}


text:
package org.kuali.rice.ksb.impl.registry;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.ojb.broker.PersistenceBroker;
import org.apache.ojb.broker.query.Criteria;
import org.apache.ojb.broker.query.QueryByCriteria;
import org.kuali.rice.ksb.api.registry.ServiceEndpointStatus;
import org.springmodules.orm.ojb.PersistenceBrokerCallback;
import org.springmodules.orm.ojb.support.PersistenceBrokerDaoSupport;

/**
 * An OJB dao implementation of the {@link ServiceRegistryDao}.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
public class ServiceRegistryDaoOjb extends PersistenceBrokerDaoSupport implements ServiceRegistryDao {

	@Override
	public ServiceInfoBo getServiceInfo(String serviceId) {
		Criteria crit = new Criteria();
		crit.addEqualTo("serviceId", serviceId);
		return (ServiceInfoBo)getPersistenceBrokerTemplate().getObjectByQuery(new QueryByCriteria(ServiceInfoBo.class, crit));
	}

	@Override
	public List<ServiceInfoBo> getOnlineServiceInfosByName(QName serviceName) {
		Criteria crit = new Criteria();
		crit.addEqualTo("serviceName", serviceName.toString());
		crit.addEqualTo("statusCode", ServiceEndpointStatus.ONLINE.getCode());
		return (List<ServiceInfoBo>)getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(ServiceInfoBo.class, crit));
	}

	@Override
	public List<ServiceInfoBo> getAllOnlineServiceInfos() {
		Criteria crit = new Criteria();
		crit.addEqualTo("statusCode", ServiceEndpointStatus.ONLINE.getCode());
		return (List<ServiceInfoBo>)getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(ServiceInfoBo.class, crit));
	}

	@Override
	public List<ServiceInfoBo> getAllServiceInfos() {
		Criteria crit = new Criteria();
		return (List<ServiceInfoBo>)getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(ServiceInfoBo.class, crit));
	}

	@Override
	public List<ServiceInfoBo> getAllServiceInfosForInstance(String instanceId) {
		Criteria crit = new Criteria();
		crit.addEqualTo("instanceId", instanceId);
		return (List<ServiceInfoBo>)getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(ServiceInfoBo.class, crit));
	}

	@Override
	public ServiceDescriptorBo getServiceDescriptor(String serviceDescriptorId) {
		Criteria crit = new Criteria();
		crit.addEqualTo("id", serviceDescriptorId);
		return (ServiceDescriptorBo)getPersistenceBrokerTemplate().getObjectByQuery(new QueryByCriteria(ServiceDescriptorBo.class, crit));
	}

	@Override
	public ServiceDescriptorBo saveServiceDescriptor(ServiceDescriptorBo serviceDescriptor) {
		getPersistenceBrokerTemplate().store(serviceDescriptor);
		return serviceDescriptor;
	}

	@Override
	public ServiceInfoBo saveServiceInfo(ServiceInfoBo serviceInfo) {
		getPersistenceBrokerTemplate().store(serviceInfo);
		return serviceInfo;
	}

	@Override
	public void removeServiceInfo(String serviceId) {
		Criteria crit = new Criteria();
		crit.addEqualTo("serviceId", serviceId);
		getPersistenceBrokerTemplate().deleteByQuery(new QueryByCriteria(ServiceInfoBo.class, crit));
	}

	@Override
	public void removeServiceDescriptor(String serviceDescriptorId) {
		Criteria crit = new Criteria();
		crit.addEqualTo("id", serviceDescriptorId);
		getPersistenceBrokerTemplate().deleteByQuery(new QueryByCriteria(ServiceDescriptorBo.class, crit));
	}

	@Override
	public boolean updateStatus(String serviceId, String statusCode) {
		ServiceInfoBo serviceInfoBo = getServiceInfo(serviceId);
		if (serviceInfoBo == null) {
			return false;
		}
		serviceInfoBo.setStatusCode(statusCode);
		saveServiceInfo(serviceInfoBo);
		return true;
	}

	private static final String UPDATE_STATUS_FOR_INSTANCE_ID = "update KRSB_SVC_DEF_T set STAT_CD=? where INSTN_ID=?";
	@Override
	public void updateStatusForInstanceId(final String instanceId, final String statusCode) {
		getPersistenceBrokerTemplate().execute(new PersistenceBrokerCallback() {
			@Override
			public Object doInPersistenceBroker(PersistenceBroker broker) {
				PreparedStatement preparedStatement = null;
				try {
					Connection connection = broker.serviceConnectionManager().getConnection();
					preparedStatement = connection.prepareStatement(UPDATE_STATUS_FOR_INSTANCE_ID);
					preparedStatement.setString(1, statusCode);
					preparedStatement.setString(2, instanceId);
					preparedStatement.executeUpdate();
				} catch (Exception e) {
					throw new RuntimeException("Failed to update status for instance id", e);
				} finally {
					if (preparedStatement != null) {
						try {
							preparedStatement.close();
						} catch (SQLException e) {}
					}
				}
				return null;
			}
		});
	}

}


text: echo alias bump=./bump >> ~/.bash_profile


text:
package com.google.shipshape.util.rpc;

import java.io.IOException;

public class ServerException extends IOException {
  public ServerException() { super(); }
  public ServerException(String message) { super(message); }
  public ServerException(String message, Throwable cause) { super(message, cause); }
  public ServerException(Throwable cause) { super(cause); }
}


text:
using System;

namespace System.Management
{
	public class CompletedEventArgs : ManagementEventArgs
	{
		[MonoTODO]
		internal CompletedEventArgs ()
		{
		}

		public ManagementStatus Status
		{
			[MonoTODO]
			get {
				throw new NotImplementedException ();
			}
		}

		public ManagementBaseObject StatusObject
		{
			[MonoTODO]
			get {
				throw new NotImplementedException ();
			}
		}
	}
}


text:
void GenerateSamplePointSet_PointCloud_SubShape(
  cisstMesh &mesh,
  TestParameters &params,
  unsigned int randSeed, unsigned int &randSeqPos,
  std::ifstream &randnStream,
  vctDynamicVector<vct3> &samples,
  vctDynamicVector<vct3> &sampleNorms,
  vctDynamicVector<vct3> &noisySamples,
  unsigned int trialNum)
{
  // get custom params
  CustomTestParams_PointCloud_SubShape *pCustomParams =
    dynamic_cast<CustomTestParams_PointCloud_SubShape*>(params.pCustomTestParams);

  std::stringstream saveSamplesPath;
  std::stringstream saveNoisySamplesPath;
  std::stringstream saveNoiseCovPath;

  saveSamplesPath << params.outputCommonDir << "/SaveSamples_" << trialNum << ".pts";
  saveNoisySamplesPath << params.outputCommonDir << "/SaveNoisySamples_" << trialNum << ".pts";
  saveNoiseCovPath << params.outputCommonDir << "/SaveNoiseCov_" << trialNum << ".txt";

  std::string  strSaveSamplesPath = saveSamplesPath.str();
  std::string  strSaveNoisySamplesPath = saveNoisySamplesPath.str();
  std::string  strSaveNoiseCovPath = saveNoiseCovPath.str();

  std::string *pSaveSamplesPath = &strSaveSamplesPath;
  std::string *pSaveNoisySamplesPath = &strSaveNoisySamplesPath;
  std::string *pSaveNoiseCovPath = &strSaveNoiseCovPath;
#ifdef DISABLE_OUTPUT_FILES
  pSaveSamplesPath = NULL;
  pSaveNoisySamplesPath = NULL;
  pSaveNoiseCovPath = NULL;
#endif

  vctDynamicVector<unsigned int>  sampleDatums(params.nSamples);
  vctDynamicVector<vct3x3>        sampleCov(params.nSamples, vct3x3(0.0));
  vctDynamicVector<vct3x3>        noiseCov(params.nSamples, vct3x3(0.0));
  vctDynamicVector<vct3x3>        surfaceModelCov(params.nSamples, vct3x3(0.0));
  //vctDynamicVector<vct3x3>        noiseInvCov(params.nSamples, vct3x3(0.0));

  // Generate Samples
  GenerateSamples(
    mesh,
    randSeed, randSeqPos,
    params.nSamples,
    samples, sampleNorms, sampleDatums,
    pSaveSamplesPath);

  // Generate Sample Noise
  switch (pCustomParams->sampleNoise_Type)
  {
  case CustomTestParams_PointCloud_SubShape::NoiseSurface:
  {
    // generate covariances oriented to the surface
    ComputeCovariances_SurfaceModel(
      //pCustomParams->sampleNoise_InPlaneSD, pCustomParams->sampleNoise_PerpPlaneSD,
      pCustomParams->sampleNoise_EigValSqrt[1], pCustomParams->sampleNoise_EigValSqrt[0],
      samples, sampleNorms,
      noiseCov,
      pSaveNoiseCovPath);
    break;
  }
  case CustomTestParams_PointCloud_SubShape::NoiseGlobal:
  {
    // generate one global covariance for all samples
    vctDynamicVector<vct3x3> cov;
    ComputeCovariances_Random(
      randSeed, randSeqPos,
      pCustomParams->sampleNoise_EigValSqrt,
      cov, 1,
      pSaveNoiseCovPath);
    noiseCov.SetAll(cov(0));
    break;
  }
  case CustomTestParams_PointCloud_SubShape::NoiseRandom:
  {
    // generate different random covariance for each sample
    ComputeCovariances_Random(
      randSeed, randSeqPos,
      pCustomParams->sampleNoise_EigValSqrt,
      noiseCov, params.nSamples,
      pSaveNoiseCovPath);
    break;
  }
  default:
  {
    std::cout << "ERROR: unrecognized noise type" << std::endl;
    assert(0);
  }
  }

  // generate sample noise according to the defined covariance
  GenerateSampleErrors_Covariance(
    randnStream,
    noiseCov,
    samples, sampleNorms,
    noisySamples,
    pSaveNoisySamplesPath);

  // Set Samples in Algorithm
  switch (params.algType)
  {
  case TestParameters::StdICP:
  {
    // configure algorithm samples
    cisstAlgorithmICP_StdICP *pAlg = dynamic_cast<cisstAlgorithmICP_StdICP*>(params.pAlg);
    pAlg->SetSamples(noisySamples);
    break;
  }

  case TestParameters::IMLP:
  {
    std::stringstream saveSampleCovPath;
    std::stringstream saveSurfaceModelCovPath;
    saveSampleCovPath << params.outputDataDir << "/SaveSampleCov_" << trialNum << ".txt";
    saveSurfaceModelCovPath << params.outputDataDir << "/SaveSurfaceModelCov_" << trialNum << ".txt";

    std::string strSaveSampleCovPath = saveSampleCovPath.str();
    std::string strSaveSurfaceModelCovPath = saveSurfaceModelCovPath.str();

    std::string *pSaveSampleCovPath = &strSaveSampleCovPath;
    std::string *pSaveSurfaceModelCovPath = &strSaveSurfaceModelCovPath;
#ifdef MINIMIZE_OUTPUT_FILES
    pSaveSampleCovPath = NULL;
    pSaveSurfaceModelCovPath = NULL;
#endif
#ifdef DISABLE_OUTPUT_FILES
    pSaveSampleCovPath = NULL;
    pSaveSurfaceModelCovPath = NULL;
#endif

    unsigned int nSamps = samples.size();

    // Set Sample Covariances
    // noise covariance
    if (pCustomParams->bSampleCov_ApplyNoiseModel)
    {
      for (unsigned int i = 0; i < nSamps; i++)
      {
        sampleCov(i) += noiseCov(i);
      }
    }
    // surface model covariance
    if (pCustomParams->bSampleCov_ApplySurfaceModel)
    {
      // compute surface model
      ComputeCovariances_SurfaceModel(
        pCustomParams->surfaceModel_InPlaneSD, pCustomParams->surfaceModel_PerpPlaneSD,
        samples, sampleNorms,
        surfaceModelCov,
        pSaveSurfaceModelCovPath);
      // add suface model to sample covariances
      for (unsigned int i = 0; i < nSamps; i++)
      {
        sampleCov(i) += surfaceModelCov(i);
      }
    }
    // save sample covariances
    if (pSaveSampleCovPath)
    {
      WriteToFile_Cov(sampleCov, *pSaveSampleCovPath);
    }

    // configure algorithm samples
    cisstAlgorithmICP_IMLP *pAlg = dynamic_cast<cisstAlgorithmICP_IMLP*>(params.pAlg);
    //cisstAlgorithmICP_IMLP_PointCloud *pAlg = dynamic_cast<cisstAlgorithmICP_IMLP_PointCloud*>(params.pAlg);
    if (!pAlg)
    {
      std::cerr << "ERROR: algorithm class unrecognized class" << std::endl;
    }
    //pAlg->SetSamples(noisySamples);
    //pAlg->SetSampleCovariances(sampleCov);
    pAlg->SetSamples(noisySamples);
    pAlg->SetSampleCovariances(sampleCov, noiseCov);

    break;
  }

  case TestParameters::RobustICP:
  {
    // configure algorithm samples
    cisstAlgorithmICP_RobustICP *pAlg = dynamic_cast<cisstAlgorithmICP_RobustICP*>(params.pAlg);
    pAlg->SetSamples(noisySamples);
    break;
  }

  default:
    std::cout << std::endl << "=====> ERROR: Algorithm Type not Recognized by Sample Generator" << std::endl << std::endl;
    assert(0);
    break;
  } // switch AlgType
}

void SetOutputDir_SubShape(TestParameters &params, std::string outputCommonDir, std::string outputSubFolder)
{
  std::string outputSubDataDir = params.outputBaseDir + "/" + params.AlgorithmDescription;
  params.outputDataDir = outputSubDataDir + "/" + outputSubFolder;
  CreateDir(outputSubDataDir);

  std::string outputSubCommonDir = outputCommonDir + "_" + params.AlgorithmDescription;
  params.outputCommonDir = outputSubCommonDir + "/" + outputSubFolder;
  CreateDir(outputSubCommonDir);
  //params.outputCommonDir = outputCommonDir + "/" + outputSubFolder;
}

void Run_ParameterizedTest_PointCloud_SubShape(TestParameters params)
{
  std::stringstream ss;

  std::string loadSourceMeshPath = params.inputDir + "/" + params.sourceMeshFile;
  std::string loadTargetMeshPath = params.inputDir + "/" + params.targetMeshFile;
  std::string saveSourceMeshPath = params.outputCommonDir + "/SaveMeshSource";
  std::string saveTargetMeshPath = params.outputCommonDir + "/SaveMeshTarget";
  std::string saveNoisyTargetMeshPath = params.outputCommonDir + "/SaveMeshTargetNoisy";

  params.GenerateSamplesFunc = GenerateSamplePointSet_PointCloud_SubShape;
  CustomTestParams_PointCloud_SubShape &customParams
    = dynamic_cast<CustomTestParams_PointCloud_SubShape&> (*params.pCustomTestParams);

  // load target mesh
  cisstMesh mesh_target;
  CreateMesh(mesh_target, loadTargetMeshPath, &saveTargetMeshPath);

  // load source mesh
  //  NOTE: the sample point set is randomly generated from this mesh
  cisstMesh mesh_source;
  CreateMesh(mesh_source, loadSourceMeshPath, &saveSourceMeshPath);

  // generate noisy target mesh
  //  NOTE: the sample point set is registered to this mesh
  cisstMesh noisyTargetMesh;
  if (params.noiseMeshSD > 0.0)
  {
    std::cout << "ERROR: noisy mesh currently disabled" << std::endl;
    return;
    //std::string normRVFile = params.inputDir + "/GaussianValues.txt";
    //std::ifstream randnStream_MeshNoise(normRVFile.c_str());
    //GenerateNoisyMesh(mesh_target, noisyTargetMesh, randnStream_MeshNoise, params.noiseMeshSD, &saveNoisyTargetMeshPath);
  }
  else
  {
    noisyTargetMesh = mesh_target;
  }

  // build point cloud covariance tree from noisy mesh
  //  and define point cloud noise model (but don't add more noise)
  cisstCovTree_PointCloud   *pTree;
  int    nThresh = 5;       // Cov Tree Params
  double diagThresh = 5.0;  //  ''
  std::cout << "Building covariance tree .... " << std::endl;
  double targetModel_InPlaneSD = params.noiseMeshSD;
  double targetModel_PerpPlaneSD = params.noiseMeshSD;
  if (customParams.bTargetCov_ApplySurfaceModel)
  {
    targetModel_InPlaneSD += customParams.surfaceModel_InPlaneSD;
    targetModel_PerpPlaneSD += customParams.surfaceModel_PerpPlaneSD;
  }
  if (customParams.bTargetCov_DynamicSurfaceModel && customParams.bTargetCov_ApplySurfaceModel)
  {
    // set target surface noise model dynamically from mesh
    pTree = new cisstCovTree_PointCloud(noisyTargetMesh, nThresh, diagThresh, targetModel_PerpPlaneSD);
    std::cout << "Tree built: NNodes=" << pTree->NumNodes() << " NData=" << pTree->NumData()
      << " TreeDepth=" << pTree->TreeDepth() << std::endl;
    std::cout << " Point Cloud Noise Model:" << std::endl
      << "  perp-plane variance = " << pow(customParams.surfaceModel_PerpPlaneSD, 2) << std::endl
      << "  in-plane variance = " << pTree->avgVarInPlane << " (avg)" << std::endl;
    assert(pTree->NumNodes());
  }
  else
  {
    // set static target surface noise model
    pTree = new cisstCovTree_PointCloud(noisyTargetMesh, nThresh, diagThresh, targetModel_PerpPlaneSD, targetModel_InPlaneSD);
    std::cout << "Tree built: NNodes=" << pTree->NumNodes() << " NData=" << pTree->NumData()
      << " TreeDepth=" << pTree->TreeDepth() << std::endl;
    std::cout << " Point Cloud Noise Model:" << std::endl
      << "  perp-plane variance = " << pow(customParams.surfaceModel_PerpPlaneSD, 2) << std::endl
      << "  in-plane variance = " << pow(customParams.surfaceModel_InPlaneSD, 2) << std::endl;
    assert(pTree->NumNodes());
  }
  // save target point cloud and covariance model
  std::string saveTargetPointCloud = params.outputCommonDir + "/SaveTargetPointCloud.pts";
  std::string saveTargetCov = params.outputCommonDir + "/SaveTargetCov.txt";
  pTree->SavePointCloud(saveTargetPointCloud);
  pTree->SavePointCloudCov(saveTargetCov);

  // ICP Options
  cisstICP::Options opt_ICP;
  opt_ICP.auxOutputDir = params.outputBaseDir + "/AuxiliaryFiles/";
  opt_ICP.maxIter = 100;
  opt_ICP.termHoldIter = 2;
  opt_ICP.minE = -std::numeric_limits<double>::max();
  opt_ICP.tolE = 0.0;
  opt_ICP.dPosThresh = 0.1;
  opt_ICP.dAngThresh = 0.1*(cmnPI / 180);
  opt_ICP.dPosTerm = 0.001;
  opt_ICP.dAngTerm = 0.001*(cmnPI / 180);
  params.opt_ICP = opt_ICP;

#define nNoises     7
#define nOffsets    1
#define nTests      (nNoises*nOffsets)
  //#define nOutliers   6
  //#define nTests      (nNoises*nOffsets*nOutliers)
  //double percentOutliers[nOutliers] = { 0.05, 0.1, 0.2, 0.3, 0.4, 0.5 };

  // used for surface model noise
  // used for random and global noise
  //double noiseInPlaneSDArr[nNoises]   = { 0.0, 0.5, 1.0, 0.5, 1.0, 0.0, 0.0 };
  //double noisePerpPlaneSDArr[nNoises] = { 0.0, 0.5, 1.0, 1.0, 0.5, 0.0, 0.0 };
  double noiseEigValSqrt1[nNoises] =  { 0.0, 0.5, 1.0, 0.5, 1.0, 0.5, 0.5 };  // perp-plane std dev for surf noise
  double noiseEigValSqrt23[nNoises] = { 0.0, 0.5, 1.0, 1.0, 0.5, 1.0, 1.0 };  // in-plane std dev for surf noise
  CustomTestParams_PointCloud_SubShape::NoiseType noiseType[nNoises] = {
    CustomTestParams_PointCloud_SubShape::NoiseSurface,
    CustomTestParams_PointCloud_SubShape::NoiseSurface,
    CustomTestParams_PointCloud_SubShape::NoiseSurface,
    CustomTestParams_PointCloud_SubShape::NoiseSurface,
    CustomTestParams_PointCloud_SubShape::NoiseSurface,
    CustomTestParams_PointCloud_SubShape::NoiseGlobal,
    CustomTestParams_PointCloud_SubShape::NoiseRandom
  };
  std::string noiseTypeStr[nNoises];
  for (unsigned int i = 0; i < nNoises; i++)
  {
    switch (noiseType[i])
    {
    case CustomTestParams_PointCloud_SubShape::NoiseSurface:
      noiseTypeStr[i] = "Surf";
      break;
    case CustomTestParams_PointCloud_SubShape::NoiseGlobal:
      noiseTypeStr[i] = "Glob";
      break;
    case CustomTestParams_PointCloud_SubShape::NoiseRandom:
      noiseTypeStr[i] = "Rand";
      break;
    default:
      std::cout << "ERROR: unrecognized noise type" << std::endl;
      noiseTypeStr[i] = "ERROR";
      assert(0);
    }
  }

  double minOffsetAngArr[nOffsets] = { 10 };
  double maxOffsetAngArr[nOffsets] = { 20 };
  double minOffsetPosArr[nOffsets] = { 10 };
  double maxOffsetPosArr[nOffsets] = { 20 };

  std::vector<unsigned int> randSeed_SamplesArr(nTests, 0);   // sample generater
  std::vector<unsigned int> randSeed_XfmsArr(nTests, 0);     // initial offset xfm generater

  for (unsigned int i = 0; i < nTests; i++)
  {
    randSeed_SamplesArr[i] = i + 23;
    randSeed_XfmsArr[i] = i + 127;
  }

  std::string outputCommonDir = params.outputCommonDir;
  //params.nSamples = customParams.nGoodSamples;

  //--- Parameterized Trials ---//

  for (unsigned int offset = 0; offset < nOffsets; offset++)
  {
    for (unsigned int noise = 0; noise < nNoises; noise++)
    {
      unsigned int testNum = offset*nNoises + noise;

      ss.str("");
      //ss << "Noise_Prll" << noiseInPlaneSDArr[noise] << "Perp" << noisePerpPlaneSDArr[noise]
      ss << "Noise_" << noiseTypeStr[noise] << "EigVal" << noiseEigValSqrt1[noise] << "-" << noiseEigValSqrt23[noise]
        << "_Offset_R" << minOffsetAngArr[offset] << "-" << maxOffsetAngArr[offset]
        << "T" << minOffsetPosArr[offset] << "-" << maxOffsetPosArr[offset];
      //<< "_Outliers" << percentOutliers[outlier];
      std::string outputSubFolder = ss.str();

      params.minOffsetAng = minOffsetAngArr[offset];
      params.maxOffsetAng = maxOffsetAngArr[offset];
      params.minOffsetPos = minOffsetPosArr[offset];
      params.maxOffsetPos = maxOffsetPosArr[offset];
      params.randSeed_Samples = randSeed_SamplesArr[testNum];
      params.randSeed_Xfms = randSeed_XfmsArr[testNum];

      //customParams.sampleNoise_InPlaneSD = noiseInPlaneSDArr[noise];
      //customParams.sampleNoise_PerpPlaneSD = noisePerpPlaneSDArr[noise];
      customParams.sampleNoise_EigValSqrt = vct3(noiseEigValSqrt1[noise], noiseEigValSqrt23[noise], noiseEigValSqrt23[noise]);
      customParams.sampleNoise_Type = noiseType[noise];

      // hold number of good samples constant and increase sample size to
      //  achieve the desired percentage of outliers
      //double p = percentOutliers[outlier];
      //unsigned int nOutlierSamps = (unsigned int)(p/(1-p) * customParams.nGoodSamples);
      //params.nSamples = customParams.nGoodSamples + nOutlierSamps;

      // TODO: remove change to output common files to separate directories below

      // Run StdICP
      {
        params.AlgorithmDescription = "StdICP";
        //params.AlgorithmDescription = "StdICP_Verbose";
        params.algType = TestParameters::StdICP;
        SetOutputDir_SubShape(params, outputCommonDir, outputSubFolder);

        vctDynamicVector<vct3> dummySamples;      // these will be set later by the sample generator routine
        params.pAlg = new cisstAlgorithmICP_StdICP_PointCloud(pTree, dummySamples);
        Run_ParameterizedTest(mesh_source, pTree, params);
        delete params.pAlg; params.pAlg = NULL;
      }

      // Run IMLP
      {
        params.AlgorithmDescription = "IMLP";
        //params.AlgorithmDescription = "IMLP_Verbose";
        params.algType = TestParameters::IMLP;
        SetOutputDir(params, outputCommonDir, outputSubFolder);

        vctDynamicVector<vct3> dummySamples;      // these will be set later by the sample generator routine
        vctDynamicVector<vct3x3> dummySampleCov;  //  ''
        cisstAlgorithmICP_IMLP_PointCloud *pAlg =
          new cisstAlgorithmICP_IMLP_PointCloud(
          pTree, dummySamples, dummySampleCov, dummySampleCov, customParams.outlier_ChiSquareThreshold);
        params.pAlg = pAlg;
        Run_ParameterizedTest(mesh_source, pTree, params);
        delete params.pAlg; params.pAlg = NULL;
      }

      // Run IMLP_MD (Mahalanobis Distance Match Criteria)
      {
        params.AlgorithmDescription = "IMLP-MD";
        //params.AlgorithmDescription = "IMLP-MD_Verbose";
        params.algType = TestParameters::IMLP;
        SetOutputDir(params, outputCommonDir, outputSubFolder);

        vctDynamicVector<vct3> dummySamples;      // these will be set later by the sample generator routine
        vctDynamicVector<vct3x3> dummySampleCov;  //  ''
        cisstAlgorithmICP_IMLP_MahalDist_PointCloud *pAlg =
          new cisstAlgorithmICP_IMLP_MahalDist_PointCloud(
          pTree, dummySamples, dummySampleCov, dummySampleCov, customParams.outlier_ChiSquareThreshold);
        params.pAlg = pAlg;
        Run_ParameterizedTest(mesh_source, pTree, params);
        delete params.pAlg; params.pAlg = NULL;
      }

      // Run IMLP_CP (Closest Point Match Criteria)
      {
        params.AlgorithmDescription = "IMLP-CP";
        //params.AlgorithmDescription = "IMLP-CP_Verbose";
        params.algType = TestParameters::IMLP;
        SetOutputDir(params, outputCommonDir, outputSubFolder);

        vctDynamicVector<vct3> dummySamples;      // these will be set later by the sample generator routine
        vctDynamicVector<vct3x3> dummySampleCov;  //  ''
        cisstAlgorithmICP_IMLP_ClosestPoint_PointCloud *pAlg =
          new cisstAlgorithmICP_IMLP_ClosestPoint_PointCloud(
          pTree, dummySamples, dummySampleCov, dummySampleCov, customParams.outlier_ChiSquareThreshold);
        params.pAlg = pAlg;
        Run_ParameterizedTest(mesh_source, pTree, params);
        delete params.pAlg; params.pAlg = NULL;
      }

    }
  }
}


text:
import { Meteor } from 'meteor/meteor';
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { Accounts } from 'meteor/accounts-base';
import expect from 'must';

import { hireEmployees } from '/server/functions/employee/hireEmployees';
import { companyFactory, pttUserFactory } from '/dev-utils/factories';
import { dbCompanies } from '/db/dbCompanies';
import { dbEmployees } from '/db/dbEmployees';

describe('function hireEmployees', function() {
  this.timeout(10000);

  let companyId;
  let userId;
  let registerAt;

  beforeEach(function() {
    resetDatabase();
    companyId = dbCompanies.insert(companyFactory.build());
    userId = Accounts.createUser(pttUserFactory.build());
    registerAt = new Date();
    dbEmployees.insert({ companyId, userId, registerAt });
  });

  it('should not hire if the user is in vacation', function() {
    setUserInVacation(userId);
    hireEmployees();

    expect(findHiredEmployee()).to.not.exist();
  });

  it('should not hire if the user is been ban deal', function() {
    setUserBeenBanDeal(userId);
    hireEmployees();

    expect(findHiredEmployee()).to.not.exist();
  });

  it('should not hire if the company does not exist', function() {
    setCompanyNotExist(companyId);
    hireEmployees();

    expect(findHiredEmployee()).to.not.exist();
  });

  it('should not hire if the company is been seal', function() {
    setCompanyBeenSeal(companyId);
    hireEmployees();

    expect(findHiredEmployee()).to.not.exist();
  });

  it('should hire employee', function() {
    hireEmployees();
    expect(findHiredEmployee({ companyId, userId, registerAt })).to.exist();
  });

  describe('when multi-user and multi companies', function() {
    let testGroups;

    beforeEach(function() {
      testGroups = [ { userId, companyId, registerAt } ];

      const newUserTest = 2;
      for (let i = 0; i < newUserTest; i += 1) {
        const newUserId = Accounts.createUser(pttUserFactory.build());
        const newTestGroup = { userId: newUserId, companyId, registerAt };
        testGroups.push(newTestGroup);
        dbEmployees.insert(newTestGroup);
      }

      const newCompanyTest = 2;
      for (let i = 0; i < newCompanyTest; i += 1) {
        const newUserId = Accounts.createUser(pttUserFactory.build());
        const newCompanyId = dbCompanies.insert(companyFactory.build());
        const newTestGroup = { userId: newUserId, companyId: newCompanyId, registerAt };
        testGroups.push(newTestGroup);
        dbEmployees.insert(newTestGroup);
      }
    });

    it('should hire normal employees and not be affected by other violations', function() {
      setUserInVacation(testGroups[1].userId);
      setUserBeenBanDeal(testGroups[2].userId);
      setCompanyNotExist(testGroups[3].companyId);
      setCompanyBeenSeal(testGroups[4].companyId);
      hireEmployees();

      expect(findHiredEmployee(testGroups[0])).to.exist();
      expect(findHiredEmployee(testGroups[1])).to.not.exist();
      expect(findHiredEmployee(testGroups[2])).to.not.exist();
      expect(findHiredEmployee(testGroups[3])).to.not.exist();
      expect(findHiredEmployee(testGroups[4])).to.not.exist();
    });

    it('should hire all normal employees', function() {
      hireEmployees();
      testGroups.forEach((testGroup) => {
        expect(findHiredEmployee(testGroup)).to.exist();
      });
    });
  });
});

function findHiredEmployee(selector) {
  if (selector) {
    return dbEmployees.findOne({ ...selector, employed: true, resigned: false });
  }
  else {
    return dbEmployees.findOne({ employed: true, resigned: false });
  }
}

function setUserInVacation(userId) {
  Meteor.users.update(userId, { $set: { 'profile.isInVacation': true } });
}

function setUserBeenBanDeal(userId) {
  Meteor.users.update(userId, { $addToSet: { 'profile.ban': 'deal' } });
}

function setCompanyNotExist(companyId) {
  dbCompanies.remove(companyId);
}

function setCompanyBeenSeal(companyId) {
  dbCompanies.update(companyId, { $set: { isSeal: true } });
}


text:
<GhostDoc>
  <SpellChecker>
    <IncludeExtensions>
    </IncludeExtensions>
    <IgnoreExtensions>
      <IgnoreExtension>.cs</IgnoreExtension>
    </IgnoreExtensions>
    <IgnoreFiles>
    </IgnoreFiles>
  </SpellChecker>
<HelpConfigurations selected="HelpFile">
  <HelpConfiguration name="HelpFile">
    <OutputPath>D:\Development\MediaBrowser.ApiClient\Help</OutputPath>
    <ImageFolderPath />
    <HtmlFormats>
      <HtmlHelp>true</HtmlHelp>
      <MSHelpViewer>false</MSHelpViewer>
      <MSHelp2>false</MSHelp2>
      <Website>false</Website>
    </HtmlFormats>
    <IncludeScopes>
      <Public>true</Public>
      <Internal>true</Internal>
      <Protected>true</Protected>
      <Private>true</Private>
      <Inherited>true</Inherited>
      <EnableTags>false</EnableTags>
      <TagList />
    </IncludeScopes>
    <ResolveCrefLinks>true</ResolveCrefLinks>
    <HeaderText />
    <FooterText />
    <SelectedProjects />
  </HelpConfiguration>
</HelpConfigurations>
</GhostDoc>


text:
package models

import (
	"github.com/bboozzoo/q3stats/store"
)

var (
	schemaModels = []interface{}{
		&Match{},
		&Alias{},
		&Player{},
		&WeaponStat{},
		&PlayerMatchStat{},
		&ItemStat{},
	}
)

func CreateSchema(store store.DBConn) error {
	store.Conn().AutoMigrate(schemaModels...)
	return nil
}


text:
"""pyzmq does not ship tornado's futures,
this just raises informative NotImplementedErrors to avoid having to change too much code.
"""

class NotImplementedFuture(object):
    def __init__(self, *args, **kwargs):
        raise NotImplementedError("pyzmq does not ship tornado's Futures, "
            "install tornado >= 3.0 for future support."
        )

Future = TracebackFuture = NotImplementedFuture

def is_future(x):
    return isinstance(x, Future)


text:
#ifndef _APIBUNDLEQUEUE_H_
#define _APIBUNDLEQUEUE_H_

#include <vector>
#include "dtn_types.h"
#include <oasys/thread/MsgQueue.h>
#include <oasys/util/ScratchBuffer.h>

namespace dtn {

/**
 * Small encapsulating structure for API bundles.
 */
struct APIBundle {
    dtn_bundle_spec_t 			spec_;
    oasys::ScratchBuffer<char*,512>	payload_;
};

/**
 * Type definition of a simple vector of APIBundles.
 */
typedef std::vector<APIBundle*> APIBundleVector;

/**
 * Type definition of an oasys blocking message queue that stores
 * APIBundle structures.
 */
typedef oasys::MsgQueue<APIBundle*> APIBundleQueue;

} // namespace dtn

#endif /* _APIBUNDLEQUEUE_H_ */


text:
package ntua.multimedia.code;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Decoder;
import javazoom.jl.decoder.Header;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.decoder.SampleBuffer;
import javazoom.jl.player.AudioDevice;
import javazoom.jl.player.FactoryRegistry;

/**
 * The Class Player.
 */
public class Player {

	/** The bitstream. */
	private Bitstream bitstream;

	/** The running. */
	private boolean running = true;

	/** The closed. */
	private boolean closed = false;

	/** The fast forward. */
	private boolean fastForward = false;

	/** The position. */
	private int position;

	/**
	 * The MPEG audio decoder.
	 */
	private Decoder		decoder;

	/** The gui initialization monitor. */
	private final Object GUI_INITIALIZATION_MONITOR = new Object();

	/**
	 * The AudioDevice the audio samples are written to.
	 */
	private AudioDevice	audio;

	/**
	 * Instantiates a new player.
	 *
	 * @param stream the stream
	 * @throws JavaLayerException the java layer exception
	 */
	protected Player(InputStream stream) throws JavaLayerException{
		bitstream = new Bitstream(stream);
		decoder = new Decoder();

		FactoryRegistry r = FactoryRegistry.systemRegistry();
		audio = r.createAudioDevice();
		audio.open(decoder);
	}

	/**
	 * Fast forward.
	 *
	 * @throws JavaLayerException the java layer exception
	 */
	protected synchronized  void fastForward() throws JavaLayerException{
		for(int i = 0; i < 200; i++){
			Header h = bitstream.readFrame();
			if (h == null)
				return;
			bitstream.closeFrame();
			position ++;
		}
		fastForward = false;
	}

	/**
	 * Decode frame.
	 *
	 * @return true, if successful
	 * @throws JavaLayerException the java layer exception
	 */
	private  boolean decodeFrame() throws JavaLayerException
	{
		try
		{
			AudioDevice out = audio;
			if (out==null)
				return false;
			Header h;
			synchronized (this) {
				if (closed)
					return false;

				if(fastForward)
					fastForward();
				h = bitstream.readFrame();
			}

			if (h==null)
				return false;

			// sample buffer set when decoder constructed
			SampleBuffer output = (SampleBuffer)decoder.decodeFrame(h, bitstream);

			synchronized (this)
			{
				out = audio;
				if (out!=null)
				{
					out.write(output.getBuffer(), 0, output.getBufferLength());
				}
			}
			bitstream.closeFrame();
		}
		catch (RuntimeException ex)
		{
			throw new JavaLayerException("Exception decoding audio frame", ex);
		}
		return true;
	}

	/**
	 * Gets the metadata.
	 *
	 * @return the metadata
	 */
	protected String getMetadata(){
		InputStream input = bitstream.getRawID3v2();
		return getStringFromInputStream(input);
	}

	/**
	 * Gets the string from input stream.
	 *
	 * @param is the is
	 * @return the string from input stream
	 */
	private static String getStringFromInputStream(InputStream is) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		String line;
		try {

			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();

	}

	/**
	 * Play.
	 *
	 * @param frames the frames
	 * @throws JavaLayerException the java layer exception
	 */
	protected void play(int frames) throws JavaLayerException{
		position = 0;
		boolean ret = true;
		running = true;
		synchronized (GUI_INITIALIZATION_MONITOR) {
			while (position < frames && ret) {
				if(running) {
					ret = decodeFrame();
				} else {
					try {
						while(!running) {
							GUI_INITIALIZATION_MONITOR.wait();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if(closed)
						return;
				}
				position++;
			}
		}

		AudioDevice out = audio;
		if (out!=null)
		{
			out.flush();
			synchronized (this)
			{
				stop();
			}
		}
		position = 0;
	}

	/**
	 * Pause.
	 */
	protected void pause(){
		running = false;
	}

	/**
	 * Resume.
	 */
	protected synchronized void resume(){
		if(running)
			return;
		synchronized (GUI_INITIALIZATION_MONITOR) {
			running = true;
			GUI_INITIALIZATION_MONITOR.notify();
		}
	}

	/**
	 * Stop.
	 */
	protected synchronized void stop()	{
		AudioDevice out = audio;
		if (out != null) {
			out.close();
			out.getPosition();
			try
			{
				bitstream.close();
				closed = true;
			}
			catch (BitstreamException ex)
			{}
			running = true;
		}
	}

	/**
	 * Gets the position.
	 *
	 * @return the position
	 */
	protected int getPosition(){
		return position;
	}

	/**
	 * Sets the fast forward.
	 *
	 * @param fastForward the new fast forward
	 */
	protected void setFastForward(boolean fastForward) {
		this.fastForward = fastForward;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Trinity.Core.Lib
{
    internal class CellTypeDictionary
    {
        private List<string> list_A;
        private List<byte> list_B;

        public CellTypeDictionary()
        {
            list_A = new List<string>();
            list_B = new List<byte>();
        }

        public byte GetValue(string key)
        {
            for (int i = 0; i < list_A.Count; i++)
            {
                if (list_A[i] == key)
                {
                    return list_B[i];
                }
            }
            return 0; //undefined
        }

        public string GetKey(byte value)
        {
            for (int i = 0; i < list_B.Count; i++)
            {
                if (list_B[i] == value)
                {
                    return list_A[i];
                }
            }
            return "undefined"; //undefined
        }
    }
}