text:
/*
 * Created on 2004-11-3
 *
 */
/**
 * @author TomHornson@hotmail.com
 *
 */
/*
 * $Id: UtilCache.java,v 1.2 2004/02/26 16:22:09 jonesde Exp $
 *
 *  Copyright (c) 2001-2004 The Open For Business Project - www.ofbiz.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 *  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
 *  OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package org.ofbiz.base.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * Generalized caching utility. Provides a number of caching features:
 *

 *
Limited or unlimited element capacity
 *
If limited, removes elements with the LRU (Least Recently Used) algorithm
 *
Keeps track of when each element was loaded into the cache
 *
Using the expireTime can report whether a given element has expired
 *
Counts misses and hits
 *

 *
 * @author David E. Jones
 * @version $Revision: 1.2 $
 * @since 2.0
 */
public class UtilCache {

	/** A static Map to keep track of all of the UtilCache instances. */
	public static Map utilCacheTable = new HashMap();

	/** An index number appended to utilCacheTable names when there are conflicts. */
	protected static Map defaultIndices = new HashMap();

	/**
	 * The name of the UtilCache instance, is also the key for the instance in
	 * utilCacheTable.
	 */
	protected String name;

	/** A list of the elements order by Least Recent Use */
	public LinkedList keyLRUList = new LinkedList();

	/**
	 * A hashtable containing a CacheLine object with a value and a loadTime for
	 * each element.
	 */
	public Map cacheLineTable = new HashMap();

	/** A count of the number of cache hits */
	protected long hitCount = 0;

	/** A count of the number of cache misses */
	protected long missCount = 0;

	/**
	 * The maximum number of elements in the cache. If set to 0, there will be no
	 * limit on the number of elements in the cache.
	 */
	protected long maxSize = 0;

	/**
	 * Specifies the amount of time since initial loading before an element will
	 * be reported as expired. If set to 0, elements will never expire.
	 */
	protected long expireTime = 0;

	/**
	 * Specifies whether or not to use soft references for this cache, defaults to
	 * false
	 */
	protected boolean useSoftReference = false;

	/**
	 * Constructor which specifies the cacheName as well as the maxSize,
	 * expireTime and useSoftReference. The passed maxSize, expireTime and
	 * useSoftReference will be overridden by values from cache.properties if
	 * found.
	 *
	 * @param maxSize
	 *          The maxSize member is set to this value
	 * @param expireTime
	 *          The expireTime member is set to this value
	 * @param cacheName
	 *          The name of the cache.
	 * @param useSoftReference
	 *          Specifies whether or not to use soft references for this cache.
	 */
	public UtilCache(String cacheName, long maxSize, long expireTime, boolean useSoftReference) {
		this.useSoftReference = useSoftReference;
		this.maxSize = maxSize;
		this.expireTime = expireTime;
		setPropertiesParams(cacheName);

		name = cacheName + this.getNextDefaultIndex(cacheName);
		utilCacheTable.put(name, this);
	}

	/**
	 * Constructor which specifies the cacheName as well as the maxSize and
	 * expireTime. The passed maxSize and expireTime will be overridden by values
	 * from cache.properties if found.
	 *
	 * @param maxSize
	 *          The maxSize member is set to this value
	 * @param expireTime
	 *          The expireTime member is set to this value
	 * @param cacheName
	 *          The name of the cache.
	 */
	public UtilCache(String cacheName, long maxSize, long expireTime) {
		this(cacheName, maxSize, expireTime, false);
	}

	/**
	 * Constructor which specifies the maxSize and expireTime.
	 *
	 * @param maxSize
	 *          The maxSize member is set to this value
	 * @param expireTime
	 *          The expireTime member is set to this value
	 */
	public UtilCache(long maxSize, long expireTime) {
		this.useSoftReference = false;
		this.maxSize = maxSize;
		this.expireTime = expireTime;
		String name = "specified" + this.getNextDefaultIndex("specified");

		setPropertiesParams(name);
		utilCacheTable.put(name, this);
	}

	/**
	 * This constructor takes a name for the cache, puts itself in the
	 * utilCacheTable. It also uses the cacheName to lookup the initialization
	 * parameters from cache.properties.
	 *
	 * @param cacheName
	 *          The name of the cache.
	 */
	public UtilCache(String cacheName) {
		setPropertiesParams("default");
		setPropertiesParams(cacheName);

		name = cacheName + this.getNextDefaultIndex(cacheName);
		utilCacheTable.put(name, this);
	}

	/**
	 * Default constructor, all members stay at default values as defined in
	 * cache.properties, or the defaults in this file if cache.properties is not
	 * found, or there are no 'default' entries in it.
	 */
	public UtilCache() {
		setPropertiesParams("default");

		name = "default" + this.getNextDefaultIndex("default");
		utilCacheTable.put(name, this);
	}

	protected String getNextDefaultIndex(String cacheName) {
		Integer curInd = (Integer) UtilCache.defaultIndices.get(cacheName);

		if (curInd == null) {
			UtilCache.defaultIndices.put(cacheName, new Integer(1));
			return "";
		} else {
			UtilCache.defaultIndices.put(cacheName, new Integer(curInd.intValue() + 1));
			return Integer.toString(curInd.intValue() + 1);
		}
	}

	protected void setPropertiesParams(String cacheName) {
		ResourceBundle res = ResourceBundle.getBundle("cache");

		if (res != null) {
			try {
				String value = res.getString(cacheName + ".maxSize");
				Long longValue = new Long(value);

				if (longValue != null) {
					maxSize = longValue.longValue();
				}
			} catch (Exception e) {
			}
			try {
				String value = res.getString(cacheName + ".expireTime");
				Long longValue = new Long(value);

				if (longValue != null) {
					expireTime = longValue.longValue();
				}
			} catch (Exception e) {
			}

			try {
				String value = res.getString(cacheName + ".useSoftReference");

				if (value != null) {
					useSoftReference = "true".equals(value);
				}
			} catch (Exception e) {
			}
		}
	}

	/**
	 * Puts or loads the passed element into the cache
	 *
	 * @param key
	 *          The key for the element, used to reference it in the hastables and
	 *          LRU linked list
	 * @param value
	 *          The value of the element
	 */
	public synchronized void put(Object key, Object value) {
		if (key == null)
			return;
		// 假如maxSize==0,说明不需要限制cache容量,那么就不需要LRU调度了。
		if (maxSize > 0) {
			// when maxSize is changed, the setter will take care of filling the LRU
			// list
			if (cacheLineTable.containsKey(key)) {
				keyLRUList.remove(key);
				keyLRUList.addFirst(key);
			} else {
				keyLRUList.addFirst(key);
			}
		}

		if (expireTime > 0) {
			cacheLineTable.put(key, new UtilCache.CacheLine(value, useSoftReference, System.currentTimeMillis()));
		} else {
			cacheLineTable.put(key, new UtilCache.CacheLine(value, useSoftReference));
		}
		if (maxSize > 0 && cacheLineTable.size() > maxSize) {
			Object lastKey = keyLRUList.getLast();
			remove(lastKey);
		}
	}

	/**
	 * Gets an element from the cache according to the specified key. If the
	 * requested element hasExpired, it is removed before it is looked up which
	 * causes the function to return null.
	 *
	 * @param key
	 *          The key for the element, used to reference it in the hastables and
	 *          LRU linked list
	 * @return The value of the element specified by the key
	 */
	public Object get(Object key) {
		if (key == null) {
			missCount++;
			return null;
		}
		UtilCache.CacheLine line = (UtilCache.CacheLine) cacheLineTable.get(key);

		if (hasExpired(line)) {
			// note that print.info in debug.properties cannot be checked through
			// UtilProperties here, it would cause infinite recursion...
			// if (Debug.infoOn()) Debug.logInfo("Element has expired with key " +
			// key, module);
			remove(key);
			line = null;
		}

		if (line == null) {
			// if (Debug.infoOn()) Debug.logInfo("Element not found with key " + key,
			// module);
			missCount++;
			return null;
		}
		// if (Debug.infoOn()) Debug.logInfo("Element found with key " + key,
		// module);
		hitCount++;

		if (maxSize > 0) {
			synchronized (this) {
				keyLRUList.remove(key);
				keyLRUList.addFirst(key);
			}
		}
		return line.getValue();
	}

	/**
	 * Removes an element from the cache according to the specified key
	 *
	 * @param key
	 *          The key for the element, used to reference it in the hastables and
	 *          LRU linked list
	 * @return The value of the removed element specified by the key
	 */
	public synchronized Object remove(Object key) {
		if (key == null) {
			missCount++;
			return null;
		}

		UtilCache.CacheLine line = (UtilCache.CacheLine) cacheLineTable.remove(key);
		if (line != null) {
			if (maxSize > 0)
				keyLRUList.remove(key);
			return line.getValue();
		} else {
			missCount++;
			return null;
		}
	}

	/** Removes all elements from this cache */
	public synchronized void clear() {
		cacheLineTable.clear();
		keyLRUList.clear();
		clearCounters();
	}

	/** Removes all elements from this cache */
	public static void clearAllCaches() {
		Iterator entries = utilCacheTable.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry entry = (Map.Entry) entries.next();
			UtilCache utilCache = (UtilCache) entry.getValue();
			utilCache.clear();
		}
	}

	/**
	 * Getter for the name of the UtilCache instance.
	 *
	 * @return The name of the instance
	 */
	public String getName() {
		return name;
	}

	/**
	 * Returns the number of successful hits on the cache
	 *
	 * @return The number of successful cache hits
	 */
	public long getHitCount() {
		return hitCount;
	}

	/**
	 * Returns the number of cache misses
	 *
	 * @return The number of cache misses
	 */
	public long getMissCount() {
		return missCount;
	}

	/**
	 * Clears the hit and miss counters
	 */
	public void clearCounters() {
		hitCount = 0;
		missCount = 0;
	}

	/**
	 * Sets the maximum number of elements in the cache. If 0, there is no
	 * maximum.
	 *
	 * @param maxSize
	 *          The maximum number of elements in the cache
	 */
	public void setMaxSize(long maxSize) {
		// if the new maxSize is <= 0, clear keyLRUList
		if (maxSize <= 0) {
			keyLRUList.clear();
		} else if (maxSize > 0 && this.maxSize <= 0) {
			// if the new maxSize > 0 and the old is <= 0, fill in LRU list - order
			// will be meaningless for now
			Iterator keys = cacheLineTable.keySet().iterator();

			while (keys.hasNext()) {
				keyLRUList.add(keys.next());
			}
		}

		// if the new maxSize is less than the current cache size, shrink the cache.
		if (maxSize > 0 && cacheLineTable.size() > maxSize) {
			while (cacheLineTable.size() > maxSize) {
				Object lastKey = keyLRUList.getLast();

				remove(lastKey);
			}
		}

		this.maxSize = maxSize;
	}

	/**
	 * Returns the current maximum number of elements in the cache
	 *
	 * @return The maximum number of elements in the cache
	 */
	public long getMaxSize() {
		return maxSize;
	}

	/**
	 * Sets the expire time for the cache elements. If 0, elements never expire.
	 *
	 * @param expireTime
	 *          The expire time for the cache elements
	 */
	public void setExpireTime(long expireTime) {
		// if expire time was <= 0 and is now greater, fill expire table now
		if (this.expireTime <= 0 && expireTime > 0) {
			long currentTime = System.currentTimeMillis();
			Iterator values = cacheLineTable.values().iterator();
			while (values.hasNext()) {
				UtilCache.CacheLine line = (UtilCache.CacheLine) values.next();
				line.loadTime = currentTime;
			}
		} else if (this.expireTime <= 0 && expireTime > 0) {// if expire time was >
																												// 0 and is now <=, do
																												// nothing, just leave
																												// the load times in
																												// place, won't hurt
																												// anything...
		}

		this.expireTime = expireTime;
	}

	/**
	 * return the current expire time for the cache elements
	 *
	 * @return The expire time for the cache elements
	 */
	public long getExpireTime() {
		return expireTime;
	}

	/** Set whether or not the cache lines should use a soft reference to the data */
	public void setUseSoftReference(boolean useSoftReference) {
		if (this.useSoftReference != useSoftReference) {
			this.useSoftReference = useSoftReference;
			Iterator values = cacheLineTable.values().iterator();
			while (values.hasNext()) {
				UtilCache.CacheLine line = (UtilCache.CacheLine) values.next();
				line.setUseSoftReference(useSoftReference);
			}
		}
	}

	/**
	 * Return whether or not the cache lines should use a soft reference to the
	 * data
	 */
	public boolean getUseSoftReference() {
		return this.useSoftReference;
	}

	/**
	 * Returns the number of elements currently in the cache
	 *
	 * @return The number of elements currently in the cache
	 */
	public long size() {
		return cacheLineTable.size();
	}

	/**
	 * Returns a boolean specifying whether or not an element with the specified
	 * key is in the cache. If the requested element hasExpired, it is removed
	 * before it is looked up which causes the function to return false.
	 *
	 * @param key
	 *          The key for the element, used to reference it in the hastables and
	 *          LRU linked list
	 * @return True is the cache contains an element corresponding to the
	 *         specified key, otherwise false
	 */
	public boolean containsKey(Object key) {
		UtilCache.CacheLine line = (UtilCache.CacheLine) cacheLineTable.get(key);

		if (hasExpired(line)) {
			remove(key);
			line = null;
		}
		if (line != null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Returns a boolean specifying whether or not the element corresponding to
	 * the key has expired. Only returns true if element is in cache and has
	 * expired. Error conditions return false, if no expireTable entry, returns
	 * true. Always returns false if expireTime <= 0. Also, if SoftReference in
	 * the CacheLine object has been cleared by the gc return true.
	 *
	 * @param key
	 *          The key for the element, used to reference it in the hastables and
	 *          LRU linked list
	 * @return True is the element corresponding to the specified key has expired,
	 *         otherwise false
	 */
	public boolean hasExpired(Object key) {
		if (key == null)
			return false;

		UtilCache.CacheLine line = (UtilCache.CacheLine) cacheLineTable.get(key);

		return hasExpired(line);
	}

	protected boolean hasExpired(UtilCache.CacheLine line) {
		if (line == null)
			return false;
		// check this BEFORE checking to see if expireTime <= 0, ie if time
		// expiration is enabled
		// check to see if we are using softReference first, slight performance
		// increase
		if (this.useSoftReference && line.getValue() == null)
			return true;
		if (expireTime <= 0)
			return false;

		if (line.loadTime <= 0)
			return true;
		if ((line.loadTime + expireTime) < System.currentTimeMillis()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Clears all expired cache entries; also clear any cache entries where the
	 * SoftReference in the CacheLine object has been cleared by the gc
	 */
	public void clearExpired() {
		Iterator keys = cacheLineTable.keySet().iterator();
		while (keys.hasNext()) {
			Object key = keys.next();
			if (hasExpired(key)) {
				remove(key);
			}
		}
	}

	/** Clears all expired cache entries from all caches */
	public static void clearExpiredFromAllCaches() {
		Iterator entries = utilCacheTable.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry entry = (Map.Entry) entries.next();
			UtilCache utilCache = (UtilCache) entry.getValue();
			utilCache.clearExpired();
		}
	}

	/** Checks for a non-expired key in a specific cache */
	public static boolean validKey(String cacheName, Object key) {
		UtilCache cache = (UtilCache) utilCacheTable.get(cacheName);
		if (cache != null) {
			if (cache.containsKey(key))
				return true;
		}
		return false;
	}

	public static class CacheLine {
		public Object valueRef = null;
		public long loadTime = 0;
		public boolean useSoftReference = false;

		public CacheLine(Object value, boolean useSoftReference) {
			if (useSoftReference) {
				this.valueRef = new java.lang.ref.SoftReference(value);
			} else {
				this.valueRef = value;
			}
			this.useSoftReference = useSoftReference;
		}

		public CacheLine(Object value, boolean useSoftReference, long loadTime) {
			this(value, useSoftReference);
			this.loadTime = loadTime;
		}

		public Object getValue() {
			if (valueRef == null)
				return null;
			if (useSoftReference) {
				return ((java.lang.ref.SoftReference) valueRef).get();
			} else {
				return valueRef;
			}
		}

		public void setUseSoftReference(boolean useSoftReference) {
			if (this.useSoftReference != useSoftReference) {
				synchronized (this) {
					this.useSoftReference = useSoftReference;
					if (useSoftReference) {
						this.valueRef = new java.lang.ref.SoftReference(this.valueRef);
					} else {
						this.valueRef = ((java.lang.ref.SoftReference) this.valueRef).get();
					}
				}
			}
		}
	}
}


text:
Loading Notice
==============

Loading Notice is a plugin, built on Prototype, which shows an indictor when a slow AJAX is under process automatically. Basically, it's like the "Loading" div appears in gmail when busy. When scrolling or resizing the window, it will still keep showing on the top of the page.

Howto
-----

Install the plugin:

    $ ruby script/plugin install git://github.com/thomd/loading_notice.git
    $ rake loading_notice:install

Include the library into your project:

    <%= javascript_include_tag :defaults, 'loading_notice' %>
    <%= stylesheet_link_tag 'loading_notice' %>

Demo
----

Use the [loading-notice-demo template](http://gist.github.com/156145) (for Rails >= 2.3) to generate a simple but fully functional proof-of-concept demo of the loading_notice plugin:

    $ rails loading-notice-demo -m http://gist.github.com/156145.txt
    $ ruby script/server

Author
------

Minor enhancements by [Thomas Duerr](http://thomd.net).

Original Plugin written by [Shaokun Wu](http://www.kudelabs.com). Mail to `shaokun at kudelabs.com` for bug reports, feature requests or any comment.

Copyright (c) 2009 Kude Labs, released under the MIT license

redpajama_set_name: RedPajamaGithub


text:
package net.etalia.crepuscolo.json;

public class DontModifyException extends RuntimeException {

	private Object entity;

	public DontModifyException(Object entity) {
		this.entity = entity;
	}

	public void setEntity(Object entity) {
		this.entity = entity;
	}
	public Object getEntity() {
		return entity;
	}

}


text:
from __future__ import division
from menpo.transform import AlignmentSimilarity, Similarity
import numpy as np
from menpo.visualize import progress_bar_str, print_dynamic, print_progress

def name_of_callable(c):
    try:
        return c.__name__  # function
    except AttributeError:
        return c.__class__.__name__  # callable class

def is_pyramid_on_features(features):
    r"""
    True if feature extraction happens once and then a gaussian pyramid
    is taken. False if a gaussian pyramid is taken and then features are
    extracted at each level.
    """
    return callable(features)

def create_pyramid(images, n_levels, downscale, features, verbose=False):
    r"""
    Function that creates a generator function for Gaussian pyramid. The
    pyramid can be created either on the feature space or the original
    (intensities) space.

    Parameters
    ----------
    images: list of :map:`Image`
        The set of landmarked images from which to build the AAM.

    n_levels: int
        The number of multi-resolution pyramidal levels to be used.

    downscale: float
        The downscale factor that will be used to create the different
        pyramidal levels.

    features: ``callable`` ``[callable]``
        If a single callable, then the feature calculation will happen once
        followed by a gaussian pyramid. If a list of callables then a
        gaussian pyramid is generated with features extracted at each level
        (after downsizing and blurring).

    Returns
    -------
    list of generators :
        The generator function of the Gaussian pyramid.

    """
    will_take_a_while = is_pyramid_on_features(features)
    if will_take_a_while and verbose:
        images = print_progress(images, show_bar=False, show_count=False,
                                prefix='- Computing top-level feature space')
    pyramids = []
    for img in images:
        pyramids.append(pyramid_of_feature_images(n_levels, downscale,
                                                  features, img))
    return pyramids

def pyramid_of_feature_images(n_levels, downscale, features, image):
    r"""
    Generates a gaussian pyramid of feature images for a single image.
    """
    if is_pyramid_on_features(features):
        # compute feature image at the top
        feature_image = features(image)
        # create pyramid on the feature image
        return feature_image.gaussian_pyramid(n_levels=n_levels,
                                              downscale=downscale)
    else:
        # create pyramid on intensities image
        # feature will be computed per level
        pyramid = image.gaussian_pyramid(n_levels=n_levels,
                                         downscale=downscale)
        # add the feature generation here
        return feature_images(pyramid, features)

# adds feature extraction to a generator of images
def feature_images(images, features):
    for feature, level in zip(reversed(features), images):
        yield feature(level)

class DeformableModel(object):

    def __init__(self, features):
        self.features = features

    @property
    def pyramid_on_features(self):
        return is_pyramid_on_features(self.features)

# TODO: Should this be a method on Similarity? AlignableTransforms?
def noisy_align(source, target, noise_std=0.04, rotation=False):
    r"""
    Constructs and perturbs the optimal similarity transform between source
    to the target by adding white noise to its weights.

    Parameters
    ----------
    source: :class:`menpo.shape.PointCloud`
        The source pointcloud instance used in the alignment
    target: :class:`menpo.shape.PointCloud`
        The target pointcloud instance used in the alignment
    noise_std: float
        The standard deviation of the white noise

        Default: 0.04
    rotation: boolean
        If False the second parameter of the Similarity,
        which captures captures inplane rotations, is set to 0.

        Default:False

    Returns
    -------
    noisy_transform : :class: `menpo.transform.Similarity`
        The noisy Similarity Transform
    """
    transform = AlignmentSimilarity(source, target, rotation=rotation)
    parameters = transform.as_vector()
    parameter_range = np.hstack((parameters[:2], target.range()))
    noise = (parameter_range * noise_std *
             np.random.randn(transform.n_parameters))
    return Similarity.init_identity(source.n_dims).from_vector(parameters + noise)

def build_sampling_grid(patch_shape):
    r"""
    """
    patch_shape = np.array(patch_shape)
    patch_half_shape = np.require(np.floor(patch_shape / 2), dtype=int)
    start = -patch_half_shape
    end = patch_half_shape + 1
    sampling_grid = np.mgrid[start[0]:end[0], start[1]:end[1]]
    return sampling_grid.swapaxes(0, 2).swapaxes(0, 1)


text:
This is a bugfix release!

### Changes:
* `unnapply(_: String)` was using a parser which only validated first 36 characters, without a length check
* `apply(_: String)` now also inlines the `Array[Char]` parsing bytecode


text:
package composition

import uk.gov.dvla.vehicles.presentation.common.ConfigProperties.{booleanProp, getIntListProperty, getOptionalProperty, intProp}
import uk.gov.dvla.vehicles.presentation.common.services.SEND.EmailConfiguration
import uk.gov.dvla.vehicles.presentation.common.webserviceclients.emailservice.From
import utils.helpers.Config

class TestConfig extends Config {

  override val assetsUrl: Option[String] = None

  // Prototype message in html
  override val isPrototypeBannerVisible: Boolean = getOptionalProperty[Boolean]("prototype.disclaimer").getOrElse(TestConfig.DEFAULT_PB_VISIBLE)

  // Google analytics
  override val googleAnalyticsTrackingId: Option[String] = None

  override val isHtml5ValidationEnabled: Boolean =
    getOptionalProperty[Boolean]("html5Validation.enabled").getOrElse(TestConfig.DEFAULT_HTML_VALIDATION)

  override val startUrl: String = TestConfig.START_URL

  // Opening and closing times
  def openingTimeMinOfDay: Int = getOptionalProperty[Int]("openingTimeMinOfDay").getOrElse(TestConfig.DEFAULT_OPENING_TIME)
  def closingTimeMinOfDay: Int = getOptionalProperty[Int]("closingTimeMinOfDay").getOrElse(TestConfig.DEFAULT_CLOSING_TIME)
  override val closingWarnPeriodMins: Int = getOptionalProperty[Int]("closingWarnPeriodMins").getOrElse(TestConfig.DEFAULT_CLOSING_WARN_PERIOD)
  override val closedDays: List[Int] = getIntListProperty("closedDays").getOrElse(List())

  // Web headers
  override val applicationCode = TestConfig.WEB_APPLICATION_CODE
  override val vssServiceTypeCode = TestConfig.WEB_VSSSERVICETYPE_CODE
  override val dmsServiceTypeCode = TestConfig.WEB_DMSSERVICETYPE_CODE
  override val channelCode = TestConfig.WEB_CHANNEL_CODE
  override val contactId = TestConfig.WEB_CONTACT_ID
  override val orgBusinessUnit = TestConfig.WEB_ORG_BU

  override val emailServiceMicroServiceUrlBase: String = TestConfig.NotFound
  override val emailServiceMsRequestTimeout: Int = TestConfig.EMAIL_REQUEST_TIMEOUT

  override val emailConfiguration: EmailConfiguration = EmailConfiguration(
    from = From(TestConfig.EMAIL_FROM_EMAIL, TestConfig.EMAIL_FROM_NAME),
    feedbackEmail = From(TestConfig.EMAILFEEDBACK_FROM_EMAIL, TestConfig.EMAILFEEDBACK_FROM_NAME),
    whiteList = None
  )

  override val imagesPath: String = TestConfig.IMAGES_PATH

//  override val surveyUrl: Option[String] = Some("test/survey/url")
  override val surveyUrl: Option[String] = None
}

// placeholder for defaults and fixed test data
object TestConfig {
  final val NotFound = "NOT FOUND"

  final val EMAIL_FROM_NAME = "Someone"
  final val EMAILFEEDBACK_FROM_NAME = "Nobody"
  final val EMAIL_FROM_EMAIL = ""
  final val EMAILFEEDBACK_FROM_EMAIL = ""

  final val WEB_HEADER_TESTVAL = "WEBVOA"
  final val WEB_APPLICATION_CODE = WEB_HEADER_TESTVAL
  final val WEB_VSSSERVICETYPE_CODE = WEB_HEADER_TESTVAL
  final val WEB_DMSSERVICETYPE_CODE = "X"
  final val WEB_CHANNEL_CODE = WEB_HEADER_TESTVAL
  final val WEB_CONTACT_ID = 1L
  final val WEB_ORG_BU = WEB_HEADER_TESTVAL

  final val VERY_LONG_SURVEY_INTERVAL = 1000000000000L // in millis (approx 11574 days!)

  final val START_URL = "/before-you-start"
  final val EMPTY_URL = ""
  final val IMAGES_PATH = ""
  final val EMAIL_REQUEST_TIMEOUT = 10000

  // defaults
  final val DEFAULT_HTML_VALIDATION = false
  final val DEFAULT_PB_VISIBLE = true
  final val DEFAULT_OPENING_TIME = 0
  final val DEFAULT_CLOSING_TIME = 1440
  final val DEFAULT_CLOSING_WARN_PERIOD = 0
}


text:
typedef struct
{
    cl_uint info;
    const char *name;
} _info;

_info platform_info_table[] = {
#define STRING(x)                                                              \
    {                                                                          \
        x, #x                                                                  \
    }
    STRING(CL_PLATFORM_EXTERNAL_MEMORY_IMPORT_HANDLE_TYPES_KHR),
    STRING(CL_PLATFORM_SEMAPHORE_EXPORT_HANDLE_TYPES_KHR),
    STRING(CL_PLATFORM_SEMAPHORE_IMPORT_HANDLE_TYPES_KHR)
#undef STRING
};

_info device_info_table[] = {
#define STRING(x)                                                              \
    {                                                                          \
        x, #x                                                                  \
    }
    STRING(CL_DEVICE_SEMAPHORE_IMPORT_HANDLE_TYPES_KHR),
    STRING(CL_DEVICE_SEMAPHORE_EXPORT_HANDLE_TYPES_KHR),
    STRING(CL_DEVICE_EXTERNAL_MEMORY_IMPORT_HANDLE_TYPES_KHR)
#undef STRING
};

int test_platform_info(cl_device_id deviceID, cl_context _context,
                       cl_command_queue _queue, int num_elements)
{
    cl_uint num_platforms;
    cl_uint i, j;
    cl_platform_id *platforms;
    cl_int errNum;
    cl_uint *handle_type;
    size_t handle_type_size = 0;
    cl_uint num_handles = 0;

    // get total # of platforms
    errNum = clGetPlatformIDs(0, NULL, &num_platforms);
    test_error(errNum, "clGetPlatformIDs (getting count) failed");

    platforms =
        (cl_platform_id *)malloc(num_platforms * sizeof(cl_platform_id));
    if (!platforms)
    {
        printf("error allocating memory\n");
        exit(1);
    }
    log_info("%d platforms available\n", num_platforms);
    errNum = clGetPlatformIDs(num_platforms, platforms, NULL);
    test_error(errNum, "clGetPlatformIDs (getting IDs) failed");

    for (i = 0; i < num_platforms; i++)
    {
        log_info("Platform%d (id %lu) info:\n", i, (unsigned long)platforms[i]);
        for (j = 0;
             j < sizeof(platform_info_table) / sizeof(platform_info_table[0]);
             j++)
        {
            errNum =
                clGetPlatformInfo(platforms[i], platform_info_table[j].info, 0,
                                  NULL, &handle_type_size);
            test_error(errNum, "clGetPlatformInfo failed");
            num_handles = handle_type_size / sizeof(cl_uint);
            handle_type = (cl_uint *)malloc(handle_type_size);
            errNum =
                clGetPlatformInfo(platforms[i], platform_info_table[j].info,
                                  handle_type_size, handle_type, NULL);
            test_error(errNum, "clGetPlatformInfo failed");

            log_info("%s: \n", platform_info_table[j].name);
            while (num_handles--)
            {
                log_info("%x \n", handle_type[num_handles]);
            }
            if (handle_type)
            {
                free(handle_type);
            }
        }
    }
    if (platforms)
    {
        free(platforms);
    }
    return TEST_PASS;
}

int test_device_info(cl_device_id deviceID, cl_context _context,
                     cl_command_queue _queue, int num_elements)
{
    cl_uint j;
    cl_uint *handle_type;
    size_t handle_type_size = 0;
    cl_uint num_handles = 0;
    cl_int errNum = CL_SUCCESS;
    for (j = 0; j < sizeof(device_info_table) / sizeof(device_info_table[0]);
         j++)
    {
        errNum = clGetDeviceInfo(deviceID, device_info_table[j].info, 0, NULL,
                                 &handle_type_size);
        test_error(errNum, "clGetDeviceInfo failed");

        num_handles = handle_type_size / sizeof(cl_uint);
        handle_type = (cl_uint *)malloc(handle_type_size);

        errNum = clGetDeviceInfo(deviceID, device_info_table[j].info,
                                 handle_type_size, handle_type, NULL);
        test_error(errNum, "clGetDeviceInfo failed");

        log_info("%s: \n", device_info_table[j].name);
        while (num_handles--)
        {
            log_info("%x \n", handle_type[num_handles]);
        }
        if (handle_type)
        {
            free(handle_type);
        }
    }
    return TEST_PASS;
}


text:
using System.Reactive.Concurrency;

namespace SoSmartTv.VideoPlayer
{
	public static class DispatcherScheduler
	{
		public static IScheduler Instance { get; set; }
	}
}


text:
layout: autoindex
css_filename: minty.css
---


text:
#include <sam.h>
#include "board_definitions.h"

/**
 * \brief system_init() configures the needed clocks and according Flash Read Wait States.
 * At reset:
 * - OSC8M clock source is enabled with a divider by 8 (1MHz).
 * - Generic Clock Generator 0 (GCLKMAIN) is using OSC8M as source.
 * We need to:
 * 1) Enable XOSC32K clock (External on-board 32.768Hz oscillator), will be used as DFLL48M reference.
 * 2) Put XOSC32K as source of Generic Clock Generator 1
 * 3) Put Generic Clock Generator 1 as source for Generic Clock Multiplexer 0 (DFLL48M reference)
 * 4) Enable DFLL48M clock
 * 5) Switch Generic Clock Generator 0 to DFLL48M. CPU will run at 48MHz.
 * 6) Modify PRESCaler value of OSCM to have 8MHz
 * 7) Put OSC8M as source for Generic Clock Generator 3
 */
// Constants for Clock generators
#define GENERIC_CLOCK_GENERATOR_MAIN      (0u)
#define GENERIC_CLOCK_GENERATOR_XOSC32K   (1u)
#define GENERIC_CLOCK_GENERATOR_OSCULP32K (2u) /* Initialized at reset for WDT */
#define GENERIC_CLOCK_GENERATOR_OSC8M     (3u)
// Constants for Clock multiplexers
#define GENERIC_CLOCK_MULTIPLEXER_DFLL48M (0u)

void board_init(void)
{
  /* Set 1 Flash Wait State for 48MHz, cf tables 20.9 and 35.27 in SAMD21 Datasheet */
  NVMCTRL->CTRLB.bit.RWS = NVMCTRL_CTRLB_RWS_HALF_Val;

  /* Turn on the digital interface clock */
  PM->APBAMASK.reg |= PM_APBAMASK_GCLK;

  /* ----------------------------------------------------------------------------------------------
   * 1) Enable XOSC32K clock (External on-board 32.768Hz oscillator)
   */
  SYSCTRL->XOSC32K.reg = SYSCTRL_XOSC32K_STARTUP( 0x6u ) | /* cf table 15.10 of product datasheet in chapter 15.8.6 */
                         SYSCTRL_XOSC32K_XTALEN | SYSCTRL_XOSC32K_EN32K;
  SYSCTRL->XOSC32K.bit.ENABLE = 1; /* separate call, as described in chapter 15.6.3 */

  while ( (SYSCTRL->PCLKSR.reg & SYSCTRL_PCLKSR_XOSC32KRDY) == 0 )
  {
    /* Wait for oscillator stabilization */
  }

  /* Software reset the module to ensure it is re-initialized correctly */
  /* Note: Due to synchronization, there is a delay from writing CTRL.SWRST until the reset is complete.
   * CTRL.SWRST and STATUS.SYNCBUSY will both be cleared when the reset is complete, as described in chapter 13.8.1
   */
  GCLK->CTRL.reg = GCLK_CTRL_SWRST;

  while ( (GCLK->CTRL.reg & GCLK_CTRL_SWRST) && (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY) )
  {
    /* Wait for reset to complete */
  }

  /* ----------------------------------------------------------------------------------------------
   * 2) Put XOSC32K as source of Generic Clock Generator 1
   */
  GCLK->GENDIV.reg = GCLK_GENDIV_ID( GENERIC_CLOCK_GENERATOR_XOSC32K ); // Generic Clock Generator 1

  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
  {
    /* Wait for synchronization */
  }

  /* Write Generic Clock Generator 1 configuration */
  GCLK->GENCTRL.reg = GCLK_GENCTRL_ID( GENERIC_CLOCK_GENERATOR_XOSC32K ) | // Generic Clock Generator 1
                      GCLK_GENCTRL_SRC_XOSC32K | // Selected source is External 32KHz Oscillator
//                      GCLK_GENCTRL_OE | // Output clock to a pin for tests
                      GCLK_GENCTRL_GENEN;

  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
  {
    /* Wait for synchronization */
  }

  /* ----------------------------------------------------------------------------------------------
   * 3) Put Generic Clock Generator 1 as source for Generic Clock Multiplexer 0 (DFLL48M reference)
   */
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID( GENERIC_CLOCK_MULTIPLEXER_DFLL48M ) | // Generic Clock Multiplexer 0
                      GCLK_CLKCTRL_GEN_GCLK1 | // Generic Clock Generator 1 is source
                      GCLK_CLKCTRL_CLKEN;

  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
  {
    /* Wait for synchronization */
  }

  /* ----------------------------------------------------------------------------------------------
   * 4) Enable DFLL48M clock
   */

  /* DFLL Configuration in Closed Loop mode, cf product datasheet chapter 15.6.7.1 - Closed-Loop Operation */

  /* Remove the OnDemand mode, Bug http://avr32.icgroup.norway.atmel.com/bugzilla/show_bug.cgi?id=9905 */
  SYSCTRL->DFLLCTRL.bit.ONDEMAND = 0;

  while ( (SYSCTRL->PCLKSR.reg & SYSCTRL_PCLKSR_DFLLRDY) == 0 )
  {
    /* Wait for synchronization */
  }

  SYSCTRL->DFLLMUL.reg = SYSCTRL_DFLLMUL_CSTEP( 31 ) | // Coarse step is 31, half of the max value
                         SYSCTRL_DFLLMUL_FSTEP( 511 ) | // Fine step is 511, half of the max value
                         SYSCTRL_DFLLMUL_MUL( (VARIANT_MCK/VARIANT_MAINOSC) ); // External 32KHz is the reference

  while ( (SYSCTRL->PCLKSR.reg & SYSCTRL_PCLKSR_DFLLRDY) == 0 )
  {
    /* Wait for synchronization */
  }

  /* Write full configuration to DFLL control register */
  SYSCTRL->DFLLCTRL.reg |= SYSCTRL_DFLLCTRL_MODE | /* Enable the closed loop mode */
                           SYSCTRL_DFLLCTRL_WAITLOCK |
                           SYSCTRL_DFLLCTRL_QLDIS; /* Disable Quick lock */

  while ( (SYSCTRL->PCLKSR.reg & SYSCTRL_PCLKSR_DFLLRDY) == 0 )
  {
    /* Wait for synchronization */
  }

  /* Enable the DFLL */
  SYSCTRL->DFLLCTRL.reg |= SYSCTRL_DFLLCTRL_ENABLE;

  while ( (SYSCTRL->PCLKSR.reg & SYSCTRL_PCLKSR_DFLLLCKC) == 0 ||
          (SYSCTRL->PCLKSR.reg & SYSCTRL_PCLKSR_DFLLLCKF) == 0 )
  {
    /* Wait for locks flags */
  }

  while ( (SYSCTRL->PCLKSR.reg & SYSCTRL_PCLKSR_DFLLRDY) == 0 )
  {
    /* Wait for synchronization */
  }

  /* ----------------------------------------------------------------------------------------------
   * 5) Switch Generic Clock Generator 0 to DFLL48M. CPU will run at 48MHz.
   */
  GCLK->GENDIV.reg = GCLK_GENDIV_ID( GENERIC_CLOCK_GENERATOR_MAIN ); // Generic Clock Generator 0

  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
  {
    /* Wait for synchronization */
  }

  /* Write Generic Clock Generator 0 configuration */
  GCLK->GENCTRL.reg = GCLK_GENCTRL_ID( GENERIC_CLOCK_GENERATOR_MAIN ) | // Generic Clock Generator 0
                      GCLK_GENCTRL_SRC_DFLL48M | // Selected source is DFLL 48MHz
//                      GCLK_GENCTRL_OE | // Output clock to a pin for tests
                      GCLK_GENCTRL_IDC | // Set 50/50 duty cycle
                      GCLK_GENCTRL_GENEN;

  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
  {
    /* Wait for synchronization */
  }

#if 0
  /* ----------------------------------------------------------------------------------------------
   * 6) Modify PRESCaler value of OSC8M to have 8MHz
   */
  SYSCTRL->OSC8M.bit.PRESC = SYSCTRL_OSC8M_PRESC_1_Val;
  SYSCTRL->OSC8M.bit.ONDEMAND = 0;

  /* ----------------------------------------------------------------------------------------------
   * 7) Put OSC8M as source for Generic Clock Generator 3
   */
  GCLK->GENDIV.reg = GCLK_GENDIV_ID( GENERIC_CLOCK_GENERATOR_OSC8M ); // Generic Clock Generator 3

  /* Write Generic Clock Generator 3 configuration */
  GCLK->GENCTRL.reg = GCLK_GENCTRL_ID( GENERIC_CLOCK_GENERATOR_OSC8M ) | // Generic Clock Generator 3
                      GCLK_GENCTRL_SRC_OSC8M | // Selected source is RC OSC 8MHz (already enabled at reset)
//                      GCLK_GENCTRL_OE | // Output clock to a pin for tests
                      GCLK_GENCTRL_GENEN;

  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
  {
    /* Wait for synchronization */
  }
#endif //0

  /*
   * Now that all system clocks are configured, we can set CPU and APBx BUS clocks.
   * These values are normally the ones present after Reset.
   */
  PM->CPUSEL.reg  = PM_CPUSEL_CPUDIV_DIV1;
  PM->APBASEL.reg = PM_APBASEL_APBADIV_DIV1_Val;
  PM->APBBSEL.reg = PM_APBBSEL_APBBDIV_DIV1_Val;
  PM->APBCSEL.reg = PM_APBCSEL_APBCDIV_DIV1_Val;
}


text:
package com.christiangp.rxfacebook;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;

import java.util.ArrayList;
import java.util.Collection;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;

final class LoginResultEventObservable
    extends Observable<LoginResultEvent> {

    private static final String FRAGMENT_TAG = "RxFacebookFragment";

    private final Collection<String> permissions;

    private       Activity           activity;

    LoginResultEventObservable(Activity activity, Collection<String> permissions) {
        this.activity = activity;
        this.permissions = permissions;
    }

    @Override
    protected void subscribeActual(Observer<? super LoginResultEvent> observer) {
        MainThreadDisposable.verifyMainThread();

        final CallbackManager facebookCallbackManager = CallbackManager.Factory.create();

        RxFacebookFragment rxFacebookFragment = (RxFacebookFragment) activity.getFragmentManager()
                                                                             .findFragmentByTag(FRAGMENT_TAG);
        if (rxFacebookFragment != null) {
            activity.getFragmentManager()
                    .beginTransaction()
                    .remove(rxFacebookFragment)
                    .commitAllowingStateLoss();
        }
        rxFacebookFragment = RxFacebookFragment.newInstance(permissions);
        rxFacebookFragment.setFacebookCallbackManager(facebookCallbackManager);
        activity.getFragmentManager()
                .beginTransaction()
                .add(rxFacebookFragment, FRAGMENT_TAG)
                .commitAllowingStateLoss();

        final Listener listener = new Listener(this, observer);
        LoginManager.getInstance()
                    .registerCallback(facebookCallbackManager, listener);

        observer.onSubscribe(listener);
    }

    @SuppressWarnings("WeakerAccess")
    void release() {
        activity = null;
    }

    private static class Listener
        extends MainThreadDisposable
        implements FacebookCallback<LoginResult> {

        private final LoginResultEventObservable         requester;

        private final Observer<? super LoginResultEvent> observer;

        Listener(LoginResultEventObservable requester, Observer<? super LoginResultEvent> observer) {
            this.requester = requester;
            this.observer = observer;
        }

        @Override
        public void onSuccess(LoginResult loginResult) {
            if (!isDisposed()) {
                observer.onNext(LoginResultSuccessfulEvent.create(loginResult));
                observer.onComplete();
            }
        }

        @Override
        public void onCancel() {
            if (!isDisposed()) {
                observer.onNext(LoginResultCanceledEvent.create());
                observer.onComplete();
            }
        }

        @Override
        public void onError(FacebookException error) {
            if (!isDisposed()) {
                observer.onError(error);
            }
        }

        @Override
        protected void onDispose() {
            requester.release();
        }
    }

    public static class RxFacebookFragment
        extends Fragment {

        private static final String KEY_PERMISSIONS = "permissions";

        private CallbackManager facebookCallbackManager;

        public static RxFacebookFragment newInstance(@NonNull Collection<String> permissions) {
            final Bundle args = new Bundle();
            args.putStringArrayList(KEY_PERMISSIONS, new ArrayList<>(permissions));

            final RxFacebookFragment fragment = new RxFacebookFragment();
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
            LoginManager.getInstance()
                        .logInWithReadPermissions(this, getArguments().getStringArrayList(KEY_PERMISSIONS));
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            facebookCallbackManager.onActivityResult(requestCode, resultCode, data);
        }

        public void setFacebookCallbackManager(CallbackManager facebookCallbackManager) {
            this.facebookCallbackManager = facebookCallbackManager;
        }
    }
}


text:
export declare class ComponentHolder {
    private components;
    private pages;
    private prototypes;
    /**
     * Загрузить все компоненты. Должен быть вызван после загрузки всех View.
     */
    load(): void;
    /**
     * Создать дубликат компонента из прототипа и вернуть его имя
     * @param componentProto
     */
    duplicateComponent(componentProto: any): string;
    /**
     * Инициализировать компонент из прототипа
     * @param componentProto
     * @param name
     * @param viewName
     * @param controllerName
     */
    initComponent(componentProto: any, name?: string, viewName?: string, controllerName?: string): void;
    /**
     * Получить компонент по имени
     * @param name
     * @returns {any}
     */
    getComponent(name: string): any;
    /**
     * Получить прототип компонента по имени
     * @param name
     * @returns {any}
     */
    getComponentPrototype(name: string): any;
    /**
     * Получить страницу по имени
     * @param name
     * @returns {any}
     */
    getPage(name: string): any;
}


text:
package com.hortonworks.hdf.android.sitetosite.client.socket;

import com.hortonworks.hdf.android.sitetosite.client.protocol.ResponseCode;
import com.hortonworks.hdf.android.sitetosite.client.transaction.DataPacketWriter;
import com.hortonworks.hdf.android.sitetosite.packet.DataPacket;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class SocketDataPacketWriter extends DataPacketWriter {
    private final DataOutputStream dataOutputStream;
    boolean first = true;

    public SocketDataPacketWriter(OutputStream outputStream) {
        super(outputStream, false);
        this.dataOutputStream = new DataOutputStream(outputStream);
    }

    @Override
    public void write(DataPacket dataPacket) throws IOException {
        if (first) {
            first = false;
        } else {
            ResponseCode.CONTINUE_TRANSACTION.writeResponse(dataOutputStream);
        }
        super.write(dataPacket);
    }
}


text:
require 'spec_helper'

module ShoppingCart
  describe Houseware do
    describe 'discount' do
      let(:shopping_day) { Date.new(2014, 11, 1) }

      context "when the prices is bigger than 100" do
        it "has a 5% discount" do
          expect(Houseware.new('Vacuum cleaner', 150).discount(shopping_day)).to eq(7.5)
        end
      end

      context "otherwise" do
        it "has no discount" do
          expect(Houseware.new('Vacuum cleaner', 80).discount(shopping_day)).to eq(0)
        end
      end
    end
  end
end


text:
#ifndef STAN_MATH_PRIM_PROB_GAMMA_CDF_HPP
#define STAN_MATH_PRIM_PROB_GAMMA_CDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/gamma_p.hpp>
#include <stan/math/prim/fun/grad_reg_inc_gamma.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/multiply_log.hpp>
#include <stan/math/prim/fun/scalar_seq_view.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/tgamma.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <boost/random/gamma_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>

namespace stan {
namespace math {

/** \ingroup prob_dists
 * The cumulative density function for a gamma distribution for y
 * with the specified shape and inverse scale parameters.
 *
 * @tparam T_y type of scalar
 * @tparam T_shape type of shape
 * @tparam T_inv_scale type of inverse scale
 * @param y A scalar variable.
 * @param alpha Shape parameter.
 * @param beta Inverse scale parameter.
 * @throw std::domain_error if alpha is not greater than 0.
 * @throw std::domain_error if beta is not greater than 0.
 * @throw std::domain_error if y is not greater than or equal to 0.
 */
template <typename T_y, typename T_shape, typename T_inv_scale>
return_type_t<T_y, T_shape, T_inv_scale> gamma_cdf(const T_y& y,
                                                   const T_shape& alpha,
                                                   const T_inv_scale& beta) {
  using T_partials_return = partials_return_t<T_y, T_shape, T_inv_scale>;
  using T_y_ref = ref_type_t<T_y>;
  using T_alpha_ref = ref_type_t<T_shape>;
  using T_beta_ref = ref_type_t<T_inv_scale>;
  using std::exp;
  static const char* function = "gamma_cdf";
  check_consistent_sizes(function, "Random variable", y, "Shape parameter",
                         alpha, "Inverse scale parameter", beta);
  T_y_ref y_ref = y;
  T_alpha_ref alpha_ref = alpha;
  T_beta_ref beta_ref = beta;
  check_positive_finite(function, "Shape parameter", alpha_ref);
  check_positive_finite(function, "Inverse scale parameter", beta_ref);
  check_nonnegative(function, "Random variable", y_ref);

  if (size_zero(y, alpha, beta)) {
    return 1.0;
  }

  T_partials_return P(1.0);
  operands_and_partials<T_y_ref, T_alpha_ref, T_beta_ref> ops_partials(
      y_ref, alpha_ref, beta_ref);

  scalar_seq_view<T_y_ref> y_vec(y_ref);
  scalar_seq_view<T_alpha_ref> alpha_vec(alpha_ref);
  scalar_seq_view<T_beta_ref> beta_vec(beta_ref);
  size_t N = max_size(y, alpha, beta);

  // Explicit return for extreme values
  // The gradients are technically ill-defined, but treated as zero
  for (size_t i = 0; i < stan::math::size(y); i++) {
    if (y_vec.val(i) == 0) {
      return ops_partials.build(0.0);
    }
  }

  using std::exp;
  using std::pow;

  VectorBuilder<!is_constant_all<T_shape>::value, T_partials_return, T_shape>
      gamma_vec(math::size(alpha));
  VectorBuilder<!is_constant_all<T_shape>::value, T_partials_return, T_shape>
      digamma_vec(math::size(alpha));

  if (!is_constant_all<T_shape>::value) {
    for (size_t i = 0; i < stan::math::size(alpha); i++) {
      const T_partials_return alpha_dbl = alpha_vec.val(i);
      gamma_vec[i] = tgamma(alpha_dbl);
      digamma_vec[i] = digamma(alpha_dbl);
    }
  }

  for (size_t n = 0; n < N; n++) {
    // Explicit results for extreme values
    // The gradients are technically ill-defined, but treated as zero
    if (y_vec.val(n) == INFTY) {
      continue;
    }

    const T_partials_return y_dbl = y_vec.val(n);
    const T_partials_return alpha_dbl = alpha_vec.val(n);
    const T_partials_return beta_dbl = beta_vec.val(n);

    const T_partials_return Pn = gamma_p(alpha_dbl, beta_dbl * y_dbl);

    P *= Pn;

    if (!is_constant_all<T_y>::value) {
      ops_partials.edge1_.partials_[n] += beta_dbl * exp(-beta_dbl * y_dbl)
                                          * pow(beta_dbl * y_dbl, alpha_dbl - 1)
                                          / tgamma(alpha_dbl) / Pn;
    }
    if (!is_constant_all<T_shape>::value) {
      ops_partials.edge2_.partials_[n]
          -= grad_reg_inc_gamma(alpha_dbl, beta_dbl * y_dbl, gamma_vec[n],
                                digamma_vec[n])
             / Pn;
    }
    if (!is_constant_all<T_inv_scale>::value) {
      ops_partials.edge3_.partials_[n] += y_dbl * exp(-beta_dbl * y_dbl)
                                          * pow(beta_dbl * y_dbl, alpha_dbl - 1)
                                          / tgamma(alpha_dbl) / Pn;
    }
  }

  if (!is_constant_all<T_y>::value) {
    for (size_t n = 0; n < stan::math::size(y); ++n) {
      ops_partials.edge1_.partials_[n] *= P;
    }
  }
  if (!is_constant_all<T_shape>::value) {
    for (size_t n = 0; n < stan::math::size(alpha); ++n) {
      ops_partials.edge2_.partials_[n] *= P;
    }
  }
  if (!is_constant_all<T_inv_scale>::value) {
    for (size_t n = 0; n < stan::math::size(beta); ++n) {
      ops_partials.edge3_.partials_[n] *= P;
    }
  }
  return ops_partials.build(P);
}

}  // namespace math
}  // namespace stan
#endif


text: .. automodule:: tenable.ad.preference.api


text:
<?php if (!defined('PAGSEGURO_LIBRARY')) { die('No direct script access allowed'); }

/*
* Library autoloader - spl_autoload_register
*/
class PagSeguroAutoloader {

	public static $loader;

	private static $dirs = Array(
		'config',
		'resources',
		'log',
		'domain',
		'exception',
		'parser',
		'service',
		'utils',
		'helper'
	);

	private function __construct() {
		if (function_exists('__autoload')) {
			spl_autoload_register('__autoload');
		}
		spl_autoload_register(Array($this, 'addClass'));
	}

	public static function init() {
		if (!function_exists('spl_autoload_register')) {
			throw new Exception("PagSeguroLibrary: Standard PHP Library (SPL) is required.");
			return false;
		}
		if (self::$loader == null) {
			self::$loader = new PagSeguroAutoloader();
		}
		return self::$loader;
	}

	private function addClass($class) {
		foreach(self::$dirs as $key => $dir) {
			$file = PagSeguroLibrary::getPath().DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$class.'.class.php';
			if (file_exists($file) && is_file($file)) {
				require_once $file;
			}
		}
	}

}
?>


text:
package in.koyad.piston.common.util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class FileUtil {

	public static Map<String, List<Property>> readIniAsMap(Path path) throws IOException {
		Map<String, List<Property>> sections = new LinkedHashMap<>();

		try(Stream<String> lines = Files.lines(path)) {
			lines.forEach(line -> processLine(line, sections));
		}

		return sections;
	}

	private static void processLine(String line, Map<String, List<Property>> sections) {
//		System.out.println("Line : " + line);
		String section = "";
		if(line.startsWith("[") && line.endsWith("]")) {
			section = line.substring(1, line.length()-1);
			sections.put(section, new ArrayList<Property>());
		} else {
			Iterator<String> iter = sections.keySet().iterator();
			while(iter.hasNext()) {
				section = iter.next();
			}
			String[] parts = line.split("=");
			if(parts.length == 2) {
				List<Property> properties = sections.get(section);
				properties.add(new Property(parts[0].trim(), parts[1].trim()));
			}
		}
	}

	public static String getFileAsString(String path) throws IOException {
		return new String(Files.readAllBytes(Paths.get(path)));
	}

	public static void main(String[] args) {
		Path path = Paths.get(args[0]);
		try {
			Map<String, List<Property>> sections = readIniAsMap(path);
			Iterator<String> iter = sections.keySet().iterator();
			while(iter.hasNext()) {
				String section = iter.next();
				System.out.println("[" + section + "]");
				for(Property property : sections.get(section)) {
					System.out.println(property.getKey() + "=" + property.getValue());
				}
				System.out.println("");
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

}


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    CustomBtnView *contentView = [CustomBtnView new];
    [self.view addSubview:contentView];
    [contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    [contentView setupUITitleArr:@[@"141341",@"2fadfad",@"3fadf",@"4a",@"5",@"6",@"7",@"8",@"9",@"1fadfa",@"2",@"3",@"4",@"5",@"6",@"fadfa7",@"8",@"9",@"1",@"2",@"3",@"fadf4",@"5",@"6",@"fadfa7",@"8",@"9"]];

    [contentView layoutContentUI];

    contentView.backgroundColor = [UIColor clearColor];

    [contentView setSelectedBlock:^(NSInteger index) {
        NSLog(@"king");
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
from typing import Any, Dict, List, Tuple, Union

import urllib3
from dateparser import parse
from pytz import utc
from requests_ntlm import HttpNtlmAuth

import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

urllib3.disable_warnings()

SEVERITY_TRANSLATION = {
    'Low': 1,
    'Medium': 2,
    'High': 3
}

class Client(BaseClient):
    def get_suspicious_activity_request(self, suspicious_activity_id: str = '') -> Dict[str, Any]:
        return self._http_request(
            method='GET',
            url_suffix=f'/suspiciousActivities/{suspicious_activity_id}'
        )

    def get_suspicious_activity_details_request(self, suspicious_activity_id: str) -> Dict[str, Any]:
        return self._http_request(
            method='GET',
            url_suffix=f'/suspiciousActivities/{suspicious_activity_id}/details'
        )

    def update_suspicious_activity_status_request(self,
                                                  suspicious_activity_id: str,
                                                  suspicious_activity_status: str
                                                  ) -> Dict[str, Any]:
        body = {
            'Status': suspicious_activity_status
        }

        return self._http_request(
            method='POST',
            url_suffix=f'/suspiciousActivities/{suspicious_activity_id}',
            json_data=body,
            ok_codes=(204,),
            resp_type='text'
        )

    def delete_suspicious_activity_request(self, suspicious_activity_id: str) -> Dict[str, Any]:
        body = {
            'shouldDeleteSametype': False
        }

        params = {
            'shouldDeleteSameType': 'false'
        }

        return self._http_request(
            method='DELETE',
            url_suffix=f'/suspiciousActivities/{suspicious_activity_id}',
            json_data=body,
            params=params,
            ok_codes=(204,),
            resp_type='text'
        )

    def get_monitoring_alert_request(self) -> Dict[str, Any]:
        return self._http_request(
            method='GET',
            url_suffix='/monitoringAlerts'
        )

    def get_entity_request(self, entity_id: str) -> Dict[str, Any]:
        return self._http_request(
            method='GET',
            url_suffix=f'/uniqueEntities/{entity_id}'
        )

    def get_entity_profile_request(self, entity_id: str) -> Dict[str, Any]:
        return self._http_request(
            method='GET',
            url_suffix=f'/uniqueEntities/{entity_id}/profile'
        )

def test_module(client: Client) -> str:
    client.get_monitoring_alert_request()
    return 'ok'

def get_suspicious_activity(client: Client, args: Dict[str, str]) -> Union[CommandResults, str]:
    suspicious_activity_id = args.get('id', '')
    suspicious_activity_status = argToList(args.get('status', ''))
    suspicious_activity_severity = argToList(args.get('severity', ''))
    suspicious_activity_type = argToList(args.get('type', ''))
    suspicious_activity_start_time = parse(args.get('start_time', ''))
    suspicious_activity_end_time = parse(args.get('end_time', ''))
    limit = int(args.get('limit', '50'))

    raw_suspicious_activity = client.get_suspicious_activity_request(suspicious_activity_id)
    suspicious_activity_output = []
    if raw_suspicious_activity:
        suspicious_activities = raw_suspicious_activity if isinstance(raw_suspicious_activity, list) \
            else [raw_suspicious_activity]
        if not suspicious_activity_id and \
                any([suspicious_activity_status, suspicious_activity_severity, suspicious_activity_type,
                     suspicious_activity_start_time, suspicious_activity_end_time]):
            for activity in suspicious_activities:
                if suspicious_activity_status and activity.get('Status') not in suspicious_activity_status:
                    continue
                if suspicious_activity_severity and activity.get('Severity') not in suspicious_activity_severity:
                    continue
                if suspicious_activity_type and activity.get('Type') not in suspicious_activity_type:
                    continue
                start_time_date = parse(activity.get('StartTime'))  # type: ignore
                assert start_time_date is not None
                if suspicious_activity_start_time and start_time_date.replace(tzinfo=utc) < \
                        suspicious_activity_start_time.replace(tzinfo=utc):
                    continue
                end_time_date = parse(activity.get('EndTime'))  # type: ignore
                assert end_time_date is not None
                if suspicious_activity_end_time and end_time_date.replace(tzinfo=utc) > \
                        suspicious_activity_end_time.replace(tzinfo=utc):
                    continue
                suspicious_activity_output.append(activity)
        else:
            suspicious_activity_output = suspicious_activities
    suspicious_activity_output = suspicious_activity_output[:limit]
    if suspicious_activity_output:
        readable_output = tableToMarkdown(
            'Microsoft Advanced Threat Analytics Suspicious Activity',
            suspicious_activity_output,
            headers=['Id', 'Type', 'Status', 'Severity', 'StartTime', 'EndTime'],
            removeNull=True
        )
        if suspicious_activity_id:
            suspicious_activity_details = client.get_suspicious_activity_details_request(suspicious_activity_id)
            details_records = suspicious_activity_details.get('DetailsRecords', [])
            if details_records:
                suspicious_activity_output[0]['DetailsRecords'] = details_records
                readable_output += tableToMarkdown(
                    'Details Records',
                    details_records,
                    removeNull=True
                )

        return CommandResults(
            readable_output=readable_output,
            outputs_prefix='MicrosoftATA.SuspiciousActivity',
            outputs_key_field='Id',
            outputs=suspicious_activity_output
        )
    else:
        return 'No results found.'

def update_suspicious_activity_status(client: Client, args: Dict[str, str]) -> str:
    suspicious_activity_id = args.get('id', '')
    suspicious_activity_status = args.get('status', '')

    if suspicious_activity_status == 'Delete':
        client.delete_suspicious_activity_request(suspicious_activity_id)
        return f'Suspicious activity {suspicious_activity_id} was deleted successfully.'
    else:
        client.update_suspicious_activity_status_request(suspicious_activity_id, suspicious_activity_status)
        return f'Suspicious activity {suspicious_activity_id} status was updated to ' \
               f'{suspicious_activity_status} successfully.'

def get_monitoring_alert(client: Client, args: Dict[str, str]) -> Union[CommandResults, str]:
    monitoring_alert_status = argToList(args.get('status', ''))
    monitoring_alert_severity = argToList(args.get('severity', ''))
    monitoring_alert_type = argToList(args.get('type', ''))
    monitoring_alert_start_time = parse(args.get('start_time', ''))
    monitoring_alert_end_time = parse(args.get('end_time', ''))
    limit = int(args.get('limit', '50'))

    raw_monitoring_alert = client.get_monitoring_alert_request()
    monitoring_alert_output = []
    if raw_monitoring_alert:
        monitoring_alerts = raw_monitoring_alert if isinstance(raw_monitoring_alert, list) else [raw_monitoring_alert]
        if any([monitoring_alert_status, monitoring_alert_severity, monitoring_alert_type,
                monitoring_alert_start_time, monitoring_alert_end_time]):
            for alert in monitoring_alerts:
                if monitoring_alert_status and alert.get('Status') not in monitoring_alert_status:
                    continue
                if monitoring_alert_severity and alert.get('Severity') not in monitoring_alert_severity:
                    continue
                if monitoring_alert_type and alert.get('Type') not in monitoring_alert_type:
                    continue
                start_time_date = parse(alert.get('StartTime')).replace(tzinfo=utc)  # type: ignore
                if monitoring_alert_start_time and start_time_date < \
                        monitoring_alert_start_time.replace(tzinfo=utc):
                    continue
                endtime_date = parse(alert.get('EndTime'))  # type: ignore
                assert endtime_date is not None
                if monitoring_alert_end_time and endtime_date.replace(tzinfo=utc) > \
                        monitoring_alert_end_time.replace(tzinfo=utc):
                    continue
                monitoring_alert_output.append(alert)
        else:
            monitoring_alert_output = monitoring_alerts
    monitoring_alert_output = monitoring_alert_output[:limit]
    if monitoring_alert_output:
        readable_output = tableToMarkdown(
            'Microsoft Advanced Threat Analytics Monitoring Alert',
            monitoring_alert_output,
            headers=['Id', 'Type', 'Status', 'Severity', 'StartTime', 'EndTime'],
            removeNull=True
        )

        return CommandResults(
            readable_output=readable_output,
            outputs_prefix='MicrosoftATA.MonitoringAlert',
            outputs_key_field='Id',
            outputs=monitoring_alert_output
        )
    else:
        return 'No results found.'

def get_entity(client: Client, args: Dict[str, str]) -> Union[CommandResults, str]:
    entity_id = args.get('id', '')

    entity = client.get_entity_request(entity_id)

    if entity:
        readable_output = tableToMarkdown(
            f'Microsoft Advanced Threat Analytics Entity {entity_id}',
            entity,
            headers=['Id', 'SystemDisplayName', 'DistinguishedName', 'UpnName', 'Type', 'CreationTime'],
            removeNull=True
        )

        entity_profile = client.get_entity_profile_request(entity_id)
        if entity_profile:
            entity['Profile'] = entity_profile
            readable_output += tableToMarkdown(
                'Entity Profile',
                entity_profile,
                headers=['Type', 'SuspiciousActivitySeverityToCountMapping', 'UpdateTime', 'IsBehaviorChanged'],
                removeNull=True
            )

        return CommandResults(
            readable_output=readable_output,
            outputs_prefix='MicrosoftATA.Entity',
            outputs_key_field='Id',
            outputs=entity
        )
    else:
        return 'No results found.'

def fetch_incidents(
        client: Client,
        last_run: Dict[str, str],
        first_fetch_time: str,
        max_results: int,
        activity_status_to_fetch: List,
        min_severity: int,
        activity_type_to_fetch: List
) -> Tuple[Dict[str, str], List[Dict[str, str]]]:
    last_fetch = last_run.get('last_fetch', '') if last_run.get('last_fetch') else first_fetch_time
    last_fetch_dt = parse(last_fetch).replace(tzinfo=utc)  # type: ignore
    latest_start_time = parse(last_fetch).replace(tzinfo=utc)  # type: ignore

    incidents_fetched = 0
    incidents: List[Dict[str, Any]] = []

    suspicious_activities = client.get_suspicious_activity_request()
    suspicious_activities_list = suspicious_activities if isinstance(suspicious_activities, list) \
        else [suspicious_activities]
    demisto.debug(suspicious_activities_list)
    for activity in suspicious_activities_list:
        if incidents_fetched == max_results:
            break
        activity_id = activity.get('Id', '')
        activity_status = activity.get('Status', '')
        activity_type = activity.get('Type', '')
        activity_severity = activity.get('Severity', '')
        if activity_status_to_fetch and activity_status not in activity_status_to_fetch:
            demisto.debug(f'Skipping suspicious activity {activity_id} with status {activity_status}')
            continue
        if activity_type_to_fetch and activity_type not in activity_type_to_fetch:
            demisto.debug(f'Skipping suspicious activity {activity_id} with type {activity_type}')
            continue
        if SEVERITY_TRANSLATION[activity_severity] < min_severity:
            demisto.debug(f'Skipping suspicious activity {activity_id} with severity {activity_severity}')
            continue
        activity_start_time = activity.get('StartTime', '')
        activity_start_time_date = parse(activity_start_time)
        assert activity_start_time_date is not None, f'could not parse {activity_start_time}'
        activity_start_time_dt = activity_start_time_date.replace(tzinfo=utc)
        if activity_start_time_dt > latest_start_time:
            incidents.append({
                'name': f'{activity_type} - {activity_id}',
                'occurred': activity_start_time,
                'rawJSON': json.dumps(activity)
            })
            if activity_start_time_dt > last_fetch_dt:
                last_fetch_dt = activity_start_time_dt
                last_fetch = activity_start_time
            incidents_fetched += 1
    next_run = {'last_fetch': last_fetch}
    return next_run, incidents

def main() -> None:
    params = demisto.params()
    base_url = urljoin(params['url'], '/api/management')
    username = params['credentials']['identifier']
    password = params['credentials']['password']
    verify_certificate = not params.get('insecure', False)
    proxy = params.get('proxy', False)

    demisto.debug(f'Command being called is {demisto.command()}')
    try:
        client = Client(
            base_url=base_url,
            auth=HttpNtlmAuth(username, password),
            verify=verify_certificate,
            proxy=proxy
        )

        if demisto.command() == 'test-module':
            result = test_module(client)
            return_results(result)
        elif demisto.command() == 'fetch-incidents':
            next_run, incidents = fetch_incidents(
                client=client,
                last_run=demisto.getLastRun(),
                first_fetch_time=params.get('first_fetch', '3 days'),
                max_results=int(params.get('max_fetch', '50')),
                activity_status_to_fetch=params.get('activity_status', ['Open']),
                min_severity=SEVERITY_TRANSLATION[params.get('min_severity', 'Low')],
                activity_type_to_fetch=argToList(params.get('activity_type', ''))
            )
            demisto.setLastRun(next_run)
            demisto.incidents(incidents)
        elif demisto.command() == 'ms-ata-suspicious-activities-list':
            return_results(get_suspicious_activity(client, demisto.args()))
        elif demisto.command() == 'ms-ata-suspicious-activity-status-set':
            return_results(update_suspicious_activity_status(client, demisto.args()))
        elif demisto.command() == 'ms-ata-monitoring-alerts-list':
            return_results(get_monitoring_alert(client, demisto.args()))
        elif demisto.command() == 'ms-ata-entity-get':
            return_results(get_entity(client, demisto.args()))
    except Exception as e:
        return_error(f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}')

if __name__ in ('__main__', '__builtin__', 'builtins'):
    main()


text:
/* the configured version and settings for clblas
 */
#define clAmdBlasVersionMajor 2
#define clAmdBlasVersionMinor 0
#define clAmdBlasVersionPatch 0


text:
<!doctype html>

  <meta charset="utf-8">

  <title>Deep Learning Workshop</title>

  <meta name="description" content="Deep Learning Workshop">
  <meta name="author" content="Martin Andrews">

  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

  <link rel="stylesheet" href="fonts/local.css">

  <link rel="stylesheet" href="css/reveal.min.css">
  <link rel="stylesheet" xhref="css/theme/default.css" href="css/theme/sky.css" id="theme">

  <link rel="stylesheet" href="lib/css/zenburn.css">

Deep Learning Workshop

  Martin Andrews @ redcatlabs.com

  <xsmall>Copy the USB key...  And pass it on!</xsmall>

  When you start the VM, there's no need to log in

Instructions

      Main Presentation

Browser-based examples :

TensorFlow - Features and Training

Meta-Learning Demo - '3 boxes'

VirtualBox / Jupyter examples :

Import Appliance :
'deep-learning ... .OVA'

Open Jupyter

- QUESTIONS -

Martin.Andrews @
 RedCatLabs.com

My blog : http://mdda.net/

GitHub : mdda


text:
"""
usage: git map [-h] [--help] [<args>]

Enhances `git log --graph` view with information on commit branches + tags that
point to them. Items are colorized as follows:

  * Cyan    - Currently checked out branch
  * Green   - Local branch
  * Red     - Remote branches
  * Magenta - Tags
  * White   - Merge Base Markers
  * Blue background - The currently checked out commit
"""

from __future__ import unicode_literals

import os
import sys

import git_common
import setup_color
import subprocess2

from third_party import colorama

if sys.version_info.major == 2:
  # On Python 3, BrokenPipeError is raised instead.
  BrokenPipeError = IOError

RESET = colorama.Fore.RESET + colorama.Back.RESET + colorama.Style.RESET_ALL
BRIGHT = colorama.Style.BRIGHT

BLUE_BACK = colorama.Back.BLUE + BRIGHT
BRIGHT_RED = colorama.Fore.RED + BRIGHT
CYAN = colorama.Fore.CYAN + BRIGHT
GREEN = colorama.Fore.GREEN + BRIGHT
MAGENTA = colorama.Fore.MAGENTA + BRIGHT
RED = colorama.Fore.RED
WHITE = colorama.Fore.WHITE + BRIGHT
YELLOW = colorama.Fore.YELLOW

def _print_help(outbuf):
  names = {
    'Cyan': CYAN,
    'Green': GREEN,
    'Magenta': MAGENTA,
    'Red': RED,
    'White': WHITE,
    'Blue background': BLUE_BACK,
  }
  msg = ''
  for line in __doc__.splitlines():
    for name, color in names.items():
      if name in line:
        msg += line.replace('* ' + name, color + '* ' + name + RESET) + '\n'
        break
    else:
      msg += line + '\n'
  outbuf.write(msg.encode('utf-8', 'replace'))

def _color_branch(branch, all_branches, all_tags, current):
  if branch == current or branch == 'HEAD -> ' + current:
    color = CYAN
    current = None
  elif branch in all_branches:
    color = GREEN
    all_branches.remove(branch)
  elif branch in all_tags:
    color = MAGENTA
  elif branch.startswith('tag: '):
    color = MAGENTA
    branch = branch[len('tag: '):]
  else:
    color = RED
  return color + branch + RESET

def _color_branch_list(branch_list, all_branches, all_tags, current):
  if not branch_list:
    return ''
  colored_branches = (GREEN + ', ').join(
      _color_branch(branch, all_branches, all_tags, current)
      for branch in branch_list if branch != 'HEAD')
  return (GREEN + '(' + colored_branches + GREEN + ') ' + RESET)

def _parse_log_line(line):
  graph, branch_list, commit_date, subject = (
      line.decode('utf-8', 'replace').strip().split('\x00'))
  branch_list = [] if not branch_list else branch_list.split(', ')
  commit = graph.split()[-1]
  graph = graph[:-len(commit)]
  return graph, commit, branch_list, commit_date, subject

def main(argv, outbuf):
  if '-h' in argv or '--help' in argv:
    _print_help(outbuf)
    return 0

  map_extra = git_common.get_config_list('depot_tools.map_extra')
  cmd = [
      git_common.GIT_EXE, 'log', git_common.root(),
      '--graph', '--branches', '--tags', '--color=always', '--date=short',
      '--pretty=format:%H%x00%D%x00%cd%x00%s'
  ] + map_extra + argv

  log_proc = subprocess2.Popen(cmd, stdout=subprocess2.PIPE, shell=False)

  current = git_common.current_branch()
  all_tags = set(git_common.tags())
  all_branches = set(git_common.branches())
  if current in all_branches:
    all_branches.remove(current)

  merge_base_map = {}
  for branch in all_branches:
    merge_base = git_common.get_or_create_merge_base(branch)
    if merge_base:
      merge_base_map.setdefault(merge_base, set()).add(branch)

  for merge_base, branches in merge_base_map.items():
    merge_base_map[merge_base] = ', '.join(branches)

  try:
    for line in log_proc.stdout:
      if b'\x00' not in line:
        outbuf.write(line)
        continue

      graph, commit, branch_list, commit_date, subject = _parse_log_line(line)

      if 'HEAD' in branch_list:
        graph = graph.replace('*', BLUE_BACK + '*')

      line = '{graph}{commit}\t{branches}{date} ~ {subject}'.format(
          graph=graph,
          commit=BRIGHT_RED + commit[:10] + RESET,
          branches=_color_branch_list(
              branch_list, all_branches, all_tags, current),
          date=YELLOW + commit_date + RESET,
          subject=subject)

      if commit in merge_base_map:
        line += '    <({})'.format(WHITE + merge_base_map[commit] + RESET)

      line += os.linesep
      outbuf.write(line.encode('utf-8', 'replace'))
  except (BrokenPipeError, KeyboardInterrupt):
    pass
  return 0

if __name__ == '__main__':
  setup_color.init()
  with git_common.less() as less_input:
    sys.exit(main(sys.argv[1:], less_input))


text:
The project aims to be a fully feature Repository for AspNet Core using the **Repository** and **UnitOfWork** patterns. Supports CRUD operations as well as pagination. It uses dependency injection by default, therefore can be injected in any component. Still, it can be used in non ASP.NET projects as well. It can be used to connect different databases in a very easily configurable way.

## Installation

The nuget package is not on nuget.org (yet). It is contained [here](https://www.myget.org/F/mindgaze-feed/api/v3/index.json). You can add it to your project.json file:

```json
"dependencies": {
  "Mindgaze.Toolkit.RepositoryContainer": "1.0.*"
}
```
Then hit the `dotnet restore -f https://www.myget.org/F/mindgaze-feed/api/v3/index.json` command. It should properly restore the packages.

## Getting started


text:
(function(module) {

  function Project (options) {
    Object.keys(options).forEach(function(each, index, keys) {
      this[each] = options[each];
    }, this);
  }

  Project.all = [];

  Project.prototype.renderHTML = function() {
    var $newProjectArticle = $('#project-article-template').html();
    var handlebarsTemplate = Handlebars.compile($newProjectArticle);
    return handlebarsTemplate(this);
  };

  Project.populateRawData = function(rawData) {
    Project.all = rawData.map(function(element) {
      return new Project(element);
    });
  };

  Project.retrieveAllProjects = function(nthPageLoad) {
    if (localStorage.rawData) {
      $.ajax({
        type: 'HEAD',
        url: 'data/projectsData.json',
        success: function(data, message, xhr) {
          var eTag = xhr.getResponseHeader('eTag');
          if (!localStorage.eTag || eTag !== localStorage.eTag) {
            // Data has been updated, so update eTag and reload JSON data
            localStorage.eTag = eTag;
            $.getJSON('/data/projectsData.json', function(data) {
              Project.populateRawData(data);
              localStorage.setItem('rawData', JSON.stringify(Project.all));
              nthPageLoad();
            });
          } else {
            // The data has not been updated, so access JSON data cached in local storage
            Project.populateRawData(JSON.parse(localStorage.getItem('rawData')));
            nthPageLoad();
          }
        }
      });
    } else {
      Project.setAllProjects(nthPageLoad);
    }
  };

  Project.setAllProjects = function(firstPageLoad) {
    $.getJSON('/data/projectsData.json', function(data) {
      Project.populateRawData(data);
      localStorage.rawData = JSON.stringify(data);
      firstPageLoad();
    });
  };

  Project.allCategories = function() {
    // locate all categories and remove duplicates
    return Project.all.map(function(projectArticle) {
      return projectArticle.projectCategory;
      // find all category names, not filtered yet...
    })
    .reduce(function(a, b) {
      if (a.indexOf(b) === -1) {
        a.push(b);
        // push filtered category names to a new array
      }
      return a;
    }, []);
  };

  Project.categoryTotalWords = function() {
    return Project.allCategories().map(function(projectCategory) {
      return {
        category: projectCategory,
        categoryNumWords: Project.all.map(function(projectArticle) {
          if (projectArticle.projectCategory === projectCategory) {
            return projectArticle.projectDescription.match(/\b\w+/g).length;
          } else {
            return 0;
          }
        })
        .reduce(function(x, y) {
          return x + y;
        })
      };
    });
  };

  module.Project = Project;
}(window));


text: console.log("LEL");


text:
sap.ui.define([
	'sap/ui/demo/cart/controller/BaseController',
	'sap/ui/demo/cart/model/formatter',
	'sap/ui/model/Filter',
	'sap/ui/model/FilterOperator'
], function (BaseController,
			 formatter,
			 Filter,
			 FilterOperator) {
	"use strict";

	return BaseController.extend("sap.ui.demo.cart.controller.Home", {
		formatter : formatter,

		onInit: function () {
			var oComponent = this.getOwnerComponent();
			this._router = oComponent.getRouter();
			// trigger first search to set visibilities right
			this._search();
		},

		onSearch: function () {
			this._search();
		},

		onRefresh: function () {
			// trigger search again and hide pullToRefresh when data ready
			var oProductList = this.getView().byId("productList");
			var oBinding = oProductList.getBinding("items");
			var fnHandler = function () {
				this.getView().byId("pullToRefresh").hide();
				oBinding.detachDataReceived(fnHandler);
			}.bind(this);
			oBinding.attachDataReceived(fnHandler);
			this._search();
		},

		_search: function () {
			var oView = this.getView();
			var oProductList = oView.byId("productList");
			var oCategoryList = oView.byId("categoryList");
			var oSearchField = oView.byId("searchField");

			// switch visibility of lists
			var bShowSearchResults = oSearchField.getValue().length !== 0;
			oProductList.setVisible(bShowSearchResults);
			oCategoryList.setVisible(!bShowSearchResults);

			if (bShowSearchResults) {
				this._changeNoDataTextToIndicateLoading(oProductList);
			}

			// filter product list
			var oBinding = oProductList.getBinding("items");
			if (oBinding) {
				if (bShowSearchResults) {
					var oFilter = new Filter("Name", FilterOperator.Contains, oSearchField.getValue());
					oBinding.filter([oFilter]);
				} else {
					oBinding.filter([]);
				}
			}
		},

		_changeNoDataTextToIndicateLoading: function (oList) {
			var sOldNoDataText = oList.getNoDataText();
			oList.setNoDataText("Loading...");
			oList.attachEventOnce("updateFinished", function () {
				oList.setNoDataText(sOldNoDataText);
			});
		},

		onCategoryListItemPress: function (oEvent) {
			var oBindContext = oEvent.getSource().getBindingContext();
			var oModel = oBindContext.getModel();
			var sCategoryId = oModel.getData(oBindContext.getPath()).Category;
			this._router.navTo("category", {id: sCategoryId});
		},

		onProductListSelect: function (oEvent) {
			var oItem = oEvent.getParameter("listItem");
			this._showProduct(oItem);
		},

		onProductListItemPress: function (oEvent) {
			var oItem = oEvent.getSource();
			this._showProduct(oItem);
		},

		_showProduct: function (oItem) {
			var oBindContext = oItem.getBindingContext();
			var oModel = oBindContext.getModel();
			var sId = oModel.getData(oBindContext.getPath()).ProductId;
			this._router.navTo("cartProduct", {productId: sId}, !sap.ui.Device.system.phone);
		},

		onNavButtonPress : function () {
			this.getOwnerComponent().myNavBack();
		},

		onCartButtonPress: function () {
			this._router.navTo("cart");
		}
	});
});


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2014 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.client;

import java.util.HashMap;
import java.util.Map;

import static com.google.appinventor.client.Ode.MESSAGES;

public class TranslationComponentProperty {

  public static String languageSetting;
  public static Map<String, String> myMap = map();

  public static enum Language {
    zh_CN, en_US
  }

  public static String getName(String key) {
    String value = myMap.get(key);
    if (key == null) {
      // This will help implementors debug if the forget to add an entry
      // when defining a new property
      return "**Missing key in TranslationComponentProperty**";
    } else {
      return value;
    }
  }

  /**
   * Get a translation map.
   *
   * The output map has the following format: Map = {propertyKey1:
   * {propertyKey1, propertyValue1}, ...}
   *
   * @return map
   */
  public static HashMap<String, String> map() {
    HashMap<String, String> map = new HashMap<String, String>();
    // Properties
    map.put("DirectMessages", MESSAGES.DirectMessagesProperties());
    map.put("ContactName", MESSAGES.ContactNameProperties());
    map.put("CurrentAddress", MESSAGES.CurrentAddressProperties());
    map.put("CurrentPageTitle", MESSAGES.CurrentPageTitleProperties());
    map.put("CurrentUrl", MESSAGES.CurrentUrlProperties());
    map.put("Accuracy", MESSAGES.AccuracyProperties());
    map.put("AddressesAndNames", MESSAGES.AddressesAndNamesProperties());
    map.put("Altitude", MESSAGES.AltitudeProperties());
    map.put("Angle", MESSAGES.AngleProperties());
    map.put("Animation", MESSAGES.AnimationProperties());
    map.put("Available", MESSAGES.AvailableProperties());
    map.put("AvailableCountries", MESSAGES.AvailableCountriesProperties());
    map.put("AvailableLanguages", MESSAGES.AvailableLanguagesProperties());
    map.put("AvailableProviders", MESSAGES.AvailableProvidersProperties());
    map.put("Azimuth", MESSAGES.AzimuthProperties());
    map.put("BallotOptions", MESSAGES.BallotOptionsProperties());
    map.put("BallotQuestion", MESSAGES.BallotQuestionProperties());
    map.put("EmailAddress", MESSAGES.EmailAddressProperties());
    map.put("EmailAddressList", MESSAGES.EmailAddressListProperties());
    map.put("Elements", MESSAGES.ElementsProperties());
    map.put("Followers", MESSAGES.FollowersProperties());
    map.put("FriendTimeline", MESSAGES.FriendTimelineProperties());
    map.put("FullScreen", MESSAGES.FullScreenProperties());
    map.put("HasAccuracy", MESSAGES.HasAccuracyProperties());
    map.put("HasAltitude", MESSAGES.HasAltitudeProperties());
    map.put("HasLongitudeLatitude", MESSAGES.HasLongitudeLatitudeProperties());
    map.put("Height", MESSAGES.HeightProperties());
    map.put("InstanceId", MESSAGES.InstanceIdProperties());
    map.put("InvitedInstances", MESSAGES.InvitedInstancesProperties());
    map.put("IsAccepting", MESSAGES.IsAcceptingProperties());
    map.put("IsConnected", MESSAGES.IsConnectedProperties());
    map.put("IsPlaying", MESSAGES.IsPlayingProperties());
    map.put("JoinedInstances", MESSAGES.JoinedInstancesProperties());
    map.put("Latitude", MESSAGES.LatitudeProperties());
    map.put("Leader", MESSAGES.LeaderProperties());
    map.put("Longitude", MESSAGES.LongitudeProperties());
    map.put("Magnitude", MESSAGES.MagnitudeProperties());
    map.put("Mentions", MESSAGES.MentionsProperties());
    map.put("ProviderLocked", MESSAGES.ProviderLockedProperties());
    map.put("ProviderName", MESSAGES.ProviderNameProperties());
    map.put("PublicInstances", MESSAGES.PublicInstancesProperties());
    map.put("PlayOnlyInForeground", MESSAGES.PlayOnlyInForegroundProperties());
    map.put("Players", MESSAGES.PlayersProperties());
    map.put("RequestHeaders", MESSAGES.RequestHeadersProperties());
    map.put("Result", MESSAGES.ResultProperties());
    map.put("UseExternalScanner", MESSAGES.UseExternalScannerProperties());
    map.put("ResultType", MESSAGES.ResultTypeProperties());
    map.put("ResultUri", MESSAGES.ResultUriProperties());
    map.put("Roll", MESSAGES.RollProperties());
    map.put("SearchResults", MESSAGES.SearchResultsProperties());
    map.put("ServiceUrl", MESSAGES.ServiceUrlProperties());
    map.put("SelectionIndex", MESSAGES.SelectionIndexProperties());
    map.put("UserChoice", MESSAGES.UserChoiceProperties());
    map.put("UserEmailAddress", MESSAGES.UserEmailAddressProperties());
    map.put("UserId", MESSAGES.UserIdProperties());
    map.put("Username", MESSAGES.UsernameProperties());
    map.put("XAccel", MESSAGES.XAccelProperties());
    map.put("YAccel", MESSAGES.YAccelProperties());
    map.put("ZAccel", MESSAGES.ZAccelProperties());
    map.put("Width", MESSAGES.WidthProperties());
    map.put("WebViewString", MESSAGES.WebViewStringProperties());
    map.put("AboveRangeEventEnabled", MESSAGES.AboveRangeEventEnabledProperties());
    map.put("Action", MESSAGES.ActionProperties());
    map.put("ActivityClass", MESSAGES.ActivityClassProperties());
    map.put("ActivityPackage", MESSAGES.ActivityPackageProperties());
    map.put("AlignHorizontal", MESSAGES.AlignHorizontalProperties());
    map.put("AlignVertical", MESSAGES.AlignVerticalProperties());
    map.put("AllowCookies", MESSAGES.AllowCookiesProperties());
    map.put("ApiKey", MESSAGES.ApiKeyProperties());
    map.put("BackgroundColor", MESSAGES.BackgroundColorProperties());
    map.put("BackgroundImage", MESSAGES.BackgroundImageProperties());
    map.put("BelowRangeEventEnabled", MESSAGES.BelowRangeEventEnabledProperties());
    map.put("BottomOfRange", MESSAGES.BottomOfRangeProperties());
    map.put("CharacterEncoding", MESSAGES.CharacterEncodingProperties());
    map.put("Checked", MESSAGES.CheckedProperties());
    map.put("ColorChangedEventEnabled", MESSAGES.ColorChangedEventEnabledProperties());
    map.put("Country", MESSAGES.CountryProperties());
    map.put("ConsumerKey", MESSAGES.ConsumerKeyProperties());
    map.put("ConsumerSecret", MESSAGES.ConsumerSecretProperties());
    map.put("DataType", MESSAGES.DataTypeProperties());
    map.put("DataUri", MESSAGES.DataUriProperties());
    map.put("DelimiterByte", MESSAGES.DelimiterByteProperties());
    map.put("DetectColor", MESSAGES.DetectColorProperties());
    map.put("DistanceInterval", MESSAGES.DistanceIntervalProperties());
    map.put("ElementsFromString", MESSAGES.ElementsFromStringProperties());
    map.put("Enabled", MESSAGES.EnabledProperties());
    map.put("ExtraKey", MESSAGES.ExtraKeyProperties());
    map.put("ExtraValue", MESSAGES.ExtraValueProperties());
    map.put("FollowLinks", MESSAGES.FollowLinksProperties());
    map.put("FontSize", MESSAGES.FontSizeProperties());
    map.put("GameId", MESSAGES.GameIdProperties());
    map.put("GenerateColor", MESSAGES.GenerateColorProperties());
    map.put("GenerateLight", MESSAGES.GenerateLightProperties());
    map.put("GoogleVoiceEnabled", MESSAGES.GoogleVoiceEnabledProperties());
    map.put("Heading", MESSAGES.HeadingProperties());
    map.put("HighByteFirst", MESSAGES.HighByteFirstProperties());
    map.put("Hint", MESSAGES.HintProperties());
    map.put("HomeUrl", MESSAGES.HomeUrlProperties());
    map.put("IgnoreSslErrors", MESSAGES.IgnoreSslErrorsProperties());
    map.put("Image", MESSAGES.ImageProperties());
    map.put("Interval", MESSAGES.IntervalProperties());
    map.put("Language", MESSAGES.LanguageProperties());
    map.put("LineWidth", MESSAGES.LineWidthProperties());
    map.put("IsLooping", MESSAGES.IsLoopingProperties());
    map.put("KeyFile", MESSAGES.KeyFileProperties());
    map.put("Message", MESSAGES.MessageProperties());
    map.put("MinimumInterval", MESSAGES.MinimumIntervalProperties());
    map.put("MultiLine", MESSAGES.MultiLineProperties());
    map.put("NumbersOnly", MESSAGES.NumbersOnlyProperties());
    map.put("PaintColor", MESSAGES.PaintColorProperties());
    map.put("PhoneNumber", MESSAGES.PhoneNumberProperties());
    map.put("PhoneNumberList", MESSAGES.PhoneNumberListProperties());
    map.put("Picture", MESSAGES.PictureProperties());
    map.put("Pitch", MESSAGES.PitchProperties());
    map.put("PressedEventEnabled", MESSAGES.PressedEventEnabledProperties());
    map.put("PromptforPermission", MESSAGES.PromptforPermissionProperties());
    map.put("Query", MESSAGES.QueryProperties());
    map.put("Radius", MESSAGES.RadiusProperties());
    map.put("ReceivingEnabled", MESSAGES.ReceivingEnabledProperties());
    map.put("ReleasedEventEnabled", MESSAGES.ReleasedEventEnabledProperties());
    map.put("ResponseFileName", MESSAGES.ResponseFileNameProperties());
    map.put("ResultName", MESSAGES.ResultNameProperties());
    map.put("Rotates", MESSAGES.RotatesProperties());
    map.put("SaveResponse", MESSAGES.SaveResponseProperties());
    map.put("SavedRecording", MESSAGES.SavedRecordingProperties());
    map.put("ScalePictureToFit", MESSAGES.ScalePictureToFitProperties());
    map.put("ScreenOrientation", MESSAGES.ScreenOrientationProperties());
    map.put("Scrollable", MESSAGES.ScrollableProperties());
    map.put("Secure", MESSAGES.SecureProperties());
    map.put("ServiceURL", MESSAGES.ServiceURLProperties());
    map.put("ServiceAccountEmail", MESSAGES.ServiceAccountEmailProperties());
    map.put("Selection", MESSAGES.SelectionProperties());
    map.put("Source", MESSAGES.SourceProperties());
    map.put("Speed", MESSAGES.SpeedProperties());
    map.put("StopBeforeDisconnect", MESSAGES.StopBeforeDisconnectProperties());
    map.put("Text", MESSAGES.TextProperties());
    map.put("TextAlignment", MESSAGES.TextAlignmentProperties());
    map.put("TextColor", MESSAGES.TextColorProperties());
    map.put("TimeInterval", MESSAGES.TimeIntervalProperties());
    map.put("TimerAlwaysFires", MESSAGES.TimerAlwaysFiresProperties());
    map.put("TimerEnabled", MESSAGES.TimerEnabledProperties());
    map.put("TimerInterval", MESSAGES.TimerIntervalProperties());
    map.put("Title", MESSAGES.TitleProperties());
    map.put("TopOfRange", MESSAGES.TopOfRangeProperties());
    map.put("Url", MESSAGES.UrlProperties());
    map.put("UseServiceAuthentication", MESSAGES.UseServiceAuthenticationProperties());
    map.put("Visible", MESSAGES.VisibleProperties());
    map.put("Volume", MESSAGES.VolumeProperties());
    map.put("WithinRangeEventEnabled", MESSAGES.WithinRangeEventEnabledProperties());
    map.put("X", MESSAGES.XProperties());
    map.put("Y", MESSAGES.YProperties());
    map.put("Z", MESSAGES.ZProperties());
    map.put("ShowFilterBar", MESSAGES.ShowFilterBarProperties());
    map.put("TextSize", MESSAGES.TextSizeProperties());
    map.put("NotifierLength", MESSAGES.NotifierLengthProperties());
    map.put("Loop", MESSAGES.LoopProperties());
    map.put("Pitch", MESSAGES.PitchProperties());
    map.put("SpeechRate", MESSAGES.SpeechRateProperties());
    map.put("Sensitivity", MESSAGES.SensitivityProperties());
    map.put("TwitPic_API_Key", MESSAGES.TwitPic_API_KeyProperties());
    map.put("Prompt", MESSAGES.PromptProperties());
    map.put("ColorLeft", MESSAGES.ColorLeftProperties());
    map.put("ColorRight", MESSAGES.ColorRightProperties());
    map.put("MaxValue", MESSAGES.MaxValueProperties());
    map.put("MinValue", MESSAGES.MinValueProperties());
    map.put("ThumbPosition", MESSAGES.ThumbPositionProperties());
    map.put("ThumbEnabled", MESSAGES.ThumbEnabled());
    map.put("FontBold", MESSAGES.FontBoldProperties());
    map.put("FontItalic", MESSAGES.FontItalicProperties());
    map.put("ShowFeedback", MESSAGES.ShowFeedbackProperties());
    map.put("UseFront", MESSAGES.UseFrontProperties());
    map.put("Day", MESSAGES.DayProperties());
    map.put("Month", MESSAGES.MonthProperties());
    map.put("MonthInText", MESSAGES.MonthInTextProperties());
    map.put("Year", MESSAGES.YearProperties());
    map.put("AboutScreen", MESSAGES.AboutScreenProperties());
    map.put("CloseScreenAnimation", MESSAGES.CloseScreenAnimationProperties());
    map.put("OpenScreenAnimation", MESSAGES.OpenScreenAnimationProperties());
    map.put("LastMessage", MESSAGES.LastMessageProperties());
    map.put("ReadMode", MESSAGES.ReadModeProperties());
    map.put("TextToWrite", MESSAGES.TextToWriteProperties());
    map.put("WriteType", MESSAGES.WriteTypeProperties());
    map.put("CalibrateStrideLength", MESSAGES.CalibrateStrideLengthProperties());
    map.put("Distance", MESSAGES.DistanceProperties());
    map.put("ElapsedTime", MESSAGES.ElapsedTimeProperties());
    map.put("Moving", MESSAGES.MovingProperties());
    map.put("StopDetectionTimeout", MESSAGES.StopDetectionTimeoutProperties());
    map.put("StrideLength", MESSAGES.StrideLengthProperties());
    map.put("UseGPS", MESSAGES.UseGPSProperties());
    map.put("Hour", MESSAGES.HourProperties());
    map.put("Minute", MESSAGES.MinuteProperties());
    map.put("HasMargins", MESSAGES.HasMarginsProperties());

    // =========== ProximitySensor
    map.put("MaximumRange", MESSAGES.MaximumRangeProperties());
    map.put("KeepRunningWhenOnPause", MESSAGES.KeepRunningWhenOnPauseProperties());
    map.put("ProximityChanged", MESSAGES.ProximityChangedPropertiesProperties());

    // ========== ListPicker
    map.put("ItemTextColor", MESSAGES.ItemTextColorProperties());
    map.put("ItemBackgroundColor", MESSAGES.ItemBackgroundColorProperties());

    return map;
  }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ShopBundle\Locale;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

final class UrlBasedLocaleSwitcher implements LocaleSwitcherInterface
{
    /** @var UrlGeneratorInterface */
    private $urlGenerator;

    public function __construct(UrlGeneratorInterface $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(Request $request, string $localeCode): RedirectResponse
    {
        return new RedirectResponse($this->urlGenerator->generate('sylius_shop_homepage', ['_locale' => $localeCode]));
    }
}