text:
/**
    @fileOverview Hash Array Mapped Trie.

    Code based on: https://github.com/exclipy/pdata
*/
const hamt = {}; // export

/* Configuration
 ******************************************************************************/
const SIZE = 5;

const BUCKET_SIZE = Math.pow(2, SIZE);

const MASK = BUCKET_SIZE - 1;

const MAX_INDEX_NODE = BUCKET_SIZE / 2;

const MIN_ARRAY_NODE = BUCKET_SIZE / 4;

/*
 ******************************************************************************/
const defaultValBind = (f, defaultValue) =>
    function(x) {
        return f(arguments.length === 0 ? defaultValue : x);
    };

/**
    Get 32 bit hash of string.

    Based on:
    http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
*/
const hash = hamt.hash = str => {
    const type = typeof str;
    if (type === 'number')
        return str;
    if (type !== 'string')
        str += '';

    let hash = 0;
    for (let i = 0, len = str.length; i < len; ++i) {
        const c = str.charCodeAt(i);
        hash = (((hash << 5) - hash) + c) | 0;
    }
    return hash;
};

/* Bit Ops
 ******************************************************************************/
/**
    Hamming weight.

    Taken from: http://jsperf.com/hamming-weight
*/
const popcount = (x) => {
    x -= ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0f0f0f0f;
    x += (x >> 8);
    x += (x >> 16);
    return (x & 0x7f);
};

const hashFragment = (shift, h) =>
    (h >>> shift) & MASK;

const toBitmap = x =>
    1 << x;

const fromBitmap = (bitmap, bit) =>
    popcount(bitmap & (bit - 1));

/* Array Ops
 ******************************************************************************/
/**
    Set a value in an array.

    @param at Index to change.
    @param v New value
    @param arr Array.
*/
const arrayUpdate = (at, v, arr) => {
    const len = arr.length;
    const out = new Array(len);
    for (let i = 0; i < len; ++i)
        out[i] = arr[i];
    out[at] = v;
    return out;
};

/**
    Remove a value from an array.

    @param at Index to remove.
    @param arr Array.
*/
const arraySpliceOut = (at, arr) => {
    const len = arr.length;
    const out = new Array(len - 1);
    let i = 0, g = 0;
    while (i < at)
        out[g++] = arr[i++];
    ++i;
    while (i < len)
        out[g++] = arr[i++];
    return out;
};

/**
    Insert a value into an array.

    @param at Index to insert at.
    @param v Value to insert,
    @param arr Array.
*/
const arraySpliceIn = (at, v, arr) => {
    const len = arr.length;
    const out = new Array(len + 1);
    let i = 0, g = 0;
    while (i < at)
        out[g++] = arr[i++];
    out[g++] = v;
    while (i < len)
        out[g++] = arr[i++];
    return out;
};

/* Node Structures
 ******************************************************************************/
const LEAF = 1;
const COLLISION = 2;
const INDEX = 3;
const ARRAY = 4;

/**
    Leaf holding a value.

    @member hash Hash of key.
    @member key Key.
    @member value Value stored.
*/
const Leaf = (hash, key, value) => ({
    type: LEAF,
    hash,
    key,
    value,
    _modify: Leaf__modify
});

/**
    Leaf holding multiple values with the same hash but different keys.

    @member hash Hash of key.
    @member children Array of collision children node.
*/
const Collision = (hash, children) => ({
    type: COLLISION,
    hash,
    children,
    _modify: Collision__modify
});

/**
    Internal node with a sparse set of children.

    Uses a bitmap and array to pack children.

    @member mask Bitmap that encode the positions of children in the array.
    @member children Array of child nodes.
*/
const IndexedNode = (mask, children) => ({
    type: INDEX,
    mask,
    children,
    _modify: IndexedNode__modify
});

/**
    Internal node with many children.

    @member size Number of children.
    @member children Array of child nodes.
*/
const ArrayNode = (size, children) => ({
    type: ARRAY,
    size,
    children,
    _modify: ArrayNode__modify
});

/**
    Is `node` a leaf node?
*/
const isLeaf = node =>
    (node.type === LEAF || node.type === COLLISION);

/* Internal node operations.
 ******************************************************************************/
/**
    Expand an indexed node into an array node.

    @param frag Index of added child.
    @param child Added child.
    @param mask Index node mask before child added.
    @param subNodes Index node children before child added.
*/
const expand = (frag, child, bitmap, subNodes) => {
    const arr = [];
    let bit = bitmap;
    let count = 0;
    for (let i = 0; bit; ++i) {
        if (bit & 1)
            arr[i] = subNodes[count++];
        bit >>>= 1;
    }
    arr[frag] = child;
    return ArrayNode(count + 1, arr);
};

/**
    Collapse an array node into a indexed node.

    @param count Number of elements in new array.
    @param removed Index of removed element.
    @param elements Array node children before remove.
*/
const pack = (count, removed, elements) => {
    const children = new Array(count - 1);
    let g = 0;
    let bitmap = 0;
    for (let i = 0, len = elements.length; i < len; ++i) {
        if (i !== removed) {
            const elem = elements[i];
            if (elem) {
                children[g++] = elem;
                bitmap |= 1 << i;
            }
        }
    }
    return IndexedNode(bitmap, children);
};

/**
    Merge two leaf nodes.

    @param shift Current shift.
    @param h1 Node 1 hash.
    @param n1 Node 1.
    @param h2 Node 2 hash.
    @param n2 Node 2.
*/
const mergeLeaves = (shift, h1, n1, h2, n2) => {
    if (h1 === h2)
        return Collision(h1, [n2, n1]);

    const subH1 = hashFragment(shift, h1);
    const subH2 = hashFragment(shift, h2);
    return IndexedNode(toBitmap(subH1) | toBitmap(subH2),
        subH1 === subH2
            ? [mergeLeaves(shift + SIZE, h1, n1, h2, n2)]
            : subH1 < subH2 ? [n1, n2] : [n2, n1]);
};

/**
    Update an entry in a collision list.

    @param hash Hash of collision.
    @param list Collision list.
    @param op Update operation.
    @param k Key to update.
    @param size Size reference
*/
const updateCollisionList = (h, list, op, k, size) => {
    const len = list.length;
    for (let i = 0; i < len; ++i) {
        const child = list[i];
        if (child.key === k) {
            const value = child.value;
            if (op.__hamt_delete_op) {
                --size.value
                return arraySpliceOut(i, list);
            }
            const newValue = op.__hamt_set_op ? op.value : op(value);
            if (newValue === value)
                return list;
            return arrayUpdate(i, Leaf(h, k, newValue), list);
        }
    }

    if (op.__hamt_delete_op)
        return list;
    const newValue = op.__hamt_set_op ? op.value : op();
    ++size.value;
    return arrayUpdate(len, Leaf(h, k, newValue), list);
};

/* Editing
 ******************************************************************************/
const Leaf__modify = function(shift, op, h, k, size) {
    if (k === this.key) {
        if (op.__hamt_delete_op) {
            --size.value;
            return undefined;
        }
        const currentValue = this.value;
        const newValue = op.__hamt_set_op ? op.value : op(currentValue);
        return newValue === currentValue ? this : Leaf(h, k, newValue);
    }
    if (op.__hamt_delete_op)
        return this;
    const newValue = op.__hamt_set_op ? op.value : op();
    ++size.value;
    return mergeLeaves(shift, this.hash, this, h, Leaf(h, k, newValue));
};

const Collision__modify = function(shift, op, h, k, size) {
    if (h === this.hash) {
        const list = updateCollisionList(this.hash, this.children, op, k, size);
        if (list === this.children)
            return this;

        return list.length > 1
            ? Collision(this.hash, list)
            : list[0]; // collapse single element collision list
    }
    if (op.__hamt_delete_op)
        return this;
    const newValue = op.__hamt_set_op ? op.value : op();
    ++size.value;
    return mergeLeaves(shift, this.hash, this, h, Leaf(h, k, newValue));
};

const IndexedNode__modify = function(shift, op, h, k, size) {
    const mask = this.mask;
    const children = this.children;
    const frag = hashFragment(shift, h);
    const bit = toBitmap(frag);
    const indx = fromBitmap(mask, bit);
    const exists = mask & bit;
    if (!exists) { // add
        const newChild = empty__modify(shift + SIZE, op, h, k, size);
        if (!newChild)
            return this;

        return children.length >= MAX_INDEX_NODE
            ? expand(frag, newChild, mask, children)
            : IndexedNode(
                mask | bit,
                arraySpliceIn(indx, newChild, children));
    }

    const current = children[indx];
    const newChild = current._modify(shift + SIZE, op, h, k, size);
    if (current === newChild)
        return this;

    if (!newChild) { // remove
        const bitmap = mask & ~bit;
        if (!bitmap)
            return undefined;

        return children.length === 2 && isLeaf(children[indx ^ 1])
            ? children[indx ^ 1] // collapse
            : IndexedNode(
                bitmap,
                arraySpliceOut(indx, children));
    }

    // modify
    return op.__hamt_delete_op && children.length === 1 && isLeaf(newChild)
        ? newChild // propagate collapse
        : IndexedNode(
            mask,
            arrayUpdate(indx, newChild, children));
};

const ArrayNode__modify = function(shift, op, h, k, size) {
    const count = this.size;
    const children = this.children;
    const frag = hashFragment(shift, h);
    const child = children[frag];
    const newChild = child ? child._modify(shift + SIZE, op, h, k, size) : empty__modify(shift + SIZE, op, h, k, size);

    if (child === newChild)
        return this;

    if (!child && newChild) { // add
        return ArrayNode(
            count + 1,
            arrayUpdate(frag, newChild, children))
    }
    if (child && !newChild) { // remove
        return count - 1 <= MIN_ARRAY_NODE
            ? pack(count, frag, children)
            : ArrayNode(
                count - 1,
                arrayUpdate(frag, undefined, children))
    }

    // modify
    return ArrayNode(
        count,
        arrayUpdate(frag, newChild, children));
};

const empty__modify = (_, op, h, k, size) => {
    if (op.__hamt_delete_op)
        return undefined;
    const newValue = op.__hamt_set_op ? op.value : op();
    ++size.value;
    return Leaf(h, k, newValue);
};

/*
 ******************************************************************************/
function Map(root, size) {
    this.root = root;
    this.size = size;
};

Map.prototype.__hamt_isMap = true;

Map.prototype.setTree = function(root, size) {
    return root === this.root ? this : new Map(root, size);
};

/* Queries
 ******************************************************************************/
/**
    Lookup the value for `key` in `map` using a custom `hash`.

    Returns the value or `alt` if none.
*/
const tryGetHash = hamt.tryGetHash = (alt, hash, key, map) => {
    if (!map.root)
        return alt;

    let node = map.root;
    let shift = 0;
    while (true) switch (node.type) {
        case LEAF:
            {
                return key === node.key ? node.value : alt;
            }
        case COLLISION:
            {
                if (hash === node.hash) {
                    const children = node.children;
                    for (let i = 0, len = children.length; i < len; ++i) {
                        const child = children[i];
                        if (key === child.key)
                            return child.value;
                    }
                }
                return alt;
            }
        case INDEX:
            {
                const frag = hashFragment(shift, hash);
                const bit = toBitmap(frag);
                if (node.mask & bit) {
                    node = node.children[fromBitmap(node.mask, bit)];
                    shift += SIZE;
                    break;
                }
                return alt;
            }
        case ARRAY:
            {
                node = node.children[hashFragment(shift, hash)];
                if (node) {
                    shift += SIZE;
                    break;
                }
                return alt;
            }
        default:
            return alt;
    }
};

Map.prototype.tryGetHash = function(alt, hash, key) {
    return tryGetHash(alt, hash, key, this);
};

/**
    Lookup the value for `key` in `map` using internal hash function.

    @see `tryGetHash`
*/
const tryGet = hamt.tryGet = (alt, key, map) =>
    tryGetHash(alt, hash(key), key, map);

Map.prototype.tryGet = function(alt, key) {
    return tryGet(alt, key, this);
};

/**
    Lookup the value for `key` in `map` using a custom `hash`.

    Returns the value or `undefined` if none.
*/
const getHash = hamt.getHash = (hash, key, map) =>
    tryGetHash(undefined, hash, key, map);

Map.prototype.getHash = function(hash, key) {
    return getHash(hash, key, this);
};

/**
    Lookup the value for `key` in `map` using internal hash function.

    @see `get`
*/
const get = hamt.get = (key, map) =>
    tryGetHash(undefined, hash(key), key, map);

Map.prototype.get = function(key, alt) {
    return tryGet(alt, key, this);
};

const nothing = ({});
/**
    Does an entry exist for `key` in `map`? Uses custom `hash`.
*/
const hasHash = hamt.has = (hash, key, map) =>
    tryGetHash(nothing, hash, key, map) !== nothing;

Map.prototype.hasHash = function(hash, key) {
    return hasHash(hash, key, this);
};

/**
    Does an entry exist for `key` in `map`? Uses internal hash function.
*/
const has = hamt.has = (key, map) =>
    hasHash(hash(key), key, map);

Map.prototype.has = function(key) {
    return has(key, this);
};

/**
    Empty node.
*/
hamt.empty = new Map(undefined, 0);

/**
    Is `value` a map?
*/
hamt.isMap = (value) =>
    !!(value && value.__hamt_isMap);

/**
    Does `map` contain any elements?
*/
hamt.isEmpty = (map) =>
    hamt.isMap(map) && !map.root;

Map.prototype.isEmpty = function() {
    return hamt.isEmpty(this);
};

/* Updates
 ******************************************************************************/
/**
    Alter the value stored for `key` in `map` using function `f` using
    custom hash.

    `f` is invoked with the current value for `k` if it exists,
    or `defaultValue` if it is specified. Otherwise, `f` is invoked with no arguments
    if no such value exists.

    `modify` will always either update or insert a value into the map.

    Returns a map with the modified value. Does not alter `map`.
*/
const modifyHash = hamt.modifyHash = (f, hash, key, map) => {
    const size = { value: map.size };
    const newRoot = map.root ? map.root._modify(0, f, hash, key, size) : empty__modify(0, f, hash, key, size);
    return map.setTree(newRoot, size.value);
};

Map.prototype.modifyHash = function(hash, key, f) {
    return modifyHash(f, hash, key, this);
};

/**
    Alter the value stored for `key` in `map` using function `f` using
    internal hash function.

    @see `modifyHash`
*/
const modify = hamt.modify = (f, key, map) =>
    modifyHash(f, hash(key), key, map);

Map.prototype.modify = function(key, f) {
    return modify(f, key, this);
};

/**
    Same as `modifyHash`, but invokes `f` with `defaultValue` if no entry exists.

    @see `modifyHash`
*/
const modifyValueHash = hamt.modifyValueHash = (f, defaultValue, hash, key, map) =>
    modifyHash(defaultValBind(f, defaultValue), hash, key, map);

Map.prototype.modifyValueHash = function(hash, key, f, defaultValue) {
    return modifyValueHash(f, defaultValue, hash, key, this);
};

/**
    @see `modifyValueHash`
*/
const modifyValue = hamt.modifyValue = (f, defaultValue, key, map) =>
    modifyValueHash(f, defaultValue, hash(key), key, map);

Map.prototype.modifyValue = function(key, f, defaultValue) {
    return modifyValue(f, defaultValue, key, this);
};

/**
    Store `value` for `key` in `map` using custom `hash`.

    Returns a map with the modified value. Does not alter `map`.
*/
const setHash = hamt.setHash = function(hash, key, value, map) {
    return modifyHash({ __hamt_set_op: true, value: value }, hash, key, map);
}

Map.prototype.setHash = function(hash, key, value) {
    return setHash(hash, key, value, this);
};

/**
    Store `value` for `key` in `map` using internal hash function.

    @see `setHash`
*/
const set = hamt.set = (key, value, map) =>
    setHash(hash(key), key, value, map);

Map.prototype.set = function(key, value) {
    return set(key, value, this);
};

/**
    Remove the entry for `key` in `map`.

    Returns a map with the value removed. Does not alter `map`.
*/
const del = { __hamt_delete_op: true };
const removeHash = hamt.removeHash = (hash, key, map) =>
    modifyHash(del, hash, key, map);

Map.prototype.removeHash = Map.prototype.deleteHash = function(hash, key) {
    return removeHash(hash, key, this);
};

/**
    Remove the entry for `key` in `map` using internal hash function.

    @see `removeHash`
*/
const remove = hamt.remove = (key, map) =>
    removeHash(hash(key), key, map);

Map.prototype.remove = Map.prototype.delete = function(key) {
    return remove(key, this);
};

/* Traversal
 ******************************************************************************/
/**
    Apply a continuation.
*/
const appk = k =>
    k && lazyVisitChildren(k.len, k.children, k.i, k.f, k.k);

/**
    Recursively visit all values stored in an array of nodes lazily.
*/
const lazyVisitChildren = (len, children, i, f, k) => {
    while (i < len) {
        const child = children[i++];
        if (child)
            return lazyVisit(child, f, {len, children, i, f, k});
    }
    return appk(k);
};

/**
    Recursively visit all values stored in `node` lazily.
*/
const lazyVisit = (node, f, k) => {
    if (node.type === LEAF)
        return { value: f(node), rest: k };

    const children = node.children;
    return lazyVisitChildren(children.length, children, 0, f, k);
};

const DONE = { done: true };

/**
    Javascript iterator over a map.
*/
function MapIterator(v) {
    this.v = v;
};

MapIterator.prototype.next = function() {
    if (!this.v)
        return DONE;
    const v0 = this.v;
    this.v = appk(v0.rest);
    return v0;
};

MapIterator.prototype[Symbol.iterator] = function() {
    return this;
};

/**
    Lazily visit each value in map with function `f`.
*/
const visit = (map, f) =>
    new MapIterator(map.root ? lazyVisit(map.root, f) : undefined);

/**
    Get a Javascript iterator of `map`.

    Iterates over `[key, value]` arrays.
*/
const buildPairs = (x) => [x.key, x.value];
const entries = hamt.entries = (map) =>
    visit(map, buildPairs);

Map.prototype.entries = Map.prototype[Symbol.iterator] = function() {
    return entries(this);
};

/**
    Get array of all keys in `map`.

    Order is not guaranteed.
*/
const buildKeys = (x) => x.key;
const keys = hamt.keys = (map) =>
    visit(map, buildKeys);

Map.prototype.keys = function() { return keys(this); }

/**
    Get array of all values in `map`.

    Order is not guaranteed, duplicates are preserved.
*/
const buildValues = x => x.value;
const values = hamt.values = Map.prototype.values = map =>
    visit(map, buildValues);

Map.prototype.values = function() {
    return values(this);
};

/* Fold
 ******************************************************************************/
/**
    Visit every entry in the map, aggregating data.

    Order of nodes is not guaranteed.

    @param f Function mapping accumulated value, value, and key to new value.
    @param z Starting value.
    @param m HAMT
*/
const fold = hamt.fold = (f, z, m) => {
    const root = m.root;
    if (!root)
        return z;

    if (root.type === LEAF)
        return f(z, root.value, root.key);

    for (let toVisit = root; toVisit; ) {
        const children = toVisit.children;
        toVisit = toVisit.next;
        for (let i = 0, len = children.length; i < len;) {
            const child = children[i++];
            if (child) {
                if (child.type === LEAF)
                    z = f(z, child.value, child.key);
                else
                    toVisit = { children: child.children, next: toVisit }
            }
        }
    }
    return z;
};

Map.prototype.fold = function(f, z) {
    return fold(f, z, this);
};

/**
    Visit every entry in the map, aggregating data.

    Order of nodes is not guaranteed.

    @param f Function invoked with value and key
    @param map HAMT
*/
const forEach = hamt.forEach = (f, map) =>
    fold((_, value, key) => f(value, key, map), null, map);

Map.prototype.forEach = function(f) {
    return forEach(f, this);
};

/* Aggregate
 ******************************************************************************/
/**
    Get the number of entries in `map`.
*/
const count = hamt.count = (map) => map.size;

Map.prototype.count = function() {
    return count(this);
};

/* Export
 ******************************************************************************/
if (typeof module !== 'undefined' && module.exports) {
    module.exports = hamt;
} else if (typeof define === 'function' && define.amd) {
    define('hamt', [], () => hamt);
} else {
    this.hamt = hamt;
}


text:
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *

### <summary>
### In this example we look at the canonical 15/30 day moving average cross. This algorithm
### will go long when the 15 crosses above the 30 and will liquidate when the 15 crosses
### back below the 30.
### </summary>
### <meta name="tag" content="indicators" />
### <meta name="tag" content="indicator classes" />
### <meta name="tag" content="moving average cross" />
### <meta name="tag" content="strategy example" />
class MovingAverageCrossAlgorithm(QCAlgorithm):

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2009, 1, 1)    #Set Start Date
        self.SetEndDate(2015, 1, 1)      #Set End Date
        self.SetCash(100000)             #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.AddEquity("SPY")

        # create a 15 day exponential moving average
        self.fast = self.EMA("SPY", 15, Resolution.Daily)

        # create a 30 day exponential moving average
        self.slow = self.EMA("SPY", 30, Resolution.Daily)

        self.previous = None

    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        # a couple things to notice in this method:
        #  1. We never need to 'update' our indicators with the data, the engine takes care of this for us
        #  2. We can use indicators directly in math expressions
        #  3. We can easily plot many indicators at the same time

        # wait for our slow ema to fully initialize
        if not self.slow.IsReady:
            return

        # only once per day
        if self.previous is not None and self.previous.date() == self.Time.date():
            return

        # define a small tolerance on our checks to avoid bouncing
        tolerance = 0.00015

        holdings = self.Portfolio["SPY"].Quantity

        # we only want to go long if we're currently short or flat
        if holdings <= 0:
            # if the fast is greater than the slow, we'll go long
            if self.fast.Current.Value > self.slow.Current.Value *(1 + tolerance):
                self.Log("BUY  >> {0}".format(self.Securities["SPY"].Price))
                self.SetHoldings("SPY", 1.0)

        # we only want to liquidate if we're currently long
        # if the fast is less than the slow we'll liquidate our long
        if holdings > 0 and self.fast.Current.Value < self.slow.Current.Value:
            self.Log("SELL >> {0}".format(self.Securities["SPY"].Price))
            self.Liquidate("SPY")

        self.previous = self.Time

redpajama_set_name: RedPajamaGithub


text:
package org.apache.tapestry5.integration.app1.data;

import org.apache.tapestry5.beaneditor.Validate;

public class RolePath
{
    private String path;

    private RoleAccess role = RoleAccess.GRANT;

    @Validate("required")
    public String getPath()
    {
        return path;
    }

    @Validate("required")
    public RoleAccess getRole()
    {
        return role;
    }

    public void setPath(String path)
    {
        this.path = path;
    }

    public void setRole(RoleAccess role)
    {
        this.role = role;
    }

}


text:
//
//  CameraLocationFetcher.m
//  SpeedCameraFinder
//
//  Created by Tullie Murrell on 4/03/2014.
//  Copyright (c) 2014 Tullie Murrell. All rights reserved.
//

/*
 HPPLE USAGE
 ===========

 #import "TFHpple.h"

 NSData  * data      = [NSData dataWithContentsOfFile:@"index.html"];

 TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:data];
 NSArray * elements  = [doc search:@"//a[@class='sponsor']"];

 TFHppleElement * element = [elements objectAtIndex:0];
 [e text];                       // The text inside the HTML element (the content of the first text node)
 [e tagName];                    // "a"
 [e attributes];                 // NSDictionary of href, class, id, etc.
 [e objectForKey:@"href"];       // Easy access to single attribute
 [e firstChildWithTagName:@"b"]; // The first "b" child node
 */

#import "CameraLocationFetcher.h"
#import "TFHpple.h"

@implementation CameraLocationFetcher

#define POLICE_SA_URL @"http://www.sapolice.sa.gov.au/sapol/road_safety/traffic_safety_camera_locations.jsp"
#define POLICE_SA_COUNTRY_URL @"http://www.sapolice.sa.gov.au/sapol/road_safety/traffic_safety_camera_locations/country_traffic_safety_camera_locations.jsp"

+ (NSURL *)URLSACameraLocations
{
    NSURL *urlPoliceSA = [[NSURL alloc] initWithString:POLICE_SA_URL];
    return urlPoliceSA;
}

+ (NSURL *)URLSACountryCameraLocations
{
    NSURL *urlPoliceCountrySA = [[NSURL alloc] initWithString:POLICE_SA_COUNTRY_URL];
    return urlPoliceCountrySA;
}

- (void)fetchCameras
{
}

@end


text:
package com.cibc.p8.complexsql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class SQLModel2 {

	private HashMap<String, ArrayList<String>> tablepartitions = new HashMap<String, ArrayList<String>>();
	private ArrayList<String> partitions = new ArrayList<String>();
	public ArrayList<String> getPartitions() {
		return partitions;
	}
	public void setPartitions(ArrayList<String> partitions) {
		this.partitions = partitions;
	}

	public ArrayList getTablepartitions (String table) {
		return  tablepartitions.get(table);
	}
	public void setTablePartitions (String table, ArrayList partitions) {
		tablepartitions.put(table, partitions);
	}
	public String[] getTables () {
		String [] result = new String [tablepartitions.keySet().size()];
		return tablepartitions.keySet().toArray(result);
	}

}


text:
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Diagrams.SVG.Fonts.Text
       ( -- * Setting text as a path using a font.

         TextOpts(..)
       , Mode(..)
       , Spacing(..)

       , textSVG
       , textSVG'
       , textSVG_

       ) where

import Data.Default.Class
import Diagrams.Prelude hiding (font, text)
import qualified Data.HashMap.Strict as H
import Data.Maybe (fromMaybe)
import qualified Data.Text as T

import Diagrams.SVG.Fonts.Fonts (lin)
import Diagrams.SVG.Fonts.ReadFont
import Diagrams.SVG.Fonts.CharReference (characterStrings)

data TextOpts n = TextOpts
  { textFont   :: PreparedFont n
  , mode       :: Mode
  , spacing    :: Spacing
  , underline  :: Bool
  , textWidth  :: n
  , textHeight :: n
  }

instance (Read n, RealFloat n) => Default (TextOpts n) where
    def = TextOpts lin INSIDE_H KERN False 1 1

-- | A short version of textSVG' with standard values. The Double value is the height.
--
-- > import Graphics.SVGFonts
-- >
-- > textSVGExample = stroke $ textSVG "Hello World" 1
--
-- <<diagrams/src_Graphics_SVGFonts_ReadFont_textSVGExample.svg#diagram=textSVGExample&width=300>>
textSVG :: (Read n, RealFloat n) => String -> n -> Path V2 n
textSVG t h = textSVG' with { textHeight = h } t

-- | Create a path from the given text and options.
--   The origin is at the center of the text and the boundaries are
--   given by the outlines of the chars.
--
-- > import Graphics.SVGFonts
-- >
-- > text' t = stroke (textSVG' (TextOpts lin INSIDE_H KERN False 1 1) t)
-- >            # fc blue # lc blue # bg lightgrey # fillRule EvenOdd # showOrigin
-- >
-- > textPic0 = (text' "Hello World") # showOrigin
--
-- <<diagrams/src_Graphics_SVGFonts_ReadFont_textPic0.svg#diagram=textPic0&width=300>>
textSVG' :: RealFloat n => TextOpts n -> String -> Path V2 n
textSVG' topts text =
  case mode topts of
    INSIDE_WH -> makeString (textHeight topts * sumh / maxY) (textHeight topts) (textWidth topts / (textHeight topts * sumh / maxY))
    INSIDE_W  -> makeString (textWidth topts) (textWidth topts * maxY / sumh)   1 -- the third character is used topts scale horizontal advances
    INSIDE_H  -> makeString (textHeight topts * sumh / maxY) (textHeight topts) 1
  where
    makeString w h space = (scaleY (h/maxY) $ scaleX (w/sumh) $
                            mconcat $
                            zipWith translate (horPos space)
                           (map polygonChar (zip str (adjusted_hs space))) ) # centerXY
    (fontD,outl) = textFont topts
    polygonChar (ch,a) = (fromMaybe mempty (H.lookup ch outl)) <> (underlineChar a)
    underlineChar a | underline topts = translateY ulinePos (rect a ulineThickness)
                    | otherwise = mempty
    ulinePos = underlinePosition fontD
    ulineThickness = underlineThickness fontD
    horPos space = reverse $ added ( zero : (map (unitX ^*) (adjusted_hs space)) )
    adjusted_hs space = map (*space) hs
    hs = horizontalAdvances str fontD (isKern (spacing topts))
    sumh = sum hs
    added = snd.(foldl (\(h,l) (b,_) -> (h ^+^ b, (h ^+^ b):l))
                       (zero,[])).  (map (\x->(x,[]))) -- [o,o+h0,o+h0+h1,..]
    maxY = bbox_dy fontD -- max height of glyph

    ligatures = ((filter ((>1) . length)) . H.keys . fontDataGlyphs) fontD
    str = map T.unpack $ characterStrings text ligatures

-- | Create a path from the given text and options.
-- The origin is at the left end of the baseline of of the text and the boundaries
-- are given by the bounding box of the Font. This is best for combining Text of different
-- fonts and for several lines of text.
-- As you can see you can also underline text by setting underline to True.
--
-- > import Graphics.SVGFonts
-- >
-- > text'' t = (textSVG_ (TextOpts lin INSIDE_H KERN True 1 1) t)
-- >            # fc blue # lc blue # bg lightgrey # fillRule EvenOdd # showOrigin
-- >
-- > textPic1 = text'' "Hello World"
--
-- <<diagrams/src_Graphics_SVGFonts_ReadFont_textPic1.svg#diagram=textPic1&width=300>>
textSVG_ :: forall b n. (TypeableFloat n, Renderable (Path V2 n) b) =>
            TextOpts n -> String -> QDiagram b V2 n Any
textSVG_ topts text =
  case mode topts of
    INSIDE_WH -> makeString (textHeight topts * sumh / maxY) (textHeight topts) ((textWidth topts) / (textHeight topts * sumh / maxY))
    INSIDE_W  -> makeString (textWidth topts) (textWidth topts * maxY / sumh)   1
    INSIDE_H  -> makeString (textHeight topts * sumh / maxY) (textHeight topts) 1
  where
    makeString w h space =( ( translate (r2 (-w*space/2,-h/2)) $
                            scaleY (h/maxY) $ scaleX (w/sumh) $
                            translateY (- bbox_ly fontD) $
                            mconcat $
                            zipWith translate (horPos space)
                            (map polygonChar (zip str (adjusted_hs space))) ) # stroke # withEnvelope ((rect (w*space) h) :: D V2 n)
                          ) # alignBL # translateY (bbox_ly fontD*h/maxY)
    (fontD,outl) = (textFont topts)
    polygonChar (ch,a) = (fromMaybe mempty (H.lookup ch outl)) <> (underlineChar a)
    underlineChar a | underline topts = translateX (a/2) $ translateY ulinePos (rect a ulineThickness)
                    | otherwise = mempty
    ulinePos = underlinePosition fontD
    ulineThickness = underlineThickness fontD
    horPos space = reverse $ added ( zero : (map (unitX ^*) (adjusted_hs space)) )
    hs = horizontalAdvances str fontD (isKern (spacing topts))
    adjusted_hs space = map (*space) hs -- the last char should not have space to the border
    sumh = sum hs
    added = snd.(foldl (\(h,l) (b,_) -> (h ^+^ b, (h ^+^ b):l))
                       (zero,[])).  (map (\x->(x,[]))) -- [o,o+h0,o+h0+h1,..]
    maxY = bbox_dy fontD -- max height of glyph

    ligatures = (filter ((>1) . length) . H.keys . fontDataGlyphs) fontD
    str = map T.unpack $ characterStrings text ligatures

data Mode = INSIDE_H  -- ^ The string fills the complete height, width adjusted. Used in text editors.
                      -- The result can be smaller or bigger than the bounding box:
                      --
                      --   <<diagrams/src_Graphics_SVGFonts_ReadFont_textH.svg#diagram=textH&width=400>>
          | INSIDE_W  -- ^ The string fills the complete width, height adjusted.
                      -- May be useful for single words in a diagram, or for headlines.
                      -- The result can be smaller or bigger than the bounding box:
                      --
                      -- <<diagrams/src_Graphics_SVGFonts_ReadFont_textW.svg#diagram=textW&width=400>>
          | INSIDE_WH -- ^ The string is stretched inside Width and Height boundaries.
                      -- The horizontal advances are increased if the string is shorter than there is space.
                      -- The horizontal advances are decreased if the string is longer than there is space.
                      -- This feature is experimental and might change in the future.
                      --
                      -- <<diagrams/src_Graphics_SVGFonts_ReadFont_textWH.svg#diagram=textWH&width=400>>
           deriving Show

-- | See <http://en.wikipedia.org/wiki/Kerning>
--
data Spacing = HADV -- ^ Every glyph has a unique horiz. advance
                    --
                    --  <<diagrams/src_Graphics_SVGFonts_ReadFont_textHADV.svg#diagram=textHADV&width=400>>
             | KERN -- ^ Recommended, same as HADV but sometimes overridden by kerning:
                    -- As You can see there is less space between \"A\" and \"V\":
                    --
                    --   <<diagrams/src_Graphics_SVGFonts_ReadFont_textKern.svg#diagram=textKern&width=400>>
             deriving Show

isKern :: Spacing -> Bool
isKern KERN = True
isKern _    = False

-- | Horizontal advances of characters inside a string.
-- A character is stored with a string (because of ligatures like \"ffi\").
horizontalAdvances :: RealFloat n => [String] -> FontData n -> Bool -> [n]
horizontalAdvances []          _  _       = []
horizontalAdvances [ch]        fd _       = [horizontalAdvance ch fd]
horizontalAdvances (ch0:ch1:s) fd kerning = ((horizontalAdvance ch0 fd) - (ka (fontDataKerning fd))) :
                                            (horizontalAdvances (ch1:s) fd kerning)
  where ka kern | kerning   = (kernAdvance ch0 ch1 kern True) + (kernAdvance ch0 ch1 kern False)
                | otherwise = 0


text:
#include "Geomatic\GridInterpolBase.h"
#include "Geomatic\ProjectionTransformation.h"
#include <unordered_map>

namespace WBSF
{

	class CThinPlateSpline : public CGridInterpolBase
	{
	public:

		CThinPlateSpline();
		virtual ~CThinPlateSpline();
		void Reset();

		virtual ERMsg Initialization(CCallback& callback);
		virtual void GetParamterset(CGridInterpolParamVector& parameterset);
		virtual std::string GetFeedbackBestParam()const;
		virtual double Evaluate(const CGridPoint& pt, int iXval = -1)const;

	protected:

//		std::unique_ptr<CANNSearch> m_pANNSearch;

		CRITICAL_SECTION CS;

		void* m_pObject;
		size_t m_nbDim;
		bool m_bGeographic;
		bool m_bUseElevation;
		bool m_bUseExposition;
		bool m_bUseShore;

		//a mettre dans m_param;
		//bool m_bClustered;

	};

}


text:
const Project = require('../index');
const Code = require('code');
const Lab = require('lab');

const expect = Code.expect;
const lab = exports.lab = Lab.script();

let server;

lab.experiment('server', function () {

  lab.before(function (done) {

    Project.run().then((newServer) => {
      server = newServer;
      done();
    });
  });

  lab.after(function (done) {

    server.stop(done);
  });

  lab.test('begins listening for requests', function (done) {

    expect(server.info.port).to.be.a.number();
    server.start(done);
  });
});


text:
var self = module.exports = {
    Link: function () {
        var method;
        var href;
    }
}


text:
<?php

/**
 * The "accounts" collection of methods.
 * Typical usage is:
 *  <code>
 *   $adsenseService = new Google_Service_AdSense(...);
 *   $accounts = $adsenseService->accounts;
 *  </code>
 */
class Google_Service_AdSense_Resource_Accounts extends Google_Service_Resource
{
  /**
   * Get information about the selected AdSense account. (accounts.get)
   *
   * @param string $accountId Account to get information about.
   * @param array $optParams Optional parameters.
   *
   * @opt_param bool tree Whether the tree of sub accounts should be returned.
   * @return Google_Service_AdSense_Account
   */
  public function get($accountId, $optParams = array())
  {
    $params = array('accountId' => $accountId);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_AdSense_Account");
  }
  /**
   * List all accounts available to this AdSense account. (accounts.listAccounts)
   *
   * @param array $optParams Optional parameters.
   *
   * @opt_param int maxResults The maximum number of accounts to include in the
   * response, used for paging.
   * @opt_param string pageToken A continuation token, used to page through
   * accounts. To retrieve the next page, set this parameter to the value of
   * "nextPageToken" from the previous response.
   * @return Google_Service_AdSense_Accounts
   */
  public function listAccounts($optParams = array())
  {
    $params = array();
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_AdSense_Accounts");
  }
}


text:
/* common .c
 * This file has any function that is truly common and platform
 * neutral.  Or at least that's the theory.
 *
 * The header files are a problem so there are a few #ifdef's to take
 * care of those.
 *
 */

#include "apr.h"
#include "apr_private.h"
#include "apr_mmap.h"
#include "apr_errno.h"

#if APR_HAS_MMAP || defined(BEOS)

APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mmap,
                                          apr_off_t offset)
{
    if (offset < 0 || (apr_size_t)offset > mmap->size)
        return APR_EINVAL;

    (*addr) = (char *) mmap->mm + offset;
    return APR_SUCCESS;
}

#endif


text:
<?php

declare(strict_types=1);

namespace DiContainerBenchmarks\Fixture\C;

class FixtureC937
{
    public function __construct(FixtureC936 $dependency)
    {
    }
}


text:
typedef struct
{
	unsigned int num;	//!< number of terms in sum
	grid2_t *psiR1;		//!< psiR1 weights
	grid_t  *psiR2;		//!< psiR2 weights
}
quadI1_t;

void QuadI1_Allocate(const unsigned int num, quadI1_t *quad);

void QuadI1_Delete(quadI1_t *quad);

//_______________________________________________________________________________________________________________________
///
/// \brief I2 quadrature formula representing Fourier transform of delta function
///
typedef struct
{
	unsigned int num;	//!< number of terms in sum
	grid_t *psiR1;		//!< psiR1 weights
	grid_t *psiR2;		//!< psiR2 weights
}
quadI2_t;

void QuadI2_Allocate(const unsigned int J, quadI2_t *quad);

void QuadI2_Delete(quadI2_t *quad);

//_______________________________________________________________________________________________________________________
///
/// \brief I3 quadrature formula representing Fourier transform of delta function
///
typedef struct
{
	unsigned int num;	//!< J, number of terms in sum
	cgrid_t *psiR1;		//!< psiR1 weights
	grid2_t *psiR2;		//!< psiR2 weights
}
quadI3_t;

void QuadI3_Allocate(const unsigned int num, quadI3_t *quad);

void QuadI3_Delete(quadI3_t *quad);

//_______________________________________________________________________________________________________________________
//

void FourierI1(const unsigned int J, const double L, const double R, quadI1_t *quad);

void FourierI2(const unsigned int J, const double L, const double R, quadI2_t *quad);

void FourierI3(const unsigned int J, const double L, const double R, const unsigned int M, quadI3_t *quad);

void FourierI4(const unsigned int J, const double L, const double R, quadI1_t *quad);

#endif


text:
import org.fusesource.scalate.RenderContext

package

object Website {

  val project_name= "hawt.io"
  val project_slogan= "its a hawt console to help you stay cool!"
  val project_id= "hawtio"
  val project_jira_key= "hawtio"
  val project_issue_url= "https://github.com/hawtio/hawtio/issues?state=open"
  val project_forums_url= "http://hawt.io/community/index.html"
  val project_wiki_url= "https://github.com/hawtio/hawtio/wiki"
  val project_logo= "/images/project-logo.png"
  val project_version= "1.2.2"
  val project_snapshot_version= "1.3-SNAPSHOT"
  val project_versions = List(
        project_version
        )

  val github_page= "https://github.com/hawtio/hawtio"
  val git_user_url= "git://github.com/hawtio/hawtio.git"
  val git_commiter_url= "git@github.com:hawtio/hawtio.git"
  val git_branch= "master"
  val git_edit_page_base = github_page+"/edit/"+git_branch+"/website/src"
  val disqus_shortname = project_id

  val scala_compat_tag = "2.9"

  // -------------------------------------------------------------------
  val project_maven_groupId= "io.hawt"
  val project_maven_artifactId= "hawtio-web"

  val app_dir = "../hawtio-web/src/main/webapp/app"

}


text:
<?php

/**
 * namespace definition and usage
 */
namespace User\View\Helper;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Show user widget view helper factory
 *
 * Generates the Show user widget view helper object
 *
 * @package    User
 */
class UserShowWidgetFactory implements FactoryInterface
{
    /**
     * Create Service Factory
     *
     * @param ServiceLocatorInterface $serviceLocator
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $sm       = $serviceLocator->getServiceLocator();
        $identity = $sm->get('User\Auth\Service')->getIdentity();
        $service  = $sm->get('User\Service\User');
        $helper   = new UserShowWidget($identity, $service);
        return $helper;
    }
}


text:
<?php  defined('C5_EXECUTE') or die(_("Access Denied."));

function s2nb($text) {
	return str_replace(' ', ' ', $text);
}

// Dashboard Style Note: We are **not** using Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper() etc...
// because that changes all the styling for the inner elements as well (and I don't feel like updating all that now).
// So we need to manually wrap in
 for 5.6 compatibility
// (5.5's dashboard theme automatically wraps page content in that, but 5.6 doesn't -- so in 5.5 we'll have two redundant
// divs with the same class -- but this doesn't effect the styling at all so it's fine).
?>

<?php  echo t('Designer Content'); ?>

	<?php  if ($is_generated): ?>

		<?php  echo t('Success!'); ?>

		<?php  echo t('%s has been installed, and will now be available in the "Add Blocks" list when pages are edited.', "{$generated_name}"); ?>

		<a href="<?php  echo View::url('/dashboard/blocks/designer_content'); ?>"><?php  echo t('Create another block type'); ?> »

	<?php  else: ?>

				<?php  echo t('Create a new block type by entering some basic info and adding one or more fields.'); ?>
				[<?php  echo t('Documentation'); ?>]
				[<?php  echo t('Help Forum'); ?>]

		<?php  if (!$can_write): ?>

			<?php  echo t('Warning: The blocks directory is not writeable. Blocks cannot be created from this page until permissions are changed on your server.'); ?>

		<?php  endif; ?>

		<form method="post" action="<?php  echo $this->action('generate_block'); ?>" id="designer-content-form">

<?php  echo t('Block Handle'); ?>:

						<?php  echo $form->text('handle', $handle, array('maxlength' => '32')); ?>
						<?php  echo t('lowercase letters and underscores only'); ?>

<?php  echo t('Block Name'); ?>:

						<?php  echo $form->text('name', $name); ?>
						<?php  echo t('human-readable name (appears in the "Add Block" list)'); ?>

<?php  echo t('Block Description'); ?>:

						<?php  echo t('(optional)'); ?>

						<?php  echo $form->textarea('description', $description, array('rows' => '3', 'cols' => '50')); ?>
						<?php  echo t('for dashboard "Add Functionality" list'); ?>

<?php  echo t('Add Field');?>:

			<?php  if ($can_write): ?>

					<?php  echo t('Make The Block!'); ?>

					<?php  echo t('Processing...'); ?>

			<?php  endif; ?>

				<?php  echo t('code + ui'); ?>: Jordan Lev

				<?php  echo t('icon design'); ?>: Kirk Roberts

		</form>

	<?php  endif; ?>


text:
layout: page
title: "JavaScript file_exists function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/file_exists:399
- /functions/view/file_exists
- /functions/view/399
- /functions/file_exists:399
- /functions/399
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's file_exists

{% codeblock filesystem/file_exists.js lang:js https://raw.github.com/kvz/phpjs/master/functions/filesystem/file_exists.js raw on github %}
function file_exists (url) {
  // http://kevin.vanzonneveld.net
  // +   original by: Enrique Gonzalez
  // +      input by: Jani Hartikainen
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
  // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.
  // *     example 1: file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
  // *     returns 1: '123'
  var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  if (!req) {
    throw new Error('XMLHttpRequest not supported');
  }

  // HEAD Results are usually shorter (faster) than GET
  req.open('HEAD', url, false);
  req.send(null);
  if (req.status == 200) {
    return true;
  }

  return false;
}
{% endcodeblock %}

 - [view on github](https://github.com/kvz/phpjs/blob/master/functions/filesystem/file_exists.js)
 - [edit on github](https://github.com/kvz/phpjs/edit/master/functions/filesystem/file_exists.js)

### Example 1
This code
{% codeblock lang:js example %}
file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
'123'
{% endcodeblock %}

### Other PHP functions in the filesystem extension
{% render_partial _includes/custom/filesystem.html %}


text:
package boj_10156;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/**
 * 백준 온라인 저지 10156번 (과자) 문제풀이
 *
 * @see https://www.acmicpc.net/problem/10156
 * @author devetude
 */
public class Main {
	public static void main(String[] args) throws Exception {
		// 버퍼를 이용해 입력을 받음
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine(), " ");
		br.close();

		int K = Integer.parseInt(st.nextToken());
		int N = Integer.parseInt(st.nextToken());
		int M = Integer.parseInt(st.nextToken());

		// 부족한 금액 계산
		int lackMoney = K * N - M;

		// 결과 값 출력
		System.out.println(lackMoney > 0 ? lackMoney : 0);
	}
}


text:
const INT64 COMDateTime::TicksPerMillisecond = 10000;
const INT64 COMDateTime::TicksPerSecond = TicksPerMillisecond * 1000;
const INT64 COMDateTime::TicksPerMinute = TicksPerSecond * 60;
const INT64 COMDateTime::TicksPerHour = TicksPerMinute * 60;
const INT64 COMDateTime::TicksPerDay = TicksPerHour * 24;

const INT64 COMDateTime::MillisPerSecond = 1000;
const INT64 COMDateTime::MillisPerDay = MillisPerSecond * 60 * 60 * 24;

const int COMDateTime::DaysPer4Years = 365 * 4 + 1;
const int COMDateTime::DaysPer100Years = DaysPer4Years * 25 - 1;
const int COMDateTime::DaysPer400Years = DaysPer100Years * 4 + 1;

// Number of days from 1/1/0001 to 1/1/10000
const int COMDateTime::DaysTo10000 = DaysPer400Years * 25 - 366;

const int COMDateTime::DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367;

const INT64 COMDateTime::DoubleDateOffset = DaysTo1899 * TicksPerDay;

// OA Min Date is Jan 1, 100 AD.  This is after converting to ticks.
const INT64 COMDateTime::OADateMinAsTicks = (DaysPer100Years - 365) * TicksPerDay;

// All OA dates must be greater than (not >=) OADateMinAsDouble
const double COMDateTime::OADateMinAsDouble = -657435.0;

// All OA dates must be less than (not <=) OADateMaxAsDouble
const double COMDateTime::OADateMaxAsDouble = 2958466.0;

const INT64 COMDateTime::MaxTicks = DaysTo10000 * TicksPerDay;
const INT64 COMDateTime::MaxMillis = DaysTo10000 * MillisPerDay;

const INT64 TicksMask = I64(0x3FFFFFFFFFFFFFFF);

// This function is duplicated in DateTime.cs
INT64 COMDateTime::DoubleDateToTicks(const double d)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    } CONTRACTL_END;

    // Make sure this date is a valid OleAut date.  This is the check from the internal
    // OleAut macro IsValidDate, found in oledisp.h.  Eventually at least the 64 bit
    // build of oleaut will define these gregorian max and min values as public constants.
    // The check done this way will take care of NaN
    if (!(d < OADateMaxAsDouble) || !(d > OADateMinAsDouble))
        COMPlusThrow(kArgumentException, W("Arg_OleAutDateInvalid"));

    // Conversion to int64 will not cause an overflow here, as at this point the "d" is in between OADateMinAsDouble and OADateMaxAsDouble
    INT64 millis = (INT64)(d * MillisPerDay + (d >= 0? 0.5: -0.5));
    if (millis < 0) millis -= (millis % MillisPerDay) * 2;
    // There are cases when we are very close to -1 and 1 in which case millis%MillisPerDay is 0 since we have exactly one day due to rounding issues.
    millis += DoubleDateOffset / TicksPerMillisecond;

    if (millis < 0 || millis >= MaxMillis)
    {
        COMPlusThrow(kArgumentException, W("Arg_OleAutDateScale"));  // Cannot be equal to MaxMillis.
    }
    return millis * TicksPerMillisecond;
}

// This function is duplicated in DateTime.cs
double COMDateTime::TicksToDoubleDate(INT64 ticks)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    } CONTRACTL_END;

    //

    // Workaround to handle uninitialized DateTime objects in the CLR
    // See explanation in DateTime.cs's TicksToOADate function.

    // Strip off the extra kind state
    ticks = (ticks & TicksMask);

    if (ticks == 0)
        return 0.0;  // OA's 0 date (12/30/1899).

    if (ticks < OADateMinAsTicks)
    {
        //We've special-cased day 0 (01/01/0001 in the Gregorian Calendar) such that the
        //date can be used to represent a DateTime the contains only a time.  OA uses
        //day 0 (12/30/1899) for the same purpose, so we'll do a mapping from our day 0
        //to their day 0.
        if (ticks < TicksPerDay)
            ticks+=DoubleDateOffset;
        else
            COMPlusThrow(kOverflowException, W("Arg_OleAutDateInvalid"));
    }

    INT64 millis = (ticks  - DoubleDateOffset) / TicksPerMillisecond;
    if (millis < 0)
    {
        INT64 frac = millis % MillisPerDay;
        if (frac != 0) millis -= (MillisPerDay + frac) * 2;
    }

    double d = (double)millis / MillisPerDay;

    // Make sure this date is a valid OleAut date.  This is the check from the internal
    // OleAut macro IsValidDate, found in oledisp.h.  Eventually at least the 64 bit
    // build of oleaut will define these gregorian max and min values as public constants.
    _ASSERTE(d < OADateMaxAsDouble && d > OADateMinAsDouble);

    return d;
}


text:
// Version 0.1

'use strict';

console.log('v0', self);

self.addEventListener('install', function(event) {
  self.skipWaiting();
  console.log('Installed', event);
});

self.addEventListener('activate', function(event) {
  console.log('Activated', event);
});

 self.addEventListener('push', function(event) {
   console.log('Push message', event);
   console.log(event.data);

  let notificationTitle = 'RevolutionUC Live';
  let notificationText = 'You\'ve recieved a notification';
  let notificationIcon = 'https://unsplash.it/200/200?random';

  if (event.data) {

    try {
      let payload = event.data.json();
      notificationText = payload.text;
      notificationIcon = payload.icon;
    } catch (error) {
      notificationText = event.data.text();
    }

  }

  const notificationOptions = {
    body: notificationText,
    icon: notificationIcon,
    tag: 'notify-sw',
    data: {
      url: 'https://live.revolutionuc.com/schedule'
    }
  };

   event.waitUntil(
     self.registration.showNotification(notificationTitle, notificationOptions)
   );
 });

self.addEventListener('notificationclick', function(event) {
  console.log('Notification click: tag', event.notification.tag);
  // Android doesn't close the notification when you click it
  // See http://crbug.com/463146
  event.notification.close();
  let url = 'https://live.revolutionuc.com/schedule';
  // Check if there's already a tab open with this URL.
  // If yes: focus on the tab.
  // If no: open a tab with the URL.
  event.waitUntil(
    clients.matchAll({
      type: 'window'
    })
    .then(function(windowClients) {
      console.log('WindowClients', windowClients);
      for (let i = 0; i < windowClients.length; i++) {
        let client = windowClients[i];
        console.log('WindowClient', client);
        if (client.url === url && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(url);
      }
    })
  );
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.samoatesgames</groupId>
    <artifactId>StylinHats</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <repositories>
        <repository>
            <id>spigot-snapshots</id>
            <url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
        </repository>
        <repository>
            <id>vault-repo</id>
            <url>http://nexus.theyeticave.net/content/repositories/pub_releases</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.8-R0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.samoatesgames</groupId>
            <artifactId>SamOatesPluginCore</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>net.milkbowl.vault</groupId>
            <artifactId>Vault</artifactId>
            <version>1.5.2</version>
            <type>jar</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <artifactSet>
                        <includes>
                            <include>com.samoatesgames:*</include>
                        </includes>
                    </artifactSet>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <targetPath>.</targetPath>
                <filtering>true</filtering>
                <directory>${basedir}/src/main/resources</directory>
                <includes>
                    <include>*.yml</include>
                </includes>
            </resource>
        </resources>
    </build>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>


text:
'use strict';

module.exports = {
	sign: require('./sign')
};


text:
title: OnClientColorChange
page_title: OnClientColorChange - RadColorPicker
description: Check our Web Forms article about OnClientColorChange.
slug: colorpicker/client-side-programming/events/onclientcolorchange
tags: onclientcolorchange
published: True
position: 4
---

# OnClientColorChange

The **OnClientColorChange** client-side event occurs when the user selects a color from the palette.

The event handler receives parameters:

1. The color picker instance that fired the event.

1. Event arguments with the following properties:

	* **get_oldValue**: returns the selected color from just prior to the change.

The example below displays the new and old values.

````ASP.NET
function colorChange(sender, eventArgs)
{
   var myDiv = document.getElementById("myDiv");
   myDiv.innerHTML = 'Color changed from ' + eventArgs.get_oldColor()
       + " to " + sender.get_selectedColor();
}
...
<telerik:RadColorPicker
   ID="RadColorPicker1"
   runat="server"
   Preset="Standard"
   OnClientColorChange="colorChange">
</telerik:RadColorPicker>
````


text:
<?php

/* WebProfilerBundle:Profiler:info.html.twig */
class __TwigTemplate_1e24f702e3e8a5493b8e1528ec5c7b51ff6fe9e14c8c247f45debdaabc3170d3 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("@WebProfiler/Profiler/base.html.twig", "WebProfilerBundle:Profiler:info.html.twig", 1);
        $this->blocks = array(
            'body' => array($this, 'block_body'),
            'panel' => array($this, 'block_panel'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "@WebProfiler/Profiler/base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "

        ";
        // line 5
        $this->loadTemplate("@WebProfiler/Profiler/header.html.twig", "WebProfilerBundle:Profiler:info.html.twig", 5)->display(array());
        // line 6
        echo "

                        ";
        // line 11
        $this->displayBlock('panel', $context, $blocks);
        // line 34
        echo "

                    ";
        // line 37
        echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('routing')->getPath("_profiler_search_bar"));
        echo "
                    ";
        // line 38
        $this->loadTemplate("@WebProfiler/Profiler/admin.html.twig", "WebProfilerBundle:Profiler:info.html.twig", 38)->display(array("token" => ""));
        // line 39
        echo "

";
    }

    // line 11
    public function block_panel($context, array $blocks = array())
    {
        // line 12
        echo "                            ";
        if (((isset($context["about"]) ? $context["about"] : $this->getContext($context, "about")) == "purge")) {
            // line 13
            echo "
The profiler database was purged successfully

                                    Now you need to browse some pages with the Symfony Profiler enabled to collect data.

                            ";
        } elseif ((        // line 17
(isset($context["about"]) ? $context["about"] : $this->getContext($context, "about")) == "upload_error")) {
            // line 18
            echo "
A problem occurred when uploading the data

                                    No file given or the file was not uploaded successfully.

                            ";
        } elseif ((        // line 22
(isset($context["about"]) ? $context["about"] : $this->getContext($context, "about")) == "already_exists")) {
            // line 23
            echo "
A problem occurred when uploading the data

                                    The token already exists in the database.

                            ";
        } elseif ((        // line 27
(isset($context["about"]) ? $context["about"] : $this->getContext($context, "about")) == "no_token")) {
            // line 28
            echo "
Token not found

                                    Token \"";
            // line 30
            echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
            echo "\" was not found in the database.

                            ";
        }
        // line 33
        echo "                        ";
    }

    public function getTemplateName()
    {
        return "WebProfilerBundle:Profiler:info.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  105 => 33,  99 => 30,  95 => 28,  93 => 27,  87 => 23,  85 => 22,  79 => 18,  77 => 17,  71 => 13,  68 => 12,  65 => 11,  57 => 39,  55 => 38,  51 => 37,  46 => 34,  44 => 11,  37 => 6,  35 => 5,  32 => 4,  29 => 3,  11 => 1,);
    }
}


text:
/*
 * Powered By agile
 * Web Site: http://www.agile.com
 * Since 2008 - 2016
 */

package persistent.prestige.modules.eshop.model;

import persistent.prestige.platform.base.model.AuditableModel;

/**
 * Order 实体类
 * @author 雅居乐 2016-8-27 10:27:01
 * @version 1.0
 */
public class Order extends AuditableModel{

	//alias
	public static final String TABLE_ALIAS = "Order";

	//columns START
	/**订单编号*/
	private java.lang.String orderNo;
	/**购买者uid*/
	private java.lang.String buyUid;
	/**商家uid*/
	private java.lang.String sellerUid;
	/**总金额,单位分*/
	private java.lang.Long totalPrice;
	/**0:新建;1:支付成功;2:支付失败*/
	private Integer status;
	//columns END

	public java.lang.String getOrderNo() {
		return this.orderNo;
	}

	public void setOrderNo(java.lang.String value) {
		this.orderNo = value;
	}

	public java.lang.String getBuyUid() {
		return this.buyUid;
	}

	public void setBuyUid(java.lang.String value) {
		this.buyUid = value;
	}

	public java.lang.String getSellerUid() {
		return this.sellerUid;
	}

	public void setSellerUid(java.lang.String value) {
		this.sellerUid = value;
	}

	public java.lang.Long getTotalPrice() {
		return this.totalPrice;
	}

	public void setTotalPrice(java.lang.Long value) {
		this.totalPrice = value;
	}

	public Integer getStatus() {
		return this.status;
	}

	public void setStatus(Integer value) {
		this.status = value;
	}

}


text:
<!DOCTYPE html>
<html class="trim full">
  <head>
    <link rel="stylesheet" href="css/foam.css" />
    <link rel="stylesheet" href="css/cab.css" />
    <script src="filesystem.js"></script>
  </head>
  <body class="trim full">
    <foam id="app" model="ConfigsController" view="AppDesignerView"></foam>
  </body>
</html>


text:
package it.could.util;

import it.could.util.encoding.Encodable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 *
An utility class providing various static methods operating on
 * {@link String}s.

 *
 *
This class implement the {@link Encodable} interface from which it
 * inherits its {@link Encodable#DEFAULT_ENCODING default encoding}.

 *
 * @author Pier Fumagalli
 */
public final class StringTools {

    /**
The {@link SimpleDateFormat} RFC-822 date format.
 */
    private static final String FORMAT_822 = "EEE, dd MMM yyyy HH:mm:ss 'GMT'";
    /**
The {@link SimpleDateFormat} RFC-822 date format.
 */
    private static final String FORMAT_ISO = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    /**
The {@link TimeZone} to use for dates.
 */
    private static final TimeZone TIMEZONE = TimeZone.getTimeZone("GMT");
    /**
The {@link Locale} to use for dates.
 */
    private static final Locale LOCALE = Locale.US;

    /**
Deny construction.
 */
    private StringTools() { }

    /* ====================================================================== */
    /* NUMBER AND DATE PARSING AND FORMATTING                                 */
    /* ====================================================================== */

    /**
     *
Format a {@link Number} into a {@link String} making sure that
     * {@link NullPointerException}s are not thrown.

     *
     * @param number the {@link Number} to format.
     * @return a {@link String} instance or null if the object was null.
     */
    public static String formatNumber(Number number) {
        if (number == null) return null;
        return (number.toString());
    }

    /**
     *
Parse a {@link String} into a {@link Long}.

     *
     * @param string the {@link String} to parse.
     * @return a {@link Long} instance or null if the date was null or
     *         if there was an error parsing the specified {@link String}.
     */
    public static Long parseNumber(String string) {
        if (string == null) return null;
        try {
            return new Long(string);
        } catch (NumberFormatException exception) {
            return null;
        }
    }

    /**
     *
Format a {@link Date} according to the HTTP/1.1 RFC.

     *
     * @param date the {@link Date} to format.
     * @return a {@link String} instance or null if the date was null.
     */
    public static String formatHttpDate(Date date) {
        if (date == null) return null;
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_822, LOCALE);
        formatter.setTimeZone(TIMEZONE);
        return formatter.format(date);
    }

    /**
     *
Format a {@link Date} according to the ISO 8601 specification.

     *
     * @param date the {@link Date} to format.
     * @return a {@link String} instance or null if the date was null.
     */
    public static String formatIsoDate(Date date) {
        if (date == null) return null;
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_ISO, LOCALE);
        formatter.setTimeZone(TIMEZONE);
        return formatter.format(date);
    }

    /**
     *
Parse a {@link String} into a {@link Date} according to the
     * HTTP/1.1 RFC (Mon, 31 Jan 2000 11:59:00 GMT).

     *
     * @param string the {@link String} to parse.
     * @return a {@link Date} instance or null if the date was null or
     *         if there was an error parsing the specified {@link String}.
     */
    public static Date parseHttpDate(String string) {
        if (string == null) return null;
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_822, LOCALE);
        formatter.setTimeZone(TIMEZONE);
        try {
            return formatter.parse(string);
        } catch (ParseException exception) {
            return null;
        }
    }

    /**
     *
Parse a {@link String} into a {@link Date} according to the ISO 8601
     * specification (2000-12-31T11:59:00Z).

     *
     * @param string the {@link String} to parse.
     * @return a {@link Date} instance or null if the date was null or
     *         if there was an error parsing the specified {@link String}.
     */
    public static Date parseIsoDate(String string) {
        if (string == null) return null;
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_ISO, LOCALE);
        formatter.setTimeZone(TIMEZONE);
        try {
            return formatter.parse(string);
        } catch (ParseException exception) {
            return null;
        }
    }

    /* ====================================================================== */
    /* STRING SPLITTING                                                       */
    /* ====================================================================== */

    /**
     *
Split the specified string in two parts according to the specified
     * delimiter, and any resulting path of zero length will be converted to
     * null.

     */
    public static String[] splitOnce(String source, char delimiter,
                                      boolean noDelimReturnSecond) {
        if (source == null) return new String[] { null, null };
        final int position = source.indexOf(delimiter);
        if (position < 0) { // --> first
            if (noDelimReturnSecond) return new String[] { null, source };
            else return new String[] { source, null };
        } else if (position == 0) {
            if (source.length() == 1) { // --> |
                return new String[] { null, null };
            } else { // --> |second
                return new String[] { null, source.substring(1) };
            }
        } else {
            final String first = source.substring(0, position);
            if (source.length() -1 == position) { // --> first|
                return new String[] { first, null };
            } else { // --> first|second
                return new String[] { first, source.substring(position + 1) };
            }
        }
    }

    /**
     *
Split the specified string according to the specified delimiter, and
     * any resulting path of zero length will be converted to null.

     */
    public static String[] splitAll(String source, char delimiter) {
        final List strings = new ArrayList();
        String current = source;
        while (current != null) {
            String split[] = splitOnce(current, delimiter, false);
            strings.add(split[0]);
            current = split[1];
        }
        if (current != null) strings.add(current);
        final int length = source.length();
        if ((length > 0) && (source.charAt(length - 1) == delimiter)) {
            strings.add(null);
        }
        return (String []) strings.toArray(new String[strings.size()]);
    }

    /**
     *
Find the first occurrence of one of the specified delimiter characters
     * in the specified source string.

     */
    public static int findFirst(String source, String delimiters) {
        final char array[] = source.toCharArray();
        final char delim[] = delimiters.toCharArray();
        for (int x = 0; x < array.length; x ++) {
            for (int y = 0; y < delim.length; y ++) {
                if (array[x] == delim[y]) return x;
            }
        }
        return -1;
    }
}


text:
layout: page
title: Sigil Corporation Award Ceremony
date: 2016-05-24
author: Judith Stanton
tags: weekly links, java
status: published
summary: Duis eget finibus nisl. Nullam id justo ut mauris tempus.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 01/12/2019
  endDate: 01/13/2019
  ctyhocn: PVGPAHX
  groupCode: SCAC
published: true
---
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec sed sodales nisi. Nullam tempor, ex at suscipit vehicula, turpis lorem feugiat ligula, sed laoreet diam nulla sed diam. Nullam vel ligula enim. Cras tincidunt mattis faucibus. Vestibulum commodo dui nec quam ultrices ornare vitae et elit. Ut quis condimentum eros. Vivamus justo diam, gravida quis velit sed, iaculis scelerisque diam. Maecenas vel eleifend orci. In ac velit orci. Aenean eget gravida odio. In ipsum quam, pharetra vitae pellentesque nec, porttitor et est. Sed pellentesque tincidunt tincidunt. Morbi quis mauris eu sem mattis rutrum at eget magna. Fusce sit amet dui erat.

* Duis at felis eget mauris blandit tristique ut at neque
* Nam eget tortor vestibulum, ullamcorper nibh id, lobortis mi
* Nulla iaculis ipsum vel tellus imperdiet vestibulum
* Etiam laoreet odio in diam aliquam, eget efficitur urna ultrices
* Integer rhoncus enim eu risus bibendum pharetra.

Phasellus accumsan libero in cursus aliquet. Aenean facilisis consectetur eleifend. Integer consectetur urna et est rhoncus, ac condimentum tellus scelerisque. In ante enim, lacinia ut facilisis sit amet, scelerisque ut felis. Nunc consectetur, diam ac ornare egestas, nulla massa rhoncus dui, at porttitor odio ipsum eu est. Suspendisse sodales velit quis tempor volutpat. Quisque eu quam pretium, euismod nulla a, aliquam ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse rutrum lorem nec euismod volutpat. Curabitur facilisis dignissim diam, non tempor elit ultrices vitae. Morbi finibus blandit commodo.


text:
require 'spec_helper'
require_relative '../lib/web_merge/constants'
require_relative '../lib/web_merge/api'

describe WebMerge::API do
  let(:api) { described_class.new(secret: 'foo', key: 'bar', force_test_mode: true) }
  let(:document) do
    double(:document, id: 123, type: 'pdf', contents: 'things', updated_at: Time.now)
  end

  describe '#get_document_file' do

    let(:url_string) { "#{WebMerge::Constants::DOCUMENTS}/#{document.id}/file" }
    let(:response) do
      { 'type' => document.type, 'last_update' => document.updated_at, 'contents' => document.contents }
    end
    it 'makes a get request' do
      expect(api).to receive(:get).with(url_string).and_return(response)
      expect(api.get_document_file(document.id)).to eq(response)
    end
  end
end


text:
import pytest
from django.utils import timezone

from api.base.settings.defaults import API_BASE
from api.users.views import UserDraftRegistrations
from api_tests.nodes.views.test_node_draft_registration_list import DraftRegistrationTestCase
from api_tests.utils import only_supports_methods
from osf.models import RegistrationSchema
from osf_tests.factories import (
    RegistrationFactory,
    AuthUserFactory,
    DraftRegistrationFactory,
)
from osf.utils import permissions
from website.project.metadata.schemas import LATEST_SCHEMA_VERSION

@pytest.mark.django_db
class TestDraftRegistrationList(DraftRegistrationTestCase):

    @pytest.fixture()
    def other_admin(self, project_public):
        user = AuthUserFactory()
        project_public.add_contributor(user, permissions=[permissions.ADMIN], save=True)
        return user

    @pytest.fixture()
    def schema(self):
        return RegistrationSchema.objects.get(
            name='Open-Ended Registration',
            schema_version=LATEST_SCHEMA_VERSION)

    @pytest.fixture()
    def draft_registration(self, user, project_public, schema):
        return DraftRegistrationFactory(
            initiator=user,
            registration_schema=schema,
            branched_from=project_public
        )

    @pytest.fixture()
    def url_draft_registrations(self, project_public):
        return '/{}users/me/draft_registrations/'.format(API_BASE)

    def test_unacceptable_methods(self):
        assert only_supports_methods(UserDraftRegistrations, ['GET'])

    def test_view_permissions(
            self, app, user, other_admin, draft_registration,
            user_write_contrib, user_read_contrib, user_non_contrib,
            schema, url_draft_registrations):
        res = app.get(url_draft_registrations, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert len(data) == 1
        assert schema._id in data[0]['relationships']['registration_schema']['links']['related']['href']
        assert data[0]['id'] == draft_registration._id
        assert data[0]['attributes']['registration_metadata'] == {}

        res = app.get(url_draft_registrations, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert len(data) == 1
        assert schema._id in data[0]['relationships']['registration_schema']['links']['related']['href']
        assert data[0]['id'] == draft_registration._id
        assert data[0]['attributes']['registration_metadata'] == {}

        #   test_read_only_contributor_cannot_view_draft_list
        res = app.get(
            url_draft_registrations,
            auth=user_read_contrib.auth)
        assert len(res.json['data']) == 0

        #   test_read_write_contributor_cannot_view_draft_list
        res = app.get(
            url_draft_registrations,
            auth=user_write_contrib.auth)
        assert len(res.json['data']) == 0

        #   test_logged_in_non_contributor_cannot_view_draft_list
        res = app.get(
            url_draft_registrations,
            auth=user_non_contrib.auth)
        assert len(res.json['data']) == 0

        #   test_unauthenticated_user_cannot_view_draft_list
        res = app.get(url_draft_registrations, expect_errors=True)
        assert res.status_code == 401

    def test_deleted_draft_registration_does_not_show_up_in_draft_list(
            self, app, user, draft_registration, url_draft_registrations):
        draft_registration.deleted = timezone.now()
        draft_registration.save()
        res = app.get(url_draft_registrations, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert len(data) == 0

    def test_draft_with_registered_node_does_not_show_up_in_draft_list(
            self, app, user, project_public, draft_registration, url_draft_registrations):
        reg = RegistrationFactory(project=project_public)
        draft_registration.registered_node = reg
        draft_registration.save()
        res = app.get(url_draft_registrations, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert len(data) == 0

    def test_draft_with_deleted_registered_node_shows_up_in_draft_list(
            self, app, user, project_public,
            draft_registration, schema,
            url_draft_registrations):
        reg = RegistrationFactory(project=project_public)
        draft_registration.registered_node = reg
        draft_registration.save()
        reg.is_deleted = True
        reg.save()
        res = app.get(url_draft_registrations, auth=user.auth)
        assert res.status_code == 200
        data = res.json['data']
        assert len(data) == 1
        assert schema._id in data[0]['relationships']['registration_schema']['links']['related']['href']
        assert data[0]['id'] == draft_registration._id
        assert data[0]['attributes']['registration_metadata'] == {}

    def test_cannot_access_other_users_draft_registration(
            self, app, user, other_admin, project_public,
            draft_registration, schema):
        url = '/{}users/{}/draft_registrations/'.format(API_BASE, user._id)
        res = app.get(url, auth=other_admin.auth, expect_errors=True)
        assert res.status_code == 403

    def test_can_access_own_draft_registrations_with_guid(
            self, app, user, draft_registration):
        url = '/{}users/{}/draft_registrations/'.format(API_BASE, user._id)
        res = app.get(url, auth=user.auth, expect_errors=True)
        assert res.status_code == 200
        assert len(res.json['data']) == 1


text:
require 'rails_helper'

RSpec.describe "questions/index", :type => :view do
  before(:each) do
    assign(:questions, [
      Question.create!(
        :title => "Title",
        :description => "Description"
      ),
      Question.create!(
        :title => "Title",
        :description => "Description"
      )
    ])
  end

  it "renders a list of questions" do
    render
    assert_select "tr>td", :text => "Title".to_s, :count => 2
    assert_select "tr>td", :text => "Description".to_s, :count => 2
  end
end


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

import java.io.IOException;
import java.util.Set;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;

import org.apache.aurora.gen.Attribute;
import org.apache.aurora.gen.HostAttributes;
import org.apache.aurora.gen.MaintenanceMode;
import org.apache.aurora.gen.ScheduledTask;
import org.apache.aurora.scheduler.base.JobKeys;
import org.apache.aurora.scheduler.base.TaskTestUtil;
import org.apache.aurora.scheduler.storage.Storage;
import org.apache.aurora.scheduler.storage.Storage.MutableStoreProvider;
import org.apache.aurora.scheduler.storage.Storage.MutateWork;
import org.apache.aurora.scheduler.storage.Storage.StoreProvider;
import org.apache.aurora.scheduler.storage.Storage.Work;
import org.apache.aurora.scheduler.storage.entities.IHostAttributes;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import org.junit.Before;
import org.junit.Test;

import static org.apache.aurora.gen.MaintenanceMode.DRAINED;
import static org.junit.Assert.assertEquals;

public class DbAttributeStoreTest {

  private static final String HOST_A = "hostA";
  private static final String HOST_B = "hostB";
  private static final String SLAVE_A = "slaveA";
  private static final String SLAVE_B = "slaveB";
  private static final Attribute ATTR1 = new Attribute("attr1", ImmutableSet.of("a", "b", "c"));
  private static final Attribute ATTR2 = new Attribute("attr2", ImmutableSet.of("d", "e", "f"));
  private static final Attribute ATTR3 = new Attribute("attr3", ImmutableSet.of("a", "d", "g"));
  private static final IHostAttributes HOST_A_ATTRS =
      IHostAttributes.build(new HostAttributes(HOST_A, ImmutableSet.of(ATTR1, ATTR2))
          .setSlaveId(SLAVE_A)
          .setAttributes(ImmutableSet.of())
          .setMode(MaintenanceMode.NONE));
  private static final IHostAttributes HOST_B_ATTRS =
      IHostAttributes.build(new HostAttributes(HOST_B, ImmutableSet.of(ATTR2, ATTR3))
          .setSlaveId(SLAVE_B)
          .setAttributes(ImmutableSet.of())
          .setMode(MaintenanceMode.DRAINING));

  private Storage storage;

  @Before
  public void setUp() throws IOException {
    storage = DbUtil.createStorage();
  }

  @Test
  public void testCrud() {
    assertEquals(Optional.absent(), read(HOST_A));
    assertEquals(ImmutableSet.of(), readAll());

    insert(HOST_A_ATTRS);
    assertEquals(Optional.of(HOST_A_ATTRS), read(HOST_A));
    assertEquals(ImmutableSet.of(HOST_A_ATTRS), readAll());

    insert(HOST_B_ATTRS);
    insert(HOST_B_ATTRS);  // Double insert should be allowed.
    assertEquals(Optional.of(HOST_B_ATTRS), read(HOST_B));
    assertEquals(ImmutableSet.of(HOST_A_ATTRS, HOST_B_ATTRS), readAll());

    IHostAttributes updatedA = IHostAttributes.build(
        HOST_A_ATTRS.newBuilder().setAttributes(ImmutableSet.of(ATTR1, ATTR3)));
    insert(updatedA);
    assertEquals(Optional.of(updatedA), read(HOST_A));
    assertEquals(ImmutableSet.of(updatedA, HOST_B_ATTRS), readAll());

    IHostAttributes updatedMode = IHostAttributes.build(updatedA.newBuilder().setMode(DRAINED));
    insert(updatedMode);
    assertEquals(Optional.of(updatedMode), read(HOST_A));
    assertEquals(ImmutableSet.of(updatedMode, HOST_B_ATTRS), readAll());

    truncate();
    assertEquals(Optional.absent(), read(HOST_A));
    assertEquals(ImmutableSet.of(), readAll());
  }

  @Test(expected = IllegalArgumentException.class)
  public void testEmptyAttributeValues() {
    IHostAttributes attributes = IHostAttributes.build(HOST_A_ATTRS.newBuilder()
        .setAttributes(ImmutableSet.of(new Attribute("attr1", ImmutableSet.of()))));
    insert(attributes);
  }

  @Test
  public void testNoAttributes() {
    IHostAttributes attributes = IHostAttributes.build(
        HOST_A_ATTRS.newBuilder().setAttributes(ImmutableSet.of()));
    insert(attributes);
    assertEquals(Optional.of(attributes), read(HOST_A));
  }

  @Test(expected = IllegalArgumentException.class)
  public void testNoMode() {
    HostAttributes noMode = HOST_A_ATTRS.newBuilder();
    noMode.unsetMode();

    insert(IHostAttributes.build(noMode));
  }

  @Test(expected = IllegalArgumentException.class)
  public void testSaveAttributesNotSet() {
    HostAttributes attributes = HOST_A_ATTRS.newBuilder();
    attributes.unsetAttributes();

    insert(IHostAttributes.build(attributes));
  }

  @Test
  public void testSlaveIdChanges() {
    insert(HOST_A_ATTRS);
    IHostAttributes updated = IHostAttributes.build(HOST_A_ATTRS.newBuilder().setSlaveId(SLAVE_B));
    insert(updated);
    assertEquals(Optional.of(updated), read(HOST_A));
  }

  @Test
  public void testUpdateAttributesWithRelations() {
    // Test for regression of AURORA-1379, where host attribute mutation performed a delete,
    // violating foreign key constraints.
    insert(HOST_A_ATTRS);

    ScheduledTask builder = TaskTestUtil.makeTask("a", JobKeys.from("role", "env", "job"))
        .newBuilder();
    builder.getAssignedTask()
        .setSlaveHost(HOST_A_ATTRS.getHost())
        .setSlaveId(HOST_A_ATTRS.getSlaveId());
    final IScheduledTask taskA = IScheduledTask.build(builder);

    storage.write(new MutateWork.NoResult.Quiet() {
      @Override
      public void execute(MutableStoreProvider storeProvider) {
        storeProvider.getUnsafeTaskStore().saveTasks(ImmutableSet.of(taskA));
      }
    });

    HostAttributes attributeBuilder = HOST_A_ATTRS.newBuilder()
        .setMode(MaintenanceMode.DRAINED);
    attributeBuilder.addToAttributes(new Attribute("newAttr", ImmutableSet.of("a", "b")));
    IHostAttributes hostAUpdated = IHostAttributes.build(attributeBuilder);
    insert(hostAUpdated);
    assertEquals(Optional.of(hostAUpdated), read(HOST_A));
  }

  private void insert(final IHostAttributes attributes) {
    storage.write(new MutateWork.NoResult.Quiet() {
      @Override
      public void execute(MutableStoreProvider storeProvider) {
        storeProvider.getAttributeStore().saveHostAttributes(attributes);
      }
    });
  }

  private Optional<IHostAttributes> read(final String host) {
    return storage.read(new Work.Quiet<Optional<IHostAttributes>>() {
      @Override
      public Optional<IHostAttributes> apply(StoreProvider storeProvider) {
        return storeProvider.getAttributeStore().getHostAttributes(host);
      }
    });
  }

  private Set<IHostAttributes> readAll() {
    return storage.read(new Work.Quiet<Set<IHostAttributes>>() {
      @Override
      public Set<IHostAttributes> apply(StoreProvider storeProvider) {
        return storeProvider.getAttributeStore().getHostAttributes();
      }
    });
  }

  private void truncate() {
    storage.write(new MutateWork.NoResult.Quiet() {
      @Override
      public void execute(MutableStoreProvider storeProvider) {
        storeProvider.getAttributeStore().deleteHostAttributes();
      }
    });
  }
}


text:
import warnings
import numpy as np

from sklearn.base import clone
from sklearn.preprocessing import LabelBinarizer
from sklearn.multiclass import OneVsRestClassifier, _ConstantPredictor

def _fit_binary(estimator, X, y, classes=None, sample_weight=None):
    """Fit a single binary estimator."""
    unique_y = np.unique(y)
    if len(unique_y) == 1:
        if classes is not None:
            if y[0] == -1:
                c = 0
            else:
                c = y[0]
            warnings.warn("Label %s is present in all training examples." %
                          str(classes[c]))
        estimator = _ConstantPredictor().fit(X, unique_y)
    else:
        estimator = clone(estimator)
        estimator.fit(X, y, sample_weight=None)
    return estimator

class MultilabelClassifier(OneVsRestClassifier):
    """Subclasses sklearn.multiclass.OneVsRestClassifier in order to add
    sample weights. Works as original code, but forwards sample_weihts to
    base estimator

    Taken from:
    https://github.com/scikit-learn/scikit-learn/blob/a95203b/sklearn/multiclass.py#L203
    """

    def fit(self, X, y, sample_weight=None):
        """Fit underlying estimators.
        Parameters
        ----------
        X : (sparse) array-like, shape = [n_samples, n_features]
            Data.
        y : (sparse) array-like, shape = [n_samples] or [n_samples, n_classes]
            Multi-class targets. An indicator matrix turns on multilabel
            classification.
        Returns
        -------
        self
        """
        # A sparse LabelBinarizer, with sparse_output=True, has been shown to
        # outpreform or match a dense label binarizer in all cases and has also
        # resulted in less or equal memory consumption in the fit_ovr function
        # overall.
        self.label_binarizer_ = LabelBinarizer(sparse_output=True)
        Y = self.label_binarizer_.fit_transform(y)
        Y = Y.tocsc()
        columns = (col.toarray().ravel() for col in Y.T)
        # In cases where individual estimators are very fast to train setting
        # n_jobs > 1 in can results in slower performance due to the overhead
        # of spawning threads.  See joblib issue #112.
        self.estimators_ = [_fit_binary(estimator=self.estimator,
                                        X=X, y=column,
                                        classes=["not %s" % self.label_binarizer_.classes_[i], self.label_binarizer_.classes_[i]],
                                        sample_weight=sample_weight)
                            for i, column in enumerate(columns)]

        return self


text:
namespace Eft.Locators.Selectors
{
    public class PositionalSelector : Selector
    {
        private readonly Selector selector;
        private readonly Position position;

        public PositionalSelector(Selector selector, Position position)
        {
            this.selector = selector;
            this.position = position;
        }

        public Selector Selector
        {
            get { return selector; }
        }

        public Position Position
        {
            get { return position; }
        }
    }
}


text:
{{program.displayName}} filters

        <button *ngIf="container.length < MAX_FILTERS" type="button" class="btn btn-default" (click)="addAttribute()">Add new filter</button>


text:
(function() {
  'use strict';

  angular.module('words').constant('vkAppId', '5847929')
  .factory('vkAuthService', ['$window', '$cookies', '$log', 'userService','vkAppId', function($window, $cookies, $log, userService, vkAppId) {

    function buildToken(session) {
      return 'expire=' + session.expire + 'mid=' + session.mid + 'secret=' + session.secret + 'sid=' + session.sid + '&' + session.sig;
    }

    var clearUserData = function() {
      userService.clear();
      $cookies.remove('auth-type');
      $cookies.remove('token');
    }

    function onConnection(res, callback) {
      if(res.status === 'connected') {
        var name = res.session.user.nickname || res.session.user.first_name + ' ' + res.session.user.last_name;
        userService.set(name);
        var token = buildToken(res.session);
        $cookies.put('auth-type', 'vk');
        $cookies.put('token', token);
        callback();
      } else {
        $log.log(res);
        clearUserData();
      }
    }

    return {
      init: function(callback) {
        $window.vkAsyncInit = function() {
          VK.init({
            apiId: vkAppId
          });

          VK.Observer.subscribe('auth.sessionChange', function(res) {
            callback(res, callback);
          });
        };

      },
      login: function(callback) {
        VK.Auth.login(function(res) {
          onConnection(res, callback);
        });
      },
      logout: function() {
        VK.Auth.logout(function() {
          clearUserData();
        });
      }
    };
  }]);
}());


text:
<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Command;

use Doctrine\ODM\MongoDB\Tools\Console\Command\ClearCache\MetadataCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Command to clear the metadata cache of the various cache drivers.
 */
class ClearMetadataCacheDoctrineODMCommand extends MetadataCommand
{
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('doctrine:mongodb:cache:clear-metadata')
            ->setDescription('Clear all metadata cache for a document manager.')
            ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
            ->setHelp(<<<EOT
The <info>doctrine:mongodb:cache:clear-metadata</info> command clears all metadata cache for the default document manager:

  <info>./app/console doctrine:mongodb:cache:clear-metadata</info>

You can also optionally specify the <comment>--dm</comment> option to specify which document manager to clear the cache for:

  <info>./app/console doctrine:mongodb:cache:clear-metadata --dm=default</info>
EOT
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));

        return parent::execute($input, $output);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:angle="270"
              android:centerColor="#00000000"
              android:endColor="#AA000000"
        />
</shape>