text:
package org.apache.tomcat.dbcp.pool.impl;

import org.apache.tomcat.dbcp.pool.BaseKeyedObjectPool;
import org.apache.tomcat.dbcp.pool.KeyedObjectPool;
import org.apache.tomcat.dbcp.pool.KeyedPoolableObjectFactory;
import org.apache.tomcat.dbcp.pool.PoolUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Stack;

/**
 * A simple, Stack-based KeyedObjectPool implementation.
 *

 * Given a {@link KeyedPoolableObjectFactory}, this class will maintain
 * a simple pool of instances.  A finite number of "sleeping"
 * or inactive instances is enforced, but when the pool is
 * empty, new instances are created to support the new load.
 * Hence this class places no limit on the number of "active"
 * instances created by the pool, but is quite useful for
 * re-using Objects without introducing
 * artificial limits.
 *

 *
 * @author Rodney Waldhoff
 * @author Sandy McArthur
 * @version $Revision: 990437 $ $Date: 2010-08-28 13:17:57 -0700 (Sat, 28 Aug 2010) $
 * @see Stack
 * @since Pool 1.0
 */
public class StackKeyedObjectPool extends BaseKeyedObjectPool implements KeyedObjectPool {
    /**
     * Create a new pool using no factory.
     * Clients must first set the {@link #setFactory factory} or
     * may populate the pool using {@link #returnObject returnObject}
     * before they can be {@link #borrowObject borrowed}.
     *
     * @see #StackKeyedObjectPool(KeyedPoolableObjectFactory)
     * @see #setFactory(KeyedPoolableObjectFactory)
     */
    public StackKeyedObjectPool() {
        this((KeyedPoolableObjectFactory)null,DEFAULT_MAX_SLEEPING,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * Create a new pool using no factory.
     * Clients must first set the {@link #setFactory factory} or
     * may populate the pool using {@link #returnObject returnObject}
     * before they can be {@link #borrowObject borrowed}.
     *
     * @param max cap on the number of "sleeping" instances in the pool
     * @see #StackKeyedObjectPool(KeyedPoolableObjectFactory, int)
     * @see #setFactory(KeyedPoolableObjectFactory)
     */
    public StackKeyedObjectPool(int max) {
        this((KeyedPoolableObjectFactory)null,max,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * Create a new pool using no factory.
     * Clients must first set the {@link #setFactory factory} or
     * may populate the pool using {@link #returnObject returnObject}
     * before they can be {@link #borrowObject borrowed}.
     *
     * @param max cap on the number of "sleeping" instances in the pool
     * @param init initial size of the pool (this specifies the size of the container,
     *             it does not cause the pool to be pre-populated.)
     * @see #StackKeyedObjectPool(KeyedPoolableObjectFactory, int, int)
     * @see #setFactory(KeyedPoolableObjectFactory)
     */
    public StackKeyedObjectPool(int max, int init) {
        this((KeyedPoolableObjectFactory)null,max,init);
    }

    /**
     * Create a new SimpleKeyedObjectPool using
     * the specified factory to create new instances.
     *
     * @param factory the {@link KeyedPoolableObjectFactory} used to populate the pool
     */
    public StackKeyedObjectPool(KeyedPoolableObjectFactory factory) {
        this(factory,DEFAULT_MAX_SLEEPING);
    }

    /**
     * Create a new SimpleKeyedObjectPool using
     * the specified factory to create new instances.
     * capping the number of "sleeping" instances to max
     *
     * @param factory the {@link KeyedPoolableObjectFactory} used to populate the pool
     * @param max cap on the number of "sleeping" instances in the pool
     */
    public StackKeyedObjectPool(KeyedPoolableObjectFactory factory, int max) {
        this(factory,max,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * Create a new SimpleKeyedObjectPool using
     * the specified factory to create new instances.
     * capping the number of "sleeping" instances to max,
     * and initially allocating a container capable of containing
     * at least init instances.
     *
     * @param factory the {@link KeyedPoolableObjectFactory} used to populate the pool
     * @param max cap on the number of "sleeping" instances in the pool
     * @param init initial size of the pool (this specifies the size of the container,
     *             it does not cause the pool to be pre-populated.)
     */
    public StackKeyedObjectPool(KeyedPoolableObjectFactory factory, int max, int init) {
        _factory = factory;
        _maxSleeping = (max < 0 ? DEFAULT_MAX_SLEEPING : max);
        _initSleepingCapacity = (init < 1 ? DEFAULT_INIT_SLEEPING_CAPACITY : init);
        _pools = new HashMap();
        _activeCount = new HashMap();
    }

    /**
     * Borrows an object with the given key.  If there are no idle instances under the
     * given key, a new one is created.
     *
     * @param key the pool key
     * @return keyed poolable object instance
     */
    public synchronized Object borrowObject(Object key) throws Exception {
        assertOpen();
        Stack stack = (Stack)(_pools.get(key));
        if(null == stack) {
            stack = new Stack();
            stack.ensureCapacity( _initSleepingCapacity > _maxSleeping ? _maxSleeping : _initSleepingCapacity);
            _pools.put(key,stack);
        }
        Object obj = null;
        do {
            boolean newlyMade = false;
            if (!stack.empty()) {
                obj = stack.pop();
                _totIdle--;
            } else {
                if(null == _factory) {
                    throw new NoSuchElementException("pools without a factory cannot create new objects as needed.");
                } else {
                    obj = _factory.makeObject(key);
                    newlyMade = true;
                }
            }
            if (null != _factory && null != obj) {
                try {
                    _factory.activateObject(key, obj);
                    if (!_factory.validateObject(key, obj)) {
                        throw new Exception("ValidateObject failed");
                    }
                } catch (Throwable t) {
                    PoolUtils.checkRethrow(t);
                    try {
                        _factory.destroyObject(key,obj);
                    } catch (Throwable t2) {
                        PoolUtils.checkRethrow(t2);
                        // swallowed
                    } finally {
                        obj = null;
                    }
                    if (newlyMade) {
                        throw new NoSuchElementException(
                            "Could not create a validated object, cause: " +
                            t.getMessage());
                    }
                }
            }
        } while (obj == null);
        incrementActiveCount(key);
        return obj;
    }

    /**
     * Returns obj to the pool under key.  If adding the
     * returning instance to the pool results in {@link #_maxSleeping maxSleeping}
     * exceeded for the given key, the oldest instance in the idle object pool
     * is destroyed to make room for the returning instance.
     *
     * @param key the pool key
     * @param obj returning instance
     */
    public synchronized void returnObject(Object key, Object obj) throws Exception {
        decrementActiveCount(key);
        if (null != _factory) {
            if (_factory.validateObject(key, obj)) {
                try {
                    _factory.passivateObject(key, obj);
                } catch (Exception ex) {
                    _factory.destroyObject(key, obj);
                    return;
                }
            } else {
                return;
            }
        }

        if (isClosed()) {
            if (null != _factory) {
                try {
                    _factory.destroyObject(key, obj);
                } catch (Exception e) {
                    // swallowed
                }
            }
            return;
        }

        Stack stack = (Stack)_pools.get(key);
        if(null == stack) {
            stack = new Stack();
            stack.ensureCapacity( _initSleepingCapacity > _maxSleeping ? _maxSleeping : _initSleepingCapacity);
            _pools.put(key,stack);
        }
        final int stackSize = stack.size();
        if (stackSize >= _maxSleeping) {
            final Object staleObj;
            if (stackSize > 0) {
                staleObj = stack.remove(0);
                _totIdle--;
            } else {
                staleObj = obj;
            }
            if(null != _factory) {
                try {
                    _factory.destroyObject(key, staleObj);
                } catch (Exception e) {
                    // swallowed
                }
            }
        }
        stack.push(obj);
        _totIdle++;
    }

    /**
     * {@inheritDoc}
     */
    public synchronized void invalidateObject(Object key, Object obj) throws Exception {
        decrementActiveCount(key);
        if(null != _factory) {
            _factory.destroyObject(key,obj);
        }
        notifyAll(); // _totalActive has changed
    }

    /**
     * Create an object using the {@link KeyedPoolableObjectFactory#makeObject factory},
     * passivate it, and then placed in the idle object pool.
     * addObject is useful for "pre-loading" a pool with idle objects.
     *
     * @param key the key a new instance should be added to
     * @throws Exception when {@link KeyedPoolableObjectFactory#makeObject} fails.
     * @throws IllegalStateException when no {@link #setFactory factory} has been set or after {@link #close} has been called on this pool.
     */
    public synchronized void addObject(Object key) throws Exception {
        assertOpen();
        if (_factory == null) {
            throw new IllegalStateException("Cannot add objects without a factory.");
        }
        Object obj = _factory.makeObject(key);
        try {
            if (!_factory.validateObject(key, obj)) {
               return;
            }
        } catch (Exception e) {
            try {
                _factory.destroyObject(key, obj);
            } catch (Exception e2) {
                // swallowed
            }
            return;
        }
        _factory.passivateObject(key, obj);

        Stack stack = (Stack)_pools.get(key);
        if(null == stack) {
            stack = new Stack();
            stack.ensureCapacity( _initSleepingCapacity > _maxSleeping ? _maxSleeping : _initSleepingCapacity);
            _pools.put(key,stack);
        }

        final int stackSize = stack.size();
        if (stackSize >= _maxSleeping) {
            final Object staleObj;
            if (stackSize > 0) {
                staleObj = stack.remove(0);
                _totIdle--;
            } else {
                staleObj = obj;
            }
            try {
                _factory.destroyObject(key, staleObj);
            } catch (Exception e) {
                // Don't swallow destroying the newly created object.
                if (obj == staleObj) {
                    throw e;
                }
            }
        } else {
            stack.push(obj);
            _totIdle++;
        }
    }

    /**
     * Returns the total number of instances currently idle in this pool.
     *
     * @return the total number of instances currently idle in this pool
     */
    public synchronized int getNumIdle() {
        return _totIdle;
    }

    /**
     * Returns the total number of instances current borrowed from this pool but not yet returned.
     *
     * @return the total number of instances currently borrowed from this pool
     */
    public synchronized int getNumActive() {
        return _totActive;
    }

    /**
     * Returns the number of instances currently borrowed from but not yet returned
     * to the pool corresponding to the given key.
     *
     * @param key the key to query
     * @return the number of instances corresponding to the given key currently borrowed in this pool
     */
    public synchronized int getNumActive(Object key) {
        return getActiveCount(key);
    }

    /**
     * Returns the number of instances corresponding to the given key currently idle in this pool.
     *
     * @param key the key to query
     * @return the number of instances corresponding to the given key currently idle in this pool
     */
    public synchronized int getNumIdle(Object key) {
        try {
            return((Stack)(_pools.get(key))).size();
        } catch(Exception e) {
            return 0;
        }
    }

    /**
     * Clears the pool, removing all pooled instances.
     */
    public synchronized void clear() {
        Iterator it = _pools.keySet().iterator();
        while(it.hasNext()) {
            Object key = it.next();
            Stack stack = (Stack)(_pools.get(key));
            destroyStack(key,stack);
        }
        _totIdle = 0;
        _pools.clear();
        _activeCount.clear();
    }

    /**
     * Clears the specified pool, removing all pooled instances corresponding to the given key.
     *
     * @param key the key to clear
     */
    public synchronized void clear(Object key) {
        Stack stack = (Stack)(_pools.remove(key));
        destroyStack(key,stack);
    }

    /**
     * Destroys all instances in the stack and clears the stack.
     *
     * @param key key passed to factory when destroying instances
     * @param stack stack to destroy
     */
    private synchronized void destroyStack(Object key, Stack stack) {
        if(null == stack) {
            return;
        } else {
            if(null != _factory) {
                Iterator it = stack.iterator();
                while(it.hasNext()) {
                    try {
                        _factory.destroyObject(key,it.next());
                    } catch(Exception e) {
                        // ignore error, keep destroying the rest
                    }
                }
            }
            _totIdle -= stack.size();
            _activeCount.remove(key);
            stack.clear();
        }
    }

    /**
     * Returns a string representation of this StackKeyedObjectPool, including
     * the number of pools, the keys and the size of each keyed pool.
     *
     * @return Keys and pool sizes
     */
    public synchronized String toString() {
        StringBuffer buf = new StringBuffer();
        buf.append(getClass().getName());
        buf.append(" contains ").append(_pools.size()).append(" distinct pools: ");
        Iterator it = _pools.keySet().iterator();
        while(it.hasNext()) {
            Object key = it.next();
            buf.append(" |").append(key).append("|=");
            Stack s = (Stack)(_pools.get(key));
            buf.append(s.size());
        }
        return buf.toString();
    }

    /**
     * Close this pool, and free any resources associated with it.
     *

     * Calling {@link #addObject addObject} or {@link #borrowObject borrowObject} after invoking
     * this method on a pool will cause them to throw an {@link IllegalStateException}.
     *

     *
     * @throws Exception deprecated: implementations should silently fail if not all resources can be freed.
     */
    public void close() throws Exception {
        super.close();
        clear();
    }

    /**
     * Sets the {@link KeyedPoolableObjectFactory factory} the pool uses
     * to create new instances.
     * Trying to change the factory after a pool has been used will frequently
     * throw an {@link UnsupportedOperationException}.
     *
     * @param factory the {@link KeyedPoolableObjectFactory} used to manage object instances
     * @throws IllegalStateException when the factory cannot be set at this time
     * @deprecated to be removed in pool 2.0
     */
    public synchronized void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException {
        if(0 < getNumActive()) {
            throw new IllegalStateException("Objects are already active");
        } else {
            clear();
            _factory = factory;
        }
    }

    /**
     * @return the {@link KeyedPoolableObjectFactory} used by this pool to manage object instances.
     * @since 1.5.5
     */
    public synchronized KeyedPoolableObjectFactory getFactory() {
        return _factory;
    }

    /**
     * Returns the active instance count for the given key.
     *
     * @param key pool key
     * @return active count
     */
    private int getActiveCount(Object key) {
        try {
            return ((Integer)_activeCount.get(key)).intValue();
        } catch(NoSuchElementException e) {
            return 0;
        } catch(NullPointerException e) {
            return 0;
        }
    }

    /**
     * Increment the active count for the given key. Also
     * increments the total active count.
     *
     * @param key pool key
     */
    private void incrementActiveCount(Object key) {
        _totActive++;
        Integer old = (Integer)(_activeCount.get(key));
        if(null == old) {
            _activeCount.put(key,new Integer(1));
        } else {
            _activeCount.put(key,new Integer(old.intValue() + 1));
        }
    }

    /**
     * Decrements the active count for the given key.
     * Also decrements the total active count.
     *
     * @param key pool key
     */
    private void decrementActiveCount(Object key) {
        _totActive--;
        Integer active = (Integer)(_activeCount.get(key));
        if(null == active) {
            // do nothing, either null or zero is OK
        } else if(active.intValue() <= 1) {
            _activeCount.remove(key);
        } else {
            _activeCount.put(key, new Integer(active.intValue() - 1));
        }
    }

    /**
     * @return map of keyed pools
     * @since 1.5.5
     */
    public Map getPools() {
        return _pools;
    }

    /**
     * @return the cap on the number of "sleeping" instances in each pool.
     * @since 1.5.5
     */
    public int getMaxSleeping() {
        return _maxSleeping;
    }

    /**
     * @return the initial capacity of each pool.
     * @since 1.5.5
     */
    public int getInitSleepingCapacity() {
        return _initSleepingCapacity;
    }

    /**
     * @return the _totActive
     */
    public int getTotActive() {
        return _totActive;
    }

    /**
     * @return the _totIdle
     */
    public int getTotIdle() {
        return _totIdle;
    }

    /**
     * @return the _activeCount
     * @since 1.5.5
     */
    public Map getActiveCount() {
        return _activeCount;
    }

    /** The default cap on the number of "sleeping" instances in the pool. */
    protected static final int DEFAULT_MAX_SLEEPING  = 8;

    /**
     * The default initial size of the pool
     * (this specifies the size of the container, it does not
     * cause the pool to be pre-populated.)
     */
    protected static final int DEFAULT_INIT_SLEEPING_CAPACITY = 4;

    /**
     *  My named-set of pools.
     *  @deprecated to be removed in pool 2.0.  Use {@link #getPools()}
     */
    protected HashMap _pools = null;

    /**
     * My {@link KeyedPoolableObjectFactory}.
     * @deprecated to be removed in pool 2.0.  Use {@link #getFactory()}
     */
    protected KeyedPoolableObjectFactory _factory = null;

    /**
     *  The cap on the number of "sleeping" instances in each pool.
     *  @deprecated to be removed in pool 2.0.  Use {@link #getMaxSleeping()}
     */
    protected int _maxSleeping = DEFAULT_MAX_SLEEPING;

    /**
     * The initial capacity of each pool.
     * @deprecated to be removed in pool 2.0.  Use {@link #getInitSleepingCapacity()}.
     */
    protected int _initSleepingCapacity = DEFAULT_INIT_SLEEPING_CAPACITY;

    /**
     * Total number of object borrowed and not yet returned for all pools.
     * @deprecated to be removed in pool 2.0.  Use {@link #getTotActive()}.
     */
    protected int _totActive = 0;

    /**
     * Total number of objects "sleeping" for all pools
     * @deprecated to be removed in pool 2.0.  Use {@link #getTotIdle()}.
     */
    protected int _totIdle = 0;

    /**
     * Number of active objects borrowed and not yet returned by pool
     * @deprecated to be removed in pool 2.0.  Use {@link #getActiveCount()}.
     */
    protected HashMap _activeCount = null;

}


text:
[![Bintray](https://img.shields.io/bintray/v/jshaptic/maven/js4j.svg?style=flat-square)](https://bintray.com/jshaptic/maven/js4j/_latestVersion)
[![Javadocs](https://www.javadoc.io/badge/com.github.jshaptic/js4j.svg?style=flat-square)](https://www.javadoc.io/doc/com.github.jshaptic/js4j)
[![Travis](https://img.shields.io/travis/jshaptic/js4j.svg?style=flat-square)](https://travis-ci.org/jshaptic/js4j)
[![Coveralls](https://img.shields.io/coveralls/jshaptic/js4j.svg?branch=master&style=flat-square)](https://coveralls.io/github/jshaptic/js4j?branch=master)
[![License](https://img.shields.io/github/license/jshaptic/js4j.svg?style=flat-square)](https://opensource.org/licenses/MIT)

Wrapper for Java classes, which emulates Javascript variables and its API. Also includes ported Lodash library.
Currently not all functions and features are implemented, but most used are here, check [API documentation](https://www.javadoc.io/doc/com.github.jshaptic/js4j)
for a full list of supported features.

## Why

Most probably a question just poped up in your head: Why the hell it's needed for?? Well, for example it can be used as a tool for a quick libraries porting from javascript to java.
Another use case is that it can be as a tool for quick prototyping, when you don't want to bother about types and things like that. Also it can be used as a JSON container
with handy methods. But to tell the truth it was created just 4fun.

## Usage

To declare new variables (or containers in js4j terms) **UniversalContainer** class should be used:
```java
// this line will produce undefined container, which is analogue of "var c = undefined;" in javascript;
UniversalContainer c = ContainerFactory.undefinedContainer(); // var c = undefined;
// this line will also produce undefined container, but will create new instance of it, which is not good, so it's better to use above aproach
UniversalContainer c = new UniversalContainer(); // var c = undefined;

// this will produce null container
UniversalContainer c = ContainerFactory.nullContainer(); // var c = null;

// this will produce liter container with number
UniversalContainer c = new UniversalContainer(69); // var c = 69;

// this will produce empty object container
UniversalContainer c = ContainerFactory.createObject(); // var c = {};
// to add values to the object following methods can be used
UniversalContainer c = ContainerFactory.createObject(0, "a", 1, "b", 2, "c"); // var c = {0: "a", 1: "b", 2: "c"};
UniversalContainer c = ContainerFactory.createObject().set(0, "a").set(1, "b").set(2, "c"); // var c = {}; c[0] = "a"; c[1] = "b"; c[2] = "c"

// this will produce empty array container
UniversalContainer c = ContainerFactory.createArray(); // var c = [];
// to add values to the array following methods can be used
UniversalContainer c = ContainerFactory.createArray("a", "b", "c"); // var c = ["a", "b", "c"];
UniversalContainer c = ContainerFactory.createArray().set(0, "a").set(1, "b").set(2, "c"); // var c = []; c[0] = "a"; c[1] = "b"; c[2] = "c"
```

To compare containers method **equals** can be used, it works like === in JS and used to compare containers with each other
or pretty much any other objects:
```java
ContainerFactory.undefinedContainer().equals(null) // => true
new UniversalContainer(69).equals(69) // => true
new UniversalContainer(false).equals(0) // => false
ContainerFactory.createArray().equals(ContainerFactory.createArray()) // => false
```

To check if container is positive in "if" condition method **test** can be used:
```java
ContainerFactory.undefinedContainer().test() == false // if (undefined) ...
ContainerFactory.nullContainer().test() == false // if (null) ...
new UniversalContainer(0).test() == false // if (0) ...
new UniversalContainer("").test() == false // if ("") ...
new UniversalContainer(10).test() == true // if (10) ...
new UniversalContainer("false").test() == true // if ("false") ...
ContainerFactory.createArray().test() == true // if ([]) ...
```

In most cases API usage is quite relaxed without any errors, since JS is a generous language, but sometimes even JS throwing runtime errors
and to reflect the same behaviour **ContainerException** class was introduced. For example it will be thrown during runtime in the following cases:
```java
ContainerFactory.undefinedContainer().get(0) // => Cannot get '0' property from Undefined container
new UniversalContainer("abcde").pop() // => Method 'pop' is not available for String container
```

For all other methods and use cases please consult [javadoc](https://www.javadoc.io/doc/com.github.jshaptic/js4j).

## Backlog

* Implement all missing methods for boolean, number, string, object and array containers
* Implement infinity, nan, date
* Implement simple mathematical operations
* Implement more functions from Lodash library
* Implement own JSON parser or at least integrate any suitable open-source parser
* Make object constructors much more complex and useful
* Refactor value storage mechanism, currently it's implemented with Map, uses to much memory and can be slow

redpajama_set_name: RedPajamaGithub


text:
import urllib2
import time
import sys
import os
import Queue
import datetime
import glob
import getopt
from xml.dom import minidom
from fluent import sender
from fluent import event
from pprint import pprint as pprint

common_path = "../common/"
sys.path.append(common_path)
import TruliaConfLoader
import DatabaseManager
import wrappers
import DataParser

def usage():

    print "python TruliaDataFetcher.py -l <geo location to load>"
    print "python TruliaDataFetcher.py -f <geo location to fetch>"
    print "geo locations are c,s,z,o for city, state, zipcode, county respectively"
    print "For example:"
    print "python TruliaDataFetcher.py -l cszo -f z"
    print "will read cities, states, zipcodes, and counties"
    print "and fetch even more recent data for zipcodes"
    print ""
    print "To actually load things parsed into a kv-store, you must pass the -k option"
    print "with the specified type of store (Redis or HBase) "
    print "-k r for Redis"
    print "-k h for Hbase"
    print ""
    print "To send parsed output to fluentd, you must pass the -d option"
    print "with the type of filesystem sent to (this host filesystem or hdfs)"
    print "-d f for this filesystem"
    print "-d h for the hdfs filesystem"
    print ""
    print "-d is equivalent to --fluentd"
    print "-k is equivalent to --kv-store"
    print "-f is equivalent to --fetch"
    print "-l is equivalent to --load"
    sys.exit(1)

def parse_args(argv):

    fetch_geo_types = ""
    load_geo_types = ""
    kv_store = ""
    fluentd_rx = ""
    try:
        opts, args = getopt.getopt(argv,"d:k:f:l:h",["fluentd=","kv-store=","fetch=","load=","help"])
    except getopt.GetoptError:
        usage()

    for opt, arg in opts:

        if opt in ("-h","--help"):
            usage()
        elif opt in ("-d","--fluentd"):
            fluentd_rx = arg.lower()
        elif opt in ("-k","--kv-store"):
            kv_store = arg.lower()
        elif opt in ("-f","--fetch"):
            fetch_geo_types = arg
        elif opt in ("-l","--load"):
            load_geo_types = arg
        else:
            print "bad argument"
            usage()

    return [fetch_geo_types, load_geo_types, kv_store, fluentd_rx]

class TruliaDataFetcher:
    def __init__(self, config_path, cla_dict):
        trulia_conf = TruliaConfLoader.TruliaConfLoader(config_path)
        self.load_trulia_params(trulia_conf)
        self.db_mgr = DatabaseManager.DatabaseManager(config_path)

        kv_store = cla_dict['kv_store']
        if kv_store == '':
            self.kv_mgr = None
        elif kv_store == 'h':
            print "loading HBase manager",
            import HBaseManager
            self.kv_mgr = HBaseManager.HBaseManager()
            print "completed"
        elif kv_store == 'r':
            print "loading Redis manager",
            import RedisManager
            self.kv_mgr = RedisManager.RedisManager()
            print "completed"

        fluentd_rx = cla_dict['fluentd_rx']
        if fluentd_rx == '':
            self.fluentd_enabled = False
            print "FluentD not enabled"
        elif fluentd_rx == 'f':
            print "loading fluentd for local fs"
            sender.setup('fs')
            self.fluentd_enabled = True
            print "FluentD enabled for local filesystem"
        elif fluentd_rx == 'h':
            print "loading fluentd for hdfs"
            sender.setup('hdfs')
            self.fluentd_enabled = True
            print "FluentD enabled for HDFS"

    def load_trulia_params(self, trulia_conf):
        self.stats_library = trulia_conf.stats_library
        self.location_library = trulia_conf.location_library
        self.stats_functions_params = trulia_conf.stats_functions_params
        self.stats_functions = trulia_conf.stats_functions
        self.location_functions_params = trulia_conf.location_functions_params
        self.location_functions = trulia_conf.location_functions
        self.url = trulia_conf.url
        self.apikeys = trulia_conf.apikeys
        self.curr_key_idx = 0
        self.data_dir = trulia_conf.data_dir

    def load_all_states_from_xml_archive(self):
        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_state", "state_code")
        for state_code_tuple in list(res):
            state_code = state_code_tuple[0]
            print "loading state from archive:",state_code
            self.read_already_fetched_files("state",{"state_code":state_code})

    def load_all_zipcodes_from_xml_archive(self):
        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_zipcode", "zipcode")
        for zipcode_tuple in list(res):
            zipcode = zipcode_tuple[0]
            zipcode = str(100000 + zipcode)[1:]
            print "loading zipcode from archive:",zipcode
            self.read_already_fetched_files("zipcode",{"zipcode":zipcode})

    def load_all_cities_from_xml_archive(self):
        state_tuples = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_state", "state_code")
        for state_code_tuple in list(state_tuples):
            state_code = state_code_tuple[0]
            city_tuples = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_city", "city", "state_code = '" + state_code + "'")
            for city_tuple in list(city_tuples):
                city = city_tuple[0]
                print "loading city from archive:", city, ",", state_code
                self.read_already_fetched_files("city",{"state_code":state_code, "city":city})

    def load_all_counties_from_xml_archive(self):
        state_tuples = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_state", "state_code")
        for state_code_tuple in list(state_tuples):
            state_code = state_code_tuple[0]
            county_tuples = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_county", "county", "state_code = '" + state_code + "'")
            for county_tuple in list(county_tuples):
                county = county_tuple[0]
                print "loading county from archive:", county, ",", state_code
                self.read_already_fetched_files("county",{"state_code":state_code, "county":county})

    def fetch_all_states_data(self):

        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_state", "state_code")

        for state_code_tuple in list(res):
            state_code = state_code_tuple[0]
            geo_type = "state"
            geo_dict = {"state_code":state_code}

            if self.fetch(geo_type, geo_dict, DataParser.parse_get_state_stats_resp):
                time.sleep(2.0/len(self.apikeys)) # trulia api restriction

    def fetch_all_cities_all_states_data(self):

        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_state", "state_code")
        for state_code_tuple in list(res):

            state_code = state_code_tuple[0]
            self.fetch_all_cities_in_state_data(state_code)

    def fetch_all_cities_in_state_data(self, state_code):

        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_city", "city", "state_code = '" + state_code + "'")
        for city_tuple in list(res):

            city = city_tuple[0]
            geo_type = "city"
            geo_dict = {"city":city, "state_code":state_code}

            if self.fetch(geo_type, geo_dict, DataParser.parse_get_city_stats_resp):
                time.sleep(2.0/len(self.apikeys)) # trulia api restriction

    def fetch_all_counties_all_states_data(self):

        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_state", "state_code")
        for state_code_tuple in list(res):
            state_code = state_code_tuple[0]
            print "Fetching counties in ", state_code
            self.fetch_all_counties_in_state_data(state_code)

    def fetch_all_counties_in_state_data(self, state_code):

        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_county", "county", "state_code = '" + state_code + "'")
        for county_tuple in list(res):

            county = county_tuple[0]
            geo_type = "county"
            geo_dict = {"county": county, "state_code": state_code}

            if self.fetch(geo_type, geo_dict, DataParser.parse_get_county_stats_resp):
                time.sleep(2.0/len(self.apikeys)) # trulia api restriction

    def fetch_all_zipcodes_data(self):

        # distinct needed since some zipcodes span multiple states (as reported by Trulia)
        res = self.db_mgr.simple_select_query(self.db_mgr.conn, "info_zipcode", "distinct zipcode")
        for zipcode_tuple in list(res):

            zipcode = str(100000 + zipcode_tuple[0])[1:]
            geo_type = "zipcode"
            geo_dict = {"zipcode":zipcode}

            if self.fetch(geo_type, geo_dict, DataParser.parse_get_zipcode_stats_resp):
                time.sleep(2.0/len(self.apikeys)) # trulia api restriction

    def fetch(self, geo_type, geo_dict, parser_func):

        print "fetching", geo_type, geo_dict
        if self.is_most_recent_api_call_today(geo_type, geo_dict):
            return False  # Notify caller that we did not hit Trulia's API

        latest_rx_date, now_date = self.get_api_call_date_range(geo_type, geo_dict)
        print latest_rx_date, now_date
        url_str = self.form_url(geo_type, geo_dict, latest_rx_date, now_date)
        text = self.fetch_executor(url_str)
        if text is None:
            return False

        self.save_xml_file(text, geo_type, geo_dict)
        json_doc = self.parse_executor(parser_func, text)
        self.write_executor(json_doc, geo_type, geo_dict)
        return True

    def get_latest_list_stat_date(self, obj_type, obj_key_dict):
        table_str = "data_" + obj_type
        where_str = ""
        for k in obj_key_dict:
            where_str += k + " = '" + str(obj_key_dict[k]) + "' and "
        where_str = where_str[:-4]
        print where_str
        res = self.db_mgr.simple_select_query(self.db_mgr.conn, table_str, "most_recent_week", where_str)
        if len(res) == 0:
            latest_ls_date = "2000-01-01"
        else:
            latest_ls_date = str(res[0][0])
        return latest_ls_date

    def get_latest_api_call_date(self, obj_type, obj_key_dict):
        table_str = "data_" + obj_type
        where_str = ""
        for k in obj_key_dict:
            where_str += k + " = '" + str(obj_key_dict[k]) + "' and "
        where_str = where_str[:-4]
        res = self.db_mgr.simple_select_query(self.db_mgr.conn, table_str, "date_fetched", where_str)
        if res is None or len(res) == 0:
            latest_ac_date = "2000-01-01"
        else:
            latest_ac_date = datetime.datetime.strftime(res[0][0], '%Y-%m-%d')

        return latest_ac_date

    def form_url(self, geo_type, geo_dict, latest_rx_date, now_date):

        url_str = self.url + "library=" + self.stats_library + "&function="

        if geo_type == 'state':
            url_str += "getStateStats&state=" + geo_dict['state_code']

        if geo_type == 'zipcode':
            url_str += "getZipCodeStats&zipCode=" + geo_dict['zipcode']

        elif geo_type == 'county':
            county_spaced = '%20'.join(geo_dict['county'].split(' '))
            url_str += "getCountyStats&county=" + county_spaced + "&state=" + geo_dict['state_code']
        elif geo_type == 'city':
            city_spaced = '%20'.join(geo_dict['city'].split(' '))
            url_str += "getCityStats&city=" + city_spaced + "&state=" + geo_dict['state_code']

        url_str += "&startDate=" + latest_rx_date + "&endDate=" + now_date + "&statType=listings" + "&apikey=" + self.apikeys[self.curr_key_idx]
        self.curr_key_idx = (self.curr_key_idx + 1) % len(self.apikeys)

        return url_str

    def get_api_call_date_range(self, geo_type, geo_dict):

        latest_rx_date = self.get_latest_list_stat_date(geo_type, geo_dict)
        now_date = TruliaDataFetcher.get_current_date()
        print "Calling API from", latest_rx_date, "to", now_date
        return latest_rx_date, now_date

    def is_most_recent_api_call_today(self, geo_type, geo_dict):

        last_api_call_date = self.get_latest_api_call_date(geo_type, geo_dict)
        now_date = TruliaDataFetcher.get_current_date()
        if now_date == last_api_call_date:
            print " already fetched data today"
            return True
        else:
            return False

    def write_executor(self, json_doc, geo_type, geo_dict):

        if json_doc is None:
            return

        metadata_table = "data_" + geo_type
        if geo_type == "city":
            metadata_key_list = ["state_code = '" + geo_dict['state_code'] + "'", "city = '" + geo_dict['city'] + "'"]
        elif geo_type == "county":
            metadata_key_list = ["state_code = '" + geo_dict['state_code'] + "'", "county = '" + geo_dict['county'] + "'"]
        elif geo_type == "state":
            metadata_key_list = ["state_code = '" + geo_dict['state_code'] + "'"]
        elif geo_type == "zipcode":
            metadata_key_list = ["zipcode = '" + geo_dict['zipcode'] + "'"]

        # send to FluentD
        if self.fluentd_enabled:
            self.send_json_doc_records_to_fluentd(geo_type + '.all_listing_stats', json_doc)

        # send to kv store
        if self.kv_mgr is not None:
            self.kv_mgr.insert_json_doc_records(json_doc)

        # update meta-store
        most_recent_week = json_doc['most_recent_week']
        date_fetched = json_doc['date_fetched']

        self.db_mgr.establish_timestamp_and_most_recent_week(self.db_mgr.conn, metadata_table, most_recent_week, date_fetched, metadata_key_list)

    # short function, may expand to threads or generator design pattern
    def parse_executor(self, parse_func, text):
        json_doc = parse_func(text)
        if json_doc is not None:
            json_doc['date_fetched'] = datetime.datetime.now().strftime('%Y-%m-%d')
            return json_doc
        else:
            return None

    def fetch_executor(self, url_str):

        try:
            resp = urllib2.urlopen(url_str)
            if resp.code == 200:
                return resp.read()
            else: # simple retry
                time.sleep(5)
                resp = urllib2.urlopen(url_str)
                if resp.code == 200:
                    return resp.read()
        except:
            # TODO log error
            print "Error fetching", url_str

        return None

    def read_already_fetched_files(self, geo_type, geo_dict):

        if geo_type == "state":
            state_code = geo_dict['state_code']
            file_list = glob.glob(self.data_dir + '/state/'+ state_code + '/*/' + state_code + '.xml')
            parser_func = DataParser.parse_get_state_stats_resp

        elif geo_type == "zipcode":
            zipcode = geo_dict['zipcode']
            file_list = glob.glob(self.data_dir + '/zipcode/'+ zipcode + '/*/' + zipcode + '.xml')
            parser_func = DataParser.parse_get_zipcode_stats_resp

        elif geo_type == "county":
            state_code = geo_dict['state_code']
            county = geo_dict['county']
            county_ = '_'.join(county.split(' '))
            file_list = glob.glob(self.data_dir + '/county/' + state_code + '/' + county_ + '/*/' + county_ + '.xml')

            parser_func = DataParser.parse_get_county_stats_resp

        elif geo_type == "city":
            state_code = geo_dict['state_code']
            city = geo_dict['city']
            city_ = '_'.join(city.split(' '))
            file_list = glob.glob(self.data_dir + '/city/' + state_code + '/' + city_ + '/*/' + city_ + '.xml')

            parser_func = DataParser.parse_get_city_stats_resp

        for file_ in file_list:
            with open(file_, 'r') as stream:

                text = stream.read()
                json_doc = self.parse_executor(parser_func, text)
                if json_doc is None:
                    return

                # overwrite what the parser wrote
                json_doc['date_fetched'] = file_.split('/')[-2]

                print 'read data up to', json_doc['most_recent_week'],
                print ', fetched on', json_doc['date_fetched']

                self.write_executor(json_doc, geo_type, geo_dict)

    def save_xml_file(self, text, geo_type, geo_dict):

        now_date = TruliaDataFetcher.get_current_date()
        dest_dir = self.data_dir + '/' + geo_type + '/'

        if geo_type != 'zipcode':
            dest_dir += geo_dict['state_code'] + '/'

        # unfortunate 1-offs
        if geo_type == 'state':
            filename = geo_dict['state_code'] + '.xml'
        else:
            geo_spaced = '_'.join(geo_dict[geo_type].split(' '))
            dest_dir += geo_spaced + '/'
            filename = geo_spaced + '.xml'

        dest_dir += now_date

        try:
            os.makedirs(dest_dir)
        except OSError:
            pass # already exists, ignore

        with open(dest_dir + "/" + filename, 'w') as stream:
            stream.write(str(text))

    def send_json_doc_records_to_fluentd(self, match_rule, json_doc):

        metadata_keys = json_doc.keys()
        metadata_keys.remove('stats')

        metadata_dict = {}
        for key in metadata_keys:
            metadata_dict[key] = json_doc[key]

        for k_bed in json_doc['stats']:
            for week in json_doc['stats'][k_bed]:
                rec = dict(metadata_dict)
                rec['num_beds'] = k_bed
                rec['week_ending_date'] = week
                rec['avg_list'] = json_doc['stats'][k_bed][week]['a']
                rec['num_list'] = json_doc['stats'][k_bed][week]['n']
                event.Event(match_rule, rec)

    @staticmethod
    def get_current_date():
        return time.strftime("%Y-%m-%d")

    @staticmethod
    def is_str_positive_int(k_bed):
        try:
            k = int(k_bed)
            if k < 0:
                return False
        except:
                return False

        return True

def fetch(tdf, fetch_geo_items):

    print "fetching items", fetch_geo_items
    if 's' in fetch_geo_items:
        tdf.fetch_all_states_data()
    if 'o' in fetch_geo_items:
        tdf.fetch_all_counties_all_states_data()
    if 'c' in fetch_geo_items:
        tdf.fetch_all_cities_all_states_data()
    if 'z' in fetch_geo_items:
        tdf.fetch_all_zipcodes_data()

def load(tdf, load_geo_items):

    print "loading items", load_geo_items
    if 's' in load_geo_items:
        tdf.load_all_states_from_xml_archive()
    if 'o' in load_geo_items:
        tdf.load_all_counties_from_xml_archive()
    if 'c' in load_geo_items:
        tdf.load_all_cities_from_xml_archive()
    if 'z' in load_geo_items:
        tdf.load_all_zipcodes_from_xml_archive()

def main(argv):

    [fetch_geo_items, load_geo_items, kv_store, fluentd_rx] = parse_args(argv)

    if fetch_geo_items == "" and load_geo_items == "":
        usage()

    params_dict = {"kv_store":kv_store, "fluentd_rx":fluentd_rx}

    tdf = TruliaDataFetcher('../conf/', params_dict)

    if len(load_geo_items) > 0:
        load(tdf, load_geo_items)

    if len(fetch_geo_items) > 0:
        fetch(tdf, fetch_geo_items)

# program
if __name__ == "__main__":
    main(sys.argv[1:])


text:
#ifndef __91x_type_H
#define __91x_type_H

  typedef long long                u64;
  typedef unsigned long            u32;
  typedef unsigned short           u16;
  typedef unsigned char            u8;

  typedef signed long              s32;
  typedef signed short             s16;
  typedef signed char              s8;

  typedef volatile unsigned long   vu32;
  typedef volatile unsigned short  vu16;
  typedef volatile unsigned char   vu8;

  typedef volatile signed long     vs32;
  typedef volatile signed short    vs16;
  typedef volatile signed char     vs8;

typedef enum { FALSE = 0, TRUE  = !FALSE } bool;

typedef enum { RESET = 0, SET   = !RESET } FlagStatus, ITStatus;

typedef enum { DISABLE = 0, ENABLE  = !DISABLE} FunctionalState;

typedef enum { ERROR = 0, SUCCESS  = !ERROR} ErrorStatus;

#endif /* __91x_type_H */

/******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/


text:
import sys

package_name = 'Theme - Glacier'

def plugin_loaded():
    from package_control import events

    if events.install(package_name):
        print('Installed %s' % events.install(package_name))
    elif events.post_upgrade(package_name):
        print('Upgraded to %s' % events.post_upgrade(package_name))

def plugin_unloaded():
    from package_control import events

    if events.pre_upgrade(package_name):
        print('Upgrading from %s' % events.pre_upgrade(package_name))
    elif events.remove(package_name):
        print('Removing %s' % events.remove(package_name))

# Compat with ST2
if sys.version_info < (3,):
    plugin_loaded()
    unload_handler = plugin_unloaded


text:
package openmods.utils.bitstream;

import java.io.IOException;
import openmods.utils.io.IByteSource;

public class InputBitStream extends InputBitStreamBase {

	private int byteCounter;

	private final IByteSource source;

	public InputBitStream(IByteSource source) {
		super(0x80);
		this.source = source;
	}

	@Override
	protected int nextByte() throws IOException {
		final int nextByte = source.nextByte();
		byteCounter++;
		return nextByte;
	}

	@Override
	public int bytesRead() {
		return byteCounter;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~
  -->

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:paddingBottom="64dp"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="64dp"
    android:fitsSystemWindows="true"
    tools:context="com.trackandtalk.pafos17.ui.feedback.FeedbackActivity">

    <include layout="@layout/feedback_layout"/>

</FrameLayout>


text:
require 'spec_helper'

describe Language do
  it { should validate_presence_of(:name) }
  it { should validate_presence_of(:locale) }
  it { should validate_uniqueness_of(:locale) }

  it 'is valid' do
    language = FactoryGirl.build(:language)
    expect(language).to be_valid
  end

  it 'is saved' do
    language = FactoryGirl.create(:language)
    expect(language).to be_persisted
  end

  it 'gets available locales' do
    FactoryGirl.create(:default_language)
    expect(Language.available_locales).to eq ['en']
  end

  # Included from has_default behavior
  context 'when saving language to default' do
    it 'sets existing languages default to false' do
      default_language = FactoryGirl.create(:old_default_language)
      FactoryGirl.create(:default_language)

      default_language.reload
      expect(default_language.default).to be false
    end

    it 'sets language default to true' do
      language = FactoryGirl.create(:default_language)
      expect(language.default).to be true
    end
  end

  context 'when updating default language as not default' do
    it 'fallbacks' do
      language = FactoryGirl.create(:default_language)
      language.default = false
      language.save
      expect(language.default).to be true
    end
  end

  context 'when destroying default language' do
    it 'must not be destroy' do
      language = FactoryGirl.create(:default_language)
      language.destroy
      expect(language).to be_persisted
    end
  end
end


text:
import React from 'react';
import R from 'ramda';
import PropTypes from 'prop-types';
import Button from 'material-ui/Button';
import Typography from 'material-ui/Typography';
import { connect } from 'react-redux';
import { selectCfeiReviewSummary, cfeiHasRecommendedPartner, isSendForDecision, isCfeiCompleted } from '../../../store';
import withDialogHandling from '../../common/hoc/withDialogHandling';
import SendCfeiForDecisionModal from '../modals/sendCfeiForDecision/sendCfeiForDecisionModal';
import ButtonWithTooltip from '../../common/buttonWithTooltipEnabled';

const messages = {
  text: 'Send for decision',
  addRecommendedPartner: 'Recommend partner before sending recommendation',
  addSummary: 'Review summary needs to be filled in before forwarding for partner selection.',
  send: 'Recommendation sent',
};

const SendForDecisionButton = (props) => {
  const { id, handleDialogClose, handleDialogOpen, dialogOpen, hasRecommendedPartner,
    summary, isSend, isCompleted } = props;
  const tooltip = !hasRecommendedPartner && messages.addRecommendedPartner
    || R.isEmpty(summary.review_summary_comment) && messages.addSummary;

  return (
    <div>
      {!isCompleted && ((!hasRecommendedPartner || R.isEmpty(summary.review_summary_comment)) ?
        <ButtonWithTooltip
          name="send"
          disabled
          text={messages.text}
          tooltipText={tooltip}
          onClick={handleDialogOpen}
        />
        : <Button
          id={id}
          raised
          color="accent"
          disabled={isSend}
          onTouchTap={handleDialogOpen}
        >
          {isSend ? messages.send : messages.text}
        </Button>)}
      <SendCfeiForDecisionModal
        id={id}
        dialogOpen={dialogOpen}
        handleDialogClose={handleDialogClose}
      />
    </div>
  );
};

SendForDecisionButton.propTypes = {
  id: PropTypes.number,
  dialogOpen: PropTypes.bool,
  handleDialogClose: PropTypes.func,
  handleDialogOpen: PropTypes.func,
  hasRecommendedPartner: PropTypes.bool,
  summary: PropTypes.object,
  isSend: PropTypes.bool,
  isCompleted: PropTypes.bool,
};

const mapStateToProps = (state, ownProps) => ({
  summary: selectCfeiReviewSummary(state, ownProps.id),
  hasRecommendedPartner: cfeiHasRecommendedPartner(state, ownProps.id),
  isSend: isSendForDecision(state, ownProps.id),
  isCompleted: isCfeiCompleted(state, ownProps.id),
});

const connected = connect(mapStateToProps)(SendForDecisionButton);

export default withDialogHandling(connected);


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.9.1: http://docutils.sourceforge.net/" />
<title>Magick::Montage Class</title>
<link rel="stylesheet" href="../docutils-articles.css" type="text/css" />

GraphicsMagick
<form action="http://www.google.com/search">
	<input type="hidden" name="domains" value="www.graphicsmagick.org" />
	<input type="hidden" name="sitesearch" value="www.graphicsmagick.org" />
    <input type="text" name="q" size="25" maxlength="255" /> <input type="submit" name="sa" value="Search" />
</form>

Home

Project

Download

Install

Source

News

Utilities

Programming

Reference

Magick::Montage Class

A montage is a single image which is composed of thumbnail images
composed in a uniform grid. The size of the montage image is
determined by the size of the individual thumbnails and the number of
rows and columns in the grid.

The following illustration shows a montage consisting of three columns
and two rows of thumbnails rendered on a gray background:

Montages may be either "plain" (undecorated thumbnails) or "framed"
(decorated thumbnails). In order to more easily understand the options
supplied to MontageImages(), montage options are supplied by two
different classes: Magick::Montage and Magick::MontageFramed.

Plain Montages

Magick::Montage is the base class to provide montage options and
provides methods to set all options required to render simple
(unframed) montages. See Magick::MontageFramedif you would like to
create a framed montage.

Unframed thumbnails consist of four components: the thumbnail image,
the thumbnail border, an optional thumbnail shadow, and an optional
thumbnail label area.

The following is the definition of the Magick::Montage class:

class Montage
{
public:
  Montage( void );
  virtual ~Montage( void );

  // Specifies the background color that thumbnails are imaged upon.
  void              backgroundColor ( const Color &backgroundColor_ );
  Color             backgroundColor ( void ) const;

  // Specifies the image composition algorithm for thumbnails. This
  // controls the algorithm by which the thumbnail image is placed
  // on the background. Use of OverCompositeOp is recommended for
  // use with images that have transparency. This option may have
  // negative side-effects for images without transparency.
  void              compose ( CompositeOperator compose_ );
  CompositeOperator compose ( void ) const;

  // Specifies the image filename to be used for the generated
  // montage images. To handle the case were multiple montage images
  // are generated, a printf-style format may be embedded within the
  // filename. For example, a filename specification of
  // image%02d.miff names the montage images as image00.miff,
  // image01.miff, etc.
  void              fileName( const std::string &fileName_ );
  std::string       fileName( void ) const;

  // Specifies the fill color to use for the label text.
  void              fillColor ( const Color &fill_ );
  Color             fillColor ( void ) const;

  // Specifies the thumbnail label font.
  void              font ( const std::string &font_ );
  std::string       font ( void ) const;

  // Specifies the size of the generated thumbnail.
  void              geometry ( const Geometry &geometry_ );
  Geometry          geometry ( void ) const;

  // Specifies the thumbnail positioning within the specified
  // geometry area. If the thumbnail is smaller in any dimension
  // than the geometry, then it is placed according to this
  // specification
  void              gravity ( GravityType gravity_ );
  GravityType       gravity ( void ) const;

  // Specifies the format used for the image label. Special format
  // characters may be embedded in the format string to include
  // information about the image.
  void              label( const std::string &label_ );
  std::string       label( void ) const;

  // Specifies the pen color to use for the label text (same as fill).
  void              penColor ( const Color &pen_ );
  Color             penColor ( void ) const;

  // Specifies the thumbnail label font size.
  void              pointSize ( unsigned int pointSize_ );
  unsigned int      pointSize ( void ) const;

  // Enable/disable drop-shadow on thumbnails.
  void              shadow ( bool shadow_ );
  bool              shadow ( void ) const;

  // Specifies the stroke color to use for the label text .
  void              strokeColor ( const Color &stroke_ );
  Color             strokeColor ( void ) const;

  // Specifies a texture image to use as montage background. The
  // built-in textures "granite:" and "plasma:" are available. A
  // texture is the same as a background image.
  void              texture ( const std::string &texture_ );
  std::string       texture ( void ) const;

  // Specifies the maximum number of montage columns and rows in the
  // montage. The montage is built by filling out all cells in a row
  // before advancing to the next row. Once the montage has reached
  // the maximum number of columns and rows, a new montage image is
  // started.
  void              tile ( const Geometry &tile_ );
  Geometry          tile ( void ) const;

  // Specifies the montage title
  void              title ( const std::string &title_ );
  std::string       title ( void ) const;

  // Specifies a montage color to set transparent. This option can
  // be set the same as the background color in order for the
  // thumbnails to appear without a background when rendered on an
  // HTML page. For best effect, ensure that the transparent color
  // selected does not occur in the rendered thumbnail colors.
  void              transparentColor ( const Color &transparentColor_ );
  Color             transparentColor ( void ) const;

};

Framed Montages

Magick::MontageFramed provides the means to specify montage options
when it is desired to have decorative frames around the image
thumbnails. MontageFramed inherits from Montage and therefore provides
all the methods of Montage as well as those shown in the table
"MontageFramed Methods".

Framed thumbnails consist of four components: the thumbnail image, the
thumbnail frame, the thumbnail border, an optional thumbnail shadow,
and an optional thumbnail label area.

The following is the definition of the Magick::MontageFramed class:

class MontageFramed : public Montage
{
public:
  MontageFramed ( void );
  /* virtual */ ~MontageFramed ( void );

  // Specifies the background color within the thumbnail frame.
  void           borderColor ( const Color &borderColor_ );
  Color          borderColor ( void ) const;

  // Specifies the border (in pixels) to place between a thumbnail
  // and its surrounding frame. This option only takes effect if
  // thumbnail frames are enabled (via frameGeometry) and the
  // thumbnail geometry specification doesn't also specify the
  // thumbnail border width.
  void           borderWidth ( unsigned int borderWidth_ );
  unsigned int   borderWidth ( void ) const;

  // Specifies the geometry specification for frame to place around
  // thumbnail. If this parameter is not specified, then the montage
  // is unframed.
  void           frameGeometry ( const Geometry &frame_ );
  Geometry       frameGeometry ( void ) const;

  // Specifies the thumbnail frame color.
  void           matteColor ( const Color &matteColor_ );
  Color          matteColor ( void ) const;

};

Copyright © Bob Friesenhahn 1999 - 2015


text:
<?php
/* ==================================================
 * Wrap interface to the excel spreasheet processing
 *
 * 07 Jun 2014
 * Neither Dump nor Export extends this - why?
 * Really need is a SpreadSheet wrapper and possibly a WorkSheet wrapper
 * Don't think anyone is using these
 */
namespace Cerad\Bundle\CoreBundle\Excel;

class Excel
{
    public function __construct()
    {
        die('CoreBundle::Excel::__construct');
        // Verify still need this for game schedule date/times
        //
        // \PHPExcel_Cell::setValueBinder( new ExcelValueBinder() );
    }
    public function newSpreadSheet()
    {
        return new \PHPExcel();
    }
    public function newWriter($ss)
    {
        return \PHPExcel_IOFactory::createWriter($ss, 'Excel5');
    }
    public function getCoordForColRow($pColumn = 0, $pRow = 1)
    {
        return \PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow;
    }
    public function setCellHorizontalAllignment($ws, $cell, $alignment = '(center|left|right)')
    {
        switch(strtolower($alignment)) {
            case "center":
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                break;
            case "left":
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                break;
            case "right":
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT;
                break;
            default:
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                break;
        }
        $ws->getStyle($cell)->getAlignment()->setHorizontal($align);
    }
    public function setColumnHorizontalAllignment($ws, $col, $rows, $alignment = '(center|left|right)')
    {
        switch(strtolower($alignment)) {
            case "center":
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                break;
            case "left":
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                break;
            case "right":
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT;
                break;
            default:
                $align = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                break;
        }
        $top = $this->getCoordForColRow($col,1);
        $bot = $this->getCoordForColRow($col,$rows);
        $range = $top . ':' . $bot;
        $ws->getStyle($range)->getAlignment()->setHorizontal($align);
    }
    protected function createReaderForFile($fileName,$readDataOnly = true)
    {
        // Most common case
        $reader5 = new \PHPExcel_Reader_Excel5();

        $reader5->setReadDataOnly($readDataOnly);

        if ($reader5->canRead($fileName)) return $reader5;

        // Make sure have zip archive
        if (class_exists('ZipArchive'))
        {
            $reader7 = new \PHPExcel_Reader_Excel2007();

            $reader7->setReadDataOnly($readDataOnly);

            if ($reader7->canRead($fileName)) return $reader7;

        }

        // Note that csv does not actually check for a csv file
        $readerCSV = new \PHPExcel_Reader_CSV();

        if ($readerCSV->canRead($fileName)) return $readerCSV;

        throw new Exception("No Reader found for $fileName");

    }
    public function load($fileName, $readDataOnly = true)
    {
        $reader = $this->createReaderForFile($fileName,$readDataOnly);

        return $reader->load($fileName);
    }
    public function loadx($file)
    {
        return \PHPExcel_IOFactory::load($file);
    }
    /* ==================================================
     * 23 Sep 2013
     * Put these in here
     * Tested on: xlsx
     */
    public function processTime($time)
    {
        return \PHPExcel_Style_NumberFormat::toFormattedString($time,'hh:mm:ss');
    }
    public function processDate($date)
    {
        return \PHPExcel_Style_NumberFormat::toFormattedString($date,'yyyy-MM-dd');
    }
    public function processDateTime($dateTime)
    {
        return \PHPExcel_Style_NumberFormat::toFormattedString($dateTime,'yyyy-MM-dd hh:mm:ss');
    }
}

?>


text:
using System.Collections.Generic;

using Amazon.Runtime.Internal.Transform;

namespace Amazon.ElastiCache.Model.Internal.MarshallTransformations
{
    /// <summary>
    ///    Result Unmarshaller for DeleteCacheCluster operation
    /// </summary>
    internal class DeleteCacheClusterResultUnmarshaller : IUnmarshaller<DeleteCacheClusterResult, XmlUnmarshallerContext> {

        public DeleteCacheClusterResult Unmarshall(XmlUnmarshallerContext context)
        {
            DeleteCacheClusterResult result = new DeleteCacheClusterResult();

            int originalDepth = context.CurrentDepth;
            int targetDepth = originalDepth + 1;
            if (context.IsStartOfDocument)
               targetDepth += 2;

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("CacheCluster", targetDepth))
                    {
                        result.CacheCluster = CacheClusterUnmarshaller.GetInstance().Unmarshall(context);
                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return result;
                }
            }

            return result;
        }

        private static DeleteCacheClusterResultUnmarshaller instance;

        public static DeleteCacheClusterResultUnmarshaller GetInstance()
        {
            if (instance == null)
            {
               instance = new DeleteCacheClusterResultUnmarshaller();
            }
            return instance;
        }
    }
}


text:
using System;
using CoreAnimation;
using CoreGraphics;
using CoreText;
using Foundation;
using UIKit;

namespace CustomVision
{
    public class BubbleLayerLabel : CATextLayer
    {
        CGSize preferredSize = CGSize.Empty;
        CGSize PreferredSize
        {
            set {
				preferredSize = value;
                base.NeedsLayout();
            }
        }

		UIFont font;

        public void UpdatePreferredSize(float maxWidth)
        {
            var text = this.String;
            if (string.IsNullOrEmpty(text))
            {
                preferredSize = CGSize.Empty;
                return;
            }

            // TODO: test .Font property
            var fontName = this.WeakFont as string;
            if (fontName == null)
            {
                Console.WriteLine("Trying to update label size without font");
                preferredSize = CGSize.Empty;
                return;
            }
			if (font == null)
			{
				font = UIFont.FromName(fontName, UIFont.ButtonFontSize);
			}

            var attributes = new UIStringAttributes
            {
                Font = font
            };
            var nsString = new NSAttributedString(text, attributes);
            var fontBounds = nsString.GetBoundingRect(new CGSize(maxWidth, float.MaxValue),
                                                      NSStringDrawingOptions.UsesLineFragmentOrigin, null);
            fontBounds.Size = new CGSize(fontBounds.Size.Width, fontBounds.Size.Height + Math.Abs(font.Descender));
            preferredSize = fontBounds.Size;
        }

        public override CGSize PreferredFrameSize()
        {
            return preferredSize;
        }
    }
}


text:
var crypto = require('crypto');

module.exports = (function () {
	'use strict';

	function ErrorReporter () {}

	ErrorReporter.prototype.init = function () {
		this.responseCache = {};
		this.errorCache = {};
	};

	ErrorReporter.prototype.addError = function (request, error) {
		var errorHash = crypto
			.createHash('sha1')
			.update(
				error
					// Offset by 7 due to the auto-prepended "Error :"
					.stack
					.substr(7 + new Error('Test: testy').message.length),
				'utf8'
			)
			.digest('hex');

		if (errorHash in this.errorCache) {
			return null;
		}

		this.errorCache[errorHash] = {
			request: request,
			error: error
		};

		return this.errorCache[errorHash];
	};

	ErrorReporter.prototype.addResponse = function (request, response) {
		var responseHash = crypto
			.createHash('sha1')
			.update(
				response
					.replace(/Content-Length:[^\n]+\n\r/g, '')
					.replace(/Date:[^\n]+\n\r/g, ''),
				'utf8'
			)
			.digest('hex');

		if (responseHash in this.responseCache) {
			return null;
		}

		this.responseCache[responseHash] = {
			response: response,
			request: request
		};

		return this.responseCache[responseHash];
	};

	return new ErrorReporter();
})();


text:
package net.javacrumbs.smock.axis2.server;

import static net.javacrumbs.smock.common.XmlUtil.getEnvelopeSource;
import static net.javacrumbs.smock.common.XmlUtil.getSourceAsStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import net.javacrumbs.smock.common.InterceptingTemplate;
import net.javacrumbs.smock.common.server.MockWebServiceClientResponseActions;

import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.Flow;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.transport.local.LocalTransportReceiver;
import org.springframework.util.Assert;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.DefaultMessageContext;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;
import org.springframework.ws.test.server.RequestCreator;
import org.springframework.ws.test.server.RequestCreators;
import org.springframework.ws.test.server.ResponseActions;
import org.springframework.ws.test.support.AssertionErrors;
import org.springframework.ws.transport.WebServiceMessageReceiver;

/**
 * Creates connection to Axis 2.
 * @author Lukas Krecan
 */
public class Axis2MockWebServiceClient {
	private final WebServiceMessageFactory messageFactory;
	private final InterceptingTemplate interceptingTemplate;
	private final LocalTransportReceiver receiver;
	private final ConfigurationContext configurationContext;

	public Axis2MockWebServiceClient(WebServiceMessageFactory messageFactory, ConfigurationContext configurationContext, ClientInterceptor[] interceptors) {
		this.messageFactory =  messageFactory;
		interceptingTemplate = new InterceptingTemplate(interceptors);
		receiver = new LocalTransportReceiver(configurationContext);
		this.configurationContext = configurationContext;
	}

	public Axis2MockWebServiceClient(ConfigurationContext configurationContext, ClientInterceptor[] interceptors) {
		this(createDefaultMessageFactory(), configurationContext, interceptors);
	}

    private static WebServiceMessageFactory createDefaultMessageFactory() {
    	SaajSoapMessageFactory factory = new SaajSoapMessageFactory();
    	factory.afterPropertiesSet();
		return factory;
	}
	/**
     * Sends a request message by using the given {@link RequestCreator}. Typically called by using the default request
     * creators provided by {@link RequestCreators}.
     *
     * @param requestCreator the request creator
     * @return the response actions
     * @see RequestCreators
     */
    public ResponseActions sendRequestTo(final EndpointReference to, final String action, RequestCreator requestCreator) {
		try {
			Assert.notNull(requestCreator, "'requestCreator' must not be null");
			WebServiceMessage requestMessage = requestCreator.createRequest(messageFactory);

			MessageContext messageContext = new DefaultMessageContext(requestMessage, messageFactory);
			interceptingTemplate.interceptRequest(messageContext, new WebServiceMessageReceiver() {
				public void receive(MessageContext messageContext) throws Exception {
					ByteArrayOutputStream response = new ByteArrayOutputStream();
					InputStream request = getSourceAsStream(getEnvelopeSource(messageContext.getRequest()));
					receiver.processMessage(createMessageContext(action, to), request, response);
					messageContext.setResponse(messageFactory.createWebServiceMessage(new ByteArrayInputStream(response.toByteArray())));
				}
			});
			return new MockWebServiceClientResponseActions(messageContext);
		} catch (Exception e) {
			AssertionErrors.fail(e.getMessage());
			return null;
		}
    }

    /**
     * Sends a request message by using the given {@link RequestCreator}. Typically called by using the default request
     * creators provided by {@link RequestCreators}.
     *
     * @param requestCreator the request creator
     * @return the response actions
     * @see RequestCreators
     */
    public ResponseActions sendRequestTo(String serviceAddress, RequestCreator requestCreator)
    {
    	EndpointReference to = new EndpointReference(serviceAddress);
		return sendRequestTo(to , null, requestCreator);
    }

	private org.apache.axis2.context.MessageContext createMessageContext(final String action, final EndpointReference to)
	{
		org.apache.axis2.context.MessageContext mc = configurationContext.createMessageContext();
		mc.setSoapAction(action);
		mc.setTo(to);
		return mc;
	}
}


text:
package com.foilen.smalltools.net.commander.channel;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foilen.smalltools.tools.CharsetTools;
import com.foilen.smalltools.tools.JsonTools;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

/**
 * <pre>
 * Decodes this protocol:
 * - classNameSize:int
 * - className:String (must be a {@link Runnable})
 * - jsonContentSize:int
 * - jsonContent:String
 * </pre>
 */
public class CommanderDecoder extends ReplayingDecoder<Void> {

    private static final Logger logger = LoggerFactory.getLogger(CommanderDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        logger.debug("Trying to decode a message. Readable bytes {}", in.readableBytes());

        // classNameSize:int
        int len = in.readInt();

        // className:String
        String className = in.readBytes(len).toString(CharsetTools.UTF_8);

        // jsonContentSize:int
        len = in.readInt();

        // jsonContent:String
        String jsonContent = in.readBytes(len).toString(CharsetTools.UTF_8);

        // Add the JSON runnable to the list
        logger.debug("Decoding class {} with json {}", className, jsonContent);

        out.add(JsonTools.readFromString(jsonContent, Class.forName(className)));
        logger.debug("Completely got a {}", className);
    }

}


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace System.Linq.Parallel
{
    /// <summary>
    /// A group join operator takes a left query tree and a right query tree, and then yields
    /// the matching elements between the two. This can be used for outer joins, i.e. those
    /// where an outer element has no matching inner elements -- the result is just an empty
    /// list. As with the join algorithm above, we currently use a hash join algorithm.
    /// </summary>
    /// <typeparam name="TLeftInput"></typeparam>
    /// <typeparam name="TRightInput"></typeparam>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TOutput"></typeparam>
    internal sealed class GroupJoinQueryOperator<TLeftInput, TRightInput, TKey, TOutput> : BinaryQueryOperator<TLeftInput, TRightInput, TOutput>
    {
        private readonly Func<TLeftInput, TKey> _leftKeySelector; // The key selection routine for the outer (left) data source.
        private readonly Func<TRightInput, TKey> _rightKeySelector; // The key selection routine for the inner (right) data source.
        private readonly Func<TLeftInput, IEnumerable<TRightInput>, TOutput> _resultSelector; // The result selection routine.
        private readonly IEqualityComparer<TKey> _keyComparer; // An optional key comparison object.

        //---------------------------------------------------------------------------------------
        // Constructs a new join operator.
        //

        internal GroupJoinQueryOperator(ParallelQuery<TLeftInput> left, ParallelQuery<TRightInput> right,
                                        Func<TLeftInput, TKey> leftKeySelector,
                                        Func<TRightInput, TKey> rightKeySelector,
                                        Func<TLeftInput, IEnumerable<TRightInput>, TOutput> resultSelector,
                                        IEqualityComparer<TKey> keyComparer)
            : base(left, right)
        {
            Debug.Assert(left != null && right != null, "child data sources cannot be null");
            Debug.Assert(leftKeySelector != null, "left key selector must not be null");
            Debug.Assert(rightKeySelector != null, "right key selector must not be null");
            Debug.Assert(resultSelector != null, "need a result selector function");

            _leftKeySelector = leftKeySelector;
            _rightKeySelector = rightKeySelector;
            _resultSelector = resultSelector;
            _keyComparer = keyComparer;
            _outputOrdered = LeftChild.OutputOrdered;

            SetOrdinalIndex(OrdinalIndexState.Shuffled);
        }

        //---------------------------------------------------------------------------------------
        // Just opens the current operator, including opening the child and wrapping it with
        // partitions as needed.
        //

        internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping)
        {
            QueryResults<TLeftInput> leftResults = LeftChild.Open(settings, false);
            QueryResults<TRightInput> rightResults = RightChild.Open(settings, false);

            return new BinaryQueryOperatorResults(leftResults, rightResults, this, settings, false);
        }

        public override void WrapPartitionedStream<TLeftKey, TRightKey>(
            PartitionedStream<TLeftInput, TLeftKey> leftStream, PartitionedStream<TRightInput, TRightKey> rightStream,
            IPartitionedStreamRecipient<TOutput> outputRecipient, bool preferStriping, QuerySettings settings)
        {
            Debug.Assert(rightStream.PartitionCount == leftStream.PartitionCount);
            int partitionCount = leftStream.PartitionCount;

            if (LeftChild.OutputOrdered)
            {
                WrapPartitionedStreamHelper<TLeftKey, TRightKey>(
                    ExchangeUtilities.HashRepartitionOrdered(leftStream, _leftKeySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
                    rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken);
            }
            else
            {
                WrapPartitionedStreamHelper<int, TRightKey>(
                    ExchangeUtilities.HashRepartition(leftStream, _leftKeySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
                    rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken);
            }
        }

        //---------------------------------------------------------------------------------------
        // This is a helper method. WrapPartitionedStream decides what type TLeftKey is going
        // to be, and then call this method with that key as a generic parameter.
        //

        private void WrapPartitionedStreamHelper<TLeftKey, TRightKey>(
            PartitionedStream<Pair, TLeftKey> leftHashStream, PartitionedStream<TRightInput, TRightKey> rightPartitionedStream,
            IPartitionedStreamRecipient<TOutput> outputRecipient, int partitionCount, CancellationToken cancellationToken)
        {
            PartitionedStream<Pair, int> rightHashStream = ExchangeUtilities.HashRepartition(
                rightPartitionedStream, _rightKeySelector, _keyComparer, null, cancellationToken);

            PartitionedStream<TOutput, TLeftKey> outputStream = new PartitionedStream<TOutput, TLeftKey>(
                partitionCount, leftHashStream.KeyComparer, OrdinalIndexState);

            for (int i = 0; i < partitionCount; i++)
            {
                outputStream[i] = new HashJoinQueryOperatorEnumerator<TLeftInput, TLeftKey, TRightInput, TKey, TOutput>(
                    leftHashStream[i], rightHashStream[i], null, _resultSelector, _keyComparer, cancellationToken);
            }

            outputRecipient.Receive(outputStream);
        }

        //---------------------------------------------------------------------------------------
        // Returns an enumerable that represents the query executing sequentially.
        //

        internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token)
        {
            IEnumerable<TLeftInput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token);
            IEnumerable<TRightInput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token);

            return wrappedLeftChild
                .GroupJoin(
                wrappedRightChild, _leftKeySelector, _rightKeySelector, _resultSelector, _keyComparer);
        }

        //---------------------------------------------------------------------------------------
        // Whether this operator performs a premature merge that would not be performed in
        // a similar sequential operation (i.e., in LINQ to Objects).
        //

        internal override bool LimitsParallelism
        {
            get { return false; }
        }
    }
}


text:
namespace tinyxml2
{
	class XMLElement;
	class XMLDocument;
}

namespace Causality
{
	using ParamArchive = tinyxml2::XMLElement;
	using ParamDocument = tinyxml2::XMLDocument;

	namespace Serialization
	{
		bool GetString(const ParamArchive* archive, const char* name, const char*(&param));
		bool GetString(const ParamArchive* archive, const char* name, string& param);
		bool GetBool(const ParamArchive* archive, const char* name, bool& param);
		bool GetFloat(const ParamArchive* archive, const char* name, float& param);
		bool GetDouble(const ParamArchive* archive, const char* name, double& param);
		bool GetInt(const ParamArchive* archive, const char* name, int& param);
		bool GetUint(const ParamArchive* archive, const char* name, unsigned& param);
		bool GetVector2(const ParamArchive* archive, const char* name, Vector2& param);
		bool GetVector3(const ParamArchive* archive, const char* name, Vector3& param);
		bool GetVector4(const ParamArchive* archive, const char* name, Vector4& param);
		bool GetColor(const ParamArchive* archive, const char* name, Color& param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, const char*(&param))
	{
		return Serialization::GetString(archive, name, param);
	}
	inline bool GetParam(const ParamArchive* archive, const char* name, string& param)
	{
		return Serialization::GetString(archive, name, param);
	}
	inline bool GetParam(const ParamArchive* archive, const char* name, bool& param)
	{
		return Serialization::GetBool(archive, name, param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, float& param)
	{
		return Serialization::GetFloat(archive, name, param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, double& param)
	{
		return Serialization::GetDouble(archive, name, param);
	}
	inline bool GetParam(const ParamArchive* archive, const char* name, int& param)
	{
		return Serialization::GetInt(archive, name, param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, unsigned& param)
	{
		return Serialization::GetUint(archive, name, param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, Vector2& param)
	{
		return Serialization::GetVector2(archive, name, param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, Vector3& param)
	{
		return Serialization::GetVector3(archive, name, param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, Vector4& param)
	{
		return Serialization::GetVector4(archive, name, param);
	}

	inline bool GetParam(const ParamArchive* archive, const char* name, Color& param)
	{
		return Serialization::GetColor(archive, name, param);
	}

	const char* GetArchiveName(const ParamArchive* archive);
	const ParamArchive* GetParentArchive(const ParamArchive* archive);
	const ParamArchive* GetFirstChildArchive(const ParamArchive* archive, const char* name = 0);
	const ParamArchive* GetPrevSiblingArchive(const ParamArchive* archive, const char* name = 0);
	const ParamArchive* GetNextSiblingArchive(const ParamArchive* archive, const char* name = 0);
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.07.27 at 08:11:57 PM EEST
//

package uk.org.siri.siri;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 * Name spaces.
 *
 *
Java class for DataNameSpacesStructure complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="DataNameSpacesStructure">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="StopPointNameSpace" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
 *         <element name="LineNameSpace" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
 *         <element name="ProductCategoryNameSpace" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
 *         <element name="ServiceFeatureNameSpace" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
 *         <element name="VehicleFeatureNameSpace" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DataNameSpacesStructure", propOrder = {
    "stopPointNameSpace",
    "lineNameSpace",
    "productCategoryNameSpace",
    "serviceFeatureNameSpace",
    "vehicleFeatureNameSpace"
})
public class DataNameSpacesStructure {

    @XmlElement(name = "StopPointNameSpace")
    @XmlSchemaType(name = "anyURI")
    protected String stopPointNameSpace;
    @XmlElement(name = "LineNameSpace")
    @XmlSchemaType(name = "anyURI")
    protected String lineNameSpace;
    @XmlElement(name = "ProductCategoryNameSpace")
    @XmlSchemaType(name = "anyURI")
    protected String productCategoryNameSpace;
    @XmlElement(name = "ServiceFeatureNameSpace")
    @XmlSchemaType(name = "anyURI")
    protected String serviceFeatureNameSpace;
    @XmlElement(name = "VehicleFeatureNameSpace")
    @XmlSchemaType(name = "anyURI")
    protected String vehicleFeatureNameSpace;

    /**
     * Gets the value of the stopPointNameSpace property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getStopPointNameSpace() {
        return stopPointNameSpace;
    }

    /**
     * Sets the value of the stopPointNameSpace property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setStopPointNameSpace(String value) {
        this.stopPointNameSpace = value;
    }

    /**
     * Gets the value of the lineNameSpace property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLineNameSpace() {
        return lineNameSpace;
    }

    /**
     * Sets the value of the lineNameSpace property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLineNameSpace(String value) {
        this.lineNameSpace = value;
    }

    /**
     * Gets the value of the productCategoryNameSpace property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getProductCategoryNameSpace() {
        return productCategoryNameSpace;
    }

    /**
     * Sets the value of the productCategoryNameSpace property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setProductCategoryNameSpace(String value) {
        this.productCategoryNameSpace = value;
    }

    /**
     * Gets the value of the serviceFeatureNameSpace property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getServiceFeatureNameSpace() {
        return serviceFeatureNameSpace;
    }

    /**
     * Sets the value of the serviceFeatureNameSpace property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setServiceFeatureNameSpace(String value) {
        this.serviceFeatureNameSpace = value;
    }

    /**
     * Gets the value of the vehicleFeatureNameSpace property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVehicleFeatureNameSpace() {
        return vehicleFeatureNameSpace;
    }

    /**
     * Sets the value of the vehicleFeatureNameSpace property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVehicleFeatureNameSpace(String value) {
        this.vehicleFeatureNameSpace = value;
    }

}


text:
- **objective**: binary:logistic
- **eval_metric**: logloss
- **eta**: 0.1
- **max_depth**: 6
- **min_child_weight**: 1
- **subsample**: 1.0
- **colsample_bytree**: 1.0
- **explain_level**: 2

## Validation
 - **validation_type**: split
 - **train_ratio**: 0.75
 - **shuffle**: True
 - **stratify**: True

## Optimized metric
logloss

## Training time

11.7 seconds

## Metric details
|           |    score |   threshold |
|:----------|---------:|------------:|
| logloss   | 0.458922 | nan         |
| auc       | 0.835427 | nan         |
| f1        | 0.74359  |   0.651504  |
| accuracy  | 0.820628 |   0.651504  |
| precision | 0.967742 |   0.877763  |
| recall    | 1        |   0.0930362 |
| mcc       | 0.615496 |   0.651504  |

## Confusion matrix (at threshold=0.651504)
|                     |   Predicted as negative |   Predicted as positive |
|:--------------------|------------------------:|------------------------:|
| Labeled as negative |                     125 |                      12 |
| Labeled as positive |                      28 |                      58 |

## Learning curves
![Learning curves](learning_curves.png)

## Permutation-based Importance
![Permutation-based Importance](permutation_importance.png)

## SHAP Importance
![SHAP Importance](shap_importance.png)

## SHAP Dependence plots

### Dependence (Fold #1)
![SHAP Dependence from fold 1](learner_1_shap_dependence.png)

## SHAP Decision plots

### Top-10 Worst decisions for class 0 (Fold #1)
![SHAP worst decisions class 0 from fold 1](learner_1_shap_class_0_worst_decisions.png)
### Top-10 Best decisions for class 0 (Fold #1)
![SHAP best decisions class 0 from fold 1](learner_1_shap_class_0_best_decisions.png)
### Top-10 Worst decisions for class 1 (Fold #1)
![SHAP worst decisions class 1 from fold 1](learner_1_shap_class_1_worst_decisions.png)
### Top-10 Best decisions for class 1 (Fold #1)
![SHAP best decisions class 1 from fold 1](learner_1_shap_class_1_best_decisions.png)


text:
//
//  MTZWhatsNew.h
//
//  MTZWhatsNew created by Matt Zanchelli on 5/16/14.
//  Copyright (c) 2014 Matt Zanchelli. All rights reserved.
//

//
//  Based off of MTMigration created by Parker Wightman on 2/7/13.
//  Copyright (c) 2013 Mysterious Trousers. All rights reserved.
//

@import Foundation;

#import "MTZWhatsNewViewController.h"

typedef void (^MTZWhatsNewHandler)(NSDictionary *whatsNew);

@interface MTZWhatsNew : NSObject

///	Show what's new in this update, if anything.
/// @param whatsNewHandler A block called to handle what's new, if there's anything new at all.
/// @discussion Call this on every app launch to keep track of used versions.
+ (void)handleWhatsNew:(MTZWhatsNewHandler)whatsNewHandler;

///
/// @param whatsNewHandler A block called to handle what's new, if there's anything new at all.
/// @param versionString A string representing the version to show changes since.
/// @discussion Only use this if you wish to show changes since a specific version. Typically, only the @c handleWhatsNew: method is need. If wishing to only show the changes since the last version used, use @c handleWhatsNew: instead.
+ (void)handleWhatsNew:(MTZWhatsNewHandler)whatsNewHandler sinceVersion:(NSString *)versionString;

///	Clears the last migration remembered by @c MTZWhatsNew. Causes migration to run from the beginning.
+ (void)reset;

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Septoria artocarpi Cooke

### Remarks
null


text:
using System;
using RawRabbit.Compatibility.Legacy.Configuration.Exchange;
using RawRabbit.Compatibility.Legacy.Configuration.Queue;

namespace RawRabbit.Compatibility.Legacy.Configuration.Respond
{
	class ResponderConfigurationBuilder : IResponderConfigurationBuilder
	{
		private readonly ExchangeConfigurationBuilder _exchangeBuilder;
		private readonly QueueConfigurationBuilder _queueBuilder;

		public ResponderConfiguration Configuration { get; }

		public ResponderConfigurationBuilder(QueueConfiguration defaultQueue = null, ExchangeConfiguration defaultExchange = null)
		{
			_exchangeBuilder = new ExchangeConfigurationBuilder(defaultExchange);
			_queueBuilder = new QueueConfigurationBuilder(defaultQueue);
			Configuration = new ResponderConfiguration
			{
				Queue = _queueBuilder.Configuration,
				Exchange = _exchangeBuilder.Configuration,
				RoutingKey = _queueBuilder.Configuration.QueueName
			};
		}

		public IResponderConfigurationBuilder WithExchange(Action<IExchangeConfigurationBuilder> exchange)
		{
			exchange(_exchangeBuilder);
			Configuration.Exchange = _exchangeBuilder.Configuration;
			return this;
		}

		public IResponderConfigurationBuilder WithPrefetchCount(ushort count)
		{
			Configuration.PrefetchCount = count;
			return this;
		}

		public IResponderConfigurationBuilder WithQueue(Action<IQueueConfigurationBuilder> queue)
		{
			queue(_queueBuilder);
			Configuration.Queue = _queueBuilder.Configuration;
			if (string.IsNullOrEmpty(Configuration.RoutingKey))
			{
				Configuration.RoutingKey = _queueBuilder.Configuration.QueueName;
			}
			return this;
		}

		public IResponderConfigurationBuilder WithRoutingKey(string routingKey)
		{
			Configuration.RoutingKey = routingKey;
			return this;
		}

		public IResponderConfigurationBuilder WithNoAck(bool noAck)
		{
			return WithAutoAck(noAck);
		}

		public IResponderConfigurationBuilder WithAutoAck(bool autoAck = true)
		{
			Configuration.AutoAck = autoAck;
			return this;
		}
	}
}


text:
NSString *const MPABTestDesignerClearRequestMessageType = @"clear_request";

@implementation MPABTestDesignerClearRequestMessage

+ (instancetype)message
{
    return [[self alloc] initWithType:MPABTestDesignerClearRequestMessageType];
}

- (NSOperation *)responseCommandWithConnection:(MPABTestDesignerConnection *)connection
{
    __weak MPABTestDesignerConnection *weak_connection = connection;
    NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        MPABTestDesignerConnection *conn = weak_connection;

        MPVariant *variant = [conn sessionObjectForKey:kSessionVariantKey];
        if (variant) {
            NSArray *actions = [self.payload objectForKey:@"actions"];
            dispatch_sync(dispatch_get_main_queue(), ^{
                for (NSString *name in actions) {
                    [variant removeActionWithName:name];
                }
            });
        }

        MPABTestDesignerClearResponseMessage *clearResponseMessage = [MPABTestDesignerClearResponseMessage message];
        clearResponseMessage.status = @"OK";
        [conn sendMessage:clearResponseMessage];
    }];
    return operation;
}

@end


text:
<!DOCTYPE HTML>

<title>About | Nova</title>
<link href="css/bootstrap.css" rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="css/font-awesome.min.css">

<link href="css/style.css" rel='stylesheet' type='text/css' />
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href='http://fonts.useso.com/css?family=Source+Sans+Pro:200,300,400,600,700,900' rel='stylesheet' type='text/css'>
</script>

Home

About

Services

Blog

Contact

About Our Company

Morbi lectus risus iaculisvel

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor.

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet.

Curabitur sodales ligula in libero

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet.

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor.

Sed accumsan nunc

Nulla quis sem at nibh elementum

Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum praesent mauris.

Quis sem at nibh elementum imperdiet

Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum praesent mauris.

Nulla quis sem at nibh elementum

Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum praesent mauris.

Quis sem at nibh elementum imperdiet

Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum praesent mauris.

Vel ad aliquid copiosae

No cum agam appareat vituperata ateum iusto paulo dignissim

Impetus tincidunt

Vel ad aliquid copiosae, cum id impetus tincidunt, solum option laoreet ei quo. No cum agam appareat vituperata ateum iusto paulo dignissim.

Paulo dignissim

Vel ad aliquid copiosae, cum id impetus tincidunt, solum option laoreet ei quo. No cum agam appareat vituperata ateum iusto paulo dignissim.

Vituperata ateum

Vel ad aliquid copiosae, cum id impetus tincidunt, solum option laoreet ei quo. No cum agam appareat vituperata ateum iusto paulo dignissim.

Appareat vituperat

Vel ad aliquid copiosae, cum id impetus tincidunt, solum option laoreet ei quo. No cum agam appareat vituperata ateum iusto paulo dignissim.

Follow us on Facebook

Follow us on Twitter

Follow us on Google +

Follow us on LinkedIn

Copyright © 2014 Nova. More Templates ģ��֮�� - Collect from ��ҳģ��