text:
package org.springframework.cloud.stream.module.utils;

import java.net.URL;
import java.net.URLClassLoader;

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

import org.springframework.boot.loader.LaunchedURLClassLoader;
import org.springframework.util.StringUtils;

/**
 * @author Marius Bogoevici
 */
public class ClassloaderUtils {

	private static final Log log = LogFactory.getLog(ClassloaderUtils.class);

	/**
	 * Creates a ClassLoader for the launched modules by merging the URLs supplied as argument with the URLs that
	 * make up the additional classpath of the launched JVM (retrieved from the application classloader), and
	 * setting the extension classloader of the JVM as parent, if accessible.
	 *
	 * @param urls a list of library URLs
	 * @return the resulting classloader
	 */
	public static ClassLoader createModuleClassloader(URL[] urls) {
		ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
		if (log.isDebugEnabled()) {
			log.debug("systemClassLoader is " + systemClassLoader);
		}
		if (systemClassLoader instanceof URLClassLoader) {
			// add the URLs of the application classloader to the created classloader
			// to compensate for LaunchedURLClassLoader not delegating to parent to retrieve resources
			@SuppressWarnings("resource")
			URLClassLoader systemUrlClassLoader = (URLClassLoader) systemClassLoader;
			URL[] mergedUrls = new URL[urls.length + systemUrlClassLoader.getURLs().length];
			if (log.isDebugEnabled()) {
				log.debug("Original URLs: " +
						StringUtils.arrayToCommaDelimitedString(urls));
				log.debug("Java Classpath URLs: " +
						StringUtils.arrayToCommaDelimitedString(systemUrlClassLoader.getURLs()));
			}
			System.arraycopy(urls, 0, mergedUrls, 0, urls.length);
			System.arraycopy(systemUrlClassLoader.getURLs(), 0, mergedUrls, urls.length,
					systemUrlClassLoader.getURLs().length);
			// add the extension classloader as parent to the created context, if accessible
			if (log.isDebugEnabled()) {
				log.debug("Classloader URLs: " + StringUtils.arrayToCommaDelimitedString(mergedUrls));
			}
			return new LaunchedURLClassLoader(mergedUrls, systemUrlClassLoader.getParent());
		}
		return new LaunchedURLClassLoader(urls, systemClassLoader);
	}
}


text:
<?php

Namespace Nova\Loader;

use Nova\Loader\Autoloader as Autoloader;

/**
 * Fully PSR-0 Compatible Autoloader
 *
 * @package     Loader
 * @author      Thomas Frei <thomast.frei@gmail.com>
 * @copyright   2013 Thomas Frei
 * @license     https://github.com/thomasfrei/Nova/blob/master/License.txt
 * @link        https://github.com/thomasfrei/Nova
 */
Class Autoloader
{
    /**
     * The Default File Extension
     * @var string
     */
    protected $_fileExtension = '.php';

    /**
     * The Default Namespace Separator
     * @var string
     */
    protected $_namespaceSeparator = '\\';

    /**
     * Array of Registered Namespaces
     * @var array
     */
    protected $_namespaces = array();

    /**
     * Constructor
     *
     * Accepts an Array of Autoloader Options
     *
     * Valid Options are:
     *
     *     - file.extension
     *     - namespace.separator
     *     - include.path
     *
     * @param null|array $options array of options
     */
    public function __construct($options = null)
    {
        if ($options !== null) {
            if (array_key_exists('file.extension', $options)) {
                $this->setFileExtension($options['file.extension']);
            }

            if (array_key_exists('namespace.separator', $options)) {
                $this->setNamespaceSeparator($options['namespace.separator']);
            }

            if (array_key_exists('include.path', $options)) {
                $this->setIncludePath($options['include.path']);
            }
        }
    }

    /**
     * Returns the File Extension.
     *
     * @return string File Extension
     */
    public function getFileExtension()
    {
        return $this->_fileExtension;
    }

    /**
     * Sets the File Extension.
     *
     * @param string $fileExtension
     * @return Autoloader
     */
    public function setFileExtension($fileExtension)
    {
        $this->_fileExtension = (string) $fileExtension;
        return $this;
    }

    /**
     * Returns the Namespace Separator.
     *
     * @return string Namespace Separator
     */
    public function getNamespaceSeparator()
    {
        return $this->_namespaceSeparator;
    }

    /**
     * Sets the Namepace Separator.
     *
     * @param string $namespaceSeparator
     * @return Autoloader
     */
    public function setNamespaceSeparator($namespaceSeparator)
    {
        $this->_namespaceSeparator = (string) $namespaceSeparator;
        return $this;
    }

    /**
     * Sets the Include Path. Does not Overwrite Previously set Paths.
     *
     * @param array|string $newIncludePath Sting or Array with the Include Path
     * @return Autoloader
     */
    public function setIncludePath($newIncludePath)
    {
        // Grab the Original Include Path
        $originalPath = explode(PATH_SEPARATOR, $this->getIncludePath());

        // Merge the Original and the New Include Path
        if (is_array($newIncludePath)) {
            $newIncludePath = array_merge($originalPath, $newIncludePath);
        } elseif (is_string($newIncludePath)) {
            array_push($originalPath, $newIncludePath);
            $newIncludePath = $originalPath;
        }

        $newIncludePath = implode(PATH_SEPARATOR, $newIncludePath);
        unset($originalPath);

        // Set the New Include Path
        set_include_path($newIncludePath);

        return $this;
    }

    /**
     * Returns the Include Path.
     *
     * @return string Include Path
     */
    public function getIncludePath()
    {
        return get_include_path();
    }

    /**
     * Registers the Autoloader with spl_autoload.
     *
     * @param  boolean $throw   Whether spl_autoload_register() should throw exceptions when the autoload_function cannot be registered.
     * @param  boolean $prepend If true, spl_autoload_register() will prepend the autoloader on the autoload stack instead of appending it.
     * @return void
     */
    public function register($throw = false, $prepend = false)
    {
        spl_autoload_register(array($this, 'loadClass'), $throw, $prepend);
    }

    /**
     * Removes the Autoloader from the spl_autoload Stack.
     *
     * @return void
     */
    public function unregister()
    {
        spl_autoload_unregister(array($this, 'loadClass'));
    }

    /**
     * Register a new namespace.
     *
     * Accepts an Array of namespace=>path.
     *
     * <code>
     *     $namespaces = array(
     *          'One' => 'path/to/namespace/one',
     *          'Two' => 'path/to/namespace/one/two',
     *      );
     *
     *      $loader->registerNamespaces($namespaces);
     * </code>
     *
     * @param  array $namespaces array containing namespace => path
     * @throws Exception If Namespace is Already Registered with Different Value
     * @return Autoloader
     */
    public function registerNamespaces($namespaces)
    {
        foreach ($namespaces as $namespace => $path) {
            if (!array_key_exists($namespace, $this->_namespaces)) {
                $this->_namespaces[$namespace] = $path;
            } elseif (array_key_exists($namespace, $this->_namespaces) && $this->_namespaces[$namespace] !== $path) {
                throw new Exception('Namespace: '.$namespace.' already registered with different value');
            }
        }
        return $this;
    }

    /**
     * Returns an array of registered namespaces.
     *
     * @return array array of registered namespaces
     */
    public function getRegisteredNamespaces()
    {
        return $this->_namespaces;
    }

    /**
     * Unregister a namespace.
     *
     * @param  string $namespace name of the namespace to unregister
     * @return Autoloader
     */
    public function unregisterNamespace($namespace)
    {
        if (isset($this->_namespaces[$namespace])) {
            unset($this->_namespaces[$namespace]);
        }

        return $this;
    }

    /**
     * Autoload a Class.
     *
     * @param  string $classname Name of the class
     * @throws Exception If The File Cannot be Found
     * @return boolean true if the file could be included
     */
    protected function loadClass($classname)
    {
        // check if the file is already loaded
        if ($this->isLoaded($classname)) {
            return true;
        }

        // Transform classname
        $filename = $this->transformClassnameToFilename($classname);

        // Search the file
        $file = $this->findFile($filename);

        // The file was not found
        if (!$file) {
            throw new Exception('File '. $filename .' could not be loaded');
        }

        // include the file
        require_once($file);

        return true;
    }

    /**
     * Checks if the class is already loaded.
     *
     * @param  string  $classname Name of the class
     * @return boolean
     */
    protected function isLoaded($classname)
    {
        if (!class_exists($classname, false)) {
            return false;
        }
        return true;
    }

    /**
     * Search the file against the registered namespaces aand the include path.
     *
     * @param  string $filename Name of the file
     * @return boolean|string $filePath False If the file can't be found or the full path to the File
     */
    protected function findFile($filename)
    {
        $filePath = '';

        // Search with registered namespaces first
        foreach ($this->_namespaces as $namespace => $path) {
            if ($found = (strripos($filename, $namespace) === 0)) {

                $class = substr($filename, strlen($namespace));
                $class = ltrim($class, DIRECTORY_SEPARATOR);
                $filePath = $this->_namespaces[$namespace] . $class;
            }

            // Check if the file exists
            if (file_exists($filePath)) {
                return $filePath;
            }
        }

        // If not found try the include path
        if ($filePath = stream_resolve_include_path($filename)) {
            return $filePath;
        }

        // The file doesn't exist
        return false;
    }

    /**
     * Transforms Classnames to Filenames by PSR-0 Standards.
     *
     * @link  https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
     * @param  string $classname Name of the Class
     * @return string $filename Name of the File
     */
    protected function transformClassnameToFilename($classname)
    {
        // Transform Classnames according to PSR-0
        $classname     = ltrim($classname, $this->_namespaceSeparator);
        $filename      = '';
        $namespace = '';

        // Find the classnamename
        if ($last_namespace_position = strripos($classname, $this->_namespaceSeparator)) {
            $namespace = substr($classname, 0, $last_namespace_position);
            $classname = substr($classname, $last_namespace_position + 1);
            $classname = str_replace('_', DIRECTORY_SEPARATOR, $classname);
            $filename = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR;
        }

        // Underscores in classnames must be converted to Directory Separators
        $filename .= str_replace('_', DIRECTORY_SEPARATOR, $classname) . $this->_fileExtension;

        return $filename;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Example for getting started with the Spray framework and Akka and writing tests.

Follow these steps to begin:

1. Launch SBT:

        $ sbt

2. Compile everything and run all tests:

        > test

3. Start the application:

        > re-start

4. Browse to http://localhost:8080/

5. Stop the application:

        > re-stop

$ sbt assembly


text:
package cheme.controls;

/**
 * The PIDController implements proportional/integral/derivative control.
 *
 * <p>Note that ALL of these methods should be assumed to be NOT re-entrant.
 * Multiple threads should instantiate separate instances to perform parallel
 * calculations.
 */
public class PIDController implements Controller {

    /**
     * The present error value: the difference between PV and SP.
     */
    private double errorNow;

    /**
     * The previous scan error value: the difference between PV and SP.
     */
    private double errorLast;

    /**
     * The number of seconds since compute() was last called.
     */
    private double lastComputeTime;

    /**
     * The controller output value, as a fraction of its span.
     */
    private double op;

    /**
     * The OP span range minimum.
     */
    private double opSpanLower;

    /**
     * The OP span range maximum.
     */
    private double opSpanUpper;

    /**
     * The present process value, as a fraction of its span.
     */
    private double pv;

    /**
     * The PV span range minimum.
     */
    private double pvSpanLower;

    /**
     * The PV span range maximum.
     */
    private double pvSpanUpper;

    /**
     * The set point, as a fraction of its span.
     */
    private double sp;

    /**
     * The SP span range minimum.
     */
    private double spSpanLower;

    /**
     * The SP span range maximum.
     */
    private double spSpanUpper;

    /**
     * The SP allowed minimum.
     */
    private double spAllowedMin;

    /**
     * The SP allowed maximum.
     */
    private double spAllowedMax;

    /**
     * Construct a new PID controller.
     *
     * @param Kd the proportional gain
     * @param Ti the integral time
     * @param Td the derivative time
     * @param pvSpanMin the min span on PV
     * @param pvSpanMax the max span on PV
     * @param spSpanMin the min span on SP
     * @param spSpanMax the max span on SP
     * @param opSpanMin the min span on OP
     * @param opSpanMax the max span on OP
     * @param opAllowedMin the min allowed on OP
     * @param opAllowedMax the max allowed on OP
     * @throws IllegalArgumentException if op allowed min/max is outside its
     * span min/max
     */

    /**
     * Compute the new state of this controller.
     *
     * @param deltaT the number of seconds between the last call to compute()
     * and this call to compute()
     */
    public void compute(final double deltaT) {
        /*
         TODO

        errorLast = errorNow;
        error_now = sp - pv;
        op = op + K*((error_now - error_last) + error_now/Ti) / xmitter_range;
        if (op < opSpanLower) {
            op = opSpanLower;
        }
        if (op > opSpanUpper) {
            op = opSpanUpper;
        }
         */
    }

    /**
     * Get the current output (OP).
     *
     * @return the controller output, as a fraction of its span (0 to 1)
     */
    public double getOutput() {
        return op;
    }

    /**
     * Get the output (OP) span lower limit.
     *
     * @return the controller output's minimum value
     */
    public double getOutputSpanLower() {
        return opSpanLower;
    }

    /**
     * Set the output (OP) span lower limit.
     *
     * @param lower the controller output's minimum value
     */
    public void setOutputSpanLower(final double lower) {
        opSpanLower = lower;
    }

    /**
     * Get the output (OP) span upper limit.
     *
     * @return the controller output's maximum value
     */
    public double getOutputSpanUpper() {
        return opSpanUpper;
    }

    /**
     * Set the output (OP) span upper limit.
     *
     * @param upper the controller output's maximum value
     */
    public void setOutputSpanUpper(final double upper) {
        opSpanUpper = upper;
    }

    /**
     * Get the current input (PV).
     *
     * @return the controller input, as a fraction of its span (0 to 1)
     */
    public double getInput() {
        return pv;
    }

    /**
     * Set the current input (PV).
     *
     * @param input the controller input, as a fraction of its span (0 to 1)
     */
    public void setInput(final double input) {
        pv = input;
    }

    /**
     * Get the input (PV) span lower limit.
     *
     * @return the controller input's minimum value
     */
    public double getInputSpanLower() {
        return pvSpanLower;
    }

    /**
     * Set the input (PV) span lower limit.
     *
     * @param lower the controller input's minimum value
     */
    public void setInputSpanLower(final double lower) {
        pvSpanLower = lower;
    }

    /**
     * Get the input (PV) span upper limit.
     *
     * @return the controller input's maximum value
     */
    public double getInputSpanUpper() {
        return pvSpanUpper;
    }

    /**
     * Set the input (PV) span upper limit.
     *
     * @param upper the controller input's maximum value
     */
    public void setInputSpanUpper(final double upper) {
        pvSpanUpper = upper;
    }

    /**
     * Get the current set point (SP).
     *
     * @return the controller set point, as a fraction of its span (0 to 1)
     */
    public double getSetPoint() {
        return sp;
    }

    /**
     * Set the current set point (SP).
     *
     * @param setPoint the controller set point, as a fraction of its span (0
     * to 1)
     */
    public void setSetPoint(final double setPoint) {
        sp = setPoint;
    }

    /**
     * Get the set point (SP) span lower limit.
     *
     * @return the controller set point's minimum value
     */
    public double getSetPointSpanLower() {
        return spSpanLower;
    }

    /**
     * Set the set point (SP) span lower limit.
     *
     * @param lower the controller set point's minimum value
     */
    public void setSetPointSpanLower(final double lower) {
        spSpanLower = lower;
    }

    /**
     * Get the set point (SP) span upper limit.
     *
     * @return the controller set point's maximum value
     */
    public double getSetPointSpanUpper() {
        return spSpanUpper;
    }

    /**
     * Set the set point (SP) span upper limit.
     *
     * @param upper the controller set point's maximum value
     */
    public void setSetPointSpanUpper(final double upper) {
        spSpanUpper = upper;
    }

    /**
     * Get the set point (SP) minimum allowed value.
     *
     * @return the controller set point's minimum allowed value
     */
    public double getSetPointMin() {
        return spAllowedMin;
    }

    /**
     * Set the set point (SP) minimum allowed value.
     *
     * @param min the controller set point's minimum allowed value
     */
    public void setSetPointMin(final double min) {
        spAllowedMin = min;
    }

    /**
     * Get the set point (SP) span maximum allowed value.
     *
     * @return the controller set point's maximum allowed value
     */
    public double getSetPointMax() {
        return spAllowedMax;
    }

    /**
     * Set the set point (SP) span maximum allowed value.
     *
     * @param max the controller set point's maximum allowed value
     */
    public void setSetPointMax(final double max) {
        spAllowedMax = max;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using MbUnit.Framework;

namespace Gallio.MbUnit2Adapter.TestResources.Metadata
{
    [TestFixture]
    public class TestDescriptionSample
    {
        [Test(Description="A sample description.")]
        public void Test()
        {
        }
    }
}


text:
describe('layer-identity-item', function() {
  var el, testRoot, client;

  beforeAll(function(done) {
    if (layerUI.components['layer-conversation-panel'] && !layerUI.components['layer-conversation-panel'].classDef) layerUI.init({});
    setTimeout(done, 1000);
  });

  beforeEach(function() {
    jasmine.clock().install();
    client = new layer.Client({
      appId: 'Fred'
    });
    client.user = new layer.Identity({
      client: client,
      userId: 'FrodoTheDodo',
      id: 'layer:///identities/FrodoTheDodo',
      displayName: 'Frodo is a Dodo',
      isFullIdentity: true
    });
    client._clientAuthenticated();

    if (layerUI.components['layer-conversation-panel'] && !layerUI.components['layer-conversation-panel'].classDef) layerUI.init({});
    testRoot = document.createElement('div');
    document.body.appendChild(testRoot);
    el = document.createElement('layer-identity-item');
    testRoot.appendChild(el);
    el.item = client.user;
    layer.Util.defer.flush();
    jasmine.clock().tick(1000);
    layer.Util.defer.flush();
    jasmine.clock().tick(10);
  });

  afterEach(function() {
    jasmine.clock().uninstall();
    document.body.removeChild(testRoot);
    layer.Client.removeListenerForNewClient();
  });

  describe("The selected property", function() {
    it("Should update checkbox state", function() {
      expect(el.nodes.checkbox.checked).toBe(false);
      el.selected = true;
      expect(el.nodes.checkbox.checked).toBe(true);
      el.selected = false;
      expect(el.nodes.checkbox.checked).toBe(false);
    });

    it("Should update layer-identity-item-selected class", function() {
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(false);
      el.selected = true;
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(true);
      el.selected = false;
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(false);
    });

    it("Should get the checkbox state", function() {
      el.nodes.checkbox.checked = false;
      expect(el.selected).toBe(false);
      el.nodes.checkbox.checked = true;
      expect(el.selected).toBe(true);
    });

    it("Should get the selected state if no checkbox", function() {
      el.nodes.checkbox = null;
      el.properties.selected = false;
      expect(el.selected).toBe(false);
      el.properties.selected = true;
      expect(el.selected).toBe(true);
    });
  });

  describe("The create() method", function() {
    it("Should initialize selected to true from innerHTML", function() {
      testRoot.innerHTML = '<layer-identity-item selected="true"></layer-identity-item>';
      CustomElements.takeRecords();
      expect(testRoot.firstChild.selected).toBe(true);
      layer.Util.defer.flush();
      expect(testRoot.firstChild.nodes.checkbox.checked).toBe(true);
    });

    it("Should initialize selected to false from innerHTML", function() {
      testRoot.innerHTML = '<layer-identity-item selected="false"></layer-identity-item>';
      CustomElements.takeRecords();
      expect(testRoot.firstChild.selected).toBe(false);
      expect(testRoot.firstChild.nodes.checkbox.checked).toBe(false);
    });

    it("Should initialize selected with default of false from innerHTML", function() {
      testRoot.innerHTML = '<layer-identity-item></layer-identity-item>';
      CustomElements.takeRecords();
      expect(testRoot.firstChild.selected).toBe(false);
      expect(testRoot.firstChild.nodes.checkbox.checked).toBe(false);
    });

    it("Should wire up the _onChange event handler", function() {
      var called = false;
      el.addEventListener('layer-identity-item-selected', function(evt) {
        called = true;
      });

      // Run
      el.nodes.checkbox.click();

      // Posttest
      expect(called).toBe(true);
    });

    it("Should setup the label for attribute", function() {
      expect(el.nodes.checkbox.id.length > 0).toBe(true);
      expect(el.nodes.title.getAttribute('for')).toEqual(el.nodes.checkbox.id);
    });
  });

  describe("The _onChange() method", function() {
    it("Should trigger layer-identity-item-selected", function() {
      var selectedCalled = false,
        deselectedCalled = false;
      el.addEventListener('layer-identity-item-selected', function(evt) {
        selectedCalled = true;
      });
      el.addEventListener('layer-identity-item-deselected', function(evt) {
        deselectedCalled = true;
      });

      // Run
      el.nodes.checkbox.click();

      // Posttest
      expect(deselectedCalled).toBe(false);
      expect(selectedCalled).toBe(true);
    });

    it("Should trigger layer-identity-item-deselected", function() {
      el.selected = true;

      var selectedCalled = false,
        deselectedCalled = false;
      el.addEventListener('layer-identity-item-selected', function(evt) {
        selectedCalled = true;
      });
      el.addEventListener('layer-identity-item-deselected', function(evt) {
        deselectedCalled = true;
      });

      // Run
      el.nodes.checkbox.click();

      // Posttest
      expect(deselectedCalled).toBe(true);
      expect(selectedCalled).toBe(false);
    });

    it("Should update the layer-identity-item-selected if evt.preventDefault not called", function() {
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(false);
      el.nodes.checkbox.click();
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(true);
      el.nodes.checkbox.click();
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(false);
    });

    it("Should undo the change if evt.preventDefault was called", function() {
      el.addEventListener('layer-identity-item-selected', function(evt) {
        evt.preventDefault();
      });
      el.addEventListener('layer-identity-item-deselected', function(evt) {
        evt.preventDefault();
      });

      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(false);
      expect(el.nodes.checkbox.checked).toBe(false);
      el.nodes.checkbox.click();
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(false);
      expect(el.nodes.checkbox.checked).toBe(false);

      el.selected = true;
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(true);
      expect(el.nodes.checkbox.checked).toBe(true);
      el.nodes.checkbox.click();
      expect(el.innerNode.classList.contains('layer-identity-item-selected')).toBe(true);
      expect(el.nodes.checkbox.checked).toBe(true);
    });
  });

  describe("The onRender() method", function() {
    it("Should setup the layer-avatar users", function() {
      el.nodes.avatar.users = [];
      el.onRender();
      expect(el.nodes.avatar.users).toEqual([client.user]);
      expect(el.querySelector('layer-presence').tagName).toEqual('LAYER-PRESENCE');
    });

    it("Should _render the displayName", function() {
      el.nodes.title.innerHTML = '';
      el.onRender();
      expect(el.nodes.title.innerHTML).toEqual(client.user.displayName);
    });

    it("Should update the displayName when it changes", function() {
      client.user.displayName = 'Quick change it back!';
      client.user.trigger('identities:change', {property: 'displayName', oldValue: 'Frodo', newValue: client.user.displayName});
      expect(el.nodes.title.innerHTML).toEqual(client.user.displayName);
    });
  });

  describe("The _runFilter() method", function() {
    it("Should add layer-item-filtered if not a match", function() {
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
      el._runFilter('Samwise');
      expect(el.classList.contains('layer-item-filtered')).toBe(true);
    });

    it("Should remove layer-item-filtered if it is a match", function() {
      el.classList.add('layer-item-filtered');
      el._runFilter('Frodo');
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
    });

    it("Should match on substring against displayName, firstName, lastName and emailAddress", function() {
      var user = client.user;
      el._runFilter('froDo');
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
      el._runFilter('MoJo');
      expect(el.classList.contains('layer-item-filtered')).toBe(true);

      user.firstName = 'Mojo';
      el._runFilter('MoJo');
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
      el._runFilter('POJO');
      expect(el.classList.contains('layer-item-filtered')).toBe(true);

      user.lastName = 'pojO';
      el._runFilter('POJO');
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
      el._runFilter('pojo@layer');
      expect(el.classList.contains('layer-item-filtered')).toBe(true);

      user.emailAddress = 'pojo@layer.com';
      el._runFilter('pojo@layer');
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
    });

    it("Should match on RegEx against displayName, firstName, lastName and emailAddress", function() {
      var user = client.user;
      el._runFilter(/froDo/);
      expect(el.classList.contains('layer-item-filtered')).toBe(true);
      el._runFilter(/froDo/i);
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
      el._runFilter(/moJo/i);
      expect(el.classList.contains('layer-item-filtered')).toBe(true);

      user.firstName = 'Mojo';
      el._runFilter(/moJo/i);
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
      el._runFilter(/POJO/i);
      expect(el.classList.contains('layer-item-filtered')).toBe(true);

      user.lastName = 'pojO';
      el._runFilter(/POJO/i);
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
      el._runFilter(/pojo@layer/);
      expect(el.classList.contains('layer-item-filtered')).toBe(true);

      user.emailAddress = 'pojo@layer.com';
      el._runFilter(/pojo@layer/);
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
    });

    it("Should match on Callback against displayName, firstName, lastName and emailAddress", function() {
      function test(user) {
        return user.firstName == 'Frodo';
      }
      el._runFilter(test);
      expect(el.classList.contains('layer-item-filtered')).toBe(true);

      client.user.firstName = 'Frodo';
      el._runFilter(test);
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
    });

    it("Should match if no filter", function() {
      el._runFilter(null);
      expect(el.classList.contains('layer-item-filtered')).toBe(false);
    });
  });

  describe("Mixin list-item", function() {
    describe("The customNodeAbove property", function() {
      it("Should add a string", function() {
        el.customNodeAbove = 'hello';
        expect(el.customNodeAbove.innerHTML).toEqual('hello');
        expect(el.firstChild).toBe(el.customNodeAbove);
        expect(el.childNodes.length).toEqual(2);
      });

      it("Should replace a string", function() {
        el.customNodeAbove = 'hello';
        el.customNodeAbove = 'there';
        expect(el.customNodeAbove.innerHTML).toEqual('there');
        expect(el.firstChild).toBe(el.customNodeAbove);
        expect(el.childNodes.length).toEqual(2);
      });

      it("Should remove a string", function() {
        el.customNodeAbove = 'hello';
        el.customNodeAbove = '';
        expect(el.customNodeAbove).toBe(null);
        expect(el.firstChild).toBe(el.innerNode);
        expect(el.childNodes.length).toEqual(1);
      });

      it("Should add a node", function() {
        var div1 = document.createElement('div');
        el.customNodeAbove = div1;
        expect(el.customNodeAbove).toBe(div1);
        expect(el.firstChild).toBe(div1);
        expect(el.childNodes.length).toEqual(2);
      });

      it("Should replace a node", function() {
        var div1 = document.createElement('div');
        var div2 = document.createElement('div');
        el.customNodeAbove = div1;
        el.customNodeAbove = div2;
        expect(el.customNodeAbove).toBe(div2);
        expect(el.firstChild).toBe(div2);
        expect(el.childNodes.length).toEqual(2);
        expect(div1.parentNode).toBe(null);
      });

      it("Should remove a node", function() {
        var div1 = document.createElement('div');
        el.customNodeAbove = div1;
        el.customNodeAbove = null;
        expect(el.customNodeAbove).toBe(null);
        expect(el.firstChild).toBe(el.innerNode);
        expect(el.childNodes.length).toEqual(1);
      });
    });

    describe("The customNodeBelow property", function() {
      it("Should add a string", function() {
        el.customNodeBelow = 'hello';
        expect(el.customNodeBelow.innerHTML).toEqual('hello');
        expect(el.childNodes[1]).toBe(el.customNodeBelow);
        expect(el.childNodes.length).toEqual(2);
      });

      it("Should replace a string", function() {
        el.customNodeBelow = 'hello';
        el.customNodeBelow = 'there';
        expect(el.customNodeBelow.innerHTML).toEqual('there');
        expect(el.childNodes[1]).toBe(el.customNodeBelow);
        expect(el.childNodes.length).toEqual(2);
      });

      it("Should remove a string", function() {
        el.customNodeBelow = 'hello';
        el.customNodeBelow = '';
        expect(el.customNodeBelow).toBe(null);
        expect(el.firstChild).toBe(el.innerNode);
        expect(el.childNodes.length).toEqual(1);
      });

      it("Should add a node", function() {
        var div1 = document.createElement('div');
        el.customNodeBelow = div1;
        expect(el.customNodeBelow).toBe(div1);
        expect(el.childNodes[1]).toBe(div1);
        expect(el.childNodes.length).toEqual(2);
      });

      it("Should replace a node", function() {
        var div1 = document.createElement('div');
        var div2 = document.createElement('div');
        el.customNodeBelow = div1;
        el.customNodeBelow = div2;
        expect(el.customNodeBelow).toBe(div2);
        expect(el.childNodes[1]).toBe(div2);
        expect(el.childNodes.length).toEqual(2);
        expect(div1.parentNode).toBe(null);
      });

      it("Should remove a node", function() {
        var div1 = document.createElement('div');
        el.customNodeBelow = div1;
        el.customNodeBelow = null;
        expect(el.customNodeBelow).toBe(null);
        expect(el.firstChild).toBe(el.innerNode);
        expect(el.childNodes.length).toEqual(1);
      });
    });

    describe("The innerNode property", function() {
      it("Should point to our user data", function() {
        expect(el.innerNode.childNodes[0].tagName).toEqual('LAYER-AVATAR');
        expect(el.innerNode.childNodes[1].tagName).toEqual('LABEL');
        expect(el.innerNode.childNodes[2].tagName).toEqual('INPUT');
      });
    });

    describe("The firstInSeries property", function() {
      it("Should default to false", function() {
        expect(el.classList.contains('layer-list-item-first')).toBe(false);
      });
      it("Should update layer-list-item-first class", function() {
        el.firstInSeries = true;
        expect(el.classList.contains('layer-list-item-first')).toBe(true);

        el.firstInSeries = false;
        expect(el.classList.contains('layer-list-item-first')).toBe(false);
      });
    })

    describe("The lastInSeries property", function() {
      it("Should default to false", function() {
        expect(el.classList.contains('layer-list-item-last')).toBe(false);
      });
      it("Should update layer-list-item-last class", function() {
        el.lastInSeries = true;
        expect(el.classList.contains('layer-list-item-last')).toBe(true);

        el.lastInSeries = false;
        expect(el.classList.contains('layer-list-item-last')).toBe(false);
      });
    });
  });
});


text:
Implementation of Kou, Markowsky and Berman algorithm (KMB 1981) using the Boost Graph Library

### Requires
1. g++-4.8
2. boost 1.55

### Build
1. Set BOOST_INSTALL_ROOT to your boost installation folder
2. Run `make` to build the release version
3. Run `make debug` to build the debug version
4. Run `make test` to test

### Scripts
1. brite2dot.sh : Converts BRITE format files to dot. Run with `./brite2dot.sh input.brite`
2. inet2dot.sh : Converts inet format files to dot. Run with `./inet2dot.sh inputfile`
2. gtitm2dot.sh : Converts gtitm format files to dot. Run with `./gtitm-alt2dot.sh inputfile`. Convert the `.gb` file to the alteraate format using `sgb2alt` provided in the gt-itm distribution.

### Author
Snehasish Kumar


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

$config['twitter_consumer_token']		= 'your_consumer_token';
$config['twitter_consumer_secret']		= 'your_consumer_token_secret';
$config['twitter_access_token']			= 'your_access_token';
$config['twitter_access_secret']		= 'your_access_token_secret';

/* End of file twitter.php */
/* Location: ./application/config/twitter.php */


text:
<?php

namespace Bankrot\SiteBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadUserData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {
        /** @var \FOS\UserBundle\Doctrine\UserManager $userManager */
        $userManager = $this->container->get('fos_user.user_manager');

        $user = $userManager->createUser();
        $user->setUsername('user');
        $user->setEmail('user@localhost');
        $user->setPlainPassword('user');
        $user->setEnabled(true);

        $this->addReference('user_user', $user);

        $userManager->updateUser($user);
    }

    public function getOrder() { return 1; }
}


text:
import {ProjectRepository} from "../repositories/project.repo";
import {SchemaHelper} from "@maxxton/microdocs-core/helpers/schema/schema.helper";
import {ProjectTree, Project} from "@maxxton/microdocs-core/domain";

export class ProjectService {

  constructor(private projectRepo: ProjectRepository) {
  }

  public storeAggregatedProjects(env: string, projectTree: ProjectTree): void {

    const problems = checkCircularStructure(projectTree);
    if (problems) {
      problems.forEach(problem => {
        console.warn(`[${env}/index] circular structure: ${problem}`);
      });
    }

    this.projectRepo.storeAggregatedProjects(env, projectTree);
  }

  public storeAggregatedProject(env: string, project: Project): void {
    this.addResponseExamples(project);

    const problems = checkCircularStructure(project);
    if (problems) {
      problems.forEach(problem => {
        console.warn(`[${env}/${project.info.title}:${project.info.version}] circular structure: ${problem}`);
      });
    }

    this.projectRepo.storeAggregatedProject(env, project);
  }

  private addResponseExamples(project: Project) {
    project.swagger = "2.0";
    if (project.paths != undefined) {
      for (const path in project.paths) {
        for (const method in project.paths[path]) {
          const endpoint = project.paths[path][method];
          if (endpoint.responses != undefined && endpoint.responses['default'] != undefined && endpoint.responses['default'].schema != undefined) {
            const response = endpoint.responses['default'];
            const schema = response.schema;
            const example = SchemaHelper.generateExample(schema, undefined, [], project);
            schema.default = example;
          }
        }
      }
    }
  }
}

/**
 * Detect circular structure in the object
 * @param object
 * @return problems detections
 */
function checkCircularStructure(object: any, objectStore: Array<{path: string, object: any}> = [], problems: Array<string> = [], path: string = '.'): Array<string> {
  const stack = objectStore.map(obj => obj);

  if (object && typeof(object) === 'object') {
    const stackItem = stack.filter(stackItem => stackItem.object === object)[0];
    if (stackItem) {
      problems.push(path + " <=> " + stackItem.path);
    } else {
      stack.push({path, object});
      for (const key in object) {
        const propertyPath = path === '.' ? key : path + '.' + key;
        checkCircularStructure(object[key], stack, problems, propertyPath);
      }
    }
  }

  return problems;
}


text:
module MongoidExtended
  module ObjectId
    class << self
      def configured
        ::BSON::ObjectId.send(:prepend, HashRepresentation)

        @configured = true
      end

      def configured?
        !!@configured
      end
    end

    # rewrite methods `BSON::ObjectId#as_json` & `BSON::ObjectId#to_json`
    # Return the object id as a JSON hash representation.
    #
    # @example Get the object id as JSON.
    #   object_id.as_json
    #
    # @return [ String ] The object id as a JSON string.
    #
    # @since 2.0.0
    module HashRepresentation
      def to_json(*args)
        to_s
      end

      def as_json(*args)
        to_s
      end
    end
  end
end


text:
package com.gl.mychat.test;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;

import java.security.Key;
import java.util.Date;

public class TMain {

	public static void main(String[] args) throws InterruptedException {
		Key key = MacProvider.generateKey();

		String s = Jwts.builder().setSubject("Joe")
				.signWith(SignatureAlgorithm.HS512, key).compact();
		System.out.println(Jwts.parser().setSigningKey(key).parseClaimsJws(s)
				.getBody().getSubject().equals("Joe"));
	}

}


text:
===

##### 29 November 2016

###### Yaroslav Serhieiev, Bohdan Litvinov

---

# to back someone up

### Translations

* поддержать
* прикрыть кого-то

### Examples

> She's here **to back me up**.
> Она здесь, чтобы поддержать меня.

---

# to back up smth (with)

### Translations

* подкрепить что-то чем-то

### Examples

> Wait... do you have any medical statistics **to back up** this theory?

---

# back where I come from

### Translations

* там, откуда я родом

### Examples

> five bucks for 2 seconds of digging is quite a lot of money **back where I come from**

---

# compound

составной, смесь, усугублять

> **to compound** existing problems
> **усугублять** существующие проблемы

> Breathe in this **compound** several times a day.
> Вдыхайте эту **смесь** несколько раз в день

> Fixed an error while processing of **compound** multi-line structure in figure brackets {...}.
> Исправлена ошибка обработки **составной** многострочной конструкции в фигурных скобках

---

# a repercussion

последствие, отголосок
> We believe that the paper addresses the symptoms and the **repercussions** of the problem but not its causes.
> Мы считаем, что в документе рассматриваются симптомы и **последствия** проблемы, а не ее причины.

> your decision not to go to college will have **repercussions** you'll feel for years to come
> твое решение не идти в колледж будет иметь **последствия**, которые ты ощутишь на себе еще долгие годы

---

# a narrative
изложение, повествование, рассказ, художественный (фильм)

> It's a narrative crafted to have the greatest impact on a jury.
> Это рассказ, созданный, чтобы повлиять на присяжных

> Narrative film can't begin to touch the horror of experience.
> Художественный фильм не может передать реальный ужас.

---

# a bugbear

страшилка, "бабай"; то, чем можно пугать

> In any event it ignores the fact that the only effective reactions are _measured_ ones; the danger with **"laying it on thick"** is often that of becoming a _mere_ **bugbear** that fails to influence its target audience.

> Так или иначе он игнорирует то обстоятельство, что эффективными являются лишь _осторожные_ действия, а метод **"вколачивания"** часто оборачивается _бесполезными_ **"страшилками"** без реальных последствий для соответствующих стран.

---

# get away with something/get by with something

избежать наказания; провернуть что-то, что сойдет с рук

> You got away with it last time.
> Прошлый раз тебе это сошло с рук.

---

# inadvertent

непреднамеренный, непроизвольный, неумышленный

> Nevertheless, **inadvertent** errors in information may occur.
> Тем не менее, в информации могут содержаться ошибки **неумышленного характера**.

---

# me gusta

**me gusta** (звучит как «ме густа» ) по-испански «мне нравится» — одна из комиксовых физиономий, выражающая удовлетворение человека, увидевшего или сделавшего нечто отвратительное.

[цитата взята отсюда](https://otvet.mail.ru/question/65448039)

---

# mindful of/that

> She was also **mindful that** the holiday began on 9 December.
> Она также помнила о том, что 9 декабря начинается праздник.

> I reiterate that we are **mindful of** our obligations.
> Я вновь повторяю, что мы помним о наших обязательствах.

---

# careless (of)

> It was **careless of you** to lose my car key.
> Это было **беспечно с твоей стороны** потерять ключ от моей машины.

---

# heedless (of)

позабыв, не обращая внимания на, оставаясь глухим к

> **Heedless of** the danger, he returned to the burning building to save his dog.
> **Позабыв об** опасности, он вернулся в горящий дом, чтобы спасти своего пса.

#### to heed

> Be careful and **heed** your instinct.
> Будь осторожен, и **прислушивайся** к своим инстинктам.

---

# superficial

поверхностный

> **superficial** injuries
> **поверхностные** раны

> Such treatment should not be **superficial** or limited by time.
> Такой подход не должен быть **поверхностным** или ограниченным по времени.

---

# to captivate

пленить, очаровывать

> to captivate someone's eyes and ears
> пленить чей-то взгляд и слух

> a captivating story
> увлекательная история (сюжет)

---

# to come down to

сводиться к, упираться в

> It all **comes down to** honesty.
> В конце концов, все **сводится к** искренности.

> You see, it all **comes down to** this fellow.
> Понимаете, все **упирается в** этого парня.

---

# to contradict

противоречить

> You're **contradicting** yourself.
> Ты сам себе **противоречишь**.

---

# to disrupt

нарушить, сорвать, подорвать

to disrupt:

* stability
* traffic
* process
* balance

---

# a hunch

догадка, предчувствие, подозрение, интуиция

> I can't just go on **a hunch**.
> Я не могу просто полагаться на **предчувствие**.

> I have **a hunch**...
> У меня есть **догадка**...
---

# нутром чувствовать

> I know in my gut that...
> I can feel it in my bones...

---

# to mitigate

смягчить, уменьшить, ослабить

> **to mitigate** risks of...
> **смягчить риски**, связанные с...

> **mitigating** circumstances
> **смягчающие** обстоятельства

---

# to push smb over the edge

> This might just be enough **to push it over the edge**.
> Этого возможно будет достаточно **чтобы переборщить**.

> So if she finds out about this, it could **push her over the edge**.
> И если она про это узнает, это **может довести её до ручки**.

> I reckon that would be enough **to push him over the edge**.
> Я полагаю, этого было достаточно, чтобы **подтолкнуть его к отчаянным действиям**.

---

# to put up with smb/smth

терпеть что-то, мириться с, выносить что-то

> Like I told you, I just can't **put up with** her attitude anymore.
> Как я вам уже говорила, мы больше не можем **терпеть** ее поведение.

---

# to shade in

заштриховать (треугольник, фигуру)

> I'd like you to shade in all the triangles.

---

# to shatter

разбить(ся) вдребезги

> Then I saw that car window shatter.
> Затем я увидел, как разбилось окно той машины.

> You're still trying to **mend** the **shattered pieces**.
> Ты все еще пытаешься **склеить** **осколки**.

---

# to be/sit on the fence about

быть на перепутьи, сомневаться

> I was **on the fence about** whether I wanted to do it.
> Я **сомневался**, хочу ли я этим заниматься.

> You know, I was **on the fence about** this purchase.
> Знаете, я и сам тут был **на перепутье** с этой покупкой.

---

# to steer away from

держаться подальше от, избегать

> **Steer away from** Earth, try not to bump into the moon otherwise the races who live there will be livid.
> **Держитесь подальше от** Земли и постарайтесь не врезаться в Луну; в противном случае, расы, живущие там, будут в ярости.

---

# to take off

снять, взлететь, стартовать

> You forgot **to take off** your watch.
> Ты забыл **снять** часы.

> Planes cannot **take off** or land.
> Самолеты не могут **взлететь** или приземлиться.

> Project **took off** in January, 2009.
> Проект **стартовал** в январе 2009 года.

---

# curtly

коротко, отрывисто

> to nod curtly
> коротко кивнуть

> to reject curtly
> наотрез отказаться

---

# somber

мрачный

> somber spectacle
> мрачное зрелище
>
> somber music
> мрачная музыка

### Synonyms
dark, gloomy, grim, bleak, dismal, sombre

---
# on the bubble
(быть)на волоске

>The Knights had been on the bubble for the tournament, but played their way in by winning their last five games.

>He failed 3 projects in last 6 month, he is 'on the bubble' in this company.

>We need 5 people for the team. We have already chosen 4 and so the remaining 6 of the applicants are on the bubble.
---

# drunk tank
вытрезвитель

>I hate to break it to you, but you spent the night in the drunk tank.

---

# rub the wrong way
раздражать

>He was known as a moody and selfish player who rubbed teammates the wrong way.

>Whenever they meet,they always manage to rub each other the wrong way.

---

# cry/say uncle
сдаваться

>She was nagging his boyfriend until he cried uncle (cry uncle).

>I'm going to make my examination cry uncle.

---

# behind the wheel
за рулем

>Mia was behind the wheel, and Kim was studying the map.

>If you've had too much to drink, don't get behind the wheel.

---

# shovel
лопата

>He is outside shoveling snow.

>Stop shoveling food into your mouth.

---

# repulse

отражать и отталкивать

>The enemy attack was quickly repulsed.

>His gross eating habits would repulse anyone sharing a meal with him.

>Because of his rude behavior that would repulse many people, he was without close friends.

---

# deserted
пустой, опустевший

> He was deserted by his friends.

>Tom stood alone under a big clock in the deserted train station.

---

# incidentally
кстати

>Incidentally, Joan is no longer returning my phone calls since she borrowed money from me. (By the way, Joan is ...)

>The city's plans include a new football stadium, which incidentally, is going to be paid for with taxpayer dollars.

---

# Thank you!


text:
package test_with_remote_apis.methods;

import com.slack.api.Slack;
import com.slack.api.methods.SlackApiException;
import com.slack.api.methods.response.dialog.DialogOpenResponse;
import com.slack.api.model.dialog.Dialog;
import com.slack.api.model.dialog.DialogSubType;
import com.slack.api.model.dialog.DialogTextElement;
import config.Constants;
import config.SlackTestConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.AfterClass;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@Slf4j
public class dialogs_Test {

    static SlackTestConfig testConfig = SlackTestConfig.getInstance();
    static Slack slack = Slack.getInstance(testConfig.getConfig());

    @AfterClass
    public static void tearDown() throws InterruptedException {
        SlackTestConfig.awaitCompletion(testConfig);
    }

    String botToken = System.getenv(Constants.SLACK_SDK_TEST_BOT_TOKEN);

    @Test
    public void open() throws IOException, SlackApiException {

        DialogTextElement quantityTextElement = DialogTextElement.builder()
                .subtype(DialogSubType.NUMBER)
                .label("Quantity")
                .name("quantity")
                .hint("The number you need")
                .maxLength(3)
                .minLength(1)
                .placeholder("Required quantity")
                .value("1")
                .build();

        Dialog dialog = Dialog.builder()
                .title("Request pens")
                .callbackId("pens-1122")
                .elements(Arrays.asList(quantityTextElement))
                .state("some-state")
                .notifyOnCancel(true)
                .submitLabel("")
                .build();

        /*
         * A dialog in Slack can only be opened in response to a user action such as a slash command or
         * button click (which now include trigger_ids in callbacks). A dialog.open request has to include
         * that same trigger_id in order to succeed. The dialog.open request must also be made within 3
         * seconds of the user action.  Therefore, only an 'invalid trigger' ID response can be tested.
         */
        DialogOpenResponse dialogOpenResponse = slack.methods().dialogOpen(r -> r
                .token(botToken)
                .triggerId("FAKE_TRIGGER_ID")
                .dialog(dialog));
        assertThat(dialogOpenResponse.isOk(), is(false));
        assertThat(dialogOpenResponse.getError(), is("invalid_trigger"));
    }
}


text:
require('./dist/ui-router-metatags');
module.exports = 'ui.router.metatags';


text:
package com.freshplanet.ane.GoogleCloudStorageUpload.functions;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREInvalidObjectException;
import com.adobe.fre.FREObject;
import com.adobe.fre.FRETypeMismatchException;
import com.adobe.fre.FREWrongThreadException;
import com.freshplanet.ane.GoogleCloudStorageUpload.tasks.UploadToGoogleCloudStorageAsyncTask;

public class UploadBinaryFileToServer implements FREFunction {

	private static String TAG = "GoogleCloudStorageUpload";

	@Override
	public FREObject call(FREContext ctx, FREObject[] args)
	{
		Log.d(TAG, "[UploadImageToServer] Entering call()");

		String localURL = null;
		String uploadURL = null;
		JSONObject uploadParamsJSON = null;
		Log.d(TAG, "[UploadImageToServer] try catch()");

		try {
			localURL = args[0].getAsString();
			uploadURL = args[1].getAsString();
			uploadParamsJSON = new JSONObject(args[2].getAsString());
			Log.d(TAG, "[UploadImageToServer] localURL: "+localURL+ " uploadURL: "+uploadURL+" uploadParamsJSON: "+uploadParamsJSON );
		} catch (IllegalStateException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		} catch (FRETypeMismatchException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		} catch (FREInvalidObjectException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		} catch (FREWrongThreadException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		} catch (JSONException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		} catch (Exception e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		}

		if (localURL != null && uploadURL != null && uploadParamsJSON != null)
		{
			new UploadToGoogleCloudStorageAsyncTask(uploadParamsJSON, localURL).execute(uploadURL);
		}

		Log.d(TAG, "[UploadImageToServer] Exiting call()");
		return null;
	}

}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Model_Product extends ORM {
    protected $_table_name = 'products';
    protected $_primary_key = 'id';
    protected $_db_group = 'default';
    protected $_has_many = array(
        'comments' => array(
            'model' => 'comment',
            'foreign_key' => 'product_id',
        ),
        'images' => array(
            'model' => 'image',
            'foreign_key' => 'product_id',
        ),
        'categori' => array(
            'model' => 'categori',
            'foreign_key' => 'product_id',
            'through' => 'productc_categoris',
            'far_key' => 'category_id',
        ),
    );
    public function rules(){
        return array(
            'title' => array(
                array('not_empty'),
                array('min_length', array(':value', 3))
            ),
        );
    }
    public function labels(){
        return array(
            'title' => 'Название',
        );
    }
    public function filters(){
        return array(
            TRUE => array(
                array('trim'),
                array('strip_tags'),
            ),
        );
    }
}


text:
#ifdef STAND_ALONE
#   define BOOST_TEST_MODULE cassandra
#endif

#include "encode.hpp"

#include <boost/test/unit_test.hpp>
#include <time.h>

using namespace cass;

BOOST_AUTO_TEST_SUITE(encode_duration)

BOOST_AUTO_TEST_CASE(base)
{
  CassDuration value(0, 0, 0);
  Buffer result = encode(value);
  BOOST_CHECK_EQUAL(3, result.size());
  const char* result_data = result.data();
  BOOST_CHECK_EQUAL(result_data[0], 0);
  BOOST_CHECK_EQUAL(result_data[1], 0);
  BOOST_CHECK_EQUAL(result_data[2], 0);
}

BOOST_AUTO_TEST_CASE(simple_positive)
{
  CassDuration value(1, 2, 3);
  Buffer result = encode(value);
  BOOST_CHECK_EQUAL(3, result.size());
  const char* result_data = result.data();
  BOOST_CHECK_EQUAL(result_data[0], 2);
  BOOST_CHECK_EQUAL(result_data[1], 4);
  BOOST_CHECK_EQUAL(result_data[2], 6);
}

BOOST_AUTO_TEST_CASE(simple_negative)
{
  CassDuration value(-1, -2, -3);
  Buffer result = encode(value);
  BOOST_CHECK_EQUAL(3, result.size());
  const char* result_data = result.data();
  BOOST_CHECK_EQUAL(result_data[0], 1);
  BOOST_CHECK_EQUAL(result_data[1], 3);
  BOOST_CHECK_EQUAL(result_data[2], 5);
}

BOOST_AUTO_TEST_CASE(edge_positive)
{
  CassDuration value((1UL << 31) - 1, (1UL << 31) - 1, (1UL << 31) - 1);
  Buffer result = encode(value);
  BOOST_CHECK_EQUAL(15, result.size());
  unsigned const char* result_data = reinterpret_cast<unsigned const char*>(result.data());

  // The first 5 bytes represent (1UL<<31 - 1), the max 32-bit number. Byte 0
  // has the first 4 bits set to indicate that there are 4 bytes beyond this one that
  // define this field (each field is a vint of a zigzag encoding of the original
  // value). Encoding places the least-significant byte at byte 4 and works backwards
  // to record more significant bytes. Zigzag encoding just left shifts a value
  // by one bit for positive values, so byte 4 ends in a 0.

  BOOST_CHECK_EQUAL(result_data[0], 0xf0);
  for (int ind = 1; ind < 4; ++ind) {
    BOOST_CHECK_EQUAL(result_data[ind], 0xff);
  }
  BOOST_CHECK_EQUAL(result_data[4], 0xfe);

  // The same interpretation applies to "days" and "nanos".
  BOOST_CHECK_EQUAL(result_data[5], 0xf0);
  for (int ind = 6; ind < 9; ++ind) {
    BOOST_CHECK_EQUAL(result_data[ind], 0xff);
  }
  BOOST_CHECK_EQUAL(result_data[9], 0xfe);

  BOOST_CHECK_EQUAL(result_data[10], 0xf0);
  for (int ind = 11; ind < 14; ++ind) {
    BOOST_CHECK_EQUAL(result_data[ind], 0xff);
  }
  BOOST_CHECK_EQUAL(result_data[14], 0xfe);
}

BOOST_AUTO_TEST_CASE(edge_negative)
{
  CassDuration value(1L << 31, 1L << 31, 1L << 31);
  Buffer result = encode(value);
  BOOST_CHECK_EQUAL(15, result.size());
  unsigned const char* result_data = reinterpret_cast<unsigned const char*>(result.data());

  // We have 5-bytes for 1L << 31, the min 32-bit number. The zigzag
  // representation is 4 bytes of 0xff, and the first byte is 0xf0 to say we have
  // 4 bytes of value beyond these size-spec-bits.

  BOOST_CHECK_EQUAL(result_data[0], 0xf0);
  for (int ind = 1; ind <= 4; ++ind) {
    BOOST_CHECK_EQUAL(result_data[ind], 0xff);
  }

  // The same is true for "days" and "nanos".
  BOOST_CHECK_EQUAL(result_data[5], 0xf0);
  for (int ind = 6; ind <= 9; ++ind) {
    BOOST_CHECK_EQUAL(result_data[ind], 0xff);
  }

  BOOST_CHECK_EQUAL(result_data[10], 0xf0);
  for (int ind = 11; ind <= 14; ++ind) {
    BOOST_CHECK_EQUAL(result_data[ind], 0xff);
  }
}

BOOST_AUTO_TEST_SUITE_END()


text:
namespace MScResearchTool.Server.Core.Enums
{
    public enum EWebKeyValues
    {
        UserData,
        LoginFailed,
        LoginAttempts,
        RegistrationResult
    }
}


text:
#ifndef LULLABY_SYSTEMS_MAP_EVENTS_MAP_EVENTS_SYSTEM_H_
#define LULLABY_SYSTEMS_MAP_EVENTS_MAP_EVENTS_SYSTEM_H_

#include <unordered_set>

#include "lullaby/generated/map_events_def_generated.h"
#include "lullaby/modules/ecs/component.h"
#include "lullaby/modules/ecs/system.h"
#include "lullaby/systems/dispatcher/event.h"

namespace lull {

// MapEventsSystem exposes EventResponders that allow complex event mapping.
// Using the |input_events| and |output_events| properties, events can cause
// new events to be sent to a set of targets (i.e. hover causing "dim" events to
// be sent to all siblings.)
class MapEventsSystem : public System {
 public:
  explicit MapEventsSystem(Registry* registry);

  void Create(Entity e, HashValue type, const Def* def) override;

  void Destroy(Entity e) override;

 private:
  using Group = std::unordered_set<Entity>;
  using EventSender = std::function<void(Entity target)>;

  enum TargetMode {
    kChildren,
    kParent,
    kSiblings,
    kGroup,
    kDescendants,
  };

  struct ResponseData {
    Entity entity = kNullEntity;
    TargetMode mode = kChildren;
    HashValue group_id = 0;
    bool include_self = false;
    const EventDefArray* input_events = nullptr;
    const EventDefArray* output_events = nullptr;
  };

  static void ProcessEventMap(const EventMapDef* data, ResponseData* response);
  void MapEvent(const ResponseData& response, const EventWrapper& event) const;
  void SendEventsToTargets(const ResponseData& response,
                           const EventSender& sender) const;
  void SendEventsToDescendants(const Entity& entity,
                               const EventSender& sender) const;

  std::unordered_map<HashValue, Group> groups_;
};

}  // namespace lull

LULLABY_SETUP_TYPEID(lull::MapEventsSystem);

#endif  // LULLABY_SYSTEMS_MAP_EVENTS_MAP_EVENTS_SYSTEM_H_


text:
package com.infinityraider.agricraft.items;

import com.agricraft.agricore.core.AgriCore;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import com.infinityraider.agricraft.api.v1.items.IAgriJournalItem;
import com.infinityraider.agricraft.api.v1.plant.IAgriPlant;
import com.infinityraider.agricraft.crafting.RecipeCopyJournal;
import com.infinityraider.agricraft.handler.GuiHandler;
import com.infinityraider.agricraft.init.AgriItems;
import com.infinityraider.agricraft.items.tabs.AgriTabs;
import com.infinityraider.agricraft.reference.AgriNBT;
import com.infinityraider.agricraft.utility.StackHelper;
import com.infinityraider.infinitylib.item.IItemWithModel;
import com.infinityraider.infinitylib.item.ItemBase;
import com.infinityraider.infinitylib.utility.IRecipeRegister;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.RecipeSorter;
import net.minecraftforge.oredict.ShapedOreRecipe;

public class ItemJournal extends ItemBase implements IAgriJournalItem, IItemWithModel, IRecipeRegister {

    public ItemJournal() {
        super("journal");
        this.setMaxStackSize(1);
        this.setCreativeTab(AgriTabs.TAB_AGRICRAFT);
    }

    //this has to return true to make it so the getContainerItem method gets called when this item is used in a recipe
    @Override
    public boolean hasContainerItem(ItemStack stack) {
        return true;
    }

    //when this item is used in a crafting recipe it is replaced by the item return by this method
    @Override
    public ItemStack getContainerItem(ItemStack itemStack) {
        return itemStack.copy();
    }

    @Override
    public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) {
        if (world.isRemote) {
            player.openGui(AgriCraft.instance, GuiHandler.JOURNAL_GUI_ID, world, player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ());
        }
        return new ActionResult<>(EnumActionResult.PASS, stack);
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void addInformation(ItemStack stack, EntityPlayer player, List<String> list, boolean flag) {
        list.add(AgriCore.getTranslator().translate("agricraft_tooltip.discoveredSeeds") + ": " + getDiscoveredSeedIds(stack).count());
    }

    private Stream<String> getDiscoveredSeedIds(@Nullable ItemStack journal) {
        return Optional.ofNullable(journal)
                .map(ItemStack::getTagCompound)
                .map(tag -> tag.getString(AgriNBT.DISCOVERED_SEEDS))
                .map(ids -> ids.split(";"))
                .map(Arrays::stream)
                .orElseGet(Stream::empty);
    }

    @Override
    public void addEntry(@Nullable ItemStack journal, @Nullable IAgriPlant plant) {
        if (journal != null && plant != null) {
            if (!isSeedDiscovered(journal, plant)) {
                NBTTagCompound tag = StackHelper.getTag(journal);
                String old = tag.getString(AgriNBT.DISCOVERED_SEEDS);
                tag.setString(AgriNBT.DISCOVERED_SEEDS, old + plant.getId() + ";");
                journal.setTagCompound(tag);
            }
        }
    }

    @Override
    public boolean isSeedDiscovered(@Nullable ItemStack journal, @Nullable IAgriPlant plant) {
        return (journal != null) && (plant != null) && getDiscoveredSeedIds(journal).anyMatch(plant.getId()::equals);
    }

    @Override
    public List<IAgriPlant> getDiscoveredSeeds(@Nullable ItemStack journal) {
        return Optional.ofNullable(journal)
                .map(this::getDiscoveredSeedIds)
                .orElseGet(Stream::empty)
                .map(AgriApi.getPlantRegistry()::get)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    @Override
    public void registerRecipes() {
        // Normal Crafting
        GameRegistry.addRecipe(new ShapedOreRecipe(this, "csc", "sbs", "csc", 'c', AgriItems.getInstance().CROPS, 's', Items.WHEAT_SEEDS, 'b', Items.BOOK));
        // Copy Crafting
        RecipeSorter.register("recipe.copy_journal", RecipeCopyJournal.class, RecipeSorter.Category.SHAPELESS, "");
        GameRegistry.addRecipe(new RecipeCopyJournal());
    }

}


text:
<?php

namespace Puli\Manager\Api\Package;

use Puli\Manager\Api\Environment\ProjectEnvironment;
use Puli\Manager\Api\InvalidConfigException;
use Webmozart\Expression\Expression;

/**
 * Manages the package repository of a Puli project.
 *
 * @since  1.0
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
interface PackageManager
{
    /**
     * Returns the manager's environment.
     *
     * @return ProjectEnvironment The project environment.
     */
    public function getEnvironment();

    /**
     * Installs the package at the given path in the repository.
     *
     * @param string      $installPath   The path to the package.
     * @param string|null $name          The package name or `null` if the name
     *                                   should be read from the package's
     *                                   puli.json.
     * @param string      $installerName The name of the installer.
     *
     * @throws InvalidConfigException If the package is not configured correctly.
     * @throws NameConflictException If the package has the same name as another
     *                               loaded package.
     */
    public function installPackage($installPath, $name = null, $installerName = InstallInfo::DEFAULT_INSTALLER_NAME);

    /**
     * Renames the package with the given name.
     *
     * @param string $name    The package name.
     * @param string $newName The new package name.
     *
     * @throws NoSuchPackageException If the package was not found.
     * @throws NameConflictException If a package with the new name exists
     *                               already.
     */
    public function renamePackage($name, $newName);

    /**
     * Removes the package with the given name.
     *
     * @param string $name The package name.
     */
    public function removePackage($name);

    /**
     * Removes all packages matching the given expression.
     *
     * If no matching packages are found, this method does nothing.
     *
     * @param Expression $expr The search criteria.
     */
    public function removePackages(Expression $expr);

    /**
     * Removes all packages.
     *
     * If matching packages are found, this method does nothing.
     */
    public function clearPackages();

    /**
     * Returns a package by name.
     *
     * @param string $name The package name.
     *
     * @return Package The package.
     *
     * @throws NoSuchPackageException If the package was not found.
     */
    public function getPackage($name);

    /**
     * Returns the root package.
     *
     * @return RootPackage The root package.
     */
    public function getRootPackage();

    /**
     * Returns all installed packages.
     *
     * @return PackageCollection The installed packages.
     */
    public function getPackages();

    /**
     * Returns all packages matching the given expression.
     *
     * @param Expression $expr The search criteria.
     *
     * @return PackageCollection The packages matching the expression.
     */
    public function findPackages(Expression $expr);

    /**
     * Returns whether the manager has the package with the given name.
     *
     * @param string $name The package name.
     *
     * @return bool Whether the manager has a package with that name.
     */
    public function hasPackage($name);

    /**
     * Returns whether the manager has any packages.
     *
     * You can optionally pass an expression to check whether the manager has
     * packages matching the expression.
     *
     * @param Expression $expr The search criteria.
     *
     * @return bool Returns `true` if the manager has packages and `false`
     *              otherwise. If an expression was passed, this method only
     *              returns `true` if the manager has packages matching the
     *              expression.
     */
    public function hasPackages(Expression $expr = null);
}


text:
<?php

	Class Extension_Url_Router extends Extension{

		private $_hasrun = false;

		public function install()
		{
			Symphony::Database()->query("
					CREATE TABLE IF NOT EXISTS `tbl_url_router` (
						`id` int(11) NOT NULL auto_increment,
						`from` varchar(255) NOT NULL,
						`to` varchar(255) NOT NULL,
						`type` enum('route','redirect') DEFAULT 'route',
						`http301` enum('yes','no') DEFAULT 'no',
						PRIMARY KEY (`id`)
					)
			");
		}

		public function fetchNavigation() {
			return array(
				array(
					'location' => __('Blueprints'),
					'name' => __('URL Routes'),
					'link' => '/routes/'
				)
			);
		}

		public function uninstall()
		{
			Symphony::Database()->query("DROP TABLE `tbl_url_router`");
		}

		public function getSubscribedDelegates()
		{
			return array(
				array(
					'page'		=> '/frontend/',
					'delegate'	=> 'FrontendPrePageResolve',
					'callback'	=> 'frontendPrePageResolve'
				)
			);
		}

		/**
		 * Get all routes
		 *
		 * @return Array	Array of routes from the database
		 */
		public function getRoutes()
		{
			$routes = Symphony::Database()->fetch("SELECT * FROM tbl_url_router");

			foreach ($routes as $i => $route)
			{
				preg_match_all('/[$:]([0-9a-zA-Z_]+)/', $route['from'], $names, PREG_PATTERN_ORDER);
				$names = $names[0];

				if (!$names) continue;

				$new  = preg_replace('/[$:][[0-9a-zA-Z_]+/', '([a-zA-Z0-9_\+\-%]+)', $route['from']);
				$new  = '/'. trim($new, '/');
				$new  = '/'. str_replace('/', "\/", $new);
				$new .= '/i';

				$to = '/'. trim($route['to'], '/');
				foreach ($names as $k => $n)
					$to = str_replace($n, '$'. ($k +1), $to);

				$route['from-clean'] = $route['from'];
				$route['to-clean'] = $route['to'];
				$route['from'] = $new;
				$route['to'] = $to;

				$routes[$i] = $route;
			}

			return $routes;
		}

		/**
		 * Get the first route that matches the given path
		 *
		 * @param String $path Thepath to regex match on
		 *
		 * @return Array	Array of matched page details
		 * @return Boolean	False if no page matched
		 */
		public function getRoute($path)
		{
			$routes = $this->getRoutes();

			$return = array();

			foreach($routes as $route)
			{
				if(preg_match($route['from'], $path, $matches) == 1)
				{
					$route['routed'] = preg_replace($route['from'], $route['to'], $path);

					$route['original'] = $path;

					$return = $route;

					break;
				}
			}

			return $return;
		}

		/**
		 * Save the routes from the preferences into the database
		 *
		 * @param unknown $context Symphony context
		 */
		public function saveRoutes()
		{
			$routes = array();

			if(!empty($_POST['settings']['url-router']['routes']))
			{
				$route = array(
					'type' => '',
					'from' => '',
					'to' => '',
					'http301' => 'no'
				);

				foreach($_POST['settings']['url-router']['routes'] as $item)
				{
					if(isset($item['type']) && !empty($item['type']))
					{
						$route = array(
							'type' => '',
							'from' => '',
							'to' => '',
							'http301' => 'no'
						);

						$route['type'] = $item['type'];
					}
					if(isset($item['from']) && !empty($item['from']))
					{
						$route['from'] = $item['from'];
					}
					if(isset($item['to']) && !empty($item['to']))
					{
						$route['to'] = $item['to'];
						$routes[] = $route;
					}
					if(isset($item['http301']) && !empty($item['http301']))
					{
						$key = count($routes) - 1;
						$routes[$key]['http301'] = $item['http301'];
					}
				}
			}

			Symphony::Database()->query("DELETE FROM tbl_url_router");

			if(count($routes) > 0) {
				Symphony::Database()->insert($routes, "tbl_url_router");
				unset($_POST['settings']['url-router']['routes']);
			}
		}

		public function frontendPrePageResolve($context)
		{
			if(!$this->_hasrun)
			{
				// Prevent an infinity loop of delegate callbacks to this function - @creativedutchmen
				$this->_hasrun = true;

				// Used to check page resolution, would cause loop.
				$frontend = FrontEnd::Page();

				// Get route or empty array
				$route = $this->getRoute($context['page']);

				// Check whether the current page resolves as it is
				$page_can_resolve = $frontend->resolvePage($context['page']);

				if(!empty($route))
				{
					// If the page can resolve, but is route the route says to force
					if(!empty($page_can_resolve) && $route['type'] == 'route' && $route['http301'] == 'yes')
					{
						$context['page'] = $route['routed'];
					}
					// If the page can't resolve, and is route
					elseif(empty($page_can_resolve) && $route['type'] == 'route')
					{
						$context['page'] = $route['routed'];
					}
					// If is redirect
					elseif($route['type'] == 'redirect')
					{
						$context['page'] = $route['routed'];
						if($route['http301'] === 'yes')
						{
							header("Location:" . URL . $context['page'], true, 301);
						}
						else
						{
							header("Location:" . URL . $context['page']);
						}
						die;
					}
				}
				else
				{
					$index = $this->__getIndexPage();

					if(!$page_can_resolve)
					{
						$context['page'] = "/" . $index['handle'] . $context['page'];
					}
				}
				unset($frontend, $route, $page_can_resolve);
			}
		}

		private function __getIndexPage()
		{
			return Symphony::Database()->fetchRow(0, "
				SELECT `tbl_pages`.* FROM `tbl_pages`, `tbl_pages_types`
				WHERE `tbl_pages_types`.page_id = `tbl_pages`.id
				AND tbl_pages_types.`type` = 'index'
				LIMIT 1
			");
		}

	}


text:
<?php
	namespace Perseids\IAM\Property\Abstractions;

	use Perseids\IAM\Exceptions\RequiredFieldException;

	class PropertyBase {
		/**
		 * The Namespace used for the xml
		 * @var string
		 */
		protected $namespace = "contacts";

		/**
		 * The name for the mother node
		 * @var string
		 */
		protected $node = "mockup";

		/**
		 * The main node attributes
		 * @var string
		 */
		protected $nodeAttributes = '';

		/**
		 * A list of property that are required for serialization and thus xml
		 * @var array
		 */
		protected $required = array();

		/**
		 * Serialization excluded vars
		 * @var array
		 */
		protected $excludeSerialization = ["namespace", "node", "excludeSerialization", "nodeAttributes", "required"];

		/**
		 * Returns XML for content
		 * @param  boolean $attributes If set to true, will put the node's attributes in its declaration
		 * @return string The XML representation of the element
		 */
		public function getXML($attributes = False) {
			$object = $this->getSerialized($deepSerialization = false);
			$xml = array();
			while(list($key, $value) = each($object)) {
				$xml[] = $this->createNode($this->namespace, $key, $value, false);
			}
			$xml = $this->createNode($this->namespace, $this->node, implode("\n", $xml), true, $attributes = $attributes);

			if(method_exists($this, "withParents") === true) {
				return $this->withParents($xml);
			}
			return $xml;
		}

		/**
		 * Create an XML node
		 * @param  string $namespace The namespace of the node
		 * @param  string $name      The name of the node
		 * @param  string $value     The value of the node
		 * @param  boolean $lb        If adding \n to to encapsulate the value
		 * @param  boolean $attributes If set to true, will put the node's attributes in its declaration
		 * @return string            An XML node
		 */
		private function createNode($namespace, $name, $value, $lb = false, $attributes = False) {
			$xml = array();
			switch (gettype($value)) {
				case "array":
					while(list($key, $subvalue) = each($value)) {
						switch (gettype($key)) {
							case "integer":
								$xml[] = $this->createNode($namespace, $name, $subvalue);
								break;
							case "string":
								$xml[] =  $this->createNode($namespace, $key, $subvalue);
								break;
							default:
								break;
						}
					}
					break;
				case "string":
				case "integer":
					$node = $namespace.":".$name;
					if($attributes === true) { $attributes = " ".$this->nodeAttributes; }
					else { $attributes = ""; }
					if($lb === true) {
						$xml[] = "<".$node.$attributes.">\n".$value."\n</".$node.">";
					} else {
						$xml[] = "<".$node.$attributes.">".$value."</".$node.">";
					}
					break;
				case "object":
					if(get_parent_class($value) === "Perseids\IAM\Property\Abstractions\PropertyBase" || get_parent_class($value) === "Perseids\IAM\Entity\Abstractions\EntityBase") {
						if(method_exists($value, "getUUID") === true && $value->getUUID() !== null) {
							$xml[] = $value->getUUIDXML();
						} else {
							$xml[] = $value->getXML();
						}
					}
					break;
				default:
					break;
			}
			$xml = implode("\n", $xml);

			return $xml;
		}

		/**
		 * Get an associative array version of the object without excluded variable set in $excludeSerialization
		 * @return	array	An associative array version of the object
		 */
		public function getSerialized($deepSerialization = true) {
			$serialized = get_object_vars($this);
			$rtn = $this->serialize($serialized, $deepSerialization);
			return $rtn;
		}

		private function serialize($serialized, $deepSerialization = true) {
			$rtn = [];
			while(list($key, $value) = each($serialized)) {
				if(array_search($key, $this->excludeSerialization, $strict = true) === false) {
					if($this->checkRequired($key, $value) === true && $value !== null) {
						switch (gettype($value)) {
							case "string":
							case "integer":
								$rtn[$key] = $value;
								break;
							case "array":
								if(count($value) > 0) {
									if($deepSerialization) {
										$rtn[$key] = $this->serialize($value);
									} else {
										$rtn[$key] = $value;
									}
								}
								break;
							case "object":
								if(method_exists($value, "getSerialized") === true && $deepSerialization === true) {
									$rtn[$key] = $value->getSerialized();
								} else {
									$rtn[$key] = $value;
								}
								break;
							default:
								break;
						}
					}
				}
			}
			return $rtn;
		}

		/**
		 * Set the namespace of the object
		 * @param string $namespace The namespace to be used
		 * @return this
		 */
		public function setNamespace($namespace) {
			$this->namespace = $namespace;
			return $this;
		}

		/**
		 * Exclude an element from serialization
		 * @param string,array $key A key
		 * @return this
		 */
		public function addExclusion($key) {
			switch (gettype($key)) {
				case "string":
					$this->excludeSerialization[] = $key;
					break;
				case "array":
					$this->excludeSerialization = array_merge($this->excludeSerialization, $key);
					break;
			}
			return $this;
		}

		/**
		 * Set a list of object
		 * Helper function for setter with array with specific object
		 * @param string $varname The property of the class to be modified
		 * @param object $values A list of object to set for the property
		 * @param string $expectedType The name of the class expected
		 * @return self
		 */
		protected function setListOfObject($varname, $values, $expectedType) {
			$this->{$varname} = array();	#We reset the property
			while(list($key, $value) = each($values)) {
				$this->addObjectToList($varname, $value, $expectedType);
			}
			return $this;
		}

		/**
		 * Add an object and check it's validity to a list
		 * Helper function for setter with array with specific object
		 * @param string $varname The property of the class to be modified
		 * @param object $value The object to add in the list
		 * @param string $expectedType The name of the class expected
		 * @return self
		 */
		protected function addObjectToList($varname, $value, $expectedType) {
			if(gettype($value) !== "object") {
				throw(new \InvalidArgumentException($expectedType." expected. ". gettype($value) . " given."));
			}
			if(get_class($value) === $expectedType) {
				$this->{$varname}[] = $value;
			} else {
				throw(new \InvalidArgumentException($expectedType." expected. ".get_class($value) . " given."));
			}
			return $this;
		}

		/**
		 * Add an element to required elements for a given object
		 * @param string,array $key A property name to be required
		 * @return self
		 */
		protected function addRequired($key) {
			switch (gettype($key)) {
				case "string":
					$this->required[] = $key;
					break;
				case "array":
					$this->required = array_merge($this->required, $key);
					break;
			}
			return $this;
		}

		/**
		 * Add an element to required elements for a given object
		 * @param string $key A property name to be required
		 * @param any $value The value for this property in self
		 * @return boolean
		 */
		protected function checkRequired($key, $value) {
			if(array_search($key, $this->required, $strict = True) !== False) {
				switch (gettype($value)) {
					case 'array':
						if(count($value) > 0) {
							return true;
						}
						throw new RequiredFieldException($key, $this);
						return false;
						break;
					case 'null':
					case 'NULL':
						throw new RequiredFieldException($key, $this);
							return false;
						break;
					case 'string':
						if(trim($value) === '') {
							throw new RequiredFieldException($key, $this);
							return false;
						}
						return true;
						break;
					default:
						return true;
						break;
				}
			}
			return true;
		}
	}


text:
package org.yotchang4s.android;

import scala.collection._
import android.app._
import android.app.ActionBar._
import android.text._
import android.view._
import android.widget._
import android.widget.AdapterView._
import android.widget.AbsListView._
import android.widget.CompoundButton._
import android.view.View.OnClickListener
import android.view.View.OnKeyListener

object Listeners extends Listeners

trait Listeners {

  object ViewOpts {
    lazy val onAllListeners = mutable.Map[View, OnAllListener]()

    class OnAllListener extends OnClickListener with OnKeyListener {
      lazy val onClicks = new mutable.ListBuffer[View => Unit]
      lazy val onKeys = new mutable.ListBuffer[(View, Int, KeyEvent) => Boolean]

      def onClick(v: View) {
        onClicks.foreach(_(v))
      }

      def onKey(view: View, keyCode: Int, event: KeyEvent): Boolean = {
        onKeys.foreach { v =>
          val result = v(view, keyCode, event)
          if (result) return true
        }
        return false
      }
    }

    def getOrCreateOnAllClickListener(view: View) = {
      val l = onAllListeners.get(view).getOrElse(new OnAllListener)
      onAllListeners(view) = l
      view.setOnClickListener(l)
      l
    }

    def getOrCreateOnAllKeyListener(view: View) = {
      val l = onAllListeners.get(view).getOrElse(new OnAllListener)
      onAllListeners(view) = l
      view.setOnKeyListener(l)
      l
    }
  }

  implicit class ViewOpts(view: View) {
    import ViewOpts._

    def onClicks = getOrCreateOnAllClickListener(view).onClicks
    def onKeys = getOrCreateOnAllKeyListener(view).onKeys
  }

  implicit class EditTextOpts(editText: EditText) {
    def onEditorAction(f: (Int, KeyEvent) => Boolean) {
      editText.setOnEditorActionListener(new TextView.OnEditorActionListener {
        def onEditorAction(textView: TextView, id: Int, keyEvent: KeyEvent): Boolean = f(id, keyEvent)
      })
    }

    def afterTextChanged(f: Editable => Unit) {
      editText.addTextChangedListener(new TextWatcher {
        def beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
        }

        def onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {

        }

        def afterTextChanged(editable: Editable) {
          f(editable)
        }
      })
    }
  }

  implicit class ActionBarOpts(actionBar: ActionBar) {
    def onNavigationItemSelected(s: SpinnerAdapter)(f: (Int, Long) => Boolean) {
      actionBar.setListNavigationCallbacks(s, new OnNavigationListener {
        def onNavigationItemSelected(itemPosition: Int, itemId: Long): Boolean = f(itemPosition, itemId)
      })
    }
  }

  private object AdapterViewOpts {
    lazy val onAllListeners = mutable.Map[AdapterView[_], OnAllListener[_]]()

    class OnAllListener[A <: Adapter] extends OnItemSelectedListener with OnItemClickListener {
      lazy val onItemSelecteds = new mutable.ListBuffer[(AdapterView[_], View, Int, Long) => Unit]
      lazy val onNothingSelecteds = new mutable.ListBuffer[(AdapterView[_]) => Unit]
      lazy val onItemClicks = new mutable.ListBuffer[(AdapterView[_], View, Int, Long) => Unit]

      def onItemSelected(parent: AdapterView[_], view: View, position: Int, id: Long) {
        onItemSelecteds.foreach(_(parent, view, position, id))
      }

      def onNothingSelected(parent: AdapterView[_]) {
        onNothingSelecteds.foreach(_(parent))
      }

      def onItemClick(parent: AdapterView[_], view: View, position: Int, id: Long) {
        onItemClicks.foreach(_(parent, view, position, id))
      }
    }

    def getOrCreateOnAllItemSelectedListener(adapterView: AdapterView[_]) = {
      val l = onAllListeners.get(adapterView).getOrElse(new OnAllListener)
      onAllListeners(adapterView) = l
      adapterView.setOnItemSelectedListener(l)
      l
    }

    def getOrCreateOnAllItemClickListener(adapterView: AdapterView[_]) = {
      val l = onAllListeners.get(adapterView).getOrElse(new OnAllListener)
      onAllListeners(adapterView) = l
      adapterView.setOnItemClickListener(l)
      l
    }
  }

  implicit class AdapterViewOpts[V <: AdapterView[_ <: Adapter]](listView: AdapterView[_]) {
    import AdapterViewOpts._

    def onItemSelecteds = getOrCreateOnAllItemSelectedListener(listView).onItemSelecteds
    def onNothingSelecteds = getOrCreateOnAllItemSelectedListener(listView).onNothingSelecteds
    def onItemClicks = getOrCreateOnAllItemClickListener(listView).onItemClicks
  }

  private object AbsListViewOpts {
    lazy val onAllListeners = mutable.Map[AdapterView[_], OnAllListener]()

    class OnAllListener extends OnScrollListener {
      lazy val onScrolls = new mutable.ListBuffer[(AbsListView, Int, Int, Int) => Unit]
      lazy val onScrollStateChangeds = new mutable.ListBuffer[(AbsListView, Int) => Unit]

      def onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
        onScrolls.foreach(_(view, firstVisibleItem, visibleItemCount, totalItemCount))
      }

      def onScrollStateChanged(view: AbsListView, scrollState: Int) {
        onScrollStateChangeds.foreach(_(view, scrollState))
      }
    }

    def getOrCreateOnAllScrollListener(absListView: AbsListView) = {
      val l = onAllListeners.get(absListView).getOrElse(new OnAllListener)
      onAllListeners(absListView) = l
      absListView.setOnScrollListener(l)
      l
    }
  }

  implicit class AbsListViewOpts(absListView: AbsListView) {
    import AbsListViewOpts._

    def onScrolls = getOrCreateOnAllScrollListener(absListView).onScrolls
    def onScrollStateChangeds = getOrCreateOnAllScrollListener(absListView).onScrollStateChangeds
  }
}


text:
namespace base {
class CommandLine;
class ScopedTempDir;
}  // namespace base

namespace chromeos {
namespace wallpaper_manager_test_utils {

// Colors used for different default wallpapers by CreateCmdlineWallpapers().
extern const SkColor kLargeDefaultWallpaperColor;
extern const SkColor kSmallDefaultWallpaperColor;
extern const SkColor kLargeGuestWallpaperColor;
extern const SkColor kSmallGuestWallpaperColor;

// A custom color, specifically chosen to not
// conflict with any of the default wallpaper colors.
extern const SkColor kCustomWallpaperColor;

// Dimension used for width and height of default wallpaper images. A
// small value is used to minimize the amount of time spent compressing
// and writing images.
extern const int kWallpaperSize;

// Creates compressed JPEG image of solid color.
// Result bytes are written to |output|.
// Returns true if gfx::JPEGCodec::Encode() succeeds.
bool CreateJPEGImage(int width,
                     int height,
                     SkColor color,
                     std::vector<unsigned char>* output);

// Creates a test image of given size.
gfx::ImageSkia CreateTestImage(int width, int height, SkColor color);

// Writes a JPEG image of the specified size and color to |path|. Returns
// true on success.
bool WriteJPEGFile(const base::FilePath& path,
                   int width,
                   int height,
                   SkColor color);

// Returns true if the color at the center of |image| is close to
// |expected_color|. (The center is used so small wallpaper images can be
// used.)
bool ImageIsNearColor(gfx::ImageSkia image, SkColor expected_color);

// Wait until all wallpaper loading is done, and WallpaperManager comes into
// a stable state.
void WaitAsyncWallpaperLoadFinished();

// Initializes default wallpaper paths "*default_*file" and writes JPEG
// wallpaper images to them.
// Only needs to be called (once) by tests that want to test loading of
// default wallpapers.
void CreateCmdlineWallpapers(const base::ScopedTempDir& dir,
                             scoped_ptr<base::CommandLine>* command_line);

}  // namespace wallpaper_manager_test_utils
}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_LOGIN_USERS_WALLPAPER_WALLPAPER_MANAGER_TEST_UTILS_H_


text:
*************
ItCase Deploy
*************

.. image:: https://travis-ci.org/petrikoz/itcase.deploy.svg
    :target: https://travis-ci.org/petrikoz/itcase.deploy

`Ansible`_ role deploy projects to `ItCase`_ dev server.

Usage
=====

.. code-block:: yaml

    # Put this code in site.yml
    ---
    - hosts: all

      roles:
      - itcase.deploy

      vars:
        deploy_app_name: 'example'
        deploy_app_repo: 'https://github.com/petrikoz/itcase.deploy.git'

      vars_prompt:
        - name: 'deploy_pg_role_password'
          prompt: 'Password for app DB role'

        - name: 'deploy_pg_password'
          prompt: 'Password for root DB role'

For 'postgres' part required `PostgreSQL`_ on remote server.
And will be install `Psycopg2`_ on remote server.
If you need skeep this part use flag ``--skip-tags=itcase.deploy.postgres``.

You can run with command ``ansible-playbook --ask-become-pass --inventory-file inventory site.yml``

Variables
=========

.. code-block:: yaml

    deploy_user: '{{ ansible_ssh_user }}'  # Set deploy user
    deploy_group: '{{ deploy_user }}'      # Set deploy group

    deploy_app_name: 'example'
    deploy_app_repo: 'git@github.com:petrikoz/itcase.deploy.git'  # E.g. Bitbucket's repo: git@bitbucket.org:OWNER_ACCOUNT_PLACE_HERE/{{ deploy_app_name }}.git
    deploy_app_ver: 'develop'

    deploy_dir: '/home/{{ deploy_user }}/{{ deploy_app_name }}'  # Root deploy directory
    deploy_etc_dir: '{{ deploy_dir }}/etc'    # Directory where placed configuration files
    deploy_log_dir: '{{ deploy_dir }}/log'    # Directory where placed logs
    deploy_run_dir: '{{ deploy_dir }}/run'    # Directory where placed unix sockets and pid files
    deploy_src_dir: '{{ deploy_dir }}/src'    # Source's directory

    deploy_venv_root: '/home/{{ deploy_user }}/.virtualenvs'           # Directory with folders of envs
    deploy_venv_name: '{{ deploy_app_name }}'
    deploy_venv_python: python
    deploy_venv_options: ''                   # E.g. --system-site-packages

    deploy_nginx_listen: 443
    deploy_nginx_server_name: '{{ deploy_app_name }}.itcase.pro'
    deploy_nginx_extra_server_name: ['www.{{ deploy_nginx_server_name }}']
    deploy_nginx_root: '{{ deploy_dir }}'
    deploy_nginx_log: '{{ deploy_log_dir }}/nginx.error.log'

    deploy_letsencrypt_live: '/etc/letsencrypt/live/{{ deploy_nginx_server_name }}'

    deploy_uwsgi_name: '{{ deploy_app_name }}'
    deploy_uwsgi_path: '{{ deploy_dir }}'

    deploy_pg_role_name: '{{ deploy_app_name }}'
    deploy_pg_role_password: '12345'
    deploy_pg_db_name: '{{ deploy_app_name }}'
    deploy_pg_user: 'postgres'
    deploy_pg_password: '{{ deploy_pg_user }}'

License
=======

Licensed under the Apache License, Version 2.0. See the `LICENSE`_ file for details.

.. _Ansible: https://github.com/ansible/ansible
.. _ItCase: http://itcase.pro
.. _PostgreSQL: http://www.postgresql.org
.. _Psycopg2: http://initd.org/psycopg/
.. _LICENSE: LICENSE