text:
package fr.inria.jessy.vector;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Map;

import com.sleepycat.persist.model.Persistent;

import fr.inria.jessy.ConstantPool;

/**
 * @author Masoud Saeida Ardekani This class implements dependence vector for
 *         jessy objects.
 *
 *         TODO WRITE DOCs
 */

@Persistent
public class DependenceVector<K> extends Vector<K> implements Externalizable {

	private static final long serialVersionUID = -ConstantPool.JESSY_MID;

	/**
	 * Needed for BerkeleyDB
	 */
	@Deprecated
	public DependenceVector() {
		super();
	}

	public DependenceVector(K selfKey) {
		super(selfKey);
		super.setValue(selfKey, 0);
	}

	@Override
	public CompatibleResult isCompatible(Vector<K> other) throws NullPointerException {
		// check special values
		if (other == null) {
			throw new NullPointerException("Input Vector is Null");
		}

		Integer selfValueOnSelfKey = getSelfValue();
		Integer otherValueOnSelfKey = other.getValue(selfKey);

		Integer selfValueOnOtherKey = getValue(other.getSelfKey());
		Integer otherValueOnOtherKey = other.getSelfValue();

		if (selfValueOnSelfKey >= otherValueOnSelfKey
				&& otherValueOnOtherKey >= selfValueOnOtherKey) {
			return Vector.CompatibleResult.COMPATIBLE;
		}

		return Vector.CompatibleResult.NOT_COMPATIBLE_TRY_NEXT;
	}

	@Override
	public CompatibleResult isCompatible(CompactVector<K> other)
			throws NullPointerException {
		// check special values

		if (other == null) {
			throw new NullPointerException("Input Vector is Null");
		}

		if (other.size() == 0)
			return Vector.CompatibleResult.COMPATIBLE;

		Integer selfValueOnSelfKey = getSelfValue();
		Integer otherValueOnSelfKey = other.getValue(selfKey);

		if (selfValueOnSelfKey < otherValueOnSelfKey) {
			return Vector.CompatibleResult.NOT_COMPATIBLE_TRY_NEXT;
		}

		Integer selfValueOnOtherKey;
		Integer otherValueOnOtherKey;

		for (K k : other.getKeys()) {
			selfValueOnOtherKey = getValue(k);
			otherValueOnOtherKey = other.getValue(k);

			if (otherValueOnOtherKey < selfValueOnOtherKey) {
				return Vector.CompatibleResult.NOT_COMPATIBLE_TRY_NEXT;
			}

		}

		return Vector.CompatibleResult.COMPATIBLE;
	}

	/**
	 * update method gets two {@link CompactVector} as readSet and writeSet and
	 * applies them into its local vector. <b> this implementation does not
	 * assume read before write rule <\b>
	 */
	@Override
	public void update(CompactVector<K> readSet, CompactVector<K> writeSet) {
		// Readset can be simply applied by using the update method of
		// ValueVector Class
		if (readSet.size() > 0)
			super.update(readSet);

		// Write set is more involved.
		Integer value;

		for (Map.Entry<K, Integer> entry : writeSet.getEntrySet()) {
			K key = entry.getKey();
			value = entry.getValue();
			if (writeSet.getKeys().contains(key))
				value++;
			if (getValue(key).compareTo(value) < 0) {
				setValue(key, value);
			}
		}

	}

	@Override
	public DependenceVector<K> clone() {
		return (DependenceVector<K>) super.clone();
	}

	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		super.readExternal(in);
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		super.writeExternal(out);
	}
}

//@Override
//public boolean isCompatible(List<Vector<K>> otherList)
//		throws NullPointerException {
//	// check special values
//	if (otherList == null) {
//		throw new NullPointerException("Input Vector is Null");
//	}
//
//	for (Vector<K> other : otherList) {
//		if (isCompatible(other) == false)
//			return false;
//	}
//	return true;
//}
//
//@Override
//public void update(List<Vector<K>> readList, List<Vector<K>> writeList) {
//	for (Vector<K> readVector : readList) {
//		super.update(readVector);
//	}
//
//	for (Vector<K> writeVector : writeList) {
//		super.update(writeVector);
//		super.setValue(writeVector.getSelfKey(),
//				writeVector.getSelfValue() + 1);
//	}
//}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<!--

-->
<metainfo>
  <schemaVersion>2.0</schemaVersion>
  <services>
    <service>
      <name>SPARK</name>
      <extends>common-services/SPARK/1.6.0</extends>
      <version>1.6.1</version>
      <deleted>true</deleted>

      <configuration-dependencies>
        <config-type>spark-defaults</config-type>
        <config-type>spark-env</config-type>
        <config-type>spark-log4j-properties</config-type>
        <config-type>spark-metrics-properties</config-type>
        <config-type>spark-thrift-sparkconf</config-type>
        <config-type>spark-hive-site-override</config-type>
        <config-type>spark-thrift-fairscheduler</config-type>
      </configuration-dependencies>

      <osSpecifics>
        <osSpecific>
          <osFamily>redhat7,amazon2015,redhat6,suse11,suse12</osFamily>
          <packages>
            <package>
              <name>spark-core_4_2_5_0*</name>
            </package>
            <package>
              <name>spark_4_2_5_0_*</name>
            </package>
          </packages>
        </osSpecific>
        <osSpecific>
          <osFamily>debian7,ubuntu12,ubuntu14</osFamily>
          <packages>
            <package>
              <name>spark-core-4_2_5*</name>
            </package>
            <package>
              <name>spark-4_2_5_*</name>
            </package>
          </packages>
        </osSpecific>
      </osSpecifics>

    </service>
  </services>
</metainfo>


text: var v = @decorate class C { static p = 1 };


text:
var express = require('express'),
    router = express.Router(),
    messagingService = require('../service/messagingService');

// TODO: simple endpoint to test the sending of message to kafka
// delete this and the index.js entry once we have the journaling stuff working
// call it with api/kafka/{message} and you should see the parm in the consumer
router.get('/:message', function (req, res) {

    messagingService.postMessage('test', req.param('message'))
        .then(
            function (data) {
                return res.send(data);
            },
            function (error) {
                res.status(500).send(error);
            });

});

module.exports = router;


text:
module Authentication
  module ApplicationHelper
  end
end


text:
/* -*- mode: c++ -*- */
/*
 * Copyright 2017-2018 Scality
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#ifndef __QUAD_ARITH_H__
#define __QUAD_ARITH_H__

#include <cassert>
#include <cstdlib>
#include <vector>

#include "big_int.h"
#include "core.h"
#include "exceptions.h"

namespace quadiron {

template <typename T>
using DoubleSizeVal = typename DoubleSize<T>::T;

template <typename T>
using SignedDoubleSizeVal = typename SignedDoubleSize<T>::T;

/** Base/core arithmetical functions of QuadIron. */
namespace arith {

template <typename T>
T sqrt(T n);
template <typename T>
T exp(T base, T exponent);
template <typename T>
T exp_mod(T base, T exponent, T modulus);
template <typename T>
bool is_power_of_2(int x);
template <typename T>
T ceil2(int x);
template <typename T>
int log2(int x);
template <typename T>
int exp2(int x);
template <typename T>
SignedDoubleSizeVal<T> extended_gcd(
    SignedDoubleSizeVal<T> a,
    SignedDoubleSizeVal<T> b,
    SignedDoubleSizeVal<T> bezout_coef[2],
    SignedDoubleSizeVal<T> quotient_gcd[2]);
template <typename T>
T chinese_remainder(int n_mod, T a[], T n[]);
template <typename T>
int jacobi(SignedDoubleSizeVal<T> n, SignedDoubleSizeVal<T> m);
template <typename T>
bool solovay_strassen1(T a, T n);
template <typename T>
bool solovay_strassen(T n, T (*rand_func)(T n));
template <typename T>
bool is_prime(T n);
template <typename T>
T gcd(T u, T v);
template <typename T>
std::vector<T> factor_distinct_prime(T n);
template <typename T>
void factor_prime(T nb, std::vector<T>* primes, std::vector<int>* exponent);
template <typename T>
std::vector<T> get_proper_divisors(T n);
template <typename T>
std::vector<T> get_proper_divisors(T n, const std::vector<T>& primes);
template <typename T>
std::vector<T> get_all_divisors(T n);
template <typename T>
T get_code_len(T order, T n);
template <typename T>
T get_code_len_high_compo(T order, T n);
template <typename T>
T get_code_len_high_compo(const std::vector<T>& factors, T n);
template <typename T>
std::vector<T> get_coprime_factors(T nb);
template <typename T>
std::vector<T> get_prime_factors(T nb);
template <typename T>
std::vector<T> get_prime_factors(
    const std::vector<T>& primes,
    const std::vector<int>& exponent);

/** Compute the integer square root.
 *
 * @param[in] n a value
 * @return the integer square root of `n`
 *
 * @pre `n` must be strictly positive.
 */
// Taken from Wikipedia.
template <typename T>
T sqrt(T n)
{
    T place = static_cast<T>(1) << (sizeof(T) * CHAR_BIT - 2);

    while (place > n) {
        place /= 4;
    }

    T root = 0;
    while (place) {
        if (n >= root + place) {
            n -= root + place;
            root += place * 2;
        }
        root /= 2;
        place /= 4;
    }

    return root;
}

/** Compute the regular exponentation.
 *
 * @param[in] base the base `b`
 * @param[in] exponent the exponent `e`
 * @return the value of \f$b^e\f$
 */
template <typename T>
T exp(T base, T exponent)
{
    if (exponent == 0) {
        return 1;
    }
    T result = 1;
    while (true) {
        if (exponent % 2 == 1) {
            result *= base;
        }
        exponent >>= 1;
        if (exponent == 0) {
            break;
        }
        base *= base;
    }

    return result;
}

/** Compute the modular exponentation.
 *
 * @param[in] base the base `b`
 * @param[in] exponent the exponent `e`
 * @param[in] modulus the modulus `m`
 * @return the value of \f$b^e \mod m\f$
 */
// Taken from Applied Cryptography by Bruce Schneier.
template <typename T>
T exp_mod(T base, T exponent, T modulus)
{
    if (modulus == 1) {
        return 0;
    }

    T result = 1;
    base = base % modulus;
    while (exponent > 0) {
        if (exponent % 2 == 1) {
            result = (result * base) % modulus;
        }
        exponent = exponent >> 1;
        base = (base * base) % modulus;
    }

    return result;
}

/** Test if `n` is a power of two.
 *
 * @param[in] n a number
 * @return true if `n` is a power of two.
 */
template <typename T>
bool is_power_of_2(int n)
{
    return n > 0 && !(n & (n - 1));
}

/** Round up to the next power of two.
 *
 * @param[in] n a number
 * @return a power of two greater than or equal to `n`
 */
template <typename T>
T ceil2(int n)
{
    if (is_power_of_2<T>(n)) {
        return n;
    }
    return exp2<T>(log2<T>(n) + 1);
}

/** Compute the binary logarithm.
 *
 * @param[in] n a number
 * @return the value of \f$log_2(n)\f$
 *
 * @pre `n` must be strictly positive.
 */
template <typename T>
int log2(int n)
{
    if (n == 0) {
        throw DomainError("pole error: n is zero");
    }
    if (n == 1) {
        return 0;
    }

    int result = 0;
    while (n > 1) {
        n >>= 1;
        result++;
    }

    return result;
}

/** Compute \f$2^n\f$.
 *
 * @param[in] n a number
 * @return the value of \f$2^n\f$
 */
template <typename T>
int exp2(int n)
{
    return static_cast<T>(1) << n;
}

/** Compute the Extended Euclidean algorithm.
 *
 * Perform ax+by = gcd(a, b)
 *   If a and b are coprime then:
 *         x = inv(a) mod b
 *         y = inv(b) mod a
 *
 * @param[in] a a number
 * @param[in] b a number
 * @param[out] bezout_coef computed bezout coefficients, might be nullptr
 * @param[out] quotient_gcd computed quotient by the GCD, might be nullptr
 *
 * @todo take care of the signs of input
 *
 * @return the GCD
 */
// Taken from Wikipedia.
template <typename T>
SignedDoubleSizeVal<T> extended_gcd(
    SignedDoubleSizeVal<T> a,
    SignedDoubleSizeVal<T> b,
    SignedDoubleSizeVal<T> bezout_coef[2],
    SignedDoubleSizeVal<T> quotient_gcd[2])
{
    SignedDoubleSizeVal<T> s = 0;
    SignedDoubleSizeVal<T> old_s = 1;
    SignedDoubleSizeVal<T> t = 1;
    SignedDoubleSizeVal<T> old_t = 0;
    SignedDoubleSizeVal<T> r = b;
    SignedDoubleSizeVal<T> old_r = a;
    SignedDoubleSizeVal<T> quotient;
    SignedDoubleSizeVal<T> tmp;

    while (0 != r) {
        quotient = old_r / r;

        tmp = r;
        r = old_r - quotient * r;
        old_r = tmp;

        tmp = s;
        s = old_s - quotient * s;
        old_s = tmp;

        tmp = t;
        t = old_t - quotient * t;
        old_t = tmp;
    }

    if (bezout_coef) {
        bezout_coef[0] = old_s;
        bezout_coef[1] = old_t;
    }

    if (quotient_gcd) {
        quotient_gcd[0] = t;
        quotient_gcd[1] = s;
    }

    return old_r;
}

/** Apply the Chinese remainder theorem.
 *
 * @param[in] n_mod number of moduli
 * @param[in] a the a's (integers)
 * @param[in] n the n's (moduli)
 *
 * @todo Check if there is a solution.
 *
 * @return the solution.
 */
// Taken from Wikipedia.
template <typename T>
T chinese_remainder(int n_mod, T a[], T n[])
{
    SignedDoubleSizeVal<T> acc;
    SignedDoubleSizeVal<T> x;
    SignedDoubleSizeVal<T>* N = new SignedDoubleSizeVal<T>[n_mod];
    SignedDoubleSizeVal<T>* M = new SignedDoubleSizeVal<T>[n_mod];

    acc = 1;
    for (int i = 0; i < n_mod; i++) {
        acc *= n[i];
    }

    for (int i = 0; i < n_mod; i++) {
        SignedDoubleSizeVal<T> bezout[2];

        N[i] = acc / n[i];
        extended_gcd<T>(N[i], n[i], bezout, nullptr);
        M[i] = bezout[0]; // XXX % n[i];
    }

    x = 0;
    for (int i = 0; i < n_mod; i++) {
        x += N[i] * M[i] * a[i];
    }

    delete[] N;
    delete[] M;

    x = x % acc;

    if (x < 0) {
        x = acc + x;
    }

    return x;
}

/** Compute the Jacobi symbol of the numbers `n` and `m`.
 *
 * The Jacobi symbol is defined as follow:
 *    n    |  0 if n % m == 0
 *  ( _) = |  1 if n % m != 0 and for some x, n % m == x^2 (quadratic residue)
 *    m    | -1 if n % m != 0 and there is no such x
 *
 * @param[in] n a value
 * @param[in] m a modulus
 *
 * @return the Jacobi symbol
 * @throw DomainError if b is even or b is negative
 */
// Taken from https://groups.google.com/forum/#!topic/sci.crypt/v9_cNF06XjU
template <typename T>
int jacobi(SignedDoubleSizeVal<T> n, SignedDoubleSizeVal<T> m)
{
    SignedDoubleSizeVal<T> t;
    int jac;

    if ((m % 2) == 0) {
        throw DomainError("m must be odd");
    }
    if (m < 0) {
        throw DomainError("m must be positive");
    }

    jac = 1;
    while (m != 1) {
        // if the gcd of $n$ and $m$ is $>1$ Jacobi returns $0$
        if ((n == 0) || ((n % 2 == 0) && (m % 2 == 0))) {
            jac = 0;
            m = 1;
        }
        // $J(n,2*m) = J(n,m) * J(n,2) = J(n,m) * (-1)^{(n^2-1)/8}$
        else if (m % 2 == 0) {
            if ((n % 8 == 3) || (n % 8 == 5))
                jac = -jac;
            m = m / 2;
        }
        // $J(2*n,m) = J(n,m) * J(2,m) = J(n,m) * (-1)^{(m^2-1)/8}$
        else if (n % 2 == 0) {
            if ((m % 8 == 3) || (m % 8 == 5))
                jac = -jac;
            n = n / 2;
        }
        // $J(-n,m) = J(n,m) * J(-1,m) = J(n,m) * (-1)^{(m-1)/2}$
        else if (n < 0) {
            if (m % 4 == 3)
                jac = -jac;
            n = -n;
        }
        // $J(n,m) = J(m,n) * (-1)^{(n-1)*(m-1)/4}$ (quadratic reciprocity)
        else {
            if ((n % 4 == 3) && (m % 4 == 3))
                jac = -jac;
            t = n;
            n = m % n;
            m = t;
        }
    }

    return jac;
}

template <typename T>
bool solovay_strassen1(T a, T n)
{
    const T exponent = (n - 1) / 2;
    const T res = exp_mod(a, exponent, n);
    int j = jacobi<T>(a, n);
    T _res;
    if (j < 0) {
        _res = res - n;
    } else {
        _res = res;
    }
    return j == _res;
}

/** Perform the Solovay–Strassen primality test.
 *
 * @param n check if `n` is prime
 * @param rand_func return a random number between 0 and n-1
 * @return true if `n` is (probably) prime else false.
 */
template <typename T>
bool solovay_strassen(T n, T (*rand_func)(T n))
{
    for (int i = 0; i < 100; i++) {
        T a = rand_func(n);
        if (!solovay_strassen1(a, n))
            return false;
    }
    return true;
}

/** Brute force prime checking until sqrt(n)
 *
 * @param[in] n a number
 * @return true if `n` is a prime number, otherwise false
 */
template <typename T>
bool is_prime(T n)
{
    if (n == 2)
        return true;

    T root = sqrt<T>(n);
    for (T i = 2; i <= root; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}

/** Factor a given number into distinct primes.
 *
 * @param nb the number to factorize.
 * @return the list of prime factor
 *
 * @note Only primes are stored, their exponent is ignored.
 */
template <typename T>
std::vector<T> factor_distinct_prime(T nb)
{
    std::vector<T> primes;
    T last_found = 1;

    while (nb % 2 == 0) {
        if (last_found != 2) {
            primes.push_back(2);
            last_found = 2;
        }
        nb = nb / 2;
    }
    // `nb` must be odd at this point => we can skip one element.
    assert((nb & 1) == 1);
    for (T i = 3; i <= sqrt<T>(nb); i = i + 2) {
        // While `i` divides `nb`, get `i` and divide `nb`.
        while (nb % i == 0) {
            if (last_found != i) {
                primes.push_back(i);
                last_found = i;
            }
            nb = nb / i;
        }
    }
    // Handle the case when `nb` is a prime number greater than 2.
    if (nb > 2) {
        primes.push_back(nb);
    }

    return primes;
}

/// Get the proper divisors of a number.
template <typename T>
std::vector<T> get_proper_divisors(T nb)
{
    const std::vector<T> primes = factor_distinct_prime<T>(nb);
    return get_proper_divisors(nb, primes);
}

/// Get proper divisors of a number from its factored distinct primes.
template <typename T>
std::vector<T> get_proper_divisors(T nb, const std::vector<T>& primes)
{
    std::vector<T> divisors;

    for (auto prime : primes) {
        if (prime < nb) {
            divisors.push_back(nb / prime);
        }
    }

    return divisors;
}

/// Factor a given number into primes.
template <typename T>
void factor_prime(T nb, std::vector<T>* primes, std::vector<int>* exponent)
{
    int occurence = 0;

    assert(primes != nullptr);
    assert(exponent != nullptr);

    while (nb % 2 == 0) {
        occurence++;
        if (occurence == 1) {
            primes->push_back(2);
        }
        nb = nb / 2;
    }

    if (occurence > 0) {
        exponent->push_back(occurence);
        occurence = 0;
    }
    // `nb` must be odd at this point => we can skip one element.
    assert((nb & 1) == 1);
    for (T i = 3; i <= sqrt<T>(nb); i = i + 2) {
        // While `i` divides `nb`, get `i` and divide `nb`.
        while (nb % i == 0) {
            occurence++;
            if (occurence == 1) {
                primes->push_back(i);
            }
            nb = nb / i;
        }
        if (occurence > 0) {
            exponent->push_back(occurence);
            occurence = 0;
        }
    }
    // Handle the case when `nb` is a prime number greater than 2.
    if (nb > 2) {
        primes->push_back(nb);
        exponent->push_back(1);
    }
}

/** Modern Euclidean algorithm implementation
 *
 * This is an implementation of the Algorithm A, p.322 of "The Art of Computer
 * Programming" by Donald Knuth
 *
 * @param[in] u a number
 * @param[in] v a number
 * @return the GCD(u, v)
 */
template <typename T>
T gcd(T u, T v)
{
    T r;
    if (v == 0)
        return u;
    if (u == 0)
        return v;
    while (1) {
        r = u % v;
        if (r == 0)
            return v;
        u = v;
        v = r;
    }
}

/// Compute all divisors of a number.
template <typename T>
std::vector<T> get_all_divisors(T n)
{
    std::vector<T> divisors;
    std::vector<T> n_div_i;

    for (T i = 1; i <= sqrt<T>(n); i++) {
        // While `i` divides `nb`, get `i` and divide `nb/i`.
        if (n % i == 0) {
            divisors.push_back(i);
            n_div_i.push_back(n / i);
        }
    }
    divisors.insert(divisors.end(), n_div_i.rbegin(), n_div_i.rend());

    return divisors;
}

/** Find smallest number that is ≥ `n` and divisible by `order`.
 *
 * @param[in] order a prime number
 * @param[in] n the lower bound for the result
 * @return the code length
 */
template <typename T>
T get_code_len(T order, T n)
{
    if (order % n == 0) {
        return n;
    }
    if (order < n) {
        assert(false);
    }
    T nb_sqrt = sqrt<T>(order);
    T i;
    if (n > nb_sqrt) {
        for (i = order / n; i >= 1; i--) {
            // if i divides n, return n/i
            if (order % i == 0) {
                return order / i;
            }
        }
        assert(false);
    }
    for (i = n; i <= nb_sqrt; i++) {
        // if i divides n, return i
        if (order % i == 0) {
            return i;
        }
    }
    // order is prime
    return order;
}

/** Find smallest number that is highly composite, ≥ `n` and divisible by
 * `order`.
 *
 * @param[in] order a prime number
 * @param[in] n the lower bound for the result
 * @return the code length
 */
template <typename T>
T get_code_len_high_compo(T order, T n)
{
    assert(order >= n);
    return get_code_len_high_compo(get_prime_factors<T>(order), n);
}

/** Find smallest number that is highly composite and ≥ `n`
 *
 * @param[in] factors vector of all prime factors of a given order
 * @param[in] n the lower bound for the result
 * @return the code length
 */
template <typename T>
T get_code_len_high_compo(const std::vector<T>& factors, T n)
{
    T x = 1;
    typename std::vector<T>::size_type i, j;
    // forward to get a divisor of (q-1) >= n and of highly composited
    for (i = 0; i != factors.size(); ++i) {
        x *= factors[i];
        if (x >= n) {
            // backward to get smaller number
            for (j = 0; j != i + 1 && j != factors.size(); j++) {
                x /= factors[j];
                if (x < n) {
                    return x * factors[j];
                }
            }
        }
    }
    assert(false);
    return 0;
}

/** Get all the coprime factors of a number.
 *
 * @param nb the number to be factored
 * @return the co-prime divisors of `nb`
 */
template <typename T>
std::vector<T> get_coprime_factors(T nb)
{
    std::vector<T> coprimes;
    std::vector<T> primes;
    std::vector<int> exponents;

    factor_prime<T>(nb, &primes, &exponents);
    assert(primes.size() == exponents.size());

    coprimes.reserve(primes.size());
    for (size_t i = 0; i != primes.size(); ++i) {
        coprimes.push_back(exp<T>(primes[i], exponents[i]));
    }

    return coprimes;
}

/** Get all the prime factors of a number.
 *
 * @param nb the number to be factored
 * @return the prime factors of `nb`.
 */
template <typename T>
std::vector<T> get_prime_factors(T nb)
{
    std::vector<T> primes;
    std::vector<int> exponent;

    factor_prime<T>(nb, &primes, &exponent);
    return get_prime_factors<T>(primes, exponent);
}

/** Get all prime factors of a number from pre-computed primes and exponents.
 *
 * @param primes primes
 * @param exponents exponents for each prime
 * @return the prime factors of `nb`.
 *
 * @pre `primes` and `exponents` must have the same size.
 */
template <typename T>
std::vector<T> get_prime_factors(
    const std::vector<T>& primes,
    const std::vector<int>& exponents)
{
    std::vector<T> factors;
    assert(primes.size() == exponents.size());

    for (size_t i = 0; i != primes.size(); ++i) {
        for (int j = 0; j != exponents[i]; ++j) {
            factors.push_back(primes[i]);
        }
    }
    return factors;
}

} // namespace arith
} // namespace quadiron

#endif


text:
var equal = require('assert').equal;
var deepEqual = require('assert').deepEqual;
var lines = require('../lines');

test('#lines', function() {
  equal(lines('Hello\nWorld').length, 2);
  equal(lines('Hello\rWorld').length, 2);
  equal(lines('Hello World').length, 1);
  equal(lines('\r\n\n\r').length, 4);
  equal(lines('Hello\r\r\nWorld').length, 3);
  equal(lines('Hello\r\rWorld').length, 3);
  equal(lines(123).length, 1);
  deepEqual(lines(''), ['']);
  deepEqual(lines(null), []);
  deepEqual(lines(undefined), []);
  deepEqual(lines('Hello\rWorld'), ['Hello', 'World']);
  deepEqual(lines('Hello\r\nWorld'), ['Hello', 'World']);
});


text:
class AddClassificationsAndChangeClassificationIdInBooks < ActiveRecord::Migration[5.0]
  def change
    rename_column :books, :classification_id, :category_id
    add_column :books, :classification, :integer
  end
end


text:
const electron = require('electron');
const remote = electron.remote;
import React, { Component, PropTypes } from 'react';
import cx from 'classnames';
import event from '../../backend/event';
import Lang from '../../backend/language';
import Router, {Link} from 'react-router';
const settingsWindow = remote.getGlobal('settingsWindow');

class Sidebar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            activeIndex: 0,
        }
    }

    componentWillReceiveProps (nextProps) {

    }

    handleSettingsClick () {
        if (!settingsWindow.isVisible()) {
            settingsWindow.show();
        }
        if (settingsWindow.isMinimized()) {
            settingsWindow.restore();
        }
        settingsWindow.focus();
        //setDockIconVisibility();
    }

    handleClickLink(index){
        this.setState({activeIndex: index});
    }

    __renderSidebarItem (item, index) {
        const activeIndex = this.state.activeIndex;
        //const { active, onEdit, onClick, onRemove } = this.props;
        /*const classNames = cx({
            'sidebar-item': true,
            'active': active,
        });*/
        return (

                        <Link to={item.to} className={item.className} onClick={this.handleClickLink.bind(this, index)}></Link>

        );
    }

    render() {
        const sidebarItems = this.props.list.map((item, index) => {
            return this.__renderSidebarItem(item, index);
        });
        return (

                    { sidebarItems }

                        <Link to="setting">  </Link>

        );
    }
}

Sidebar.propTypes = {
    list: PropTypes.array
};

export default Sidebar;


text:
using P01.SchoolClasses.Contracts;

namespace P01.SchoolClasses.Models
{
    public class Discipline : INamable, ICommentable
    {
        private string name;
        private int numberOfLectures;
        private int numberOfExercises;
        private string comment;

        public Discipline(string name, int numberOfLectures, int numberOfExercises)
        {
            this.Name = name;
            this.NumberOfLectures = numberOfLectures;
            this.NumberOfExercises = numberOfExercises;
        }

        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }

        public int NumberOfLectures
        {
            get { return this.numberOfLectures; }
            set { this.numberOfLectures = value; }
        }

        public int NumberOfExercises
        {
            get { return this.numberOfExercises; }
            set { this.numberOfExercises = value; }
        }

        public string Comment
        {
            get { return this.comment; }
            set { this.comment = value; }
        }
    }
}


text:
BEGIN_INANITY_MONO

Any::Any(ptr<State> state, MonoObject* object)
: state(state), object(object)
{
	handle = object ? mono_gchandle_new(object, true) : 0;
}

Any::~Any()
{
	if(object)
		mono_gchandle_free(handle);
}

ptr<State> Any::GetState() const
{
	return state;
}

MonoObject* Any::GetObject() const
{
	return object;
}

bool Any::IsNull() const
{
	return !!object;
}

bool Any::IsBoolean() const
{
	return mono_object_isinst(object, mono_get_boolean_class());
}

bool Any::IsNumber() const
{
	decltype(&mono_get_byte_class) classes[] =
	{
		&mono_get_byte_class,
		&mono_get_sbyte_class,
		&mono_get_int16_class,
		&mono_get_int32_class,
		&mono_get_int64_class,
		&mono_get_uint16_class,
		&mono_get_uint32_class,
		&mono_get_uint64_class,
		&mono_get_intptr_class,
		&mono_get_uintptr_class,
		&mono_get_single_class,
		&mono_get_double_class
	};
	for(size_t i = 0; i < sizeof(classes) / sizeof(classes[0]); ++i)
		if(mono_object_isinst(object, classes[i]()))
			return true;
	return false;
}

bool Any::IsString() const
{
	return mono_object_isinst(object, mono_get_string_class());
}

bool Any::IsArray() const
{
	return mono_object_isinst(object, mono_get_array_class());
}

bool Any::IsFunction() const
{
	// not implemented yet
	return false;
}

bool Any::IsObject() const
{
	return State::instance->IsObjectWrapper(object);
}

ptr<RefCounted> Any::AsObject() const
{
	return State::instance->UnwrapObject(object);
}

bool Any::AsBool() const
{
	return *(MonoBoolean*)mono_object_unbox(object);
}

int Any::AsInt() const
{
	return *(int*)mono_object_unbox(object);
}

float Any::AsFloat() const
{
	return *(float*)mono_object_unbox(object);
}

double Any::AsDouble() const
{
	return *(double*)mono_object_unbox(object);
}

String Any::AsString() const
{
	if(!IsString())
		THROW("Any is not a string");
	return Value<String>::From((MonoString*)object);
}

ptr<Script::Any> Any::CallWith(ptr<Script::Any> arguments[], int count)
{
	THROW("Not implemented yet");
}

ptr<Script::Any> Any::ApplyWith(ptr<Script::Any> thisValue, ptr<Script::Any> arguments[], int count)
{
	THROW("Not implemented yet");
}

int Any::GetLength() const
{
	return (int)mono_array_length((MonoArray*)object);
}

ptr<Script::Any> Any::Get(int index) const
{
	MonoClass* elementClass = mono_class_get_element_class(mono_object_get_class(object));
	void* element = mono_array_addr_with_size(
		(MonoArray*)object,
		mono_class_array_element_size(elementClass),
		index);
	MonoObject* result;
	if(mono_type_is_reference(mono_class_get_type(elementClass)))
		result = *(MonoObject**)element;
	else
		result = mono_value_box(state->GetDomain(), elementClass, element);
	return state->CreateAny(result);
}

ptr<Script::Any> Any::Get(ptr<Script::Any> index) const
{
	return Get(index->AsInt());
}

void Any::Set(int index, ptr<Script::Any> value)
{
	MonoClass* elementClass = mono_class_get_element_class(mono_object_get_class(object));
	int32_t elementSize = mono_class_array_element_size(elementClass);
	void* element = mono_array_addr_with_size((MonoArray*)object, elementSize, index);
	MonoObject* valueObject = fast_cast<Any*>(&*value)->GetObject();
	if(mono_type_is_reference(mono_class_get_type(elementClass)))
		*(MonoObject**)element = valueObject;
	else
		memcpy(element, mono_object_unbox(valueObject), elementSize);
}

void Any::Set(ptr<Script::Any> index, ptr<Script::Any> value)
{
	Set(index->AsInt(), value);
}

void Any::Dump(std::ostream& stream) const
{
	THROW("Not implemented yet");
}

END_INANITY_MONO


text:
using AutoMapper;

using Marketplace.Client.Models.Geography;
using Marketplace.Domain.Models.Geography;

namespace Marketplace.Api.Mappings.Geography
{
    public class ProvinceMap : Profile
    {
        public ProvinceMap()
        {
            CreateMap<Province, ProvinceModel>()
                .ReverseMap();
        }
    }
}


text:
<?php

namespace GassTests\TestDoubles\BotInfo;

use Gass\BotInfo\BotInfoInterface;

abstract class BaseEmpty implements BotInfoInterface
{
    public function __construct(array $options = array())
    {
    }

    public function setOptions(array $options)
    {
    }

    public function setOption($name, $value)
    {
    }

    public function getOptions()
    {
    }

    public function getOption($name)
    {
    }

    public function isBot($userAgent = null, $remoteAddress = null)
    {
    }

    public function getRemoteAddress()
    {
    }

    public function getUserAgent()
    {
    }

    public function setRemoteAddress($remoteAddress)
    {
    }

    public function setUserAgent($userAgent)
    {
    }
}


text:
layout: page
title: Contact
permalink: /contact/
---

Our laboratory is located at the Mission Bay campus in sunny south-east San Francisco. It is a couple of blocks from SBC Park, home of the SF Giants, and within walking distance of bars, restaurants and shopping in the Potrero, Mission and SOMA districts. There is on-campus housing at Mission Bay as well as a brand new Recreation Center, including two pools.

![bridge](../img/golden.gif)

Map of Mission Bay campus

Mailing Address:
SHAH LAB
UCSF/ MC 2722
RH - 345
1550 4th Street
San Francisco, CA 94158-2722

Tel: 415.514.4383
Fax: 415.514.4360

Administrative Assistant:
Mayra Melville
415.476.0873
(mayra dot melville at ucsf dot edu)


text:
package org.jscep.jester.io;

import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.encoders.Base64;
import org.jscep.jester.CertificationRequest;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Collection;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;

public class BouncyCastleCertificateRequestDecoderTest {
    private EntityDecoder<CertificationRequest> decoder;

    @Before
    public void setUp() {
        decoder = new BouncyCastleCertificateRequestDecoder();
    }

    @Test(expected = NullPointerException.class)
    public void testInvalidContent() throws IOException {
        ByteArrayInputStream bIn = new ByteArrayInputStream(new byte[0]);
        decoder.decode(bIn);
    }

    @Test
    public void testIsCertificationRequest() throws IOException {
        PEMParser parser = new PEMParser(new InputStreamReader(getClass().getResourceAsStream("/jester.p10")));
        PKCS10CertificationRequest expected = (PKCS10CertificationRequest) parser.readObject();
        CertificationRequest csr = decoder.decode(new ByteArrayInputStream(expected.getEncoded()));
        PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(csr.getBytes());

        assertThat(pkcs10.getSubject().toString(), containsString("Jester"));
    }
}


text:
<?php
namespace Etu\Stream;

use Etu\Stream;

class RequestBody extends Stream
{
    public function __construct()
    {
        $stream = fopen('php://temp', 'w+');
        stream_copy_to_stream(fopen('php://input', 'r'), $stream);
        parent::__construct($stream);
    }
}


text:
package org.jatronizer.handler;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

import junit.framework.TestCase;

public class SuperConstructorCallsHandledMethodTest extends TestCase {

	// these are arbitrary, I just did not want them to be 0
	private static final int PARENT = 7;
	private static final int CHILD = ~PARENT;

	public static class Parent {

		public final int result;

		public Parent() {
			result = call();
		}

		public int call() {
			return PARENT;
		}
	}

	public static class Child extends Parent {

		public Child() {
			super();
		}

		public int call() {
			return CHILD;
		}
	}

	public static class InstrumentedChild extends Parent implements Callable {

		public transient volatile Callable Callable;

		public InstrumentedChild() {
			super();
			this.Callable = this;
		}

		public int call(Callable Callable) {
			return CHILD;
		}

		public int call() {
			return Callable.call(this);
		}

		public void setCallable(Callable Callable) {
			if (Callable == null) Callable = this;
			this.Callable = Callable;
		}
	}

	@Test
	public void testInstrumentedBehaviour() {
		Child child = new Child();
		assertEquals(new Parent().result, PARENT);
		assertEquals(child.result, CHILD);
		assertEquals(child.call(), CHILD);
		final AtomicInteger callResult = new AtomicInteger(0);
		Callable childHandler = new Callable() {
			public int call(Callable caller) {
				return callResult.get();
			}

			public void setCallable(Callable callee) {
				throw new UnsupportedOperationException();
			}
		};
		((Callable) child).setCallable(childHandler);
		for (int i = 0; i < 10; i++) {
			callResult.incrementAndGet();
			assertEquals(child.call(), callResult.get());
		}
	}
}


text:
<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class CasehistoryRequest extends Request {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		return true;
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		return [
			'titolo' => 'required'
		];
	}

}


text:
package org.gearvrf.bulletphysics.collision.broadphase;

/**
 *
 * @author jezek2
 */
public enum DispatchFunc {

	DISPATCH_DISCRETE(1),
	DISPATCH_CONTINUOUS(2);

	private int value;

	private DispatchFunc(int value) {
		this.value = value;
	}

	public int getValue() {
		return value;
	}

}


text:
package zxw.utils.beanutils;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;

public class Run {

	public static void main(String[] args) {
		Orign orign = new Orign();
		orign.setDate(new Date());
		orign.setName("test");

//		IfreeDateBeanConvert convert = new IfreeDateBeanConvert();
//		ConvertUtils.register(convert, Date.class);

		Orign n = new Orign();
		try {
			BeanUtils.copyProperties(n, orign);

			System.out.println(n);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


text:
concurrent = require 'concurrent'

function pong()
    while true do
        local msg = concurrent.receive()
        if msg.body == 'finished' then
            break
        elseif msg.body == 'ping' then
            print('pong received ping')
            concurrent.send(msg.from, { body = 'pong' })
        end
    end
    print('pong finished')
end

concurrent.init('pong@gaia')

pid = concurrent.spawn(pong)

concurrent.register('pong', pid)
concurrent.loop()
concurrent.shutdown()


text:
#include "Stdafx.h"
#include "GraphicBuffer10.h"
#include "Utils.h"

using namespace System::Runtime::InteropServices;

namespace IgneelD3D10
{
	GraphicBuffer10::GraphicBuffer10(ID3D10Device* device, ID3D10Buffer * buffer ,
		int size,
		int stride,
		ResourceUsage usage,
		CpuAccessFlags cpuAcces,
		D3D10_SUBRESOURCE_DATA* sbData,
		ResourceBinding binding)
			:GraphicBuffer(size, stride, usage,cpuAcces, binding)
	{
		_srv = NULL;
		_stagingBuffer = NULL;
		this->device = device;
		this->_buffer = buffer;
		if(stride == 2)
			this->_format = DXGI_FORMAT_R16_UINT;
		else if(stride == 4)
			this->_format = DXGI_FORMAT_R32_UINT;

		if(FLAG_SET(binding, ResourceBinding::ShaderResource))
		{
			D3D10_SHADER_RESOURCE_VIEW_DESC viewDesc;
			ZeroMemory(&viewDesc,  sizeof(D3D10_SHADER_RESOURCE_VIEW_DESC));
			viewDesc.ViewDimension = D3D10_SRV_DIMENSION_BUFFER;
			viewDesc.Buffer.FirstElement = 0;
			viewDesc.Buffer.ElementWidth = stride;

			ID3D10ShaderResourceView * pview;
			SAFECALL( device->CreateShaderResourceView(_buffer, &viewDesc , &pview) );
			_srv = pview;
		}

		GC::AddMemoryPressure(size);
	}

	void GraphicBuffer10::CreateStaginResource()
	{
		if(Usage == ResourceUsage::Default && CpuAccess != CpuAccessFlags::None && _stagingBuffer == NULL)
		{
			D3D10_BUFFER_DESC stagingDesc;
			_buffer->GetDesc(&stagingDesc);
			stagingDesc.Usage = D3D10_USAGE_STAGING;
			stagingDesc.BindFlags = 0;
			stagingDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;

			ID3D10Buffer* staginbBuff;
			SAFECALL( device->CreateBuffer(&stagingDesc, NULL, &staginbBuff) );
			_stagingBuffer = staginbBuff;
		}
	}

	/*GraphicBuffer10::GraphicBuffer10(ID3D10Device* device, BufferDesc desc)
	{
		D3D10_BUFFER_DESC bd;
		ZeroMemory(&bd, sizeof(D3D10_BUFFER_DESC));

		if((desc.Binding & BufferBinding::VertexBuffer) == BufferBinding::VertexBuffer)
			bd.BindFlags |= D3D10_BIND_VERTEX_BUFFER;

		if((desc.Binding & BufferBinding::IShaderResource) == BufferBinding::IShaderResource)
			bd.BindFlags |= D3D10_BIND_SHADER_RESOURCE;

		if((desc.Binding & BufferBinding::StreamOutput) == BufferBinding::StreamOutput)
			bd.BindFlags |= D3D10_BIND_STREAM_OUTPUT;

		bd.ByteWidth = desc.SizeInBytes;
		bd.MiscFlags = 0;
		bd.Usage = (D3D10_USAGE)desc.Usage;
		if(bd.Usage == D3D10_USAGE_DEFAULT)
			bd.CPUAccessFlags = 0;
		else
			bd.CPUAccessFlags =	 (UINT)desc.Access;

		ID3D10Buffer * buffer = NULL;

		D3D10_SUBRESOURCE_DATA sbData;
		ZeroMemory(&sbData, sizeof(D3D10_SUBRESOURCE_DATA));

		if(desc.Data != IntPtr::Zero)
		{
			sbData.pSysMem = static_cast<void*>(desc.Data);
			sbData.SysMemPitch = 0;
			sbData.SysMemSlicePitch = 0;

			SAFECALL( device->CreateBuffer(&bd, &sbData, &buffer) );
		}
		else
		{
			SAFECALL(device->CreateBuffer(&bd, NULL, &buffer) );
		}

		_buffer = buffer;
		_lenght = desc.SizeInBytes;
		_usage =  desc.Usage;
		_cpuAccesType = desc.Access;
		_stride = desc.Stride;
		binding = desc.Binding;

		if((desc.Binding & BufferBinding::IShaderResource) == BufferBinding::IShaderResource)
		{
			D3D10_SHADER_RESOURCE_VIEW_DESC viewDesc;
			ZeroMemory(&viewDesc,  sizeof(D3D10_SHADER_RESOURCE_VIEW_DESC));
			viewDesc.ViewDimension = D3D10_SRV_DIMENSION_BUFFER;
			viewDesc.Buffer.FirstElement = 0;
			viewDesc.Buffer.ElementWidth = desc.Stride;

			ID3D10ShaderResourceView * pview;
			SAFECALL( device->CreateShaderResourceView(_buffer, &viewDesc , &pview) );
			_srv = pview;
		}

		if(desc.Usage == ResourceUsage::Default && desc.Access != CpuAccessFlags::None)
		{
			D3D10_BUFFER_DESC stagingDesc;
			buffer->GetDesc(&stagingDesc);
			stagingDesc.Usage = D3D10_USAGE_STAGING;
			stagingDesc.BindFlags = 0;
			stagingDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;

			ID3D10Buffer* staginbBuff;
			if (sbData.pSysMem)
			{
				SAFECALL( device->CreateBuffer(&stagingDesc, &sbData, &staginbBuff) );
			}
			else
			{
				SAFECALL( device->CreateBuffer(&stagingDesc, NULL, &staginbBuff) );
			}

			_stagingBuffer = staginbBuff;
		}

		GC::AddMemoryPressure(desc.SizeInBytes);
	}*/

	IntPtr GraphicBuffer10::Map(MapType map, bool doNotWait)
	{
		void *pData = NULL;
		CreateStaginResource();
		if(_stagingBuffer)
		{
			if((map & MapType::Read) == MapType::Read || (map & MapType::Write) == MapType::Write)
			{
				device->CopyResource(_stagingBuffer, _buffer);
			}
			else if(map == MapType::Write_Discard)
			{
				map = MapType::Write;
			}

			SAFECALL( _stagingBuffer->Map(static_cast<D3D10_MAP>( map ), doNotWait ? D3D10_MAP_FLAG_DO_NOT_WAIT : 0, &pData));
		}
		else
		{
			SAFECALL( _buffer->Map(static_cast<D3D10_MAP>( map ), doNotWait ? D3D10_MAP_FLAG_DO_NOT_WAIT : 0, &pData) );
		}
		return IntPtr(pData);
	}

	void GraphicBuffer10::Unmap()
	{
		if(_stagingBuffer)
		{
			_stagingBuffer->Unmap();
			//void *pData;
			//_stagingBuffer->Map(D3D10_MAP::D3D10_MAP_READ, D3D10_MAP_FLAG_DO_NOT_WAIT , &pData);
			//device->UpdateSubresource(_buffer, 0, NULL, pData, 0, 0);
			device->CopyResource(_buffer,_stagingBuffer);
			_stagingBuffer->Release();
			_stagingBuffer = NULL;
		}
		else
		{
			_buffer->Unmap();
		}
	}

	void  GraphicBuffer10::OnDispose(bool disposing)
	{
		__super::OnDispose(disposing);
		if(_buffer)
		{
			if(_srv)
			{
				_srv->Release();
				_srv = NULL;
			}

			_buffer->Release();
			_buffer = NULL;

			if(_stagingBuffer)
			{
				_stagingBuffer->Release();
				_stagingBuffer = NULL;
			}
		}
	}

}


text:
/*
 * Find the sum of all left leaves in a given binary tree.
 */
public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        // 12:59 - 1:02
        if(root == null) return 0;
        int res = 0;
        if(root.left != null && root.left.left == null && root.left.right == null) {
            res += root.left.val;
        } else {
            res += sumOfLeftLeaves(root.left);
        }
        res += sumOfLeftLeaves(root.right);
        return res;
    }
}

// v2
public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        // 12:59 - 1:02 - 1:10
        if(root == null) return 0;
        if(root.left != null && root.left.left == null && root.left.right == null) {
            return root.left.val + sumOfLeftLeaves(root.right);
        }
        return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
    }
}


text:
require_relative './data_getter'
require_relative './displayers/displayer_mapper'

module Gugl
  module Search
    class Searcher
      attr_reader :results
      attr_accessor :limit, :query

      DEFAULT_LIMIT = 5

      def search
        configure_getter
        @results = getter.get
      end

      def display
        results.each_with_index.map do |result, index|
          displayer.display result, index
        end
      end

      def authorize(&blk)
        getter.searcher.authorize(&blk)
      end

      def search_and_display
        search
        display
      end

      def displayer=(displayer)
        @displayer = if displayer.is_a?(Symbol)
          mapped_displayer(displayer)
        else
          displayer
        end
      end

      def displayer
        @displayer ||= mapped_displayer(:default)
      end

      def limit
        @limit ||= DEFAULT_LIMIT
      end

      private

      def mapped_displayer(key)
        Displayers::DisplayerMapper[key]
      end

      def getter
        @getter ||= DataGetter.new
      end

      def configure_getter
        getter.query = query
        getter.limit = limit
      end

    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.DisplayManagement.Implementation;
using OrchardCore.DisplayManagement.Shapes;
using OrchardCore.Modules;
using OrchardCore.Mvc.Utilities;

namespace OrchardCore.DisplayManagement.Zones
{
    [Feature(Application.DefaultFeatureId)]
    public class ZoneShapes : IShapeAttributeProvider
    {
        [Shape]
        public async Task<IHtmlContent> Zone(dynamic DisplayAsync, dynamic Shape)
        {
            var htmlContentBuilder = new HtmlContentBuilder();
            foreach (var item in Shape)
            {
                htmlContentBuilder.AppendHtml(await DisplayAsync(item));
            }

            return htmlContentBuilder;
        }

        [Shape]
        public async Task<IHtmlContent> ContentZone(dynamic DisplayAsync, dynamic Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();

            var shapes = ((IEnumerable<dynamic>)Shape);

            var groupings = shapes.GroupBy(x =>
            {
                // By convention all placement delimiters default to the name 'Content' when not specified during placement.
                var key = (string)x.Metadata.Tab;
                if (String.IsNullOrEmpty(key))
                {
                    key = "Content";
                }

                // Remove any positioning modifier.
                var modifierIndex = key.IndexOf(';');
                if (modifierIndex != -1)
                {
                    key = key.Substring(0, modifierIndex);
                }

                return key;
            }).ToList();

            // Process Tabs first, then Cards, then Columns.
            if (groupings.Count > 1)
            {
                 var orderedGroupings = groupings.OrderBy(grouping => {
                    var firstGroupWithModifier = grouping.FirstOrDefault(group => {
                        var key = (string)group.Metadata.Tab;
                        if (!String.IsNullOrEmpty(key))
                        {
                            var modifierIndex = key.IndexOf(';');
                            if (modifierIndex != -1)
                            {
                                return true;
                            }
                        }
                        return false;
                    });

                    if (firstGroupWithModifier != null)
                    {
                        var key = (string)firstGroupWithModifier.Metadata.Tab;
                        var modifierIndex = key.IndexOf(';');
                        return new PositionalGrouping(key.Substring(modifierIndex));
                    }

                    return new PositionalGrouping(null);
                }, FlatPositionComparer.Instance).ToList();

                Shape container = (Shape)await ShapeFactory.CreateAsync("TabContainer", Arguments.From(
                    new
                    {
                        ContentItem = Shape.ContentItem,
                        Grouping = orderedGroupings
                    }));
                foreach(var orderedGrouping in orderedGroupings)
                {
                    Shape groupingShape = (Shape)await ShapeFactory.CreateAsync("Tab", Arguments.From(
                        new
                        {
                            Grouping = orderedGrouping,
                            ContentItem = Shape.ContentItem
                        }));
                    foreach(var item in orderedGrouping)
                    {
                        groupingShape.Add(item);
                    }
                    container.Add(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync(container));
            }
            else if (groupings.Count == 1)
            {
                // Evaluate for cards.
                var cardGrouping = await ShapeFactory.CreateAsync("CardGrouping", Arguments.From(
                    new
                    {
                        Grouping = groupings[0],
                        ContentItem = Shape.ContentItem
                    }));

                htmlContentBuilder.AppendHtml(await DisplayAsync(cardGrouping));
            }

            return htmlContentBuilder;
        }

        [Shape]
        public async Task<IHtmlContent> CardGrouping(dynamic DisplayAsync, dynamic Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();
            IGrouping<string, dynamic> grouping = Shape.Grouping;

            var groupings = grouping.GroupBy(x =>
            {
                // By convention all placement delimiters default to the name 'Content' when not specified during placement.
                var key = (string)x.Metadata.Card;
                if (String.IsNullOrEmpty(key))
                {
                    key = "Content";
                }

                // Remove positional modifier.
                var modifierIndex = key.IndexOf(';');
                if (modifierIndex != -1)
                {
                    key = key.Substring(0, modifierIndex);
                }

                return key;
            }).ToList();

            if (groupings.Count > 1)
            {
                 var orderedGroupings = groupings.OrderBy(grouping => {
                    var firstGroupWithModifier = grouping.FirstOrDefault(group => {
                        var key = (string)group.Metadata.Card;
                        if (!String.IsNullOrEmpty(key))
                        {
                            var modifierIndex = key.IndexOf(';');
                            if (modifierIndex != -1)
                            {
                                return true;
                            }
                        }
                        return false;
                    });

                    if (firstGroupWithModifier != null)
                    {
                        var key = (string)firstGroupWithModifier.Metadata.Card;
                        var modifierIndex = key.IndexOf(';');
                        return new PositionalGrouping(key.Substring(modifierIndex));
                    }

                    return new PositionalGrouping();
                }, FlatPositionComparer.Instance).ToList();

                Shape container = (Shape)await ShapeFactory.CreateAsync("CardContainer", Arguments.From(
                    new
                    {
                        ContentItem = Shape.ContentItem
                    }));
                foreach(var orderedGrouping in orderedGroupings)
                {
                    Shape groupingShape = (Shape)await ShapeFactory.CreateAsync("Card", Arguments.From(
                        new
                        {
                            Grouping = orderedGrouping,
                            ContentItem = Shape.ContentItem
                        }));
                    foreach(var item in orderedGrouping)
                    {
                        groupingShape.Add(item);
                    }
                    container.Add(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync(container));
            }
            else
            {
                // Evaluate for columns.
                var groupingShape = await ShapeFactory.CreateAsync("ColumnGrouping", Arguments.From(
                    new
                    {
                        Grouping = grouping,
                        ContentItem = Shape.ContentItem
                    }));
                htmlContentBuilder.AppendHtml(await DisplayAsync(groupingShape));
            }

            return htmlContentBuilder;
        }

        [Shape]
        public async Task<IHtmlContent> ColumnGrouping(dynamic DisplayAsync, dynamic Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();
            IGrouping<string, dynamic> grouping = Shape.Grouping;

            var groupings = grouping.GroupBy(x => {
                // By convention all placement delimiters default to the name 'Content' when not specified during placement.
                var key = (string)x.Metadata.Column;
                if (String.IsNullOrEmpty(key))
                {
                    key = "Content";
                }

                // Remove column modifier.
                var modifierIndex = key.IndexOf('_');
                if (modifierIndex != -1)
                {
                    key = key.Substring(0, modifierIndex);
                }

                // Remove positional modifier.
                modifierIndex = key.IndexOf(';');
                if (modifierIndex != -1)
                {
                    key = key.Substring(0, modifierIndex);
                }

                return key;
            }).ToList();

            if (groupings.Count > 1)
            {
                var positionModifiers = GetColumnPositions(groupings);

                var orderedGroupings = groupings.OrderBy(grouping => {
                    if (positionModifiers.TryGetValue(grouping.Key, out var position))
                    {
                        return new PositionalGrouping { Position = position };
                    }
                    else
                    {
                        return new PositionalGrouping();
                    }
                }, FlatPositionComparer.Instance).ToList();

                var columnModifiers = GetColumnModifiers(orderedGroupings);

                Shape container = (Shape)await ShapeFactory.CreateAsync("ColumnContainer", Arguments.From(
                    new
                    {
                        ContentItem = Shape.ContentItem
                    }));
                foreach(var orderedGrouping in orderedGroupings)
                {
                    Shape groupingShape = (Shape)await ShapeFactory.CreateAsync("Column", Arguments.From(
                        new
                        {
                            Grouping = orderedGrouping,
                            ContentItem = Shape.ContentItem
                        }));
                    groupingShape.Classes.Add("ta-col-grouping");
                    groupingShape.Classes.Add("column-" + orderedGrouping.Key.HtmlClassify());

                    // To adjust this breakpoint apply a modifier of lg-3 to every column.
                    var columnClasses = "col-12 col-md";
                    if (columnModifiers.TryGetValue(orderedGrouping.Key, out var columnModifier))
                    {
                        // When the modifier also has a - assume it is providing a breakpointed class.
                        if (columnModifier.IndexOf('-') != -1)
                        {
                            columnClasses = "col-12 col-" + columnModifier;
                        }
                        else // Otherwise assume a default md breakpoint.
                        {
                            columnClasses = "col-12 col-md-" + columnModifier;
                        }
                    }

                    groupingShape.Classes.Add(columnClasses);

                    foreach(var item in orderedGrouping)
                    {
                        groupingShape.Add(item);
                    }
                    container.Add(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync(container));
            }
            else
            {
                foreach (var item in grouping)
                {
                    htmlContentBuilder.AppendHtml(await DisplayAsync(item));
                }
            }

            return htmlContentBuilder;
        }
        private static Dictionary<string, string> GetColumnPositions(IList<IGrouping<string, dynamic>> groupings)
        {
            var positionModifiers = new Dictionary<string, string>();
            foreach(var grouping in groupings)
            {
                var firstGroupWithModifier = FirstGroupingWithModifierOrDefault(grouping, ';');
                if (firstGroupWithModifier != null)
                {
                    var key = (string)firstGroupWithModifier.Metadata.Column;
                    var columnModifierIndex = key.IndexOf('_');
                    if (columnModifierIndex != -1)
                    {
                        var positionModifierIndex = key.IndexOf(';');
                        // Column-9;56
                        if (positionModifierIndex > columnModifierIndex)
                        {
                            positionModifiers.Add(key.Substring(0, columnModifierIndex), key.Substring(positionModifierIndex + 1));
                        }
                        else // Column;56-9
                        {
                            var length = columnModifierIndex - positionModifierIndex;
                            positionModifiers.Add(key.Substring(0, positionModifierIndex), key.Substring(positionModifierIndex + 1, length - 1));
                        }
                    }
                    else
                    {
                        var positionModifierIndex = key.IndexOf(';');
                        positionModifiers.Add(key.Substring(0, positionModifierIndex), key.Substring(positionModifierIndex + 1));
                    }
                }
            }

            return positionModifiers;
        }

        private static Dictionary<string, string> GetColumnModifiers(IList<IGrouping<string, dynamic>> groupings)
        {
            var columnModifiers = new Dictionary<string, string>();
            foreach(var grouping in groupings)
            {
                var firstGroupWithModifier = FirstGroupingWithModifierOrDefault(grouping, '_');
                if (firstGroupWithModifier != null)
                {
                    var key = (string)firstGroupWithModifier.Metadata.Column;
                    var posModifierIndex = key.IndexOf(';');
                    if (posModifierIndex != -1)
                    {
                        var colModifierIndex = key.IndexOf('_');
                        // Column;5.1_9
                        if (colModifierIndex > posModifierIndex)
                        {
                            columnModifiers.Add(key.Substring(0, posModifierIndex), key.Substring(colModifierIndex + 1));
                        }
                        else // Column_9;5.1
                        {
                            var length = posModifierIndex - colModifierIndex;
                            columnModifiers.Add(key.Substring(0, colModifierIndex), key.Substring(colModifierIndex + 1, length - 1));
                        }
                    }
                    else
                    {
                        var columnModifierIndex = key.IndexOf('_');
                        columnModifiers.Add(key.Substring(0, columnModifierIndex), key.Substring(columnModifierIndex + 1));
                    }
                }
            }

            return columnModifiers;
        }

        private static dynamic FirstGroupingWithModifierOrDefault(IGrouping<string, dynamic> grouping, char modifier)
        {
            var firstGroupWithModifier = grouping.FirstOrDefault(group =>
            {
                var key = (string)group.Metadata.Column;
                if (!String.IsNullOrEmpty(key))
                {
                    var modifierIndex = key.IndexOf(modifier);
                    if (modifierIndex != -1)
                    {
                        return true;
                    }
                }
                return false;
            });

            return firstGroupWithModifier;
        }
    }

    internal class PositionalGrouping : IPositioned
    {
        public PositionalGrouping()
        {
        }

        public PositionalGrouping(string key)
        {
            if (!String.IsNullOrEmpty(key))
            {
                var modifierIndex = key.IndexOf(';');
                if (modifierIndex != -1)
                {
                    Position = key.Substring(modifierIndex + 1);
                }
            }
        }
        public string Position { get; set; }
    }
}


text:
package net.oschina.app.v2.activity.settings.fragment;

import net.oschina.app.v2.activity.settings.view.ChangeLogDialog;
import net.oschina.app.v2.base.BaseFragment;
import net.oschina.app.v2.utils.TDevice;
import net.oschina.app.v2.utils.UIHelper;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.tonlin.osc.happy.R;
import com.umeng.analytics.MobclickAgent;

public class AboutFragment extends BaseFragment {

	private static final String ABOUT_SCREEN = "about_screen";

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.v2_fragment_about, container,
				false);
		initViews(view);
		return view;
	}

	private void initViews(View view) {
		view.findViewById(R.id.ly_author).setOnClickListener(this);
		view.findViewById(R.id.ly_osc_git).setOnClickListener(this);
		view.findViewById(R.id.ly_lisence).setOnClickListener(this);
		view.findViewById(R.id.ly_change_log).setOnClickListener(this);

		TextView tvVersionName = (TextView) view
				.findViewById(R.id.tv_version_name);
		tvVersionName.setText(TDevice.getVersionName());
	}

	@Override
	public void onClick(View v) {
		final int id = v.getId();
		if (id == R.id.ly_lisence) {
			UIHelper.showLisence(getActivity());
		} else if (id == R.id.ly_author) {
			UIHelper.showUrlRedirect(getActivity(),
					getString(R.string.author_center));
		} else if (id == R.id.ly_osc_git) {
			UIHelper.showUrlRedirect(getActivity(),
					getString(R.string.osc_git_path));
		} else if(id == R.id.ly_change_log){
			ChangeLogDialog dialog = new ChangeLogDialog(getActivity());
			dialog.show();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(ABOUT_SCREEN);
		MobclickAgent.onResume(getActivity());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(ABOUT_SCREEN);
		MobclickAgent.onPause(getActivity());
	}
}


text:
<core:FragmentDefinition
  xmlns="sap.m"
  xmlns:core="sap.ui.core">
  <Dialog
    title="Settings"
    class="sapUiPopupWithPadding"
    contentWidth="350px"
    id="AppSettingsDialog">
    <content>
		<Label text="Theme" design="Bold" id="ThemeLabel"/>
		<SegmentedButton
			selectedButton="sap_bluecrystal"
			id="ThemeButtons"
			width="100%" >
		      <Button text="High Contrast Black" id="sap_hcb" />
		      <Button text="Blue Crystal" id="sap_bluecrystal" />
		</SegmentedButton>
		<Label text="Compact Form Factor" design="Bold" />
		<SegmentedButton
			selectedButton="compactOn"
			id="CompactModeButtons"
			width="100%" >
		      <Button text="On" id="compactOn" />
		      <Button text="Off" id="compactOff" />
		</SegmentedButton>
		<Label text="Right To Left Mode" design="Bold" />
		<SegmentedButton
			selectedButton="RTLOff"
			id="RTLButtons"
			width="100%" >
		      <Button text="On" id="RTLOn" />
		      <Button text="Off" id="RTLOff" />
		</SegmentedButton>
	</content>
		<beginButton>
			<Button text="Ok" press="onSaveAppSettings" />
		</beginButton>
		<endButton>
			<Button text="Cancel" press="onDialogCloseButton" />
		</endButton>
  </Dialog>
</core:FragmentDefinition>


text:
  <head>
    {% include favicon.html %}
    {% seo %}

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">

  	<link rel="stylesheet" href="/css/main.css">
    <link href="/css/transfonter/stylesheet.css" rel='stylesheet' type='text/css'>
    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
    <script src="/js/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>
    <script src="/js/site.js"></script>
    <script src="/js/moment.min.js"></script>

    {% webmentions_head %}
  </head>


text:
package com.spotify.heroic.rpc.grpc;

import static com.google.common.base.Preconditions.checkNotNull;
import static io.grpc.MethodDescriptor.generateFullMethodName;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.ByteStreams;
import com.spotify.heroic.cluster.ClusterNode;
import com.spotify.heroic.cluster.NodeMetadata;
import com.spotify.heroic.cluster.RpcProtocol;
import com.spotify.heroic.common.Grouped;
import com.spotify.heroic.common.UsableGroupManager;
import com.spotify.heroic.metadata.CountSeries;
import com.spotify.heroic.metadata.DeleteSeries;
import com.spotify.heroic.metadata.FindKeys;
import com.spotify.heroic.metadata.FindSeries;
import com.spotify.heroic.metadata.FindTags;
import com.spotify.heroic.metadata.WriteMetadata;
import com.spotify.heroic.metric.FullQuery;
import com.spotify.heroic.metric.WriteMetric;
import com.spotify.heroic.suggest.KeySuggest;
import com.spotify.heroic.suggest.TagKeyCount;
import com.spotify.heroic.suggest.TagSuggest;
import com.spotify.heroic.suggest.TagValueSuggest;
import com.spotify.heroic.suggest.TagValuesSuggest;
import eu.toolchain.async.AsyncFramework;
import eu.toolchain.async.AsyncFuture;
import eu.toolchain.async.Managed;
import eu.toolchain.async.ManagedSetup;
import eu.toolchain.async.ResolvableFuture;
import io.grpc.CallOptions;
import io.grpc.ManagedChannel;
import io.grpc.MethodDescriptor;
import io.grpc.netty.NettyChannelBuilder;
import io.netty.channel.nio.NioEventLoopGroup;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ToString(of = {})
@GrpcRpcScope
public class GrpcRpcProtocol implements RpcProtocol {
    private final AsyncFramework async;
    private final ObjectMapper mapper;
    private final ResolvableFuture<InetSocketAddress> bindFuture;

    private final int defaultPort;
    private final int maxFrameSize;
    private final NioEventLoopGroup workerGroup;

    private final Object lock = new Object();

    @Inject
    public GrpcRpcProtocol(
        AsyncFramework async, @Named("application/json+internal") ObjectMapper mapper,
        @Named("bindFuture") ResolvableFuture<InetSocketAddress> bindFuture,
        @Named("defaultPort") int defaultPort, @Named("maxFrameSize") int maxFrameSize,
        @Named("worker") NioEventLoopGroup workerGroup
    ) {
        this.async = async;
        this.mapper = mapper;
        this.bindFuture = bindFuture;
        this.defaultPort = defaultPort;
        this.maxFrameSize = maxFrameSize;
        this.workerGroup = workerGroup;
    }

    @Override
    public AsyncFuture<ClusterNode> connect(final URI uri) {
        final InetSocketAddress address =
            new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? defaultPort : uri.getPort());

        final Managed<ManagedChannel> channel = async.managed(new ManagedSetup<ManagedChannel>() {
            @Override
            public AsyncFuture<ManagedChannel> construct() throws Exception {
                final ManagedChannel channel = NettyChannelBuilder
                    .forAddress(address.getHostName(), address.getPort())
                    .usePlaintext(true)
                    .executor(workerGroup)
                    .eventLoopGroup(workerGroup)
                    .maxInboundMessageSize(maxFrameSize)
                    .build();

                return async.resolved(channel);
            }

            @Override
            public AsyncFuture<Void> destruct(final ManagedChannel value) throws Exception {
                return async.call(() -> {
                    value.shutdown();
                    value.awaitTermination(10, TimeUnit.SECONDS);
                    return null;
                });
            }
        });

        final AsyncFuture<ClusterNode> setup = channel.start().lazyTransform(n -> {
            final GrpcRpcClient client = new GrpcRpcClient(async, address, mapper, channel);

            return client.request(
                METADATA,
                CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS)
            ).<ClusterNode>directTransform(m -> new GrpcRpcClusterNode(client, m));
        });

        /* close managed channel on errors */
        return setup
            .lazyCatchFailed(e -> channel.stop().lazyTransform(v -> async.<ClusterNode>failed(e)))
            .lazyCatchCancelled(
                ignore -> channel.stop().lazyTransform(v -> async.<ClusterNode>cancelled()));
    }

    @Override
    public AsyncFuture<String> getListenURI() {
        return bindFuture.directTransform(s -> {
            if (s.getAddress() instanceof Inet6Address) {
                return String.format("grpc://[%s]:%d", s.getAddress().getHostAddress(),
                    s.getPort());
            }

            return String.format("grpc://%s:%d", s.getHostString(), s.getPort());
        });
    }

    @RequiredArgsConstructor
    public class GrpcRpcClusterNode implements ClusterNode {
        private final GrpcRpcClient client;
        private final NodeMetadata metadata;

        @Override
        public NodeMetadata metadata() {
            return metadata;
        }

        @Override
        public AsyncFuture<NodeMetadata> fetchMetadata() {
            // metadata requests are also used as health checks, used a much smaller deadline.
            return client.request(METADATA,
                CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS));
        }

        @Override
        public AsyncFuture<Void> close() {
            return client.close();
        }

        @Override
        public ClusterNode.Group useOptionalGroup(Optional<String> group) {
            return new Group(group);
        }

        @Override
        public boolean isAlive() {
            return client.isAlive();
        }

        @Override
        public String toString() {
            return client.toString();
        }

        @RequiredArgsConstructor
        private class Group implements ClusterNode.Group {
            private final Optional<String> group;

            @Override
            public ClusterNode node() {
                return GrpcRpcClusterNode.this;
            }

            @Override
            public AsyncFuture<Void> ping() {
                return client
                    .request(PING, CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS))
                    .directTransform(v -> null);
            }

            @Override
            public AsyncFuture<FullQuery> query(final FullQuery.Request request) {
                return request(METRICS_FULL_QUERY, request);
            }

            @Override
            public AsyncFuture<WriteMetric> writeMetric(final WriteMetric.Request request) {
                return request(METRICS_WRITE, request);
            }

            @Override
            public AsyncFuture<FindTags> findTags(final FindTags.Request request) {
                return request(METADATA_FIND_TAGS, request);
            }

            @Override
            public AsyncFuture<FindKeys> findKeys(final FindKeys.Request request) {
                return request(METADATA_FIND_KEYS, request);
            }

            @Override
            public AsyncFuture<FindSeries> findSeries(final FindSeries.Request request) {
                return request(METADATA_FIND_SERIES, request);
            }

            @Override
            public AsyncFuture<CountSeries> countSeries(final CountSeries.Request request) {
                return request(METADATA_COUNT_SERIES, request);
            }

            @Override
            public AsyncFuture<DeleteSeries> deleteSeries(final DeleteSeries.Request request) {
                return request(METADATA_DELETE_SERIES, request);
            }

            @Override
            public AsyncFuture<WriteMetadata> writeSeries(final WriteMetadata.Request request) {
                return request(METADATA_WRITE, request);
            }

            @Override
            public AsyncFuture<TagKeyCount> tagKeyCount(final TagKeyCount.Request request) {
                return request(SUGGEST_TAG_KEY_COUNT, request);
            }

            @Override
            public AsyncFuture<TagSuggest> tagSuggest(final TagSuggest.Request request) {
                return request(SUGGEST_TAG, request);
            }

            @Override
            public AsyncFuture<KeySuggest> keySuggest(final KeySuggest.Request request) {
                return request(SUGGEST_KEY, request);
            }

            @Override
            public AsyncFuture<TagValuesSuggest> tagValuesSuggest(
                final TagValuesSuggest.Request request
            ) {
                return request(SUGGEST_TAG_VALUES, request);
            }

            @Override
            public AsyncFuture<TagValueSuggest> tagValueSuggest(TagValueSuggest.Request request) {
                return request(SUGGEST_TAG_VALUE, request);
            }

            private <T, R> AsyncFuture<R> request(
                GrpcDescriptor<GroupedQuery<T>, R> endpoint, T body
            ) {
                final GroupedQuery<T> grouped = new GroupedQuery<>(group, body);
                return client.request(endpoint, grouped, CallOptions.DEFAULT);
            }
        }
    }

    @Data
    public static class GroupedQuery<T> {
        private final Optional<String> group;
        private final T query;

        @JsonCreator
        public GroupedQuery(
            @JsonProperty("group") Optional<String> group, @JsonProperty("query") T query
        ) {
            this.group = group;
            this.query = checkNotNull(query, "query");
        }

        public <G extends Grouped, R> R apply(
            UsableGroupManager<G> manager, BiFunction<G, T, R> function
        ) {
            return function.apply(group.map(manager::useGroup).orElseGet(manager::useDefaultGroup),
                query);
        }
    }

    private static final MethodDescriptor.Marshaller<byte[]> BYTE_MARSHALLER =
        new MethodDescriptor.Marshaller<byte[]>() {
            @Override
            public InputStream stream(final byte[] value) {
                return new ByteArrayInputStream(value);
            }

            @Override
            public byte[] parse(final InputStream stream) {
                try {
                    return ByteStreams.toByteArray(stream);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };

    public static final String SERVICE = "heroic";

    private static <Q, R> GrpcDescriptor<Q, R> descriptor(
        final String endpointName, final TypeReference<Q> requestType,
        final TypeReference<R> responseType
    ) {
        final MethodDescriptor<byte[], byte[]> descriptor =
            MethodDescriptor.create(MethodDescriptor.MethodType.SERVER_STREAMING,
                generateFullMethodName(SERVICE, endpointName), BYTE_MARSHALLER, BYTE_MARSHALLER);

        return new GrpcRpcEndpointSpec<>(requestType, responseType, descriptor);
    }

    public static final GrpcDescriptor<GrpcRpcEmptyBody, NodeMetadata> METADATA =
        descriptor("metadata", new TypeReference<GrpcRpcEmptyBody>() {
        }, new TypeReference<NodeMetadata>() {
        });

    public static final GrpcDescriptor<GrpcRpcEmptyBody, GrpcRpcEmptyBody>
        PING =
        descriptor("ping", new TypeReference<GrpcRpcEmptyBody>() {
        }, new TypeReference<GrpcRpcEmptyBody>() {
        });

    public static final GrpcDescriptor<GroupedQuery<FullQuery.Request>, FullQuery>
        METRICS_FULL_QUERY =
        descriptor("metrics:fullQuery", new TypeReference<GroupedQuery<FullQuery.Request>>() {
        }, new TypeReference<FullQuery>() {
        });

    public static final GrpcDescriptor<GroupedQuery<WriteMetric.Request>, WriteMetric>
        METRICS_WRITE =
        descriptor("metrics:write", new TypeReference<GroupedQuery<WriteMetric.Request>>() {
        }, new TypeReference<WriteMetric>() {
        });

    public static final GrpcDescriptor<GroupedQuery<FindTags.Request>, FindTags>
        METADATA_FIND_TAGS =
        descriptor("metadata:findTags", new TypeReference<GroupedQuery<FindTags.Request>>() {
        }, new TypeReference<FindTags>() {
        });

    public static final GrpcDescriptor<GroupedQuery<FindKeys.Request>, FindKeys>
        METADATA_FIND_KEYS =
        descriptor("metadata:findKeys", new TypeReference<GroupedQuery<FindKeys.Request>>() {
        }, new TypeReference<FindKeys>() {
        });

    public static final GrpcDescriptor<GroupedQuery<FindSeries.Request>, FindSeries>
        METADATA_FIND_SERIES =
        descriptor("metadata:findSeries", new TypeReference<GroupedQuery<FindSeries.Request>>() {
        }, new TypeReference<FindSeries>() {
        });

    public static final GrpcDescriptor<GroupedQuery<CountSeries.Request>, CountSeries>
        METADATA_COUNT_SERIES =
        descriptor("metadata:countSeries", new TypeReference<GroupedQuery<CountSeries.Request>>() {
        }, new TypeReference<CountSeries>() {
        });

    public static final GrpcDescriptor<GroupedQuery<DeleteSeries.Request>, DeleteSeries>
        METADATA_DELETE_SERIES = descriptor("metadata:deleteSeries",
        new TypeReference<GroupedQuery<DeleteSeries.Request>>() {
        }, new TypeReference<DeleteSeries>() {
        });

    public static final GrpcDescriptor<GroupedQuery<WriteMetadata.Request>, WriteMetadata>
        METADATA_WRITE = descriptor("metadata:writeSeries",
        new TypeReference<GroupedQuery<WriteMetadata.Request>>() {
        }, new TypeReference<WriteMetadata>() {
        });

    public static final GrpcDescriptor<GroupedQuery<TagKeyCount.Request>, TagKeyCount>
        SUGGEST_TAG_KEY_COUNT =
        descriptor("suggest:tagKeyCount", new TypeReference<GroupedQuery<TagKeyCount.Request>>() {
        }, new TypeReference<TagKeyCount>() {
        });

    public static final GrpcDescriptor<GroupedQuery<KeySuggest.Request>, KeySuggest> SUGGEST_KEY =
        descriptor("suggest:key", new TypeReference<GroupedQuery<KeySuggest.Request>>() {
        }, new TypeReference<KeySuggest>() {
        });

    public static final GrpcDescriptor<GroupedQuery<TagSuggest.Request>, TagSuggest> SUGGEST_TAG =
        descriptor("suggest:tag", new TypeReference<GroupedQuery<TagSuggest.Request>>() {
        }, new TypeReference<TagSuggest>() {
        });

    public static final GrpcDescriptor<GroupedQuery<TagValuesSuggest.Request>, TagValuesSuggest>
        SUGGEST_TAG_VALUES = descriptor("suggest:tagValues",
        new TypeReference<GroupedQuery<TagValuesSuggest.Request>>() {
        }, new TypeReference<TagValuesSuggest>() {
        });

    public static final GrpcDescriptor<GroupedQuery<TagValueSuggest.Request>, TagValueSuggest>
        SUGGEST_TAG_VALUE =
        descriptor("suggest:tagValue", new TypeReference<GroupedQuery<TagValueSuggest.Request>>() {
        }, new TypeReference<TagValueSuggest>() {
        });
}


text:
title: "Van Buren Street Improvement Project Public Open House"
published: false
excerpt: "Residents, commuters, property owners and business owners are invited to review preliminary design plans and provide input."
image:
  teaser: van-buren.jpg
  feature: public-input-session-banner.jpg
facebook-event: 1807748169493929
---

**Tuesday, Aug. 16, 6 p.m. – 8 p.m.**

[Verde Park - Community Center](https://goo.gl/maps/eBJpTo3X1Ut).

The city of Phoenix Street Transportation Department is advancing efforts to improve safety and develop a stronger pedestrian and bicycle environment along east **Van Buren Street** between **Seventh and 40th streets**.

You can find out more about the project [here](https://www.phoenix.gov/streetssite/Pages/Van-Buren-Street---7th-Street-to-40th-Street0726-8439.aspx).

Join Phoenix Spokes People members and help us show the community is keen to see these projects realized.


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Unit Tests for Blockly</title>
    <script type="text/javascript" src="../../closure-library-read-only/closure/goog/base.js"></script>
    <script type="text/javascript">goog.require('goog.testing.jsunit');</script>
    <script type="text/javascript" src="../blockly_uncompressed.js"></script>
  </head>
  <body>
    <script type="text/javascript" src="blockly_test.js"></script>
    <script type="text/javascript" src="generator_test.js"></script>
    <script type="text/javascript" src="names_test.js"></script>
  </body>
</html>


text:
JyuWeather
==========

A piece of TCL that parses current weather conditions from http://weather.jyu.fi


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

namespace SmartSync
{
    public class PublisherState : AgentState
    {
        public Uri RepositoryUri { get; set; }
        public string LatestSnapshotIdToken { get; set; }
        public string StableSnapshotIdToken { get; set; }
    }
}


text:
Bower wrapper for JockeyJs.

## Notice

This repo is a fork of `JockeyJS/js` path of [https://github.com/tcoulter/jockeyjs/](https://github.com/tcoulter/jockeyjs/).

Thanks to author [Tim Coulter](https://github.com/tcoulter).

## Contribute

You may make pull requests to this repo or the original one.


text:
#import "common_Leaderboard_getAllLeaderboards.h"

@interface common_Leaderboard_getAllLeaderboards()
FREObject ANE4MBG_social_common_Leaderboard_getAllLeaderboards(FREContext cxt,
                                                               void* functionData,
                                                               uint32_t argc,
                                                               FREObject argv[]);
@end

@implementation common_Leaderboard_getAllLeaderboards
+ (void)ContextInitializer:(FunctionSets *)funcSets {
    LOG_METHOD;
    [funcSets addFuncSet:@"ANE4MBG_social_common_Leaderboard_getAllLeaderboards"
                 pointer:&ANE4MBG_social_common_Leaderboard_getAllLeaderboards];

}

FREObject ANE4MBG_social_common_Leaderboard_getAllLeaderboards(FREContext cxt,
                                                               void* functionData,
                                                               uint32_t argc,
                                                               FREObject argv[]) {
    LOG_METHOD;
    ArgsParser *parser = [ArgsParser sharedParser];
    [parser setArgc:argc argv:argv];
    NSArray *fields = [parser nextLeaderboardFeilds];
    NSString *onSuccess  = [parser nextString];
    NSString *onError = [parser nextString];

    FREContext context = [ContextOwner sharedContext];

    [MBGSocialLeaderboard
     getAllLeaderboards:fields
     onSuccess:^(NSArray* response, MBGResult* result) {
         NSArray *ary = [NSArray arrayWithObjects:
                         [ArgsParser leaderboardsToJSON:response],
                         [ArgsParser resultToJSON:result], nil];
         FREResult freResult = TCDispatch(context,
                                          onSuccess,
                                          ary);
         if(freResult != FRE_OK) [ArgsParser reportResult:freResult];
     }
     onError:^(MBGError *error) {
         FREResult freResult = TCDispatch(context,
                                          onError,
                                          error);
         if(freResult != FRE_OK) [ArgsParser reportResult:freResult];
     }];

    return NULL;
}
@end