text:
package org.cojen.util;

import java.lang.ref.Reference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

/**
 * A Map that references its values and can be used as a simple cache.
 * Instances are not thread-safe and must be wrapped with
 * Collections.synchronizedMap to be made thread-safe.
 * <p>
 * Note: Referenced entries may be automatically removed during
 * either accessor or mutator operations, possibly causing a concurrent
 * modification to be detected. Therefore, even if multiple threads are only
 * accessing this map, be sure to synchronize this map first. Also, do not
 * rely on the value returned by size() when using an iterator from this map.
 * The iterators may return less entries than the amount reported by size().
 *
 * @author Brian S O'Neill
 */
public abstract class ReferencedValueHashMap<K, V> extends AbstractMap<K, V>
    implements Map<K, V>, Cloneable
{
    private transient Entry<K, V>[] table;
    private transient int count;
    private int threshold;
    private final float loadFactor;
    private transient volatile int modCount;

    // Views

    private transient Set<K> keySet;
    private transient Set<Map.Entry<K, V>> entrySet;
    private transient Collection<V> values;

    /**
     * Constructs a new, empty map with the specified initial
     * capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the HashMap.
     * @param      loadFactor        the load factor of the HashMap
     * @throws     IllegalArgumentException  if the initial capacity is less
     *               than zero, or if the load factor is nonpositive.
     */
    public ReferencedValueHashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("Illegal Initial Capacity: "+
                                               initialCapacity);
        }

        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new IllegalArgumentException("Illegal Load factor: "+
                                               loadFactor);
        }

        if (initialCapacity == 0) {
            initialCapacity = 1;
        }

        this.loadFactor = loadFactor;
        this.table = new Entry[initialCapacity];
        this.threshold = (int)(initialCapacity * loadFactor);
    }

    /**
     * Constructs a new, empty map with the specified initial capacity
     * and default load factor, which is <tt>0.75</tt>.
     *
     * @param   initialCapacity   the initial capacity of the HashMap.
     * @throws    IllegalArgumentException if the initial capacity is less
     *              than zero.
     */
    public ReferencedValueHashMap(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }

    /**
     * Constructs a new, empty map with a default capacity and load
     * factor, which is <tt>0.75</tt>.
     */
    public ReferencedValueHashMap() {
        this(11, 0.75f);
    }

    /**
     * Constructs a new map with the same mappings as the given map.  The
     * map is created with a capacity of twice the number of mappings in
     * the given map or 11 (whichever is greater), and a default load factor,
     * which is <tt>0.75</tt>.
     */
    public ReferencedValueHashMap(Map<? extends K, ? extends V> t) {
        this(Math.max(2 * t.size(), 11), 0.75f);
        putAll(t);
    }

    public int size() {
        return this.count;
    }

    public boolean isEmpty() {
        return this.count == 0;
    }

    public boolean containsValue(Object value) {
        if (value == null) {
            value = KeyFactory.NULL;
        }

        Entry[] tab = this.table;

        for (int i = tab.length ; i-- > 0 ;) {
            for (Entry e = tab[i], prev = null; e != null; e = e.next) {
                Object entryValue = e.get();

                if (entryValue == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[i] = e.next;
                    }
                    this.count--;
                } else if (value.equals(entryValue)) {
                    return true;
                } else {
                    prev = e;
                }
            }
        }

        return false;
    }

    public boolean containsKey(Object key) {
        Entry<K, V>[] tab = this.table;

        if (key != null) {
            int hash = key.hashCode();
            int index = (hash & 0x7fffffff) % tab.length;
            for (Entry<K, V> e = tab[index], prev = null; e != null; e = e.next) {
                if (e.get() == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[index] = e.next;
                    }
                    this.count--;
                } else if (e.hash == hash && key.equals(e.key)) {
                    return true;
                } else {
                    prev = e;
                }
            }
        } else {
            for (Entry<K, V> e = tab[0], prev = null; e != null; e = e.next) {
                if (e.get() == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[0] = e.next;
                    }
                    this.count--;
                } else if (e.key == null) {
                    return true;
                } else {
                    prev = e;
                }
            }
        }

        return false;
    }

    public V get(Object key) {
        Entry<K, V>[] tab = this.table;

        if (key != null) {
            int hash = key.hashCode();
            int index = (hash & 0x7fffffff) % tab.length;

            for (Entry<K, V> e = tab[index], prev = null; e != null; e = e.next) {
                V entryValue = e.get();

                if (entryValue == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[index] = e.next;
                    }
                    count--;
                } else if (e.hash == hash && key.equals(e.key)) {
                    return (entryValue == KeyFactory.NULL) ? null : entryValue;
                } else {
                    prev = e;
                }
            }
        } else {
            for (Entry<K, V> e = tab[0], prev = null; e != null; e = e.next) {
                V entryValue = e.get();

                if (entryValue == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    }
                    else {
                        tab[0] = e.next;
                    }
                    this.count--;
                } else if (e.key == null) {
                    return (entryValue == KeyFactory.NULL) ? null : entryValue;
                } else {
                    prev = e;
                }
            }
        }

        return null;
    }

    /**
     * Scans the contents of this map, removing all entries that have a
     * cleared soft value.
     */
    private void cleanup() {
        Entry<K, V>[] tab = this.table;

        for (int i = tab.length ; i-- > 0 ;) {
            for (Entry<K, V> e = tab[i], prev = null; e != null; e = e.next) {
                if (e.get() == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[i] = e.next;
                    }
                    this.count--;
                } else {
                    prev = e;
                }
            }
        }
    }

    /**
     * Rehashes the contents of this map into a new <tt>HashMap</tt> instance
     * with a larger capacity. This method is called automatically when the
     * number of keys in this map exceeds its capacity and load factor.
     */
    private void rehash() {
        int oldCapacity = this.table.length;
        Entry<K, V>[] oldMap = this.table;

        int newCapacity = oldCapacity * 2 + 1;
        Entry<K, V>[] newMap = new Entry[newCapacity];

        this.modCount++;
        this.threshold = (int)(newCapacity * this.loadFactor);
        this.table = newMap;

        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K, V> old = oldMap[i] ; old != null ; ) {
                Entry<K, V> e = old;
                old = old.next;

                // Only copy entry if its value hasn't been cleared.
                if (e.get() == null) {
                    this.count--;
                } else {
                    int index = (e.hash & 0x7fffffff) % newCapacity;
                    e.next = newMap[index];
                    newMap[index] = e;
                }
            }
        }
    }

    public V put(K key, V value) {
        if (value == null) {
            value = (V) KeyFactory.NULL;
        }

        // Makes sure the key is not already in the HashMap.
        Entry<K, V>[] tab = this.table;
        int hash;
        int index;

        if (key != null) {
            hash = key.hashCode();
            index = (hash & 0x7fffffff) % tab.length;
            for (Entry<K, V> e = tab[index], prev = null; e != null; e = e.next) {
                V entryValue = e.get();

                if (entryValue == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[index] = e.next;
                    }
                    this.count--;
                } else if (e.hash == hash && key.equals(e.key)) {
                    e.setValue(value);
                    return (entryValue == KeyFactory.NULL) ? null : entryValue;
                } else {
                    prev = e;
                }
            }
        } else {
            hash = 0;
            index = 0;
            for (Entry<K, V> e = tab[0], prev = null; e != null; e = e.next) {
                V entryValue = e.get();

                if (entryValue == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[0] = e.next;
                    }
                    this.count--;
                } else if (e.key == null) {
                    e.setValue(value);
                    return (entryValue == KeyFactory.NULL) ? null : entryValue;
                } else {
                    prev = e;
                }
            }
        }

        this.modCount++;

        if (this.count >= this.threshold) {
            // Cleanup the table if the threshold is exceeded.
            cleanup();
        }

        if (this.count >= this.threshold) {
            // Rehash the table if the threshold is still exceeded.
            rehash();
            tab = this.table;
            index = (hash & 0x7fffffff) % tab.length;
        }

        // Creates the new entry.
        Entry<K, V> e = newEntry(hash, key, (V)value, tab[index]);
        tab[index] = e;
        this.count++;
        return null;
    }

    public V remove(Object key) {
        Entry<K, V>[] tab = this.table;

        if (key != null) {
            int hash = key.hashCode();
            int index = (hash & 0x7fffffff) % tab.length;

            for (Entry<K, V> e = tab[index], prev = null; e != null; e = e.next) {
                V entryValue = e.get();

                if (entryValue == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[index] = e.next;
                    }
                    this.count--;
                } else if (e.hash == hash && key.equals(e.key)) {
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[index] = e.next;
                    }
                    this.count--;

                    e.setValue(null);
                    return (entryValue == KeyFactory.NULL) ? null : entryValue;
                } else {
                    prev = e;
                }
            }
        } else {
            for (Entry<K, V> e = tab[0], prev = null; e != null; e = e.next) {
                V entryValue = e.get();

                if (entryValue == null) {
                    // Clean up after a cleared Reference.
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[0] = e.next;
                    }
                    this.count--;
                } else if (e.key == null) {
                    this.modCount++;
                    if (prev != null) {
                        prev.next = e.next;
                    } else {
                        tab[0] = e.next;
                    }
                    this.count--;

                    e.setValue(null);
                    return (entryValue == KeyFactory.NULL) ? null : entryValue;
                } else {
                    prev = e;
                }
            }
        }

        return null;
    }

    public void putAll(Map<? extends K, ? extends V> t) {
        Iterator i = t.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<K, V> e = (Map.Entry<K, V>) i.next();
            put(e.getKey(), e.getValue());
        }
    }

    public void clear() {
        Entry[] tab = this.table;
        this.modCount++;
        for (int index = tab.length; --index >= 0; ) {
            tab[index] = null;
        }
        this.count = 0;
    }

    public Object clone() {
        try {
            ReferencedValueHashMap t = (ReferencedValueHashMap)super.clone();
            t.table = new Entry[this.table.length];
            for (int i = this.table.length ; i-- > 0 ; ) {
                t.table[i] = (this.table[i] != null)
                    ? (Entry)this.table[i].clone() : null;
            }
            t.keySet = null;
            t.entrySet = null;
            t.values = null;
            t.modCount = 0;
            return t;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError();
        }
    }

    public Set<K> keySet() {
        if (this.keySet == null) {
            this.keySet = new AbstractSet<K>() {
                public Iterator iterator() {
                    return createHashIterator(WeakIdentityMap.KEYS);
                }
                public int size() {
                    return ReferencedValueHashMap.this.count;
                }
                public boolean contains(Object o) {
                    return containsKey(o);
                }
                public boolean remove(Object o) {
                    if (o == null) {
                        if (ReferencedValueHashMap.this.containsKey(null)) {
                            ReferencedValueHashMap.this.remove(null);
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return ReferencedValueHashMap.this.remove(o) != null;
                    }
                }
                public void clear() {
                    ReferencedValueHashMap.this.clear();
                }
                public String toString() {
                    return WeakIdentityMap.toString(this);
                }
            };
        }
        return this.keySet;
    }

    public Collection<V> values() {
        if (this.values==null) {
            this.values = new AbstractCollection<V>() {
                public Iterator iterator() {
                    return createHashIterator(WeakIdentityMap.VALUES);
                }
                public int size() {
                    return ReferencedValueHashMap.this.count;
                }
                public boolean contains(Object o) {
                    return containsValue(o);
                }
                public void clear() {
                    ReferencedValueHashMap.this.clear();
                }
                public String toString() {
                    return WeakIdentityMap.toString(this);
                }
            };
        }
        return this.values;
    }

    public Set<Map.Entry<K, V>> entrySet() {
        if (this.entrySet==null) {
            this.entrySet = new AbstractSet<Map.Entry<K, V>>() {
                public Iterator iterator() {
                    return createHashIterator(WeakIdentityMap.ENTRIES);
                }

                public boolean contains(Object o) {
                    if (!(o instanceof Map.Entry)) {
                        return false;
                    }
                    Map.Entry entry = (Map.Entry)o;
                    Object key = entry.getKey();

                    Entry[] tab = ReferencedValueHashMap.this.table;
                    int hash = key == null ? 0 : key.hashCode();
                    int index = (hash & 0x7fffffff) % tab.length;

                    for (Entry e = tab[index], prev = null; e != null; e = e.next) {
                        Object entryValue = e.get();

                        if (entryValue == null) {
                            // Clean up after a cleared Reference.
                            ReferencedValueHashMap.this.modCount++;
                            if (prev != null) {
                                prev.next = e.next;
                            } else {
                                tab[index] = e.next;
                            }
                            ReferencedValueHashMap.this.count--;
                        } else if (e.hash == hash && e.equals(entry)) {
                            return true;
                        } else {
                            prev = e;
                        }
                    }

                    return false;
                }

                public boolean remove(Object o) {
                    if (!(o instanceof Map.Entry)) {
                        return false;
                    }
                    Map.Entry entry = (Map.Entry)o;
                    Object key = entry.getKey();
                    Entry[] tab = ReferencedValueHashMap.this.table;
                    int hash = key == null ? 0 : key.hashCode();
                    int index = (hash & 0x7fffffff) % tab.length;

                    for (Entry e = tab[index], prev = null; e != null; e = e.next) {
                        Object entryValue = e.get();

                        if (entryValue == null) {
                            // Clean up after a cleared Reference.
                            ReferencedValueHashMap.this.modCount++;
                            if (prev != null) {
                                prev.next = e.next;
                            } else {
                                tab[index] = e.next;
                            }
                            ReferencedValueHashMap.this.count--;
                        } else if (e.hash == hash && e.equals(entry)) {
                            ReferencedValueHashMap.this.modCount++;
                            if (prev != null) {
                                prev.next = e.next;
                            } else {
                                tab[index] = e.next;
                            }
                            ReferencedValueHashMap.this.count--;

                            e.setValue(null);
                            return true;
                        } else {
                            prev = e;
                        }
                    }
                    return false;
                }

                public int size() {
                    return ReferencedValueHashMap.this.count;
                }

                public void clear() {
                    ReferencedValueHashMap.this.clear();
                }

                public String toString() {
                    return WeakIdentityMap.toString(this);
                }
            };
        }

        return this.entrySet;
    }

    public String toString() {
        // Cleanup stale entries first, so as not to allocate a larger than
        // necessary StringBuffer.
        cleanup();
        return WeakIdentityMap.toString(this);
    }

    abstract Entry<K, V> newEntry(int hash, K key, V value, Entry<K, V> next);

    private Iterator createHashIterator(int type) {
        if (this.count == 0) {
            return Collections.EMPTY_SET.iterator();
        } else {
            return new HashIterator(type);
        }
    }

    /**
     * Collision list entry.
     */
    abstract static class Entry<K, V> implements Map.Entry<K, V> {
        int hash;
        K key;
        Entry<K, V> next;

        private Reference<V> value;

        Entry(int hash, K key, V value, Entry<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = newReference(value);
            this.next = next;
        }

        Entry(int hash, K key, Reference<V> value, Entry<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        // Map.Entry Ops

        public K getKey() {
            return this.key;
        }

        public V getValue() {
            V value = this.value.get();
            return value == KeyFactory.NULL ? null : value;
        }

        public V setValue(V value) {
            V oldValue = getValue();
            this.value = newReference(value == null ? ((V) KeyFactory.NULL) : value);
            return oldValue;
        }

        public boolean equals(Object obj) {
            if (!(obj instanceof Map.Entry)) {
                return false;
            }
            return equals((Map.Entry)obj);
        }

        boolean equals(Map.Entry e) {
            Object thisValue = get();
            if (thisValue == null) {
                return false;
            } else if (thisValue == KeyFactory.NULL) {
                thisValue = null;
            }
            return (this.key == null ? e.getKey() == null : this.key.equals(e.getKey())) &&
                (thisValue == null ? e.getValue() == null : thisValue.equals(e.getValue()));
        }

        public int hashCode() {
            return this.hash ^ get().hashCode();
        }

        public String toString() {
            return this.key + "=" + getValue();
        }

        protected Object clone() {
            return newEntry(this.hash, this.key, (Reference)this.value,
                            (this.next == null ? null : (Entry)this.next.clone()));
        }

        abstract Entry newEntry(int hash, K key, Reference<V> value, Entry<K, V> next);

        abstract Reference<V> newReference(V value);

        // Like getValue(), except does not convert NULL to null.
        V get() {
            return this.value.get();
        }
    }

    private class HashIterator implements Iterator {
        private final int type;
        private final Entry[] table;

        private int index;

        // To ensure that the iterator doesn't return cleared entries, keep a
        // hard reference to the value. Its existence will prevent the soft
        // value from being cleared.
        private Object entryValue;
        private Entry entry;

        private Entry last;

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        private int expectedModCount = ReferencedValueHashMap.this.modCount;

        HashIterator(int type) {
            this.table = ReferencedValueHashMap.this.table;
            this.type = type;
            this.index = table.length;
        }

        public boolean hasNext() {
            while (this.entry == null || (this.entryValue = this.entry.get()) == null) {
                if (this.entry != null) {
                    // Clean up after a cleared Reference.
                    remove(this.entry);
                    this.entry = this.entry.next;
                }

                if (this.entry == null) {
                    if (this.index <= 0) {
                        return false;
                    } else {
                        this.entry = this.table[--this.index];
                    }
                }
            }

            return true;
        }

        public Object next() {
            if (ReferencedValueHashMap.this.modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }

            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            this.last = this.entry;
            this.entry = this.entry.next;

            return this.type == WeakIdentityMap.KEYS ? this.last.getKey() :
                (this.type == WeakIdentityMap.VALUES ? this.last.getValue() : this.last);
        }

        public void remove() {
            if (this.last == null) {
                throw new IllegalStateException();
            }
            if (ReferencedValueHashMap.this.modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            remove(this.last);
            this.last = null;
        }

        private void remove(Entry toRemove) {
            Entry[] tab = this.table;
            int index = (toRemove.hash & 0x7fffffff) % tab.length;

            for (Entry e = tab[index], prev = null; e != null; e = e.next) {
                if (e == toRemove) {
                    ReferencedValueHashMap.this.modCount++;
                    expectedModCount++;
                    if (prev == null) {
                        tab[index] = e.next;
                    } else {
                        prev.next = e.next;
                    }
                    ReferencedValueHashMap.this.count--;
                    return;
                } else {
                    prev = e;
                }
            }
            throw new ConcurrentModificationException();
        }
    }
}


text:
package org.datavec.api.transform.transform.longtransform;

import lombok.Data;
import org.datavec.api.transform.MathOp;
import org.datavec.api.transform.metadata.ColumnMetaData;
import org.datavec.api.transform.metadata.LongMetaData;
import org.datavec.api.transform.transform.BaseColumnTransform;
import org.datavec.api.writable.LongWritable;
import org.datavec.api.writable.Writable;
import org.nd4j.shade.jackson.annotation.JsonProperty;

@Data
public class LongMathOpTransform extends BaseColumnTransform {

    private final MathOp mathOp;
    private final long scalar;

    public LongMathOpTransform(@JsonProperty("columnName") String columnName, @JsonProperty("mathOp") MathOp mathOp,
                    @JsonProperty("scalar") long scalar) {
        super(columnName);
        this.mathOp = mathOp;
        this.scalar = scalar;
    }

    @Override
    public ColumnMetaData getNewColumnMetaData(String newName, ColumnMetaData oldColumnType) {
        if (!(oldColumnType instanceof LongMetaData))
            throw new IllegalStateException("Column is not an Long column");
        LongMetaData meta = (LongMetaData) oldColumnType;
        Long minValue = meta.getMinAllowedValue();
        Long maxValue = meta.getMaxAllowedValue();
        if (minValue != null)
            minValue = doOp(minValue);
        if (maxValue != null)
            maxValue = doOp(maxValue);
        if (minValue != null && maxValue != null && minValue > maxValue) {
            //Consider rsub 1, with original min/max of 0 and 1: (1-0) -> 1 and (1-1) -> 0
            //Or multiplication by -1: (0 to 1) -> (-1 to 0)
            //Need to swap min/max here...
            Long temp = minValue;
            minValue = maxValue;
            maxValue = temp;
        }
        return new LongMetaData(newName, minValue, maxValue);
    }

    private long doOp(long input) {
        switch (mathOp) {
            case Add:
                return input + scalar;
            case Subtract:
                return input - scalar;
            case Multiply:
                return input * scalar;
            case Divide:
                return input / scalar;
            case Modulus:
                return input % scalar;
            case ReverseSubtract:
                return scalar - input;
            case ReverseDivide:
                return scalar / input;
            case ScalarMin:
                return Math.min(input, scalar);
            case ScalarMax:
                return Math.max(input, scalar);
            default:
                throw new IllegalStateException("Unknown or not implemented math op: " + mathOp);
        }
    }

    @Override
    public Writable map(Writable columnWritable) {
        return new LongWritable(doOp(columnWritable.toLong()));
    }

    @Override
    public String toString() {
        return "LongMathOpTransform(mathOp=" + mathOp + ",scalar=" + scalar + ")";
    }

    /**
     * Transform an object
     * in to another object
     *
     * @param input the record to transform
     * @return the transformed writable
     */
    @Override
    public Object map(Object input) {
        Number n = (Number) input;
        return doOp(n.longValue());
    }
}

redpajama_set_name: RedPajamaGithub


text:
find_cuda(${USE_CUDA} ${USE_CUDNN})

if(CUDA_FOUND)
  # always set the includedir when cuda is available
  # avoid global retrigger of cmake
  include_directories(SYSTEM ${CUDA_INCLUDE_DIRS})
endif(CUDA_FOUND)

if(USE_CUDA)
  if(NOT CUDA_FOUND)
    message(FATAL_ERROR "Cannot find CUDA, USE_CUDA=" ${USE_CUDA})
  endif()
  message(STATUS "Build with CUDA ${CUDA_VERSION} support")
  tvm_file_glob(GLOB RUNTIME_CUDA_SRCS src/runtime/cuda/*.cc)
  list(APPEND RUNTIME_SRCS ${RUNTIME_CUDA_SRCS})
  list(APPEND COMPILER_SRCS src/target/opt/build_cuda_on.cc)

  list(APPEND TVM_LINKER_LIBS ${CUDA_NVRTC_LIBRARY})
  list(APPEND TVM_RUNTIME_LINKER_LIBS ${CUDA_CUDART_LIBRARY})
  list(APPEND TVM_RUNTIME_LINKER_LIBS ${CUDA_CUDA_LIBRARY})
  list(APPEND TVM_RUNTIME_LINKER_LIBS ${CUDA_NVRTC_LIBRARY})

  if(USE_CUDNN)
    message(STATUS "Build with cuDNN support")
    include_directories(SYSTEM ${CUDA_CUDNN_INCLUDE_DIRS})
    tvm_file_glob(GLOB CONTRIB_CUDNN_SRCS src/runtime/contrib/cudnn/*.cc)
    list(APPEND RUNTIME_SRCS ${CONTRIB_CUDNN_SRCS})
    list(APPEND TVM_RUNTIME_LINKER_LIBS ${CUDA_CUDNN_LIBRARY})
  endif(USE_CUDNN)

  if(USE_CUBLAS)
    message(STATUS "Build with cuBLAS support")
    tvm_file_glob(GLOB CONTRIB_CUBLAS_SRCS src/runtime/contrib/cublas/*.cc)
    list(APPEND RUNTIME_SRCS ${CONTRIB_CUBLAS_SRCS})
    list(APPEND TVM_RUNTIME_LINKER_LIBS ${CUDA_CUBLAS_LIBRARY})
    if(NOT CUDA_CUBLASLT_LIBRARY STREQUAL "CUDA_CUBLASLT_LIBRARY-NOTFOUND")
      list(APPEND TVM_RUNTIME_LINKER_LIBS ${CUDA_CUBLASLT_LIBRARY})
    endif()
  endif(USE_CUBLAS)

  if(USE_THRUST)
    message(STATUS "Build with Thrust support")
    cmake_minimum_required(VERSION 3.13) # to compile CUDA code
    enable_language(CUDA)
    set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --expt-extended-lambda")
    tvm_file_glob(GLOB CONTRIB_THRUST_SRC src/runtime/contrib/thrust/*.cu)
    list(APPEND RUNTIME_SRCS ${CONTRIB_THRUST_SRC})
  endif(USE_THRUST)

  if(USE_GRAPH_EXECUTOR_CUDA_GRAPH)
    if(NOT USE_GRAPH_EXECUTOR)
      message(FATAL_ERROR "CUDA Graph is only supported by graph executor, please set USE_GRAPH_EXECUTOR=ON")
    endif()
    if(CUDAToolkit_VERSION_MAJOR LESS "10")
      message(FATAL_ERROR "CUDA Graph requires CUDA 10 or above, got=" ${CUDAToolkit_VERSION})
    endif()
    message(STATUS "Build with Graph executor with CUDA Graph support...")
    tvm_file_glob(GLOB RUNTIME_CUDA_GRAPH_SRCS src/runtime/graph_executor/cuda_graph/*.cc)
    list(APPEND RUNTIME_SRCS ${RUNTIME_CUDA_GRAPH_SRCS})
  endif()
else(USE_CUDA)
  list(APPEND COMPILER_SRCS src/target/opt/build_cuda_off.cc)
endif(USE_CUDA)


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.03.26 at 05:36:33 PM IST
//

package com.emc.cto.ridagent.rid.jaxb;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for duration-type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="duration-type">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
 *     <enumeration value="second"/>
 *     <enumeration value="minute"/>
 *     <enumeration value="hour"/>
 *     <enumeration value="day"/>
 *     <enumeration value="month"/>
 *     <enumeration value="quarter"/>
 *     <enumeration value="year"/>
 *     <enumeration value="ext-value"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "duration-type")
@XmlEnum
public enum DurationType {

    @XmlEnumValue("second")
    SECOND("second"),
    @XmlEnumValue("minute")
    MINUTE("minute"),
    @XmlEnumValue("hour")
    HOUR("hour"),
    @XmlEnumValue("day")
    DAY("day"),
    @XmlEnumValue("month")
    MONTH("month"),
    @XmlEnumValue("quarter")
    QUARTER("quarter"),
    @XmlEnumValue("year")
    YEAR("year"),
    @XmlEnumValue("ext-value")
    EXT_VALUE("ext-value");
    private final String value;

    DurationType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static DurationType fromValue(String v) {
        for (DurationType c: DurationType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
package org.clulab.learning

import org.scalatest._

/**
 *
 * User: mihais
 * Date: 12/10/13
 */
class TestRandomForestClassifier extends FlatSpec with Matchers {
  "RFClassifier" should "work with BVFDataset" in {
    val classifier = new RFClassifier[String, String](numTrees = 1, trainBagPct = 1.0, howManyFeaturesPerNode = RFClassifier.featuresPerNodeAll)
    val dataset = new BVFDataset[String, String]()

    val d1 = new BVFDatum[String, String]("+", List("good", "good", "great"))
    val d2 = new BVFDatum[String, String]("-", List("good", "good", "bad", "awful"))
    val d3 = new BVFDatum[String, String]("-", List("good", "horrible"))
    dataset += d1
    dataset += d2
    dataset += d3

    classifier.verbose = true
    classifier.train(dataset)

    classOf(classifier, List("good", "horrible")) should be ("-")
    classOf(classifier, List("bad", "horrible")) should be ("-")
    classOf(classifier, List("good", "great")) should be ("+")
  }

  "RandomForestClassifier" should "have an accuracy > .95 on this dataset" in {
    //val classifier = new RandomForestClassifier[Int, String](numTrees = 50, maxTreeDepth = 0)
    val classifier = new RFClassifier[Int, String]

    var dataset = RVFDataset.mkDatasetFromSvmLightResource("org/clulab/learning/classification_train.txt.gz").asInstanceOf[Dataset[Int, String]]
    dataset = dataset.removeFeaturesByInformationGain(0.75)
    classifier.train(dataset)

    val datums = RVFDataset.mkDatumsFromSvmLightResource("org/clulab/learning/classification_test.txt.gz")
    var total = 0
    var correct = 0
    for(datum <- datums) {
      val l = classifier.classOf(datum)
      //println(s"prediction: $l")
      if(l == datum.label) correct += 1
      total += 1
    }
    val acc = correct.toDouble / total.toDouble
    println("Accuracy: " + acc)
    acc should be >= 0.955
  }

  def classOf(c:RFClassifier[String, String], feats:List[String]):String = {
    val d = new BVFDatum[String, String]("?", feats)
    val l = c.classOf(d)
    println(s"Class of $feats: $l")
    l
  }

}


text:
from utils import filter

class Button:

	text = ""
	onclick = ""
	href = ""

	def __init__(self, text, onclick="", href=""):
		self.text = filter.filter(text)
		self.onclick = onclick
		self.href = href

	def reparse(self):
		self.text = filter.filter(self.text)

	def getRaw(self):
		if self.href == "":
			return "<button onclick='" + self.onclick + "'>" + self.text + "</button>"
		else:
			return "<button onclick='" + self.onclick + "'>" + self.text + "</button>"


text:
namespace Conf {
	void Init(int argc, char* argv[]);

	YAML::Node Get(const std::string& k);
	std::string GetStr(const std::string& k);
};


text:
Router.onBeforeAction(function () {
  if (!Meteor.userId()) {
    this.layout('loginLayout');
    this.render('login',{
    	data: function() {
    		return {title: 'Login'};
    	}
    });
  } else {
    this.next();
  }
});

Router.configure({
  layoutTemplate: 'appLayout'
});

Router.route('/', function(){
  Meteor.subscribe('games');

  this.render('gameList', {
    data: function(){
      return {
        activeGames: function () {
          return Games.find({state: 0});
        },
        inactiveGames: function () {
          return Games.find({state: 1});
        }
      }
    }
  });
  this.render('newGameButton', {to: 'header'});
});

Router.route('/games', function(){
	this.redirect('/');
});

Router.route('/games/new', function(){
	var cake = randomCake();
  this.render('gameNew', {
  	data: {
  		placeholder: cake
  	}
  });
});

Router.route('/games/:id', function(route){
  Meteor.subscribe('game', this.params.id);
  Meteor.subscribe('users');
  Meteor.subscribe('guesses');

  this.render('gameView', {
    data: function(){
      var game = Games.findOne();
      if (game) {
        game.suggestion = randomCake();
        game.isOwner = (game.owner) ? game.owner._id == Meteor.userId() : false;
        game.guesses = Guesses.find({ game_id: game._id, "user._id": {$ne: Meteor.userId()} }, {sort: {state: -1} } );
        game.yourGuess = Guesses.findOne({ game_id: game._id, "user._id": Meteor.userId() });
        game.winners = Guesses.find({ game_id: game._id, state: 1 });
        return game;
      }
    }
  });
});


text:
import { Injectable, Inject, Optional } from "@angular/core";
import { DomHelper } from "./dom.helper";
import { FluentApiCall } from "./fluent.api.call";
import { AsyncSubject } from "rxjs/AsyncSubject";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Observer } from "rxjs/Observer";
import { Observable } from "rxjs/Observable";
import { switchMap } from "rxjs/operators";

@Injectable()
export class LinkedInService {
    /**
     * An observable that emits true and completes when library has finished loading.
     */
    public isInitialized$: Observable<boolean>;
    /**
     * An observable that has an initial value of undefined.
     * It emits a boolean value when the library has finished loading and when a login or logout is performed.
     */
    public isUserAuthenticated$: BehaviorSubject<boolean>;

    private _authorize: boolean;
    private _initializationStateSource: AsyncSubject<boolean>;
    private _sdkIN: any = undefined;

    public constructor(
        private _domHelper: DomHelper,
        @Inject("window") private _window: any,
        @Inject("apiKey") private _apiKey: string,
        @Inject("authorize")
        @Optional()
        authorize?: boolean,
        @Inject("isServer")
        @Optional()
        isServer?: boolean
    ) {
        this._authorize = authorize || false;
        this._initializationStateSource = new AsyncSubject<boolean>();
        this.isInitialized$ = this._initializationStateSource.asObservable();
        this.isUserAuthenticated$ = new BehaviorSubject(undefined);
        // Load Linkedin SDK once the service is provided
        this._domHelper.insertLinkedInScriptElement(
            () => this._onLibraryLoadedAndInitialized(),
            this._apiKey,
            this._authorize,
            isServer
        );
    }

    /**
     * Gets the IN variable from the LinkedIN SDK.
     */
    public getSdkIN(): any {
        return this._sdkIN;
    }

    /**
     * Log a member in. If the user is not logged in,
     * it will present the popup authorization window.
     */
    public login() {
        return this.isInitialized$.pipe(
            switchMap(() => {
                return Observable.create((observer: Observer<boolean>) => {
                    this._window.IN.User.authorize(() => {
                        observer.next(true);
                        observer.complete();
                    });
                });
            })
        );
    }

    /**
     * Log a member out. Logging the member out is defined as logging them out of
     * the LinkedIn network (i.e. clearing cookies). This does not revoke or
     * delete the user's authorization grant for your application.
     */
    public logout() {
        return this.isInitialized$.pipe(
            switchMap(() => {
                return Observable.create((observer: Observer<void>) => {
                    this._window.IN.User.logout(() => {
                        observer.next(undefined);
                        observer.complete();
                    });
                });
            })
        );
    }

    /**
     * Refreshes a member token for an additional 30 minutes.
     * Repeated continual use of the refresh() function to keep a member indefinitely
     * logged in can result in your application being disabled.  Use this call sparingly.
     */
    public refresh() {
        return this.isInitialized$.pipe(
            switchMap(() => {
                return Observable.create((observer: Observer<any>) => {
                    this._window.IN.User.refresh();
                    observer.next(undefined);
                    observer.complete();
                });
            })
        );
    }

    /**
     * Enables authenticated calls to the LinkedIn REST API using the generic call wrapper.
     * @param url The API URL to invoke: should not include https://api.linkedin.com/v1.
     */
    public raw(url: string): FluentApiCall {
        return new FluentApiCall(this.isInitialized$, this._window, url);
    }

    private _getIsAuthorized() {
        return this._window.IN.User.isAuthorized();
    }

    private _onLibraryLoadedAndInitialized() {
        this._initializationStateSource.next(true);
        this._initializationStateSource.complete();
        this.isUserAuthenticated$.next(this._getIsAuthorized());
        this._setEventsOn();
        this._sdkIN = this._window.IN;
    }

    private _setEventsOn() {
        this._window.IN.Event.on(this._window.IN, "auth", () => {
            this.isUserAuthenticated$.next(true);
        });
        this._window.IN.Event.on(this._window.IN, "logout", () => {
            this.isUserAuthenticated$.next(false);
        });
    }
}


text:
package com.dylan.recom.offline;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.dylan.recom.common.ItemSimilarity;
import com.dylan.recom.common.RedisUtil;
import org.apache.mahout.cf.taste.similarity.precompute.SimilarItem;
import org.apache.mahout.cf.taste.similarity.precompute.SimilarItems;
import org.apache.mahout.cf.taste.similarity.precompute.SimilarItemsWriter;
import redis.clients.jedis.Jedis;

// generate item-item similarity table
public class ItemsSimilarityTableRedisWriter implements SimilarItemsWriter {
  private long itemCounter = 0;
  private Jedis jedis = null;
  @Override
  public void open() throws IOException {
    jedis = RedisUtil.getJedis();
  }

  @Override
  public void add(SimilarItems similarItems) throws IOException {
    ItemSimilarity[] values = new ItemSimilarity[similarItems.numSimilarItems()];
    int counter = 0;
    for (SimilarItem item: similarItems.getSimilarItems()) {
      values[counter] = new ItemSimilarity(item.getItemID(), item.getSimilarity());
      counter++;
    }
    String key = "II:" + similarItems.getItemID();
    String items = JSON.toJSONString(values);
    jedis.set(key, items);
    itemCounter++;
    if(itemCounter % 100 == 0) {
      System.out.println("Store " + key + " to redis, total:" + itemCounter);
    }
  }

  @Override
  public void close() throws IOException {
    jedis.close();
  }
}


text:
from django.contrib.auth import get_user_model
from django.core import serializers
from django.test import TestCase

from chemtrails.contrib.permissions.models import AccessRule
from chemtrails.contrib.permissions.utils import get_content_type
from tests.utils import TestCaseMixins

USER_MODEL = get_user_model()

class JSONFieldTestCase(TestCase, TestCaseMixins):

    def test_field_is_json_serializable(self):
        instance = AccessRule.objects.create(ctype_source=get_content_type(USER_MODEL),
                                             ctype_target=get_content_type(USER_MODEL),
                                             relation_types=[
                                                 {'GROUPS': None}
                                             ])
        json = serializers.serialize('json', [instance])
        self.assertIsJSON(json)


text:
"""Functional test for moving_averages.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
from tensorflow.python.ops import state_ops
from tensorflow.python.training import moving_averages

class MovingAveragesTest(tf.test.TestCase):

  def testAssignMovingAverage(self):
    with self.test_session():
      var = tf.Variable([10.0, 11.0])
      val = tf.constant([1.0, 2.0], tf.float32)
      decay = 0.25
      assign = moving_averages.assign_moving_average(var, val, decay)
      tf.initialize_all_variables().run()
      self.assertAllClose([10.0, 11.0], var.eval())
      assign.op.run()
      self.assertAllClose([10.0 * 0.25 + 1.0 * (1.0 - 0.25),
                           11.0 * 0.25 + 2.0 * (1.0 - 0.25)],
                          var.eval())

  def testWeightedMovingAverage(self):
    with self.test_session() as sess:
      decay = 0.5
      weight = tf.placeholder(tf.float32, [])
      val = tf.placeholder(tf.float32, [])

      wma = moving_averages.weighted_moving_average(val, decay, weight)
      tf.initialize_all_variables().run()

      # Get the first weighted moving average.
      val_1 = 3.0
      weight_1 = 4.0
      wma_array = sess.run(
          wma, feed_dict={val: val_1, weight: weight_1})
      numerator_1 = val_1 * weight_1 * (1.0 - decay)
      denominator_1 = weight_1 * (1.0 - decay)
      self.assertAllClose(numerator_1 / denominator_1, wma_array)

      # Get the second weighted moving average.
      val_2 = 11.0
      weight_2 = 22.0
      wma_array = sess.run(
          wma, feed_dict={val: val_2, weight: weight_2})
      numerator_2 = numerator_1 * decay + val_2 * weight_2 * (1.0 - decay)
      denominator_2 = denominator_1 * decay + weight_2 * (1.0 - decay)
      self.assertAllClose(numerator_2 / denominator_2, wma_array)

def _Repeat(value, dim):
  if dim == 1:
    return value
  return [value] * dim

class ExponentialMovingAverageTest(tf.test.TestCase):

  def _CheckDecay(self, ema, actual_decay, dim):
    tens = _Repeat(10.0, dim)
    thirties = _Repeat(30.0, dim)
    var0 = tf.Variable(tens, name="v0")
    var1 = tf.Variable(thirties, name="v1")
    tf.initialize_all_variables().run()
    # Note that tensor2 is not a Variable but just a plain Tensor resulting
    # from the sum operation.
    tensor2 = var0 + var1
    update = ema.apply([var0, var1, tensor2])
    avg0 = ema.average(var0)
    avg1 = ema.average(var1)
    avg2 = ema.average(tensor2)

    self.assertItemsEqual([var0, var1], tf.moving_average_variables())

    self.assertFalse(avg0 in tf.trainable_variables())
    self.assertFalse(avg1 in tf.trainable_variables())
    self.assertFalse(avg2 in tf.trainable_variables())
    tf.initialize_all_variables().run()

    self.assertEqual("v0/ExponentialMovingAverage:0", avg0.name)
    self.assertEqual("v1/ExponentialMovingAverage:0", avg1.name)
    self.assertEqual("add/ExponentialMovingAverage:0", avg2.name)

    # Check initial values.
    self.assertAllClose(tens, var0.eval())
    self.assertAllClose(thirties, var1.eval())
    self.assertAllClose(_Repeat(10.0 + 30.0, dim), tensor2.eval())

    # Check that averages are initialized correctly.
    self.assertAllClose(tens, avg0.eval())
    self.assertAllClose(thirties, avg1.eval())
    # Note that averages of Tensor's initialize to zeros_like since no value
    # of the Tensor is known because the Op has not been run (yet).
    self.assertAllClose(_Repeat(0.0, dim), avg2.eval())

    # Update the averages and check.
    update.run()
    dk = actual_decay

    expected = _Repeat(10.0 * dk + 10.0 * (1 - dk), dim)
    self.assertAllClose(expected, avg0.eval())
    expected = _Repeat(30.0 * dk + 30.0 * (1 - dk), dim)
    self.assertAllClose(expected, avg1.eval())
    expected = _Repeat(0.0 * dk + (10.0 + 30.0) * (1 - dk), dim)
    self.assertAllClose(expected, avg2.eval())

    # Again, update the averages and check.
    update.run()
    expected = _Repeat((10.0 * dk + 10.0 * (1 - dk)) * dk + 10.0 * (1 - dk),
                       dim)
    self.assertAllClose(expected, avg0.eval())
    expected = _Repeat((30.0 * dk + 30.0 * (1 - dk)) * dk + 30.0 * (1 - dk),
                       dim)
    self.assertAllClose(expected, avg1.eval())
    expected = _Repeat(((0.0 * dk + (10.0 + 30.0) * (1 - dk)) * dk +
                        (10.0 + 30.0) * (1 - dk)),
                       dim)
    self.assertAllClose(expected, avg2.eval())

  def testAverageVariablesNoNumUpdates_Scalar(self):
    with self.test_session():
      ema = tf.train.ExponentialMovingAverage(0.25)
      self._CheckDecay(ema, actual_decay=0.25, dim=1)

  def testAverageVariablesNoNumUpdates_Vector(self):
    with self.test_session():
      ema = tf.train.ExponentialMovingAverage(0.25)
      self._CheckDecay(ema, actual_decay=0.25, dim=5)

  def testAverageVariablesNumUpdates_Scalar(self):
    with self.test_session():
      # With num_updates 1, the decay applied is 0.1818
      ema = tf.train.ExponentialMovingAverage(0.25, num_updates=1)
      self._CheckDecay(ema, actual_decay=0.181818, dim=1)

  def testAverageVariablesNumUpdates_Vector(self):
    with self.test_session():
      # With num_updates 1, the decay applied is 0.1818
      ema = tf.train.ExponentialMovingAverage(0.25, num_updates=1)
      self._CheckDecay(ema, actual_decay=0.181818, dim=5)

  def testAverageVariablesWithControlDeps(self):
    with self.test_session() as sess:
      v0 = tf.Variable(0, name="v0")
      add_to_v0 = v0.assign_add(1)
      v1 = tf.Variable([10.0], name="v1")
      assign_to_v1 = v1.assign([20.0])
      ema = tf.train.ExponentialMovingAverage(0.25)
      with tf.control_dependencies([add_to_v0]):
        ema_op = ema.apply([v1])
      # the moving average of v1 should not have any control inputs
      v1_avg = ema.average(v1)
      self.assertEqual([], v1_avg.initializer.control_inputs)
      self.assertEqual([], v1_avg.value().op.control_inputs)
      self.assertEqual([], v1_avg.ref().op.control_inputs)
      # We should be able to initialize v1_avg before v0.
      sess.run(v1_avg.initializer)
      sess.run(v0.initializer)
      self.assertEqual([10.0], sess.run(v1_avg))
      # running ema_op should add to v0 (in addition to updating v1_avg)
      sess.run(assign_to_v1)
      sess.run(ema_op)
      self.assertEqual(1, sess.run(v0))
      self.assertEqual([17.5], sess.run(v1_avg))

  def testAverageVariablesNames(self):
    v0 = tf.Variable(10.0, name="v0")
    v1 = tf.Variable(30.0, name="v1")
    # Add a non-trainable variable.
    v2 = tf.Variable(20.0, name="v2", trainable=False)
    tensor2 = v0 + v1
    ema = tf.train.ExponentialMovingAverage(0.25, name="foo_avg")
    self.assertEqual("v0/foo_avg", ema.average_name(v0))
    self.assertEqual("v1/foo_avg", ema.average_name(v1))
    self.assertEqual("add/foo_avg", ema.average_name(tensor2))
    ema.apply([v0, v1, tensor2])
    vars_to_restore = ema.variables_to_restore()
    # vars_to_restore should contain the following:
    # {v0/foo_avg : v0,
    #  v1/foo_avg : v1,
    #  add/foo_avg : add/foo_avg
    #  v2 : v2}
    self.assertEqual(sorted(vars_to_restore.keys()),
                     sorted([ema.average_name(v0),
                             ema.average_name(v1),
                             ema.average_name(tensor2),
                             v2.op.name]))
    self.assertEqual(ema.average_name(v0), ema.average(v0).op.name)
    self.assertEqual(ema.average_name(v1), ema.average(v1).op.name)
    self.assertEqual(ema.average_name(tensor2), ema.average(tensor2).op.name)

  def testAverageVariablesDeviceAssignment(self):
    with tf.device("/job:dev_v0"):
      v0 = tf.Variable(10.0, name="v0")
    with tf.device("/job:dev_v1"):
      v1 = state_ops.variable_op(shape=[1], dtype=tf.float32, name="v1")
    tensor2 = v0 + v1
    ema = tf.train.ExponentialMovingAverage(0.25, name="foo_avg")
    with tf.device("/job:default"):
      ema.apply([v0, v1, tensor2])
    self.assertDeviceEqual("/job:dev_v0", ema.average(v0).device)
    self.assertDeviceEqual("/job:dev_v1", ema.average(v1).device)
    # However, the colocation property is maintained.
    self.assertEqual([b"loc:@v1"],
                     ema.average(v1).op.colocation_groups())
    self.assertDeviceEqual("/job:default", ema.average(tensor2).device)

if __name__ == "__main__":
  tf.test.main()


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

namespace _17_vegetableMarket
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the price of the vegetables?: ");
            double vegetablePrice = double.Parse(Console.ReadLine());
            Console.Write("Enter the price of the fruits?: ");
            double fruitsPrice = double.Parse(Console.ReadLine());
            Console.Write("Enter how many weight are the vegetables?: ");
            double vegetableWeight = double.Parse(Console.ReadLine());
            Console.Write("Enter how many weight are the fruits?: ");
            double fruitsWeight = double.Parse(Console.ReadLine());

            double vegetableProfit = (vegetablePrice * vegetableWeight)/1.94;
            double fruitProfit = (fruitsWeight*fruitsPrice) / 1.94;
            Console.WriteLine($"Your total profit in EUR will be { Math.Round(vegetableProfit + fruitProfit, 2)}!!!");
            Console.ReadLine();

        }
    }
}


text:
{% load staticfiles %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script>


text:
Bot per ottenere informazioni sulle aule libere al Politecnico di Torino

[@polito_aule_bot](https://t.me/polito_aule_bot)

## Dettagli

Il bot riceve le frasi, le invia a [wit.ai](https://wit.ai/) ed estrae intento ed entità.

I dati vengono ricavati in tempo reale dal sito del Politecnico.


text:
package ucar.nc2.internal.dataset.conv;

import java.io.IOException;
import ucar.nc2.Attribute;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.VariableDS;
import ucar.nc2.dataset.spi.CoordSystemBuilderFactory;
import ucar.nc2.internal.dataset.CoordSystemBuilder;
import ucar.nc2.internal.dataset.CoordSystemFactory;
import ucar.nc2.internal.ncml.NcmlReader;
import ucar.nc2.util.CancelTask;

/**
 * GEIF Convention.
 * https://www.metnet.navy.mil/~hofschnr/GIEF-F/1.2/
 */
public class GIEFConvention extends CoordSystemBuilder {
  private static final String CONVENTION_NAME = "GIEF";

  GIEFConvention(NetcdfDataset.Builder datasetBuilder) {
    super(datasetBuilder);
    this.conventionName = CONVENTION_NAME;
  }

  @Override
  protected void augmentDataset(CancelTask cancelTask) throws IOException {
    NcmlReader.wrapNcmlResource(datasetBuilder, CoordSystemFactory.resourcesDir + "GIEF.ncml", cancelTask);

    Dimension timeDim = rootGroup.findDimension("time").orElse(null);
    VariableDS.Builder base_time = (VariableDS.Builder) rootGroup.findVariableLocal("base_time").orElse(null);
    VariableDS.Builder time_offset = (VariableDS.Builder) rootGroup.findVariableLocal("time_offset").orElse(null);

    Variable.Builder timeVar =
        rootGroup.findVariableLocal("time").orElseThrow(() -> new IllegalStateException("must have time variable"));
    String time_units = rootGroup.getAttributeContainer().findAttributeString("time_units", null);
    timeVar.addAttribute(new Attribute(CDM.UNITS, time_units));

    Variable.Builder levelVar =
        rootGroup.findVariableLocal("level").orElseThrow(() -> new IllegalStateException("must have level variable"));
    String level_units = rootGroup.getAttributeContainer().findAttributeString("level_units", null);
    String level_name = rootGroup.getAttributeContainer().findAttributeString("level_name", null);
    levelVar.addAttribute(new Attribute(CDM.UNITS, level_units));
    levelVar.addAttribute(new Attribute(CDM.LONG_NAME, level_name));

    // may be 1 or 2 data variables
    String unit_name = rootGroup.getAttributeContainer().findAttributeString("unit_name", null);
    String parameter_name = rootGroup.getAttributeContainer().findAttributeString("parameter_name", null);
    for (Variable.Builder v : rootGroup.vbuilders) {
      if (v.getRank() > 1) {
        v.addAttribute(new Attribute(CDM.UNITS, unit_name));
        v.addAttribute(new Attribute(CDM.LONG_NAME, v.shortName + " " + parameter_name));
        v.addAttribute(new Attribute(_Coordinate.Axes, "time level latitude longitude"));
      }
    }

    Attribute translation = rootGroup.getAttributeContainer().findAttributeIgnoreCase("translation");
    Attribute affine = rootGroup.getAttributeContainer().findAttributeIgnoreCase("affine_transformation");

    // LOOK only handling the 1D case
    // add lat
    double startLat = translation.getNumericValue(1).doubleValue();
    double incrLat = affine.getNumericValue(6).doubleValue();
    Variable.Builder latVar = rootGroup.findVariableLocal("latitude")
        .orElseThrow(() -> new IllegalStateException("must have latitude variable"));
    latVar.setAutoGen(startLat, incrLat);

    // add lon
    double startLon = translation.getNumericValue(0).doubleValue();
    double incrLon = affine.getNumericValue(3).doubleValue();
    Variable.Builder lonVar = rootGroup.findVariableLocal("longitude")
        .orElseThrow(() -> new IllegalStateException("must have longitude variable"));
    lonVar.setAutoGen(startLon, incrLon);
  }

  public static class Factory implements CoordSystemBuilderFactory {
    @Override
    public String getConventionName() {
      return CONVENTION_NAME;
    }

    @Override
    public CoordSystemBuilder open(NetcdfDataset.Builder datasetBuilder) {
      return new GIEFConvention(datasetBuilder);
    }
  }

}