text:
from __future__ import absolute_import

import math
import numbers
from operator import add, sub

import ROOT

from .. import log; log = log[__name__]
from .. import QROOT
from ..extern.six.moves import range
from ..base import NamelessConstructorObject
from ..decorators import snake_case_methods
from .base import Plottable

__all__ = [
    'Graph',
    'Graph1D',
    'Graph2D',
]

class _GraphBase(object):

    class GraphPoint(object):
        """
	Class similar to BinProxy for histograms, useful for
	getting single point information
	"""
        class Measurement(object):
            """
	    Generalized measusement class, each graph point
	    has one for each axis
	    """
            def __init__(self, graph, axis, idx):
                self.isdefault = not hasattr(graph, axis)
                self.axis_ = axis
                self.index_ = idx
                self.graph_ = graph

            @property
            def value(self):
                return 0. if self.isdefault else getattr(self.graph_, self.axis_)(self.index_)

            @value.setter
            def value(self, value):
                axes = ['x', 'y']
                if hasattr(self.graph_, 'z'):
                    axes.append('z')
                vals = []
                for axis in axes:
                    if axis == self.axis_:
                        vals.append(value)
                    else:
                        vals.append(
                            getattr(
                                self.graph_,
                                axis)(self.index_)
                            )
                self.graph_.SetPoint(self.index_, *vals)

            @property
            def error(self):
                return 0. if self.isdefault else getattr(
                    self.graph_,
                    '{0}err'.format(self.axis_)
                    )(self.index_)

            @property
            def error_hi(self):
                return 0. if self.isdefault else getattr(
                    self.graph_,
                    '{0}errh'.format(self.axis_)
                    )(self.index_)

            @error_hi.setter
            def error_hi(self, val):
                if self.isdefault: return
                getattr(
                    self.graph_,
                    'SetPointE{0}high'.format(self.axis_.upper())
                    )(self.index_, val)

            @property
            def error_low(self):
                return 0. if self.isdefault else getattr(
                    self.graph_,
                    '{0}errl'.format(self.axis_)
                    )(self.index_)

            @error_low.setter
            def error_low(self, val):
                if self.isdefault: return
                getattr(
                    self.graph_,
                    'SetPointE{0}low'.format(self.axis_.upper())
                    )(self.index_, val)

            @property
            def error_avg(self):
                return 0. if self.isdefault else getattr(
                    self.graph_,
                    '{0}erravg'.format(self.axis_)
                    )(self.index_)

            @property
            def error_max(self):
                return 0. if self.isdefault else getattr(
                    self.graph_,
                    '{0}errmax'.format(self.axis_)
                    )(self.index_)

        def __init__(self, graph, idx):
            self.graph_ = graph
            self.idx_ = idx

        @property
        def x(self):
            """returns the x coordinate
            """
            return _GraphBase.GraphPoint.Measurement(self.graph_, 'x', self.idx_)

        @property
        def y(self):
            """returns the y coordinate
            """
            return _GraphBase.GraphPoint.Measurement(self.graph_, 'y', self.idx_)

        @property
        def z(self):
            """returns the z coordinate
            """
            return _GraphBase.GraphPoint.Measurement(self.graph_, 'z', self.idx_)

    @classmethod
    def from_file(cls, filename, sep=' ', name=None, title=None):
        with open(filename, 'r') as gfile:
            lines = gfile.readlines()
        numpoints = len(lines)
        graph = cls(numpoints, name=name, title=title)
        for idx, line in enumerate(lines):
            point = list(map(float, line.rstrip().split(sep)))
            if len(point) != cls.DIM + 1:
                raise ValueError(
                    "line {0:d} does not contain "
                    "{1:d} values: {2}".format(
                        idx + 1, cls.DIM + 1, line))
            graph.SetPoint(idx, *point)
        graph.Set(numpoints)
        return graph

    def __len__(self):
        return self.GetN()

    def __iter__(self):
        for index in range(len(self)):
            yield self[index]

    @property
    def num_points(self):
        return self.GetN()

    @num_points.setter
    def num_points(self, n):
        if n < 0:
            raise ValueError("number of points in a graph must "
                             "be non-negative")
        # ROOT, why not SetN with GetN?
        self.Set(n)

    def x(self, index=None):
        if index is None:
            return (self.GetX()[i] for i in range(self.GetN()))
        index = index % len(self)
        return self.GetX()[index]

    def xerr(self, index=None):
        if index is None:
            return ((self.GetEXlow()[i], self.GetEXhigh()[i])
                    for i in range(self.GetN()))
        index = index % len(self)
        return (self.GetErrorXlow(index), self.GetErrorXhigh(index))

    def xerrh(self, index=None):
        if index is None:
            return (self.GetEXhigh()[i] for i in range(self.GetN()))
        index = index % len(self)
        return self.GetErrorXhigh(index)

    def xerrl(self, index=None):
        if index is None:
            return (self.GetEXlow()[i] for i in range(self.GetN()))
        index = index % len(self)
        return self.GetErrorXlow(index)

    def xerravg(self, index=None):
        if index is None:
            return (self.xerravg(i) for i in range(self.GetN()))
        index = index % len(self)
        return math.sqrt(self.GetErrorXhigh(index) ** 2 +
                         self.GetErrorXlow(index) ** 2)

    def xerrmax(self, index=None):
        if index is None:
            return (self.xerravg(i) for i in range(self.GetN()))
        index = index % len(self)
        return max(self.GetErrorXhigh(index),
                   self.GetErrorXlow(index))

    def y(self, index=None):
        if index is None:
            return (self.GetY()[i] for i in range(self.GetN()))
        index = index % len(self)
        return self.GetY()[index]

    def yerr(self, index=None):
        if index is None:
            return (self.yerr(i) for i in range(self.GetN()))
        index = index % len(self)
        return (self.GetErrorYlow(index), self.GetErrorYhigh(index))

    def yerrh(self, index=None):
        if index is None:
            return (self.GetEYhigh()[i] for i in range(self.GetN()))
        index = index % len(self)
        return self.GetEYhigh()[index]

    def yerrl(self, index=None):
        if index is None:
            return (self.GetEYlow()[i] for i in range(self.GetN()))
        index = index % len(self)
        return self.GetEYlow()[index]

    def yerravg(self, index=None):
        if index is None:
            return (self.yerravg()[i] for i in range(self.GetN()))
        index = index % len(self)
        return math.sqrt(self.GetEYhigh()[index] ** 2 +
                         self.GetEYlow()[index] ** 2)

    def yerravg(self, index=None):
        if index is None:
            return (self.yerravg()[i] for i in range(self.GetN()))
        index = index % len(self)
        return max(self.GetEYhigh()[index],
                   self.GetEYlow()[index])

    def __getitem__(self, idx):
        return _GraphBase.GraphPoint(self, idx)

    def __setitem__(self, index, point):
        if not 0 <= index <= self.GetN():
            raise IndexError("graph point index out of range")
        self.SetPoint(index, *point)

class _Graph1DBase(_GraphBase):

    @classmethod
    def divide(cls, top, bottom, option='cp'):
        from .hist import Hist
        if isinstance(top, _Graph1DBase):
            top = Hist(top)
        if isinstance(bottom, _Graph1DBase):
            bottom = Hist(bottom)
        ratio = Graph(type='asymm')
        ratio.Divide(top, bottom, option)
        return ratio

    def __add__(self, other):
        copy = self.Clone()
        copy += other
        return copy

    def __radd__(self, other):
        return self + other

    def __sub__(self, other):
        copy = self.Clone()
        copy -= other
        return copy

    def __rsub__(self, other):
        return -1 * (self - other)

    def __div__(self, other):
        copy = self.Clone()
        copy /= other
        return copy

    __truediv__ = __div__

    def __mul__(self, other):
        copy = self.Clone()
        copy *= other
        return copy

    def __rmul__(self, other):
        return self * other

    def __iadd__(self, other):
        if isinstance(other, numbers.Real):
            for index in range(len(self)):
                point = self[index]
                self.SetPoint(index, point.x.value, point.y.value + other)
            return self
        for index in range(len(self)):
            mypoint = self[index]
            otherpoint = other[index]
            xlow = self.GetEXlow()[index]
            xhigh = self.GetEXhigh()[index]
            ylow = math.sqrt((self.GetEYlow()[index]) ** 2 +
                            (other.GetEYlow()[index]) ** 2)
            yhigh = math.sqrt((self.GetEYhigh()[index]) ** 2 +
                                (other.GetEYhigh()[index]) ** 2)
            self.SetPoint(index, mypoint.x.value, mypoint.y.value + otherpoint.y.value)
            self.SetPointError(index, xlow, xhigh, ylow, yhigh)
        return self

    def __isub__(self, other):
        if isinstance(other, numbers.Real):
            for index in range(len(self)):
                point = self[index]
                self.SetPoint(index, point.x.value, point.y.value - other)
            return self
        for index in range(len(self)):
            mypoint = self[index]
            otherpoint = other[index]
            xlow = self.GetEXlow()[index]
            xhigh = self.GetEXhigh()[index]
            ylow = math.sqrt((self.GetEYlow()[index]) ** 2 +
                            (other.GetEYlow()[index]) ** 2)
            yhigh = math.sqrt((self.GetEYhigh()[index]) ** 2 +
                                (other.GetEYhigh()[index]) ** 2)
            self.SetPoint(index, mypoint.x.value, mypoint.y.value - otherpoint.y.value)
            self.SetPointError(index, xlow, xhigh, ylow, yhigh)
        return self

    def __idiv__(self, other):
        if isinstance(other, numbers.Real):
            for index in range(len(self)):
                point = self[index]
                ylow, yhigh = self.GetEYlow()[index], self.GetEYhigh()[index]
                xlow, xhigh = self.GetEXlow()[index], self.GetEXhigh()[index]
                self.SetPoint(index, point.x.value, point.y.value / other)
                self.SetPointError(index, xlow, xhigh,
                                   ylow / other, yhigh / other)
            return self
        for index in range(len(self)):
            mypoint = self[index]
            otherpoint = other[index]
            xlow = self.GetEXlow()[index]
            xhigh = self.GetEXhigh()[index]
            ylow = (
                (mypoint.y.value / otherpoint.y.value) *
                math.sqrt((self.GetEYlow()[index] / mypoint.y.value) ** 2 +
                            (other.GetEYlow()[index] /
                                otherpoint.y.value) ** 2))
            yhigh = (
                (mypoint.y.value / otherpoint.y.value) *
                math.sqrt((self.GetEYhigh()[index] / mypoint.y.value) ** 2 +
                            (other.GetEYhigh()[index] /
                                otherpoint.y.value) ** 2))
            self.SetPoint(index, mypoint.x.value, mypoint.y.value / otherpoint.y.value)
            self.SetPointError(index, xlow, xhigh, ylow, yhigh)
        return self

    __itruediv__ = __idiv__

    def __imul__(self, other):
        if isinstance(other, numbers.Real):
            for index in range(len(self)):
                point = self[index]
                ylow, yhigh = self.GetEYlow()[index], self.GetEYhigh()[index]
                xlow, xhigh = self.GetEXlow()[index], self.GetEXhigh()[index]
                self.SetPoint(index, point.x.value, point.y.value * other)
                self.SetPointError(index, xlow, xhigh,
                                   ylow * other, yhigh * other)
            return self
        for index in range(len(self)):
            mypoint = self[index]
            otherpoint = other[index]
            xlow = self.GetEXlow()[index]
            xhigh = self.GetEXhigh()[index]
            ylow = (
                (mypoint.y.value * otherpoint.y.value) *
                math.sqrt((self.GetEYlow()[index] / mypoint.y.value) ** 2 +
                            (other.GetEYlow()[index] / otherpoint.y.value) ** 2))
            yhigh = (
                (mypoint.y.value * otherpoint.y.value) *
                math.sqrt((self.GetEYhigh()[index] / mypoint.y.value) ** 2 +
                            (other.GetEYhigh()[index] / otherpoint.y.value) ** 2))
            self.SetPoint(index, mypoint.x.value, mypoint.y.value * otherpoint.y.value)
            self.SetPointError(index, xlow, xhigh, ylow, yhigh)
        return self

    def GetMaximum(self, include_error=False):
        if not include_error:
            return self.GetYmax()
        summed = map(add, self.y(), self.yerrh())
        return max(summed)

    def GetMinimum(self, include_error=False):
        if not include_error:
            return self.GetYmin()
        summed = map(sub, self.y(), self.yerrl())
        return min(summed)

    def GetXmin(self):
        if len(self) == 0:
            raise ValueError("Attemping to get xmin of empty graph")
        return min(list(self.x()))

    def GetXmax(self):
        if len(self) == 0:
            raise ValueError("Attempting to get xmax of empty graph")
        return max(list(self.x()))

    def GetYmin(self):
        if len(self) == 0:
            raise ValueError("Attempting to get ymin of empty graph")
        return min(list(self.y()))

    def GetYmax(self):
        if len(self) == 0:
            raise ValueError("Attempting to get ymax of empty graph!")
        return max(list(self.y()))

    def GetEXhigh(self):
        if isinstance(self, ROOT.TGraphErrors):
            return self.GetEX()
        return super(_Graph1DBase, self).GetEXhigh()

    def GetEXlow(self):
        if isinstance(self, ROOT.TGraphErrors):
            return self.GetEX()
        return super(_Graph1DBase, self).GetEXlow()

    def GetEYhigh(self):
        if isinstance(self, ROOT.TGraphErrors):
            return self.GetEY()
        return super(_Graph1DBase, self).GetEYhigh()

    def GetEYlow(self):
        if isinstance(self, ROOT.TGraphErrors):
            return self.GetEY()
        return super(_Graph1DBase, self).GetEYlow()

    def Crop(self, x1, x2, copy=False):
        """
        Remove points which lie outside of [x1, x2].
        If x1 and/or x2 is below/above the current lowest/highest
        x-coordinates, additional points are added to the graph using a
        linear interpolation
        """
        numPoints = self.GetN()
        if copy:
            cropGraph = self.Clone()
            copyGraph = self
        else:
            cropGraph = self
            copyGraph = self.Clone()
        cropGraph.Set(0)
        X = copyGraph.GetX()
        EXlow = copyGraph.GetEXlow()
        EXhigh = copyGraph.GetEXhigh()
        Y = copyGraph.GetY()
        EYlow = copyGraph.GetEYlow()
        EYhigh = copyGraph.GetEYhigh()
        xmin = copyGraph.GetXmin()
        if x1 < xmin-EXlow[0]:
            cropGraph.Set(numPoints + 1)
        xmax = copyGraph.GetXmax()
        if x2 > xmax+EXhigh[numPoints-1]:
            cropGraph.Set(numPoints + 1)
        index = 0
        for i in range(numPoints):
            if i == 0 and x1 < xmin:
                cropGraph.SetPoint(0, x1, copyGraph.Eval(x1))
                index += 1
            elif i == numPoints-1 and x2 > xmax+EXhigh[i]:
                cropGraph.SetPoint(i, x2, copyGraph.Eval(x2))
            if x1<=X[i]-EXlow[i] and X[i]+EXhigh[i]<=x2:
                cropGraph.SetPoint(index, X[i], Y[i])
                cropGraph.SetPointError(
                    index,
                    EXlow[i], EXhigh[i],
                    EYlow[i], EYhigh[i])
                index += 1
        return cropGraph

    def Reverse(self, copy=False):
        """
        Reverse the order of the points
        """
        numPoints = self.GetN()
        if copy:
            revGraph = self.Clone()
        else:
            revGraph = self
        X = self.GetX()
        EXlow = self.GetEXlow()
        EXhigh = self.GetEXhigh()
        Y = self.GetY()
        EYlow = self.GetEYlow()
        EYhigh = self.GetEYhigh()
        for i in range(numPoints):
            index = numPoints - 1 - i
            revGraph.SetPoint(i, X[index], Y[index])
            revGraph.SetPointError(
                i,
                EXlow[index], EXhigh[index],
                EYlow[index], EYhigh[index])
        return revGraph

    def Invert(self, copy=False):
        """
        Interchange the x and y coordinates of all points
        """
        numPoints = self.GetN()
        if copy:
            invGraph = self.Clone()
        else:
            invGraph = self
        X = self.GetX()
        EXlow = self.GetEXlow()
        EXhigh = self.GetEXhigh()
        Y = self.GetY()
        EYlow = self.GetEYlow()
        EYhigh = self.GetEYhigh()
        for i in range(numPoints):
            invGraph.SetPoint(i, Y[i], X[i])
            invGraph.SetPointError(
                i,
                EYlow[i], EYhigh[i],
                EXlow[i], EXhigh[i])
        return invGraph

    def Scale(self, value, copy=False):
        """
        Scale the graph vertically by value
        """
        numPoints = self.GetN()
        if copy:
            scaleGraph = self.Clone()
        else:
            scaleGraph = self
        X = self.GetX()
        EXlow = self.GetEXlow()
        EXhigh = self.GetEXhigh()
        Y = self.GetY()
        EYlow = self.GetEYlow()
        EYhigh = self.GetEYhigh()
        for i in range(numPoints):
            scaleGraph.SetPoint(i, X[i], Y[i] * value)
            scaleGraph.SetPointError(
                i,
                EXlow[i], EXhigh[i],
                EYlow[i] * value, EYhigh[i] * value)
        return scaleGraph

    def Stretch(self, value, copy=False):
        """
        Stretch the graph horizontally by a factor of value
        """
        numPoints = self.GetN()
        if copy:
            stretchGraph = self.Clone()
        else:
            stretchGraph = self
        X = self.GetX()
        EXlow = self.GetEXlow()
        EXhigh = self.GetEXhigh()
        Y = self.GetY()
        EYlow = self.GetEYlow()
        EYhigh = self.GetEYhigh()
        for i in range(numPoints):
            stretchGraph.SetPoint(i, X[i] * value, Y[i])
            stretchGraph.SetPointError(
                i,
                EXlow[i] * value, EXhigh[i] * value,
                EYlow[i], EYhigh[i])
        return stretchGraph

    def Shift(self, value, copy=False):
        """
        Shift the graph left or right by value
        """
        numPoints = self.GetN()
        if copy:
            shiftGraph = self.Clone()
        else:
            shiftGraph = self
        X = self.GetX()
        EXlow = self.GetEXlow()
        EXhigh = self.GetEXhigh()
        Y = self.GetY()
        EYlow = self.GetEYlow()
        EYhigh = self.GetEYhigh()
        for i in range(numPoints):
            shiftGraph.SetPoint(i, X[i] + value, Y[i])
            shiftGraph.SetPointError(
                i,
                EXlow[i], EXhigh[i],
                EYlow[i], EYhigh[i])
        return shiftGraph

    def Integrate(self):
        """
        Integrate using the trapazoidal method
        """
        area = 0.
        X = self.GetX()
        Y = self.GetY()
        for i in range(self.GetN() - 1):
            area += (X[i + 1] - X[i]) * (Y[i] + Y[i + 1]) / 2.
        return area

    def Append(self, other):
        """
        Append points from another graph
        """
        orig_len = len(self)
        self.Set(orig_len + len(other))
        ipoint = orig_len
        if hasattr(self, 'SetPointError'):
            for point in other:
                self.SetPoint(ipoint, point.x.value, point.y.value)
                self.SetPointError(
                    ipoint,
                    point.x.error_low, point.x.error_hi,
                    point.y.error_low, point.y.error_hi)
                ipoint += 1
        else:
            for point in other:
                self.SetPoint(ipoint, point.x.value, point.y.value)
                ipoint += 1

class _Graph2DBase(_GraphBase):

    def z(self, index=None):
        if index is None:
            return (self.GetZ()[i] for i in range(self.GetN()))
        index = index % len(self)
        return self.GetZ()[index]

    def zerr(self, index=None):
        if index is None:
            return (self.zerr(i) for i in range(self.GetN()))
        index = index % len(self)
        return self.GetErrorZ(index)

_GRAPH1D_BASES = {
    'default': QROOT.TGraph,
    'asymm': QROOT.TGraphAsymmErrors,
    'errors': QROOT.TGraphErrors,
    'benterrors': QROOT.TGraphBentErrors,
}
_GRAPH1D_CLASSES = {}

def _Graph_class(base):

    class Graph(_Graph1DBase, Plottable, NamelessConstructorObject,
                base):
        _ROOT = base
        DIM = 1

        def __init__(self, npoints_or_hist=None,
                     name=None, title=None, **kwargs):
            if npoints_or_hist is not None:
                super(Graph, self).__init__(npoints_or_hist,
                                            name=name, title=title)
            else:
                super(Graph, self).__init__(name=name, title=title)
            self._post_init(**kwargs)

    return Graph

for name, base in _GRAPH1D_BASES.items():
    _GRAPH1D_CLASSES[name] = snake_case_methods(_Graph_class(base))

class Graph(_Graph1DBase, QROOT.TGraph):
    """
    Returns a Graph object which inherits from the associated
    ROOT.TGraph* class (TGraph, TGraphErrors, TGraphAsymmErrors)
    """
    _ROOT = QROOT.TGraph
    DIM = 1

    @classmethod
    def dynamic_cls(cls, type='asymm'):
        return _GRAPH1D_CLASSES[type]

    def __new__(cls, *args, **kwargs):
        type = kwargs.pop('type', 'asymm').lower()
        return cls.dynamic_cls(type)(
            *args, **kwargs)

# alias Graph1D -> Graph
Graph1D = Graph

_GRAPH2D_BASES = {
    'default': QROOT.TGraph2D,
    'errors': QROOT.TGraph2DErrors,
}
_GRAPH2D_CLASSES = {}

def _Graph2D_class(base):

    class Graph2D(_Graph2DBase, Plottable, NamelessConstructorObject,
                base):
        _ROOT = base
        DIM = 2

        def __init__(self, npoints_or_hist=None,
                     name=None, title=None, **kwargs):
            if npoints_or_hist is not None:
                super(Graph2D, self).__init__(npoints_or_hist,
                                              name=name, title=title)
            else:
                super(Graph2D, self).__init__(name=name, title=title)
            if isinstance(npoints_or_hist, int):
                # ROOT bug in TGraph2D
                self.Set(npoints_or_hist)
            self._post_init(**kwargs)

    return Graph2D

for name, base in _GRAPH2D_BASES.items():
    _GRAPH2D_CLASSES[name] = snake_case_methods(_Graph2D_class(base))

class Graph2D(_Graph2DBase, QROOT.TGraph2D):
    """
    Returns a Graph2D object which inherits from the associated
    ROOT.TGraph2D* class (TGraph2D, TGraph2DErrors)
    """
    _ROOT = QROOT.TGraph2D
    DIM = 2

    @classmethod
    def dynamic_cls(cls, type='errors'):
        return _GRAPH2D_CLASSES[type]

    def __new__(cls, *args, **kwargs):
        type = kwargs.pop('type', 'errors').lower()
        return cls.dynamic_cls(type)(
            *args, **kwargs)


text:
namespace chatterino {

class Modes
{
public:
    Modes();

    static const Modes &instance();

    bool isNightly{};
    bool isPortable{};
};

}  // namespace chatterino

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const path = require('path');
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '..', 'config', 'dynamo.js'))(env);
const Dynasty = require('dynasty')({
  accessKeyId: process.env.NICBOT_AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.NICBOT_AWS_SECRET_ACCESS_KEY,
  region: process.env.NICBOT_AWS_REGION || 'us-east-1'
}, process.env.NODE_ENV === 'development' ? `${config.host}:${config.port}` : null);

module.exports = Dynasty;


text:
#region License

#endregion

namespace Gremlin.Net.Process.Traversal
{
    /// <summary>
    ///     A comparison function, which imposes a total ordering on some collection of objects.
    /// </summary>
    public interface IComparator
    {
    }
}


text:
<?php

namespace PhraseanetSDK\Entity;

class QueryFacetValue
{
    /**
     * @param \stdClass[] $values
     * @return QueryFacetValue[]
     */
    public static function fromList(array $values)
    {
        $facetValues = array();

        foreach ($values as $value) {
            $facetValues[] = self::fromValue($value);
        }

        return $facetValues;
    }

    /**
     * @param \stdClass $value
     * @return QueryFacetValue
     */
    public static function fromValue(\stdClass $value)
    {
        return new self($value);
    }

    /**
     * @var \stdClass
     */
    protected $source;

    /**
     * @param \stdClass $source
     */
    public function __construct(\stdClass $source)
    {
        $this->source = $source;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->source->value;
    }

    /**
     * @return int
     */
    public function getCount()
    {
        return $this->source->count;
    }

    /**
     * @return string
     */
    public function getQuery()
    {
        return $this->source->query;
    }
}


text:
void ble_address_to_string_convert(ble_gap_addr_t address,
                                   uint8_t *string_buffer);
bool flash_access_in_progress(void);
void set_arduino_coding(void);
void set_arduino_coding_false(void);
bool get_arduino_coding(void);

void set_arduino_button(void);
bool get_arduino_button(void);

void set_run_loop_charging(void);
bool get_run_loop_charging(void);

void set_erase_bonds(void);
bool get_erase_bonds(void);

#endif


text:
import { $, camelize, isPlainObject } from '../util/index';

export default function (UIkit) {

    const DATA = UIkit.data;

    UIkit.components = {};

    UIkit.component = function (id, options) {

        var name = camelize(id);

        if (isPlainObject(options)) {
            options.name = name;
            options = UIkit.extend(options);
        } else {
            options.options.name = name;
        }

        UIkit.components[name] = options;

        UIkit[name] = function (element, data) {

            if (isPlainObject(element)) {
                return new UIkit.components[name]({data: element});
            }

            if (UIkit.components[name].options.functional) {
                return new UIkit.components[name]({data: [...arguments]});
            }

            var result = [];

            data = data || {};

            $(element).each((i, el) => result.push(el[DATA] && el[DATA][name] || new UIkit.components[name]({el, data})));

            return result;
        };

        if (document.body && !options.options.functional) {
            UIkit[name](`[uk-${id}],[data-uk-${id}]`);
        }

        return UIkit.components[name];
    };

    UIkit.getComponents = element => element && element[DATA] || {};
    UIkit.getComponent = (element, name) => UIkit.getComponents(element)[name];

    UIkit.connect = node => {

        var name;

        if (node[DATA]) {

            if (!~UIkit.elements.indexOf(node)) {
                UIkit.elements.push(node);
            }

            for (name in node[DATA]) {

                var component = node[DATA][name];

                if (!(component._uid in UIkit.instances)) {
                    UIkit.instances[component._uid] = component;
                }

                component._callHook('connected');
            }
        }

        for (var i = 0; i < node.attributes.length; i++) {

            name = node.attributes[i].name;

            if (name.lastIndexOf('uk-', 0) === 0 || name.lastIndexOf('data-uk-', 0) === 0) {

                name = camelize(name.replace('data-uk-', '').replace('uk-', ''));

                if (UIkit[name]) {
                    UIkit[name](node);
                }
            }
        }

    };

    UIkit.disconnect = node => {

        var index = UIkit.elements.indexOf(node);

        if (~index) {
            UIkit.elements.splice(index, 1);
        }

        for (var name in node[DATA]) {
            var component = node[DATA][name];
            if (component._uid in UIkit.instances) {
                delete UIkit.instances[component._uid];
                component._callHook('disconnected');
            }
        }

    }

}


text:
package com.lucidworks.spark;

import org.apache.solr.common.params.ModifiableSolrParams;
import scala.collection.JavaConverters;

import java.io.Serializable;
import java.util.*;

import static com.lucidworks.spark.util.ConfigurationConstants.*;
import static com.lucidworks.spark.util.QueryConstants.*;

public class SolrConf implements Serializable{

  private Map<String, String> sqlOptions = Collections.emptyMap();
  private ModifiableSolrParams solrConfigParams;
  private static final List<String> ESCAPE_FIELD_NAMES = Arrays.asList("fl", "rows", "q");

  public SolrConf(scala.collection.immutable.Map<String, String> config) {
    if (config != null) {
      this.sqlOptions = JavaConverters.asJavaMapConverter(config).asJava();
    }
    this.solrConfigParams = parseSolrParams(this.sqlOptions);
  }

  public String getZKHost() {
    if (sqlOptions.containsKey(SOLR_ZK_HOST_PARAM)) {
      return sqlOptions.get(SOLR_ZK_HOST_PARAM);
    }
    return null;
  }

  public String getCollection() {
    if (sqlOptions.containsKey(SOLR_COLLECTION_PARAM)) {
      return sqlOptions.get(SOLR_COLLECTION_PARAM);
    }
    return null;
  }

  public String getQuery() {
    if (sqlOptions.containsKey(SOLR_QUERY_PARAM)) {
      return sqlOptions.get(SOLR_QUERY_PARAM);
    }
    return DEFAULT_QUERY;
  }

  public String getFields() {
    if (sqlOptions.containsKey(SOLR_FIELD_LIST_PARAM)) {
      return sqlOptions.get(SOLR_FIELD_LIST_PARAM);
    }
    return null;
  }

  public String[] getFieldList() {
    return (getFields() != null) ? getFields().split(","): new String[0];
  }

  public int getRows() {
    if (sqlOptions.containsKey(SOLR_ROWS_PARAM)) {
      return Integer.parseInt(sqlOptions.get(SOLR_ROWS_PARAM));
    }
    return DEFAULT_PAGE_SIZE;
  }

  public String getSplitField() {
    if (sqlOptions.containsKey(SOLR_SPLIT_FIELD_PARAM)) {
      return sqlOptions.get(SOLR_SPLIT_FIELD_PARAM);
    }
    return null;
  }

  public int getSplitsPerShard() {
    if (sqlOptions.containsKey(SOLR_SPLITS_PER_SHARD_PARAM)) {
      return Integer.parseInt(sqlOptions.get(SOLR_SPLITS_PER_SHARD_PARAM));
    }
    return DEFAULT_SPLITS_PER_SHARD;
  }

  public boolean escapeFieldNames() {
    return Boolean.parseBoolean(sqlOptions.get(ESCAPE_FIELDNAMES));
  }

  public ModifiableSolrParams getSolrParams() {
    return this.solrConfigParams;
  }

  // Extract config params with prefix "solr."
  private static ModifiableSolrParams parseSolrParams(Map<String, String> sqlOptions) {
    ModifiableSolrParams params = new ModifiableSolrParams();

    for (String s: sqlOptions.keySet()) {
      if (s.startsWith(CONFIG_PREFIX)) {
        String param = s.substring(CONFIG_PREFIX.length());
        if (!ESCAPE_FIELD_NAMES.contains(param) && sqlOptions.get(param) != null) {
          params.add(param, sqlOptions.get(s));
        }
      }
    }
    return params;
  }

}


text:
/* general */
h1, h2, h3, body {
  font-family: "Open sans", sans-serif;
}

.header-buttons {
    margin-top: 16px;
}

/* jumbotron */

#simpledatagrid {
  background: #001F3F;
  padding-top: 24px;
  text-align: center;
}

#simpledatagrid h1 {
  margin-bottom: 32px;
  font-weight: bold;
  color: #0074D9;
}

#simpledatagrid p {
  color: #fff;
}

#simpledatagrid .btn-primary {
  background-color: #FFDC00;
  background-image: none;
  border: solid 1px #FFDC00;
  color: #001F3F;
}

#simpledatagrid .btn-primary:hover {
  background-color: #FFDC00;
}

#simpledatagrid strong {
  color: #F012BE;
}

/* sidebar */
#menu.affix-top h2 {
  display: none;
}

#menu h2 {
  background: #001F3F;
  margin: 0;
  color: #fff;
  font-size: 18px;
  padding: 8px 10px;
}

#menu a:hover {
  text-decoration: none;
}

/*
 * Side navigation
 *
 * Scrollspy and affixed enhanced navigation to highlight sections and secondary
 * sections of docs content.
 */

/* By default it's not affixed in mobile views, so undo that */
.bs-sidebar.affix {
  position: static;
}

/* First level of nav */
.bs-sidenav {
  margin-top: 0;
  margin-bottom: 30px;
}

/* All levels of nav */
.bs-sidebar .nav > li > a {
  display: block;
  color: #000;
  padding: 5px 10px;
}
.bs-sidebar .nav > li > a:hover,
.bs-sidebar .nav > li > a:focus {
  text-decoration: none;
  background: #fff;
}
.bs-sidebar .nav > .active > a,
.bs-sidebar .nav > .active:hover > a,
.bs-sidebar .nav > .active:focus > a {
  font-weight: bold;
  color: #000;
  background-color: transparent;
}

/* Nav: second level (shown on .active) */
.bs-sidebar .nav .nav {
  display: none; /* Hide by default, but at >768px, show it */
  margin-bottom: 8px;
}
.bs-sidebar .nav .nav > li > a {
  padding-top: 3px;
  padding-bottom: 3px;
  padding-left: 20px;
  font-size: 90%;
}

/* Show and affix the side nav when space allows it */
@media screen and (min-width: 992px) {
  .bs-sidebar .nav > .active > ul {
    display: block;
  }
  /* Widen the fixed sidebar */
  .bs-sidebar.affix,
  .bs-sidebar.affix-bottom {
    width: 213px;
  }
  .bs-sidebar.affix {
    position: fixed; /* Undo the static from mobile first approach */
    top: 0;
  }
  .bs-sidebar.affix-bottom {
    position: absolute; /* Undo the static from mobile first approach */
  }
  .bs-sidebar.affix-bottom .bs-sidenav,
  .bs-sidebar.affix .bs-sidenav {
    margin-top: 0;
    margin-bottom: 0;
  }
}
@media screen and (min-width: 1200px) {
  /* Widen the fixed sidebar again */
  .bs-sidebar.affix-bottom,
  .bs-sidebar.affix {
    width: 263px;
  }
}


text:
desc 'AdminAppsApproved methods.'
command 'admin_apps_approved' do |g|
  g.desc 'List approved apps for an org or workspace.'
  g.long_desc %( List approved apps for an org or workspace. )
  g.command 'list' do |c|
    c.flag 'cursor', desc: 'Set cursor to next_cursor returned by the previous call to list items in the next page.'
    c.flag 'enterprise_id', desc: '.'
    c.flag 'limit', desc: 'The maximum number of items to return. Must be between 1 - 1000 both inclusive.'
    c.flag 'team_id', desc: '.'
    c.action do |_global_options, options, _args|
      puts JSON.dump($client.admin_apps_approved_list(options))
    end
  end
end


text:
package functions.poj;

import java.util.*;
import java.util.function.*;
import java.math.*;
import org.jetbrains.annotations.*;
import org.jooq.lambda.*;

import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.util.stream.Collectors.*;
import static org.jooq.lambda.Seq.*;

public class Item
{
    private final int size;
    private final @Nullable Item subItem;

    public Item(int size, @Nullable Item subItem)
    {
        this.size = size;
        this.subItem = subItem;
    }

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

    public Optional<Item> getSubItem()
    {
        return Optional.ofNullable(this.subItem);
    }

    public String toString()
    {
        return new StringBuilder(Item.class.getSimpleName())
                   .append('(')
                   .append("size=").append(String.format("\"%s\"", this.getSize())).append(", ")
                   .append("subItem=").append(this.getSubItem().isPresent() ? String.format("\"%s\"", this.getSubItem()) : "not present")
                   .append(')')
                   .toString();
    }
}


text:
/*
 * ImageDisplayWithPanel.java
 *
 * Created on February 22, 2007, 3:16 PM
 *
 */
package ika.colororacle;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * ImageDisplayWithPanel extends ImageDisplay by drawing a second centered
 * raster image ( = the panel) over the image drawn by ImageDisplay. The panel
 * can be interactively moved with the mouse.
 *
 * @author Bernhard Jenny, Institute of Cartography, ETH Zurich.
 */
public class ImageDisplayWithPanel extends ImageDisplay
        implements MouseListener, MouseMotionListener {

    /**
     * The raster image to display.
     */
    private Image panel = null;

    /**
     * Vertical position of the top left corner of the panel. The panel will be
     * centered when it is first drawn.
     */
    private int panelTop = -1;

    /**
     * Horizontal position of the top left corner of the panel. The panel will
     * be centered when it is first drawn.
     */
    private int panelLeft = -1;

    /**
     * Horizontal distance between the left border of the panel and the position
     * of the mouse click that started a dragging operation.
     */
    private int dx = 0;

    /**
     * Vertical distance between the left border of the panel and the position
     * of the mouse click that started a dragging operation.
     */
    private int dy = 0;

    /**
     * Flag that is true if the panel is currently being dragged, false
     * otherwise.
     */
    private boolean dragging = false;

    /**
     * A reference to the controller of the application, which is used to hide
     * the main window if the user clicks outside the panel.
     */
    private final ColorOracle colorOracle;

    /**
     * Creates a new instance of ImageDisplayWithPanel
     */
    public ImageDisplayWithPanel(ColorOracle colorOracle) {
        this.colorOracle = colorOracle;
        addMouseListener(this);
        addMouseMotionListener(this);
    }

    /**
     * Set the image to display.
     */
    public void setPanel(Image panel) {
        this.panel = panel;
        repaint();
    }

    /**
     * Draw the panel image over what ImageDisplay draws.
     */
    @Override
    public void paint(Graphics g) {
        super.paint(g);

        if (panel == null) {
            return;
        }

        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_OFF);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
                RenderingHints.VALUE_COLOR_RENDER_SPEED);
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING,
                RenderingHints.VALUE_DITHER_DISABLE);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_SPEED);

        // make sure the panel is entirely visible. This also initializes
        // the position of the panel when it is first drawn.
        if (panelTop < 0 || panelLeft < 0) {
            panelLeft = (getWidth() - panel.getWidth(null)) / 2;
            panelTop = (int) ((getHeight() - panel.getHeight(null)) / 2.5);
        }
        g2d.drawImage(panel, panelLeft, panelTop, this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        colorOracle.switchToNormalVision();
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if (pointOnPanel(e.getPoint())) {
            dx = e.getX() - panelLeft;
            dy = e.getY() - panelTop;
            dragging = true;
        } else {
            dragging = false;
            colorOracle.switchToNormalVision();
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (dragging) {
            dragging = false;
        } else {
            colorOracle.switchToNormalVision();
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (!dragging) {
            return;
        }

        final int panelWidth = panel.getWidth(null);
        final int panelHeight = panel.getHeight(null);

        // remember the old position of the panel
        final int oldPanelLeft = panelLeft;
        final int oldPanelTop = panelTop;

        // compute the new position of the panel and make sure it is entirely
        // visible on screen.
        panelLeft = Math.max(0, e.getX() - dx);
        panelTop = Math.max(0, e.getY() - dy);
        if (panelLeft + panelWidth > getWidth()) {
            panelLeft = getWidth() - panelWidth;
        }
        if (panelTop + panelHeight > getHeight()) {
            panelTop = getHeight() - panelHeight;
        }

        // compute the dirty region: the union of the area previously covered
        // by the panel and the area covered now.
        final int dirtyX, dirtyY, dirtyWidth, dirtyHeight;
        if (panelLeft > oldPanelLeft) {
            dirtyX = oldPanelLeft;
            dirtyWidth = panelLeft + panelWidth - oldPanelLeft;
        } else {
            dirtyX = panelLeft;
            dirtyWidth = oldPanelLeft + panelWidth - panelLeft;
        }
        if (panelTop > oldPanelTop) {
            dirtyY = oldPanelTop;
            dirtyHeight = panelTop + panelHeight - oldPanelTop;
        } else {
            dirtyY = panelTop;
            dirtyHeight = oldPanelTop + panelHeight - panelTop;
        }

        // only paint the dirty region.
        // paintImmediately is safe to call, since this is running in the
        // swing event dispatching thread.
        paintImmediately(dirtyX, dirtyY, dirtyWidth, dirtyHeight);
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }

    /**
     * Returns true if the passed point is inside the panel, false otherwise.
     */
    private boolean pointOnPanel(Point point) {
        final int w = panel.getWidth(null);
        final int h = panel.getHeight(null);
        if (point.x < panelLeft || point.x > panelLeft + w) {
            return false;
        }
        if (point.y < panelTop || point.y > panelTop + h) {
            return false;
        }
        return true;
    }

}


text:
```
npm install pure-typography-i
```
Than you can link the compiled css from the `dist`folder.

## Develop

```
$ git clone https://github.com/zsim0n/pure-typography.git
$ cd pure-typography
$ npm install
$ npm start
```

npm build scripts and live server included.

```
package.json
{
...
    "autoprefixer": "postcss -u autoprefixer -r dist/css/*.css",
    "scss": "node-sass --source-map true --output-style compressed -o dist/css src/scss",
    "build:scss": "npm run scss && npm run autoprefixer",
...
    "devDependencies": {
        ...
        "autoprefixer": "^6.7.3",
        "node-sass": "^4.5.0",
        "postcss": "^5.2.14",
        "postcss-cli": "^3.0.0-beta",
        ...
    }
}
```
## References & Credit

* [Pure.css](http://purecss.io)
* [Pure.css Icons(ICONO)](https://saeedalipoor.github.io/icono/)
* [Ionic Framework (V1)](https://ionicframework.com/docs/components/#colors)

## Contribution

Thank you for taking the time to contribute! See [code of conduct](http://contributor-covenant.org) for contribution guidelines and details

## License

This project is licensed under the Apache 2.0 License - see the [License](https://choosealicense.com/licenses/apache-2.0/) for details


text:
package surf

import (
	"fmt"
	"gopkg.in/guregu/null.v3"
	"io"
	"strconv"
	"strings"
	"time"
)

var (
	loggingEnabled = false
	loggingWriter  io.Writer
)

// SetLogging adjusts the configuration for logging. You can enable
// and disable the logging here. By default, logging is disabled.
//
// Most calls to this function will be called like SetLogging(true, os.Stdout)
func SetLogging(enabled bool, writer io.Writer) {
	loggingEnabled = enabled
	loggingWriter = writer
}

// printQuery prints a query if the user has enabled logging
func PrintSqlQuery(query string, args ...interface{}) {
	if loggingEnabled {
		for i, arg := range args {
			query = strings.Replace(query, "$"+strconv.Itoa(i+1), pointerToLogString(arg), 1)
		}
		fmt.Fprint(loggingWriter, query)
	}
}

// pointerToLogString converts a value pointer to the string
// that should be logged for it
func pointerToLogString(pointer interface{}) string {
	switch v := pointer.(type) {
	case *string:
		return "'" + *v + "'"
	case *float32:
		return strconv.FormatFloat(float64(*v), 'f', -1, 32)
	case *float64:
		return strconv.FormatFloat(*v, 'f', -1, 64)
	case *bool:
		return strconv.FormatBool(*v)
	case *int:
		return strconv.Itoa(*v)
	case *int8:
		return strconv.FormatInt(int64(*v), 10)
	case *int16:
		return strconv.FormatInt(int64(*v), 10)
	case *int32:
		return strconv.FormatInt(int64(*v), 10)
	case *int64:
		return strconv.FormatInt(*v, 10)
	case *uint:
		return strconv.FormatUint(uint64(*v), 10)
	case *uint8:
		return strconv.FormatUint(uint64(*v), 10)
	case *uint16:
		return strconv.FormatUint(uint64(*v), 10)
	case *uint32:
		return strconv.FormatUint(uint64(*v), 10)
	case *uint64:
		return strconv.FormatUint(*v, 10)
	case *time.Time:
		return "'" + (*v).Format(time.RFC3339) + "'"
	case *null.Int:
		if v.Valid {
			return strconv.FormatInt(v.Int64, 10)
		}
		break
	case *null.String:
		if v.Valid {
			return "'" + v.String + "'"
		}
		break
	case *null.Bool:
		if v.Valid {
			return strconv.FormatBool(v.Bool)
		}
		break
	case *null.Float:
		if v.Valid {
			return strconv.FormatFloat(v.Float64, 'f', -1, 64)
		}
		break
	case *null.Time:
		if v.Valid {
			return "'" + v.Time.Format(time.RFC3339) + "'"
		}
		break
	default:
		return fmt.Sprintf("%v", v)
	}
	return "null"
}


text:
'use strict';

describe('Controller: EditorsCtrl', function () {

  // load the controller's module
  beforeEach(module('makeawesomespeechesApp'));

  var EditorsCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    EditorsCtrl = $controller('EditorsCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});


text:
package edu.cmu.lti.oaqa.baseqa.eval;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;

public class EvalCalculatorUtil {

  public static double sumMeasurementValues(Collection<Double> values) {
    return values.stream().mapToDouble(Double::doubleValue).sum();
  }

  public static double sumOfLogMeasurementValues(Collection<Double> values) {
    return values.stream().mapToDouble(v -> Math.log(v + Double.MIN_NORMAL)).sum();
  }

  public static double calculateAveragePrecision(List<String> resultArray, Set<String> gsSet) {
    int[] relIndices = IntStream.range(0, resultArray.size())
            .filter(i -> gsSet.contains(resultArray.get(i))).toArray();
    double sumPrec = IntStream.range(0, relIndices.length)
            .mapToDouble(i -> (i + 1.0) / (relIndices[i] + 1.0)).sum();
    return sumPrec / gsSet.size();
  }

  public static double calculateRecall(double relevant, double relevantRetrieved) {
    return (relevant != 0.0) ? relevantRetrieved / relevant : 0.0;
  }

  public static double calculatePrecision(double retrieved, double relevantRetrieved) {
    return (retrieved != 0.0) ? relevantRetrieved / retrieved : 0.0;
  }

  public static double calculateF1(double precision, double recall) {
    return ((precision + recall) != 0) ? (2 * precision * recall) / (precision + recall) : 0.0;
  }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WhatToDo.Helpers;
using WhatToDo.Models;
using WhatToDo.UWP.ViewRenderers;
using WhatToDo.Views;
using Windows.Security.Authentication.Web;
using Windows.Web.Http;
using Xamarin.Forms.Platform.UWP;

[assembly: ExportRenderer(typeof(Login), typeof(LoginRenderer))]

namespace WhatToDo.UWP.ViewRenderers
{
    /// <summary>
    /// The login page for the UWP platform.
    /// </summary>
    /// <seealso cref="Xamarin.Forms.ContentPage"/>
    public class LoginRenderer : PageRenderer
    {
        private bool isShown = false;
        private GoogleCredentials googleCredentials = GoogleCredentialsHelper.GetCredentials;

        protected override async void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (isShown)
            {
                return;
            }

            isShown = true;

            var code = await GetAuthorizationCode();

            if (code != null)
            {
                await GetTokenFromCode(code);
                await NavigationHelper.Current.NavigateLoginSuccess();
            }
            else
            {
                await NavigationHelper.Current.NavigateLoginFailure();
            }
        }

        private async System.Threading.Tasks.Task<string> GetAuthorizationCode()
        {
            var googleUrl = this.googleCredentials.AuthUri
                + "?client_id=" + this.googleCredentials.ClientId
                + "&redirect_uri=" + (this.googleCredentials.RedirectUris.FirstOrDefault() ?? string.Empty)
                + "&response_type=code"
                + "&scope=https://www.googleapis.com/auth/tasks"
                + "&access_type=offline"
                + "&approval_prompt=force";

            var startUri = new Uri(googleUrl);
            var endUri = new Uri(this.googleCredentials.RedirectUris.FirstOrDefault() ?? string.Empty);

            var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

            return webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success ?
                webAuthenticationResult.ResponseData.Substring(webAuthenticationResult.ResponseData.IndexOf('=') + 1) :
                null;
        }

        private async System.Threading.Tasks.Task GetTokenFromCode(string code)
        {
            var httpClient = new HttpClient();
            var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>
            {
                { "code", code },
                { "client_id", this.googleCredentials.ClientId },
                { "client_secret", this.googleCredentials.ClientSecret },
                { "redirect_uri", this.googleCredentials.RedirectUris.FirstOrDefault() ?? string.Empty },
                { "grant_type", "authorization_code" }
            });
            var tokenResponse = await httpClient.PostAsync(new Uri(this.googleCredentials.TokenUri), content);
            var responseDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(tokenResponse.Content.ToString());

            Settings.RefreshToken = responseDictionary.ContainsKey("refresh_token") ? responseDictionary["refresh_token"] : string.Empty;
            Settings.AccessToken = responseDictionary.ContainsKey("access_token") ? responseDictionary["access_token"] : string.Empty;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Lexer;

use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\LexerInterface;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Token;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\TokenType;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use ReflectionClass;

/**
 * @covers \Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Lexer\StringThenReferenceLexer
 */
class StringThenReferenceLexerTest extends TestCase
{
    public function testIsALexer()
    {
        $this->assertTrue(is_a(StringThenReferenceLexer::class, LexerInterface::class, true));
    }

    public function testIsNotClonable()
    {
        $this->assertFalse((new ReflectionClass(StringThenReferenceLexer::class))->isCloneable());
    }

    public function testMergesNonEmptyStringFollowedByAReference()
    {
        $value = 'foo55@example.com';
        $expected = [
            new Token('foo', new TokenType(TokenType::STRING_TYPE)),
            new Token('55@example.com', new TokenType(TokenType::STRING_TYPE)),
            new Token(' bar', new TokenType(TokenType::STRING_TYPE)),
        ];

        $decoratedLexerProphecy = $this->prophesize(LexerInterface::class);
        $decoratedLexerProphecy
            ->lex($value)
            ->willReturn(
                [
                    new Token('foo', new TokenType(TokenType::STRING_TYPE)),
                    new Token('55', new TokenType(TokenType::STRING_TYPE)),
                    new Token('@example.com', new TokenType(TokenType::SIMPLE_REFERENCE_TYPE)),
                    new Token(' bar', new TokenType(TokenType::STRING_TYPE)),
                ]
            )
        ;
        /** @var LexerInterface $decoratedLexer */
        $decoratedLexer = $decoratedLexerProphecy->reveal();

        $lexer = new StringThenReferenceLexer($decoratedLexer);
        $actual = $lexer->lex($value);

        $this->assertEquals(count($expected), count($actual));
        $this->assertEquals($expected, $actual);

        $decoratedLexerProphecy->lex(Argument::any())->shouldHaveBeenCalledTimes(1);
    }
}


text:
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;

use capnp_rpc::{RpcSystem, twoparty, rpc_twoparty_capnp};
use pubsub_capnp::{publisher, subscriber, subscription};

use capnp::capability::Promise;
use capnp::Error;

use futures::{Future, Stream};

use tokio_core::reactor;
use tokio_io::AsyncRead;

struct SubscriberHandle {
    client: subscriber::Client<::capnp::text::Owned>,
    requests_in_flight: i32,
}

struct SubscriberMap {
    subscribers: HashMap<u64, SubscriberHandle>,
}

impl SubscriberMap {
    fn new() -> SubscriberMap {
        SubscriberMap { subscribers: HashMap::new() }
    }
}

struct SubscriptionImpl {
    id: u64,
    subscribers: Rc<RefCell<SubscriberMap>>,
}

impl SubscriptionImpl {
    fn new(id: u64, subscribers: Rc<RefCell<SubscriberMap>>) -> SubscriptionImpl {
        SubscriptionImpl { id: id, subscribers: subscribers }
    }
}

impl Drop for SubscriptionImpl {
    fn drop(&mut self) {
        println!("subscription dropped");
        self.subscribers.borrow_mut().subscribers.remove(&self.id);
    }
}

impl subscription::Server for SubscriptionImpl {}

struct PublisherImpl {
    next_id: u64,
    subscribers: Rc<RefCell<SubscriberMap>>,
}

impl PublisherImpl {
    pub fn new() -> (PublisherImpl, Rc<RefCell<SubscriberMap>>) {
        let subscribers = Rc::new(RefCell::new(SubscriberMap::new()));
        (PublisherImpl { next_id: 0, subscribers: subscribers.clone() },
         subscribers.clone())
    }
}

impl publisher::Server<::capnp::text::Owned> for PublisherImpl {
    fn subscribe(&mut self,
                 params: publisher::SubscribeParams<::capnp::text::Owned>,
                 mut results: publisher::SubscribeResults<::capnp::text::Owned>,)
                 -> Promise<(), ::capnp::Error>
    {
        println!("subscribe");
        self.subscribers.borrow_mut().subscribers.insert(
            self.next_id,
            SubscriberHandle {
                client: pry!(pry!(params.get()).get_subscriber()),
                requests_in_flight: 0,
            }
        );

        results.get().set_subscription(
            subscription::ToClient::new(SubscriptionImpl::new(self.next_id, self.subscribers.clone()))
                .into_client::<::capnp_rpc::Server>());

        self.next_id += 1;
        Promise::ok(())
    }
}
pub fn main() {
    use std::net::ToSocketAddrs;
    let args: Vec<String> = ::std::env::args().collect();
    if args.len() != 3 {
        println!("usage: {} server HOST:PORT", args[0]);
        return;
    }

    let mut core = reactor::Core::new().unwrap();
    let handle = core.handle();

    let addr = args[2].to_socket_addrs().unwrap().next().expect("could not parse address");
    let socket = ::tokio_core::net::TcpListener::bind(&addr, &handle).unwrap();

    let (publisher_impl, subscribers) = PublisherImpl::new();

    let publisher = publisher::ToClient::new(publisher_impl).into_client::<::capnp_rpc::Server>();

    let handle1 = handle.clone();
    let done = socket.incoming().for_each(move |(socket, _addr)| {
        socket.set_nodelay(true)?;
        let (reader, writer) = socket.split();
        let handle = handle1.clone();

        let network =
            twoparty::VatNetwork::new(reader, writer,
                                      rpc_twoparty_capnp::Side::Server, Default::default());

        let rpc_system = RpcSystem::new(Box::new(network), Some(publisher.clone().client));

        handle.spawn(rpc_system.map_err(|_| ()));
        Ok(())
    }).map_err(|e| e.into());

    let infinite = ::futures::stream::iter_ok::<_, Error>(::std::iter::repeat(()));
    let send_to_subscribers = infinite.fold((handle, subscribers), move |(handle, subscribers), ()| -> Promise<(::tokio_core::reactor::Handle, Rc<RefCell<SubscriberMap>>), Error> {
        {
            let subscribers1 = subscribers.clone();
            let subs = &mut subscribers.borrow_mut().subscribers;
            for (&idx, mut subscriber) in subs.iter_mut() {
                if subscriber.requests_in_flight < 5 {
                    subscriber.requests_in_flight += 1;
                    let mut request = subscriber.client.push_message_request();
                    pry!(request.get().set_message(
                        &format!("system time is: {:?}", ::std::time::SystemTime::now())[..]));

                    let subscribers2 = subscribers1.clone();
                    handle.spawn(request.send().promise.then(move |r| {
                        match r {
                            Ok(_) => {
                                subscribers2.borrow_mut().subscribers.get_mut(&idx).map(|ref mut s| {
                                    s.requests_in_flight -= 1;
                                });
                            }
                            Err(e) => {
                                println!("Got error: {:?}. Dropping subscriber.", e);
                                subscribers2.borrow_mut().subscribers.remove(&idx);
                            }
                        }
                        Ok::<(), Error>(())
                    }).map_err(|_| unreachable!()));
                }
            }
        }

        let timeout = pry!(::tokio_core::reactor::Timeout::new(::std::time::Duration::from_secs(1), &handle));
        let timeout = timeout.and_then(move |()| Ok((handle, subscribers))).map_err(|e| e.into());
        Promise::from_future(timeout)
    });

    core.run(send_to_subscribers.join(done)).unwrap();
}


text:
<?php defined('BX_DOL') or die('hack attempt');

/*
 * Module database queries
 */
class BxBaseModGeneralDb extends BxDolModuleDb
{
    protected $_oConfig;

    public function __construct(&$oConfig)
    {
        parent::__construct($oConfig);
        $this->_oConfig = $oConfig;
    }

    public function getEntriesByAuthor ($iProfileId)
    {
        $sQuery = $this->prepare ("SELECT * FROM `" . $this->_oConfig->CNF['TABLE_ENTRIES'] . "` WHERE `" . $this->_oConfig->CNF['FIELD_AUTHOR'] . "` = ?", $iProfileId);
        return $this->getAll($sQuery);
    }

    public function getEntriesNumByAuthor ($iProfileId)
    {
        $sQuery = $this->prepare ("SELECT COUNT(*) FROM `" . $this->_oConfig->CNF['TABLE_ENTRIES'] . "` WHERE `" . $this->_oConfig->CNF['FIELD_AUTHOR'] . "` = ?", $iProfileId);
        return $this->getOne($sQuery);
    }
}

/** @} */


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

  var util = require('sassUtil');

  var defaults = {
    extension: 'scss'
  };

  function loadStyle(name, content, options, req, callback) {
    require(['sassLib'], function (Sass) {
      Sass.options(options);

      var css = Sass.compile(content);
      if (css.message) {
        return callback(css.message);
      }

      callback(null, css);
    });
  }

  function loadStyleBuild(name, content, options, req, callback) {
    var Sass = requirejs.nodeRequire('node-sass');

    try {
      util.extend(options, {data: content});
      callback(null, Sass.renderSync(options));
    }
    catch (err) {
      callback(err);
    }
  }

  return {
    load:       util.loadGenerator('sass', defaults, loadStyle, loadStyleBuild),
    write:      util.writeGenerator('sass'),
    onLayerEnd: util.layerGenerator('sass')
  };
});


text:
package com.sduwh.match.sitemesh;

import org.sitemesh.SiteMeshContext;
import org.sitemesh.content.ContentProperty;
import org.sitemesh.content.tagrules.TagRuleBundle;
import org.sitemesh.content.tagrules.html.ExportTagToContentRule;
import org.sitemesh.tagprocessor.State;

/**
 * Created by qxg on 17-6-30.
 */
public class DivTagRoleBundle implements TagRuleBundle {
    @Override
    public void install(State state, ContentProperty contentProperty, SiteMeshContext siteMeshContext) {
        state.addRule("mydiv", new ExportTagToContentRule(siteMeshContext, contentProperty.getChild("mydiv"), false));
        state.addRule("myscript", new ExportTagToContentRule(siteMeshContext, contentProperty.getChild("myscript"), false));
        state.addRule("mylink", new ExportTagToContentRule(siteMeshContext, contentProperty.getChild("mylink"), false));
    }

    @Override
    public void cleanUp(State state, ContentProperty contentProperty, SiteMeshContext siteMeshContext) {

    }
}


text:
Lite implementation of MS SQL Exception logger for ASP.Net Core (based on StackExchange.Exceptional)

To implement add the following in Startup.cs:

```
 Exceptional.Core.ErrorStore.Setup(new SQLErrorStore("applicationname","your connection string here"));

 var globalExceptionFilter = new GlobalExceptionFilter {RollupPerServer = false};

 services.AddMvc(config =>
 {
     config.Filters.Add(globalExceptionFilter);
 });

```

Please note this is highly experimental and lacking a lot of features. Just a quick hack to get basic exception logging working!

Original Exception logger source: https://github.com/NickCraver/StackExchange.Exceptional


text:
class MinValuePropertyView : public PropertyView
{
public:

    void getAttr( struct stat* statbuf )
    {
        statbuf->st_mode = S_IFREG | S_IRUSR;
        statbuf->st_size = 4096;
    }

    template< typename TYPE >
    struct MinScalarOp
    {
        int operator()(
                char *buf,
                const Alembic::Abc::CompoundPropertyReaderPtr ptr,
                const std::string& propertyName,
                const Alembic::Abc::uint8_t extent
                )
        {
            Alembic::Abc::BasePropertyReaderPtr vals = ptr->getScalarProperty( propertyName );

            std::vector< TYPE > data( extent );

            vals->asScalarPtr()->getSample( 0, &(data.front()) );

            typename OutputTrait< TYPE >::output_type min
                = std::numeric_limits< typename OutputTrait< TYPE >::output_type >::max();

            for ( uint32_t i = 0; i < extent; ++i )
            {
                min = std::min(
                        typename OutputTrait< TYPE >::output_type( data[ i ] ),
                        min
                        );
            }

            std::ostringstream stream;
            stream << min << std::endl;

            sprintf( buf, "%s", stream.str().c_str() );

            return stream.str().size();
        }
    };

    template< typename TYPE >
    struct MinArrayOp
    {
        int operator()(
                char *buf,
                const Alembic::Abc::CompoundPropertyReaderPtr ptr,
                const std::string& propertyName
                )
        {
            Alembic::Abc::BasePropertyReaderPtr vals = ptr->getProperty(
                    propertyName
                    );

            Alembic::Abc::ArraySamplePtr arraySamplePtr;
            vals->asArrayPtr()->getSample( 0, arraySamplePtr );

            size_t numVals = arraySamplePtr->getDimensions().numPoints();
            TYPE* data = (TYPE *)(arraySamplePtr->getData());

            typename OutputTrait< TYPE >::output_type min
                = std::numeric_limits< typename OutputTrait< TYPE >::output_type >::max();

            for ( size_t i = 0; i < numVals; ++i )
            {
                min = std::min(
                        typename OutputTrait< TYPE >::output_type( data[ i ] ),
                        min
                        );
            }

            std::ostringstream stream;
            stream << min << std::endl;

            sprintf( buf, "%s", stream.str().c_str() );

            return stream.str().size();
        }
    };

    int handleProperty( PropertyData& propertyData, char* buf )
    {
        PropertyHandler< MinScalarOp, MinArrayOp> propertyHandler;

        return propertyHandler.handle( propertyData, buf );
    }

private:

};

#endif // ALEMBICFS_MINVALUEPROPERTYVIEW_HH


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.
// ----------------------------------------------------------------------------------

namespace Microsoft.WindowsAzure.Management.Websites
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Management.Automation;
    using System.Security.Permissions;
    using System.ServiceModel;
    using System.Text.RegularExpressions;
    using Microsoft.WindowsAzure.Management.Utilities.Common;
    using Microsoft.WindowsAzure.Management.Utilities.Properties;
    using Microsoft.WindowsAzure.Management.Utilities.Websites;
    using Microsoft.WindowsAzure.Management.Utilities.Websites.Common;
    using Microsoft.WindowsAzure.Management.Utilities.Websites.Services;
    using Microsoft.WindowsAzure.Management.Utilities.Websites.Services.Github;
    using Microsoft.WindowsAzure.Management.Utilities.Websites.Services.WebEntities;
    using GitClass = Microsoft.WindowsAzure.Management.Utilities.Websites.Services.Git;

    /// <summary>
    /// Creates a new azure website.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "AzureWebsite"), OutputType(typeof(SiteWithConfig))]
    public class NewAzureWebsiteCommand : WebsiteContextBaseCmdlet, IGithubCmdlet
    {
        public IWebsitesClient WebsitesClient { get; set; }

        [Parameter(Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The geographic region to create the website.")]
        [ValidateNotNullOrEmpty]
        public string Location
        {
            get;
            set;
        }

        [Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Custom host name to use.")]
        [ValidateNotNullOrEmpty]
        public string Hostname
        {
            get;
            set;
        }

        [Parameter(Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The publishing user name.")]
        [ValidateNotNullOrEmpty]
        public string PublishingUsername
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Configure git on the web site and local folder.")]
        public SwitchParameter Git
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Configure github on the web site.")]
        public SwitchParameter GitHub
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The github credentials.")]
        [ValidateNotNullOrEmpty]
        public PSCredential GithubCredentials
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The github repository.")]
        [ValidateNotNullOrEmpty]
        public string GithubRepository
        {
            get;
            set;
        }

        public IGithubServiceManagement GithubChannel { get; set; }

        /// <summary>
        /// Initializes a new instance of the NewAzureWebsiteCommand class.
        /// </summary>
        public NewAzureWebsiteCommand()
            : this(null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the NewAzureWebsiteCommand class.
        /// </summary>
        /// <param name="channel">
        /// Channel used for communication with Azure's service management APIs.
        /// </param>
        public NewAzureWebsiteCommand(IWebsitesServiceManagement channel)
        {
            Channel = channel;
        }

        /// <summary>
        /// Initializes a new instance of the NewAzureWebsiteCommand class.
        /// </summary>
        /// <param name="channel">
        /// Channel used for communication with Azure's service management APIs.
        /// </param>
        /// <param name="githubChannel">
        /// Channel used for communication with the github APIs.
        /// </param>
        public NewAzureWebsiteCommand(IWebsitesServiceManagement channel, IGithubServiceManagement githubChannel)
        {
            Channel = channel;
            GithubChannel = githubChannel;
        }

        internal void CopyIisNodeWhenServerJsPresent()
        {
            if (!File.Exists("iisnode.yml") && (File.Exists("server.js") || File.Exists("app.js")))
            {
                string cmdletPath = Directory.GetParent(MyInvocation.MyCommand.Module.Path).FullName;
                File.Copy(Path.Combine(cmdletPath, "Scaffolding/Node/Website/iisnode.yml"), "iisnode.yml");
            }
        }

        internal void UpdateLocalConfigWithSiteName(string websiteName, string webspace)
        {
            GitWebsite gitWebsite = new GitWebsite(websiteName, webspace);
            gitWebsite.WriteConfiguration();
        }

        internal string GetPublishingUser()
        {
            if (!string.IsNullOrEmpty(PublishingUsername))
            {
                return PublishingUsername;
            }

            // Get publishing users
            IList<string> users = null;
            try
            {
                InvokeInOperationContext(() => { users = RetryCall(s => Channel.GetSubscriptionPublishingUsers(s)); });
            }
            catch
            {
                throw new Exception(Resources.NeedPublishingUsernames);
            }

            IEnumerable<string> validUsers = users.Where(user => !string.IsNullOrEmpty(user)).ToList();
            if (!validUsers.Any())
            {
                throw new ArgumentException(Resources.InvalidGitCredentials);
            }

            if (!(validUsers.Count() == 1 && users.Count() == 1))
            {
                throw new Exception(Resources.MultiplePublishingUsernames);
            }

            return users.First();
        }

        internal void InitializeRemoteRepo(string webspace, string websiteName)
        {
            try
            {
                // Create website repository
                InvokeInOperationContext(() => RetryCall(s => Channel.CreateSiteRepository(s, webspace, websiteName)));
            }
            catch (Exception ex)
            {
                // Handle site creating indepently so that cmdlet is idempotent.
                string message = ProcessException(ex, false);
                if (message.Equals(string.Format(Resources.WebsiteRepositoryAlreadyExists,
                                                 Name)))
                {
                    WriteWarning(message);
                }
                else
                {
                    WriteExceptionError(new Exception(message));
                }
            }
        }

        internal void AddRemoteToLocalGitRepo(Site website)
        {
            // Get remote repos
            IList<string> remoteRepositories = GitClass.GetRemoteRepositories();
            if (remoteRepositories.Any(repository => repository.Equals("azure")))
            {
                // Removing existing azure remote alias
                GitClass.RemoveRemoteRepository("azure");
            }

            string repositoryUri = website.GetProperty("RepositoryUri");

            string uri = GitClass.GetUri(repositoryUri, Name, PublishingUsername);
            GitClass.AddRemoteRepository("azure", uri);
        }

        [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        public override void ExecuteCmdlet()
        {
            WebsitesClient = WebsitesClient ?? new WebsitesClient(CurrentSubscription, WriteDebug);
            string suffix = WebsitesClient.GetWebsiteDnsSuffix();

            if (Git && GitHub)
            {
                throw new Exception("Please run the command with either -Git or -GitHub options. Not both.");
            }

            if (Git)
            {
                PublishingUsername = GetPublishingUser();
            }

            WebSpaces webspaceList = null;
            InvokeInOperationContext(() => { webspaceList = RetryCall(s => Channel.GetWebSpaces(s)); });
            if (Git && webspaceList.Count == 0)
            {
                // If location is still empty or null, give portal instructions.
                string error = string.Format(Resources.PortalInstructions, Name);
                throw new Exception(!Git
                    ? error
                    : string.Format("{0}\n{1}", error, Resources.PortalInstructionsGit));
            }

            WebSpace webspace = null;
            if (string.IsNullOrEmpty(Location))
            {
                // If no location was provided as a parameter, try to default it
                webspace = webspaceList.FirstOrDefault();
                if (webspace == null)
                {
                    string defaultLocation;

                    try
                    {
                        defaultLocation = WebsitesClient.GetDefaultLocation();
                    }
                    catch
                    {
                        throw new Exception(Resources.CreateWebsiteFailed);
                    }

                    webspace = new WebSpace
                    {
                        Name = Regex.Replace(defaultLocation.ToLower(), " ", "") + "webspace",
                        GeoRegion = defaultLocation,
                        Subscription = CurrentSubscription.SubscriptionId,
                        Plan = "VirtualDedicatedPlan"
                    };
                }
            }
            else
            {
                // Find the webspace that corresponds to the georegion
                webspace = webspaceList.FirstOrDefault(w => w.GeoRegion.Equals(Location, StringComparison.OrdinalIgnoreCase));
                if (webspace == null)
                {
                    // If no webspace corresponding to the georegion was found, attempt to create it
                    webspace = new WebSpace
                    {
                        Name = Regex.Replace(Location.ToLower(), " ", "") + "webspace",
                        GeoRegion = Location,
                        Subscription = CurrentSubscription.SubscriptionId,
                        Plan = "VirtualDedicatedPlan"
                    };
                }
            }

            SiteWithWebSpace website = new SiteWithWebSpace
            {
                Name = Name,
                HostNames = new[] { string.Format("{0}.{1}", Name, suffix) },
                WebSpace = webspace.Name,
                WebSpaceToCreate = webspace
            };

            if (!string.IsNullOrEmpty(Hostname))
            {
                List<string> newHostNames = new List<string>(website.HostNames);
                newHostNames.Add(Hostname);
                website.HostNames = newHostNames.ToArray();
            }

            try
            {
                InvokeInOperationContext(() => RetryCall(s => Channel.CreateSite(s, webspace.Name, website)));

                Cache.AddSite(CurrentSubscription.SubscriptionId, website);
                SiteConfig websiteConfiguration = null;
                InvokeInOperationContext(() =>
                {
                    websiteConfiguration = RetryCall(s => Channel.GetSiteConfig(s, website.WebSpace, website.Name));
                    WaitForOperation(CommandRuntime.ToString());
                });
                WriteObject(new SiteWithConfig(website, websiteConfiguration));
            }
            catch (ProtocolException ex)
            {
                // Handle site creating indepently so that cmdlet is idempotent.
                string message = ProcessException(ex, false);
                if (message.Equals(string.Format(Resources.WebsiteAlreadyExistsReplacement,
                                                 Name)) && (Git || GitHub))
                {
                    WriteWarning(message);
                }
                else if (message.Equals(Resources.DefaultHostnamesValidation))
                {
                    WriteExceptionError(new Exception(Resources.InvalidHostnameValidation));
                }
                else
                {
                    WriteExceptionError(new Exception(message));
                }
            }

            if (Git || GitHub)
            {
                try
                {
                    Directory.SetCurrentDirectory(SessionState.Path.CurrentFileSystemLocation.Path);
                }
                catch (Exception)
                {
                    // Do nothing if session state is not present
                }

                LinkedRevisionControl linkedRevisionControl = null;
                if (Git)
                {
                    linkedRevisionControl = new GitClient(this);
                }
                else if (GitHub)
                {
                    linkedRevisionControl = new GithubClient(this, GithubCredentials, GithubRepository);
                }

                linkedRevisionControl.Init();

                CopyIisNodeWhenServerJsPresent();
                UpdateLocalConfigWithSiteName(Name, webspace.Name);

                InitializeRemoteRepo(webspace.Name, Name);

                Site updatedWebsite = RetryCall(s => Channel.GetSite(s, webspace.Name, Name, "repositoryuri,publishingpassword,publishingusername"));
                if (Git)
                {
                    AddRemoteToLocalGitRepo(updatedWebsite);
                }

                linkedRevisionControl.Deploy(updatedWebsite);
                linkedRevisionControl.Dispose();
            }
        }

        public Action<string> GetLogger()
        {
            return WriteDebug;
        }
    }
}


text:
<?xml version="1.0"?>
<openerp>
	<data>

        <!--Report for hotel folio -->
		<report id="hotel_folio_details"
			string="Folio Total"
			model="hotel.folio"
			name="folio.total"
			rml="hotel/report/total_folio.rml"
			menu="False"
			auto="False"/>

	</data>
</openerp>


text:
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from django.db import transaction
from django.db import IntegrityError
from ..models.author import Author
from api.utils import scaffold
import os
import uuid
import json

# Values to be inserted and checked in the Author model
GITHUB_USERNAME = "jmaguire"
BIO = "I'm the best sports agent around!"
HOST = "http://examples.com/"

# Values to be inserted and checked in the User model
# required User model attributes
RUSERNAME = "jmaquire2"
USERNAME = "jmaguire"
PASSWORD = str(uuid.uuid4())

# optional User model attributes
FIRST_NAME = "Jerry"
LAST_NAME = "Maguire"
EMAIL = "jmaguire@smi.com"

class AuthorAuthentication(APITestCase):
    """
    Basic testing of the Author model creation and database insertion
    """
    def setUp(self):
        self.user_dict = {
            'username':USERNAME,
            'displayname':USERNAME,
            'first_name':FIRST_NAME,
            'last_name':LAST_NAME,
            'password':PASSWORD,
            'email':EMAIL,
            'github_username':GITHUB_USERNAME,
            'bio':BIO,
            'host': HOST }

        self.user_dict_with_img = {
            'username':USERNAME,
            'displayname':USERNAME,
            'first_name':FIRST_NAME,
            'last_name':LAST_NAME,
            'password':PASSWORD,
            'email':EMAIL,
            'github_username':GITHUB_USERNAME,
            'bio':BIO,
            'host': HOST,
            'image': "data:image/jpeg;base64," + scaffold.get_test_image() }

        self.login_dict = {
            'username':USERNAME,
            'password':PASSWORD }

        # Create an already registered user for testing
        self.registed_user = {
            'username':RUSERNAME,
            'password':PASSWORD,
            'first_name':FIRST_NAME,
            'email':EMAIL,
            'last_name':LAST_NAME }

        self.user = User.objects.create_user(**self.registed_user)
        self.author = Author.objects.create(
            user = self.user,
            github_username = GITHUB_USERNAME,
            bio = BIO,
            host = HOST )

        # Use for non authenticated requests
        self.c = scaffold.SocialAPIClient()

        self.basic_client = scaffold.SocialAPIClient()
        self.basic_client.basic_credentials(RUSERNAME, PASSWORD)
        #enable registered user
        scaffold.enable_author(RUSERNAME)

        self.token_client = scaffold.SocialAPIClient()
        self.token_client.token_credentials(self.author)

        self.bad_auth_client = scaffold.SocialAPIClient()
        self.bad_auth_client.bad_credentials(True)

    def tearDown(self):
        """Remove all created objects from mock database"""
        Author.objects.all().delete()
        User.objects.all().delete()
        self.basic_client.credentials()
        self.token_client.credentials()
        self.bad_auth_client.credentials()

    def test_registration(self):
        """
        Test a registration where all values are given in the JSON body
        """
        response = self.c.post('/author/registration', self.user_dict)

        self.assertEquals(response.status_code, 201, "User and Author not created")

        # Confirm that model and all attributes were inserted
        user = User.objects.get(username = USERNAME)
        self.assertEquals(user.username, USERNAME, "Usernames don't match")
        self.assertEquals(user.first_name, FIRST_NAME, "Name doesn't match")
        self.assertEquals(user.last_name, LAST_NAME, "Name doesn't match")

        details = Author.objects.get(user = user)
        self.assertEquals(details.bio, BIO, "Bio doesn't match")
        self.assertEquals(details.github_username, GITHUB_USERNAME, "Username doesn't match")

    def test_registration_with_image(self):
        response = self.c.post('/author/registration', self.user_dict_with_img, format='multipart')
        self.assertEquals(response.status_code, 201)

        # Get image.
        self.c.basic_credentials(self.user_dict_with_img['username'], self.user_dict_with_img['password'])
        id = Author.objects.get(user__username = self.user_dict_with_img['username']).id
        response = self.c.get('/author/%s' % id)

        self.assertEquals(response.data['image'],
                          self.user_dict_with_img['image'])
        self.assertEquals(response.status_code, 200)

    def test_registration_same_user(self):
        """
        Test registering duplicate users
        """
        try:
            with transaction.atomic():
                response = self.c.post('/author/registration', self.user_dict)
                self.assertEquals(response.status_code, 201)

                response = self.c.post('/author/registration', self.user_dict)
                self.assertEquals(response.status_code, 400)
            self.assertTrue(True, 'Duplicate users not allowed')
        except IntegrityError:
            pass

    def test_registration_without_username(self):
        self.user_dict.pop('displayname', None)
        response = self.c.post('/author/registration', self.user_dict)

        self.assertEquals(response.status_code, 400, "User should not be created")

    def test_registration_without_email(self):
        self.user_dict.pop('email', None)
        response = self.c.post('/author/registration', self.user_dict)

        self.assertEquals(response.status_code, 201, "User should be created")

    def test_registration_without_name(self):
        self.user_dict.pop('first_name', None)
        response = self.c.post('/author/registration', self.user_dict)

        self.assertEquals(response.status_code, 201, "User should be created")

    def test_registration_without_github(self):
        self.user_dict.pop('github_username', None)
        response = self.c.post('/author/registration', self.user_dict)

        self.assertEquals(response.status_code, 201, "User should be created")

    def test_login_unapproved_user(self):
        """
        Test a registration where all values are given in the JSON body
        """
        response = self.c.post('/author/registration', self.user_dict)

        self.assertEquals(response.status_code, 201, "User and Author not created")

        # Confirm that model matches
        user = User.objects.get(username = USERNAME)
        self.assertEquals(user.username, USERNAME, "Usernames don't match")

        self.c.basic_credentials(self.user_dict['username'], self.user_dict['password'])
        response = self.c.get('/author/login')
        self.assertEquals(response.status_code, 401, 'user should not be allowed to log in')

    def test_login(self):
        response = self.basic_client.get('/author/login')
        content = json.loads(response.content)
        self.assertIsNot(content['token'], '', 'Empty Token')
        self.assertIsNotNone(content['token'], 'Empty Token')

        profile = content['author']
        self.assertEquals(profile.has_key('host'), True, "Host key doesn't exist")

        keys = set(profile.keys()).intersection(self.user_dict.keys());
        # Can't test for host since it will be auto-created
        keys.remove('host')

        self.user_dict['displayname'] = RUSERNAME

        for key in keys:
            self.assertEquals(profile[key], self.user_dict[key])

        self.assertEquals(response.status_code, 200, 'user not logged in')

    def test_bad_login(self):
        response = self.bad_auth_client.get('/author/login')
        self.assertEquals(response.status_code, 401, 'user not logged in')

    def test_logout(self):
        response = self.basic_client.delete('/author/login')
        self.assertEquals(response.status_code, 204, "User not logged out")

    def test_author_update(self):
        # All fields are good and should return 200
        update_author_dict = {
            'first_name':FIRST_NAME + "u",
            'last_name':LAST_NAME + "u",
            'email':EMAIL + "u",
            'github_username':GITHUB_USERNAME + "u",
            'bio':BIO + "u",
            'image': "data:image/jpeg;base64," + scaffold.get_test_image() }

        response = self.token_client.post('/author/profile', update_author_dict, format='multipart')
        self.assertEquals(response.status_code, 200)

        # Get image.
        self.assertEquals(response.data.get('image'), update_author_dict['image'])
        # scaffold.pretty_print(response.data)

        # Compare the response content to that content in the database
        user = User.objects.get(username = RUSERNAME)
        details = Author.objects.get(user = user)

        self.assertEquals(user.email, update_author_dict['email'])
        self.assertEquals(user.first_name, update_author_dict['first_name'])
        self.assertEquals(user.last_name, update_author_dict['last_name'])

        self.assertEquals(details.bio, update_author_dict['bio'])
        self.assertEquals(details.github_username, update_author_dict['github_username'])

    def test_author_update_bad_authorization(self):
        old = User.objects.get(username = RUSERNAME)

        update_author_dict = {
            'email':EMAIL + "u",
            'bio':BIO + "u" }

        response = self.bad_auth_client.post('/author/profile', update_author_dict)
        self.assertEquals(response.status_code, 401)

        new = User.objects.get(last_name = LAST_NAME)
        self.assertEquals(old, new, "Author profile should not have been updated")

    def test_author_update_partial(self):
        # All fields are good and should return 200
        update_author_dict = {
            'email':EMAIL + "u",
            'bio':BIO + "u" }

        response = self.token_client.post('/author/profile', update_author_dict)
        self.assertEquals(response.status_code, 200)

        # scaffold.pretty_print(response.data)

        # Compare the response content to that content in the database
        user = User.objects.get(username = RUSERNAME)
        details = Author.objects.get(user = user)

        self.assertEquals(user.email, update_author_dict['email'])
        self.assertEquals(details.bio, update_author_dict['bio'])

    def test_author_update_bad_fields(self):
        """Good fields will still be parsed; bad fields ignored"""
        # All fields are good and should return 200
        update_author_dict = {
            'bad_email':EMAIL + "u",
            'bio':BIO + "u" }

        response = self.token_client.post('/author/profile', update_author_dict)
        self.assertEquals(response.status_code, 200)

        # Compare the response content to that content in the database
        user = User.objects.get(username = RUSERNAME)
        details = Author.objects.get(user = user)

        self.assertTrue(user.email != update_author_dict['bad_email'])
        self.assertEquals(details.bio, update_author_dict['bio'])


text:
package de.intarsys.tools.objectmodel;

abstract public class CommonClassSelector implements IClassSelector {

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Engler & Prantl, Nat. Pflanzenfam. (Leipzig), Teil. <b>I</b> 1**: 383 (1900)

#### Original name
Eurotiella Lindau

### Remarks
null


text:
using B2Net.Models;
using System;
using System.Net.Http;

namespace B2Net.Http {
	public static class AuthRequestGenerator {
		private static class Endpoints {
			public const string Auth = "b2_authorize_account";
		}

		public static HttpRequestMessage Authorize(B2Options options) {
			var uri = new Uri(Constants.ApiBaseUrl + "/" + Constants.Version + "/" + Endpoints.Auth);
			var request = new HttpRequestMessage() {
				Method = HttpMethod.Get,
				RequestUri = uri
			};

			request.Headers.Add("Authorization", Utilities.CreateAuthorizationHeader(options.KeyId, options.ApplicationKey));

			return request;
		}
	}
}


text:
namespace HodStudio.XitSoap.Tests.Model
{
    public class ProductFilter
    {
        /// <summary>
        /// Different property name to test the WsMapper
        /// </summary>
        public string ProductCode { get; set; }
    }
}


text:
package com.glazebrook.tictactoe.db;

import com.fasterxml.jackson.annotation.JsonProperty;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.UUID;

public class Game {
    @JsonProperty
    @NotNull
    private UUID id;

    @JsonProperty
    @NotNull
    private boolean gameEnded;

    @JsonProperty
    private UUID winningPlayerId;

    @JsonProperty
    private UUID lastPlayerId;

    public Game() {

    }

    public Game(UUID id, boolean gameEnded, UUID winningPlayerId, UUID lastPlayerId) {
        this.id = id;
        this.gameEnded = gameEnded;
        this.winningPlayerId = winningPlayerId;
        this.lastPlayerId = lastPlayerId;
    }

    public List<Player> getPlayers() {
        return players;
    }

    public void setPlayers(List<Player> players) {
        this.players = players;
    }

    private List<Player> players;

    public UUID getId() {
        return id;
    }

    public boolean isGameEnded() {
        return gameEnded;
    }

    public UUID getWinningPlayerId() {
        return winningPlayerId;
    }

    public UUID getLastPlayerId() {
        return lastPlayerId;
    }

}


text:
using UnityEngine;
using System.Collections;

public class Wall : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D col)
    {
        GameManager.Instance.WallHit(gameObject, col.gameObject);

    }
}


text:
var po = org.polymaps;

var svg = document.getElementById("map").appendChild(po.svg("svg")),
    defs = svg.appendChild(po.svg("defs"));

/* Create three linear gradients for each category. */
defs.appendChild(gradient("#D90000", "#A30000")).setAttribute("id", "gradient-violent");
defs.appendChild(gradient("#23965E", "#1A7046")).setAttribute("id", "gradient-property");
defs.appendChild(gradient("#3489BA", "#27678B")).setAttribute("id", "gradient-quality");

/* Create a marker path. */
defs.appendChild(icons.marker()).setAttribute("id", "marker");

var map = po.map()
    .container(svg)
    .center({lat: 37.787, lon: -122.228})
    .zoomRange([11,16])
    .zoom(12)
    .add(po.interact());

map.add(po.image()
    .url(po.url("http://{S}tile.cloudmade.com"
    + "/1a1b06b230af4efdbb989ea99e9841af" // http://cloudmade.com/register
    + "/998/256/{Z}/{X}/{Y}.png")
    .hosts(["a.", "b.", "c.", ""])));

map.add(po.geoJson()
    .url(crimespotting("http://oakland.crimespotting.org"
        + "/crime-data"
        + "?count=100"
        + "&format=json"
        + "&bbox={B}"
        + "&dstart=2010-04-01"
        + "&dend=2010-04-01"))
    .on("load", load)
    .clip(false)
    .scale("fixed")
    .zoom(12));

map.add(po.compass()
    .pan("none"));

/* Post-process the GeoJSON points and replace them with markers! */
function load(e) {
  e.features.sort(function(a, b) {
    return b.data.geometry.coordinates[1] - a.data.geometry.coordinates[1];
  });
  for (var i = 0; i < e.features.length; i++) {
    var f = e.features[i],
        d = f.data,
        c = f.element,
        p = c.parentNode,
        u = f.element = po.svg("use");
    u.setAttributeNS(po.ns.xlink, "href", "url(#marker)");
    u.setAttribute("transform", c.getAttribute("transform"));
    u.setAttribute("fill", "url(#gradient-" + crimespotting.categorize(d) + ")");
    p.removeChild(c);
    p.appendChild(u);
  }
}

/* Helper method for constructing a linear gradient. */
function gradient(a, b) {
  var g = po.svg("linearGradient");
  g.setAttribute("x1", 0);
  g.setAttribute("y1", 1);
  g.setAttribute("x2", 0);
  g.setAttribute("y2", 0);
  var s0 = g.appendChild(po.svg("stop"));
  s0.setAttribute("offset", "0%");
  s0.setAttribute("stop-color", a);
  var s1 = g.appendChild(po.svg("stop"));
  s1.setAttribute("offset", "100%");
  s1.setAttribute("stop-color", b);
  return g;
}