text:
<?php

namespace spec\Tworzenieweb\SqlProvisioner\Filesystem;

use Prophecy\Argument;
use Symfony\Component\Filesystem\Filesystem;
use Tworzenieweb\SqlProvisioner\Filesystem\CandidatesFinder;
use Tworzenieweb\SqlProvisioner\Filesystem\EnvironmentLoaderInterface;
use Tworzenieweb\SqlProvisioner\Filesystem\WorkingDirectory;
use PhpSpec\ObjectBehavior;

/**
 * @author Luke Adamczewski
 * @package spec\Tworzenieweb\SqlProvisioner\Filesystem
 * @mixin WorkingDirectory
 */
class WorkingDirectorySpec extends ObjectBehavior
{
    private $dotEnvPath;

    private $currentDirectory;

    function let(CandidatesFinder $candidatesFinder, Filesystem $filesystem, EnvironmentLoaderInterface $environmentLoader)
    {
        $this->currentDirectory = __DIR__;
        $this->dotEnvPath = $this->currentDirectory . DIRECTORY_SEPARATOR . '.env';
        $filesystem->isAbsolutePath($this->currentDirectory)->willReturn(true);
        $this->beConstructedWith($this->currentDirectory, $candidatesFinder, $filesystem, $environmentLoader);
    }

    function it_should_change_working_directory(Filesystem $filesystem)
    {
        $temp = sys_get_temp_dir();
        $filesystem->isAbsolutePath($temp)->willReturn(true);
        $newWorkingDirectory = $this->cd(sys_get_temp_dir());
        $newWorkingDirectory->shouldReturnAnInstanceOf(WorkingDirectory::class);
        $this->shouldNotEqual($newWorkingDirectory);
        $newWorkingDirectory->getCurrentDirectoryAbsolute()->shouldBe($temp);
    }

    function it_should_provide_absolute_path()
    {
        $this->getCurrentDirectoryAbsolute()->shouldReturn($this->currentDirectory);
    }

    function it_should_return_path_for_to_string_method()
    {
        $this->__toString()->shouldReturn($this->currentDirectory);
    }

    function it_should_touch_dot_file(Filesystem $filesystem)
    {
        $filesystem->isAbsolutePath($this->getCurrentDirectoryAbsolute())->shouldBeCalled();
        $filesystem->dumpFile(Argument::type('string'), WorkingDirectory::DRAFT_CONTENT)->shouldBeCalled();
        $this->createEnvironmentFile();
    }

    /**
     * @param EnvironmentLoaderInterface $environmentLoader
     */
    function it_should_load_dot_env(EnvironmentLoaderInterface $environmentLoader)
    {
        $environmentLoader->load($this)->shouldBeCalled();
        $this->loadEnvironment();
    }

    function it_should_get_candidates(CandidatesFinder $candidatesFinder)
    {
        $candidatesFinder->find($this->currentDirectory)->shouldBeCalled();
        $this->getCandidates();
    }
}


text:
//
//  MessageTableCell.h
//  Chat_Test
//
//  Created by Frank on 5/02/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface MessageTableCell : UITableViewCell
{

    UILabel *senderAndTimeLabel;
    UITextView *messageControlView;
    UIImageView *bgImageView;

}

@property (nonatomic,strong) UILabel *senderAndTimeLabel;
@property (nonatomic,strong) UITextView *messageContentView;
@property (nonatomic,strong) UIImageView *bgImageView;

/*- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier text:(NSString *)text imageName:(NSString *)imageName origin:(CGRect)origin messageSize:(CGSize)messageSize message:(NSString *)message;*/

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;

@end

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe "/home/index" do
  include HomeHelper

  before do
    login_and_assign
  end

  it "should render list of activities if it's not empty" do
    assign(:activities, [ FactoryGirl.create(:version, :event => "update", :item => FactoryGirl.create(:account)) ])
    assign(:my_tasks, [])
    assign(:my_opportunities, [])
    assign(:my_accounts, [])
    render
    view.should render_template(:partial => "_activity")
  end

  it "should render a message if there're no activities" do
    assign(:activities, [])
    assign(:my_tasks, [])
    assign(:my_opportunities, [])
    assign(:my_accounts, [])
    render
    view.should_not render_template(:partial => "_activity")

    rendered.should include("No activity records found.")
  end
end


text:
"""
    tablib.core
    ~~~~~~~~~~~

    This module implements the central Tablib objects.

    :copyright: (c) 2014 by Kenneth Reitz.
    :license: MIT, see LICENSE for more details.
"""

from copy import copy
from operator import itemgetter

from tablib import formats

from tablib.compat import OrderedDict, unicode

__title__ = 'tablib'
__version__ = '0.10.0'
__build__ = 0x001000
__author__ = 'Kenneth Reitz'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Kenneth Reitz'
__docformat__ = 'restructuredtext'

class Row(object):
    """Internal Row object. Mainly used for filtering."""

    __slots__ = ['_row', 'tags']

    def __init__(self, row=list(), tags=list()):
        self._row = list(row)
        self.tags = list(tags)

    def __iter__(self):
        return (col for col in self._row)

    def __len__(self):
        return len(self._row)

    def __repr__(self):
        return repr(self._row)

    def __getslice__(self, i, j):
        return self._row[i,j]

    def __getitem__(self, i):
        return self._row[i]

    def __setitem__(self, i, value):
        self._row[i] = value

    def __delitem__(self, i):
        del self._row[i]

    def __getstate__(self):

        slots = dict()

        for slot in self.__slots__:
            attribute = getattr(self, slot)
            slots[slot] = attribute

        return slots

    def __setstate__(self, state):
        for (k, v) in list(state.items()): setattr(self, k, v)

    def rpush(self, value):
        self.insert(0, value)

    def lpush(self, value):
        self.insert(len(value), value)

    def append(self, value):
        self.rpush(value)

    def insert(self, index, value):
        self._row.insert(index, value)

    def __contains__(self, item):
        return (item in self._row)

    @property
    def tuple(self):
        """Tuple representation of :class:`Row`."""
        return tuple(self._row)

    @property
    def list(self):
        """List representation of :class:`Row`."""
        return list(self._row)

    def has_tag(self, tag):
        """Returns true if current row contains tag."""

        if tag == None:
            return False
        elif isinstance(tag, str):
            return (tag in self.tags)
        else:
            return bool(len(set(tag) & set(self.tags)))

class Dataset(object):
    """The :class:`Dataset` object is the heart of Tablib. It provides all core
    functionality.

    Usually you create a :class:`Dataset` instance in your main module, and append
    rows as you collect data. ::

        data = tablib.Dataset()
        data.headers = ('name', 'age')

        for (name, age) in some_collector():
            data.append((name, age))

    Setting columns is similar. The column data length must equal the
    current height of the data and headers must be set ::

        data = tablib.Dataset()
        data.headers = ('first_name', 'last_name')

        data.append(('John', 'Adams'))
        data.append(('George', 'Washington'))

        data.append_col((90, 67), header='age')

    You can also set rows and headers upon instantiation. This is useful if
    dealing with dozens or hundreds of :class:`Dataset` objects. ::

        headers = ('first_name', 'last_name')
        data = [('John', 'Adams'), ('George', 'Washington')]

        data = tablib.Dataset(*data, headers=headers)

    :param \*args: (optional) list of rows to populate Dataset
    :param headers: (optional) list strings for Dataset header row

    .. admonition:: Format Attributes Definition

     If you look at the code, the various output/import formats are not
     defined within the :class:`Dataset` object. To add support for a new format, see
     :ref:`Adding New Formats <newformats>`.

    """

    def __init__(self, *args, **kwargs):
        self._data = list(Row(arg) for arg in args)
        self.__headers = None

        # ('title', index) tuples
        self._separators = []

        # (column, callback) tuples
        self._formatters = []

        try:
            self.headers = kwargs['headers']
        except KeyError:
            self.headers = None

        try:
            self.title = kwargs['title']
        except KeyError:
            self.title = None

        self._register_formats()

    def __len__(self):
        return self.height

    def __getitem__(self, key):
        if isinstance(key, str) or isinstance(key, unicode):
            if key in self.headers:
                pos = self.headers.index(key) # get 'key' index from each data
                return [row[pos] for row in self._data]
            else:
                raise KeyError
        else:
            _results = self._data[key]
            if isinstance(_results, Row):
                return _results.tuple
            else:
                return [result.tuple for result in _results]

    def __setitem__(self, key, value):
        self._validate(value)
        self._data[key] = Row(value)

    def __delitem__(self, key):
        if isinstance(key, str) or isinstance(key, unicode):

            if key in self.headers:

                pos = self.headers.index(key)
                del self.headers[pos]

                for i, row in enumerate(self._data):

                    del row[pos]
                    self._data[i] = row
            else:
                raise KeyError
        else:
            del self._data[key]

    def __repr__(self):
        try:
            return '<%s dataset>' % (self.title.lower())
        except AttributeError:
            return '<dataset object>'

    def __unicode__(self):
        result = [self.__headers]

        result.extend(list(map(unicode, row)) for row in self._data)

        # here, we calculate max width for each column
        lens = (list(map(len, row)) for row in result)
        field_lens = list(map(max, zip(*lens)))

        # delimiter between header and data
        result.insert(1, ['-' * length for length in field_lens])

        format_string = '|'.join('{%s:%s}' % item for item in enumerate(field_lens))

        return '\n'.join(format_string.format(*row) for row in result)

    def __str__(self):
        return self.__unicode__()

    # ---------
    # Internals
    # ---------

    @classmethod
    def _register_formats(cls):
        """Adds format properties."""
        for fmt in formats.available:
            try:
                try:
                    setattr(cls, fmt.title, property(fmt.export_set, fmt.import_set))
                except AttributeError:
                    setattr(cls, fmt.title, property(fmt.export_set))

            except AttributeError:
                pass

    def _validate(self, row=None, col=None, safety=False):
        """Assures size of every row in dataset is of proper proportions."""
        if row:
            is_valid = (len(row) == self.width) if self.width else True
        elif col:
            if len(col) < 1:
                is_valid = True
            else:
                is_valid = (len(col) == self.height) if self.height else True
        else:
            is_valid = all((len(x) == self.width for x in self._data))

        if is_valid:
            return True
        else:
            if not safety:
                raise InvalidDimensions
            return False

    def _package(self, dicts=True, ordered=True):
        """Packages Dataset into lists of dictionaries for transmission."""
        # TODO: Dicts default to false?

        _data = list(self._data)

        if ordered:
            dict_pack = OrderedDict
        else:
            dict_pack = dict

        # Execute formatters
        if self._formatters:
            for row_i, row in enumerate(_data):
                for col, callback in self._formatters:
                    try:
                        if col is None:
                            for j, c in enumerate(row):
                                _data[row_i][j] = callback(c)
                        else:
                            _data[row_i][col] = callback(row[col])
                    except IndexError:
                        raise InvalidDatasetIndex

        if self.headers:
            if dicts:
                data = [dict_pack(list(zip(self.headers, data_row))) for data_row in _data]
            else:
                data = [list(self.headers)] + list(_data)
        else:
            data = [list(row) for row in _data]

        return data

    def _get_headers(self):
        """An *optional* list of strings to be used for header rows and attribute names.

        This must be set manually. The given list length must equal :class:`Dataset.width`.

        """
        return self.__headers

    def _set_headers(self, collection):
        """Validating headers setter."""
        self._validate(collection)
        if collection:
            try:
                self.__headers = list(collection)
            except TypeError:
                raise TypeError
        else:
            self.__headers = None

    headers = property(_get_headers, _set_headers)

    def _get_dict(self):
        """A native Python representation of the :class:`Dataset` object. If headers have
        been set, a list of Python dictionaries will be returned. If no headers have been set,
        a list of tuples (rows) will be returned instead.

        A dataset object can also be imported by setting the `Dataset.dict` attribute: ::

            data = tablib.Dataset()
            data.json = '[{"last_name": "Adams","age": 90,"first_name": "John"}]'

        """
        return self._package()

    def _set_dict(self, pickle):
        """A native Python representation of the Dataset object. If headers have been
        set, a list of Python dictionaries will be returned. If no headers have been
        set, a list of tuples (rows) will be returned instead.

        A dataset object can also be imported by setting the :class:`Dataset.dict` attribute. ::

            data = tablib.Dataset()
            data.dict = [{'age': 90, 'first_name': 'Kenneth', 'last_name': 'Reitz'}]

        """

        if not len(pickle):
            return

        # if list of rows
        if isinstance(pickle[0], list):
            self.wipe()
            for row in pickle:
                self.append(Row(row))

        # if list of objects
        elif isinstance(pickle[0], dict):
            self.wipe()
            self.headers = list(pickle[0].keys())
            for row in pickle:
                self.append(Row(list(row.values())))
        else:
            raise UnsupportedFormat

    dict = property(_get_dict, _set_dict)

    def _clean_col(self, col):
        """Prepares the given column for insert/append."""

        col = list(col)

        if self.headers:
            header = [col.pop(0)]
        else:
            header = []

        if len(col) == 1 and hasattr(col[0], '__call__'):

            col = list(map(col[0], self._data))
        col = tuple(header + col)

        return col

    @property
    def height(self):
        """The number of rows currently in the :class:`Dataset`.
           Cannot be directly modified.
        """
        return len(self._data)

    @property
    def width(self):
        """The number of columns currently in the :class:`Dataset`.
           Cannot be directly modified.
        """

        try:
            return len(self._data[0])
        except IndexError:
            try:
                return len(self.headers)
            except TypeError:
                return 0

    # -------
    # Formats
    # -------

    @property
    def xls():
        """A Legacy Excel Spreadsheet representation of the :class:`Dataset` object, with :ref:`separators`. Cannot be set.

        .. note::

            XLS files are limited to a maximum of 65,000 rows. Use :class:`Dataset.xlsx` to avoid this limitation.

         .. admonition:: Binary Warning

             :class:`Dataset.xls` contains binary data, so make sure to write in binary mode::

                with open('output.xls', 'wb') as f:
                    f.write(data.xls)
        """
        pass

    @property
    def xlsx():
        """An Excel '07+ Spreadsheet representation of the :class:`Dataset` object, with :ref:`separators`. Cannot be set.

         .. admonition:: Binary Warning

             :class:`Dataset.xlsx` contains binary data, so make sure to write in binary mode::

                with open('output.xlsx', 'wb') as f:
                    f.write(data.xlsx)
        """
        pass

    @property
    def ods():
        """An OpenDocument Spreadsheet representation of the :class:`Dataset` object, with :ref:`separators`. Cannot be set.

         .. admonition:: Binary Warning

             :class:`Dataset.ods` contains binary data, so make sure to write in binary mode::

                with open('output.ods', 'wb') as f:
                    f.write(data.ods)
        """
        pass

    @property
    def csv():
        """A CSV representation of the :class:`Dataset` object. The top row will contain
        headers, if they have been set. Otherwise, the top row will contain
        the first row of the dataset.

        A dataset object can also be imported by setting the :class:`Dataset.csv` attribute. ::

            data = tablib.Dataset()
            data.csv = 'age, first_name, last_name\\n90, John, Adams'

        Import assumes (for now) that headers exist.

        .. admonition:: Binary Warning

             :class:`Dataset.csv` uses \\r\\n line endings by default, so make
             sure to write in binary mode::

                 with open('output.csv', 'wb') as f:
                     f.write(data.csv)

             If you do not do this, and you export the file on Windows, your
             CSV file will open in Excel with a blank line between each row.
        """
        pass

    @property
    def tsv():
        """A TSV representation of the :class:`Dataset` object. The top row will contain
        headers, if they have been set. Otherwise, the top row will contain
        the first row of the dataset.

        A dataset object can also be imported by setting the :class:`Dataset.tsv` attribute. ::

            data = tablib.Dataset()
            data.tsv = 'age\tfirst_name\tlast_name\\n90\tJohn\tAdams'

        Import assumes (for now) that headers exist.
        """
        pass

    @property
    def yaml():
        """A YAML representation of the :class:`Dataset` object. If headers have been
        set, a YAML list of objects will be returned. If no headers have
        been set, a YAML list of lists (rows) will be returned instead.

        A dataset object can also be imported by setting the :class:`Dataset.yaml` attribute: ::

            data = tablib.Dataset()
            data.yaml = '- {age: 90, first_name: John, last_name: Adams}'

        Import assumes (for now) that headers exist.
        """
        pass

    @property
    def json():
        """A JSON representation of the :class:`Dataset` object. If headers have been
        set, a JSON list of objects will be returned. If no headers have
        been set, a JSON list of lists (rows) will be returned instead.

        A dataset object can also be imported by setting the :class:`Dataset.json` attribute: ::

            data = tablib.Dataset()
            data.json = '[{age: 90, first_name: "John", liast_name: "Adams"}]'

        Import assumes (for now) that headers exist.
        """
        pass

    @property
    def html():
        """A HTML table representation of the :class:`Dataset` object. If
        headers have been set, they will be used as table headers.

        ..notice:: This method can be used for export only.
        """
        pass

    # ----
    # Rows
    # ----

    def insert(self, index, row, tags=list()):
        """Inserts a row to the :class:`Dataset` at the given index.

        Rows inserted must be the correct size (height or width).

        The default behaviour is to insert the given row to the :class:`Dataset`
        object at the given index.
       """

        self._validate(row)
        self._data.insert(index, Row(row, tags=tags))

    def rpush(self, row, tags=list()):
        """Adds a row to the end of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        """

        self.insert(self.height, row=row, tags=tags)

    def lpush(self, row, tags=list()):
        """Adds a row to the top of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        """

        self.insert(0, row=row, tags=tags)

    def append(self, row, tags=list()):
        """Adds a row to the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        """

        self.rpush(row, tags)

    def extend(self, rows, tags=list()):
        """Adds a list of rows to the :class:`Dataset` using
        :class:`Dataset.append`
        """

        for row in rows:
            self.append(row, tags)

    def lpop(self):
        """Removes and returns the first row of the :class:`Dataset`."""

        cache = self[0]
        del self[0]

        return cache

    def rpop(self):
        """Removes and returns the last row of the :class:`Dataset`."""

        cache = self[-1]
        del self[-1]

        return cache

    def pop(self):
        """Removes and returns the last row of the :class:`Dataset`."""

        return self.rpop()

    # -------
    # Columns
    # -------

    def insert_col(self, index, col=None, header=None):
        """Inserts a column to the :class:`Dataset` at the given index.

        Columns inserted must be the correct height.

        You can also insert a column of a single callable object, which will
        add a new column with the return values of the callable each as an
        item in the column. ::

            data.append_col(col=random.randint)

        If inserting a column, and :class:`Dataset.headers` is set, the
        header attribute must be set, and will be considered the header for
        that row.

        See :ref:`dyncols` for an in-depth example.

        .. versionchanged:: 0.9.0
           If inserting a column, and :class:`Dataset.headers` is set, the
           header attribute must be set, and will be considered the header for
           that row.

        .. versionadded:: 0.9.0
           If inserting a row, you can add :ref:`tags <tags>` to the row you are inserting.
           This gives you the ability to :class:`filter <Dataset.filter>` your
           :class:`Dataset` later.

        """

        if col is None:
            col = []

        # Callable Columns...
        if hasattr(col, '__call__'):
            col = list(map(col, self._data))

        col = self._clean_col(col)
        self._validate(col=col)

        if self.headers:
            # pop the first item off, add to headers
            if not header:
                raise HeadersNeeded()

            # corner case - if header is set without data
            elif header and self.height == 0 and len(col):
                raise InvalidDimensions

            self.headers.insert(index, header)

        if self.height and self.width:

            for i, row in enumerate(self._data):

                row.insert(index, col[i])
                self._data[i] = row
        else:
            self._data = [Row([row]) for row in col]

    def rpush_col(self, col, header=None):
        """Adds a column to the end of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        """

        self.insert_col(self.width, col, header=header)

    def lpush_col(self, col, header=None):
        """Adds a column to the top of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        """

        self.insert_col(0, col, header=header)

    def insert_separator(self, index, text='-'):
        """Adds a separator to :class:`Dataset` at given index."""

        sep = (index, text)
        self._separators.append(sep)

    def append_separator(self, text='-'):
        """Adds a :ref:`separator <separators>` to the :class:`Dataset`."""

        # change offsets if headers are or aren't defined
        if not self.headers:
            index = self.height if self.height else 0
        else:
            index = (self.height + 1) if self.height else 1

        self.insert_separator(index, text)

    def append_col(self, col, header=None):
        """Adds a column to the :class:`Dataset`.
        See :class:`Dataset.insert_col` for additional documentation.
        """

        self.rpush_col(col, header)

    def get_col(self, index):
        """Returns the column from the :class:`Dataset` at the given index."""

        return [row[index] for row in self._data]

    # ----
    # Misc
    # ----

    def add_formatter(self, col, handler):
        """Adds a :ref:`formatter` to the :class:`Dataset`.

        .. versionadded:: 0.9.5
           :param col: column to. Accepts index int or header str.
           :param handler: reference to callback function to execute
           against each cell value.
        """

        if isinstance(col, str):
            if col in self.headers:
                col = self.headers.index(col) # get 'key' index from each data
            else:
                raise KeyError

        if not col > self.width:
            self._formatters.append((col, handler))
        else:
            raise InvalidDatasetIndex

        return True

    def filter(self, tag):
        """Returns a new instance of the :class:`Dataset`, excluding any rows
        that do not contain the given :ref:`tags <tags>`.
        """
        _dset = copy(self)
        _dset._data = [row for row in _dset._data if row.has_tag(tag)]

        return _dset

    def sort(self, col, reverse=False):
        """Sort a :class:`Dataset` by a specific column, given string (for
        header) or integer (for column index). The order can be reversed by
        setting ``reverse`` to ``True``.

        Returns a new :class:`Dataset` instance where columns have been
        sorted.
        """

        if isinstance(col, str) or isinstance(col, unicode):

            if not self.headers:
                raise HeadersNeeded

            _sorted = sorted(self.dict, key=itemgetter(col), reverse=reverse)
            _dset = Dataset(headers=self.headers, title=self.title)

            for item in _sorted:
                row = [item[key] for key in self.headers]
                _dset.append(row=row)

        else:
            if self.headers:
                col = self.headers[col]

            _sorted = sorted(self.dict, key=itemgetter(col), reverse=reverse)
            _dset = Dataset(headers=self.headers, title=self.title)

            for item in _sorted:
                if self.headers:
                    row = [item[key] for key in self.headers]
                else:
                    row = item
                _dset.append(row=row)

        return _dset

    def transpose(self):
        """Transpose a :class:`Dataset`, turning rows into columns and vice
        versa, returning a new ``Dataset`` instance. The first row of the
        original instance becomes the new header row."""

        # Don't transpose if there is no data
        if not self:
            return

        _dset = Dataset()
        # The first element of the headers stays in the headers,
        # it is our "hinge" on which we rotate the data
        new_headers = [self.headers[0]] + self[self.headers[0]]

        _dset.headers = new_headers
        for column in self.headers:

            if column == self.headers[0]:
                # It's in the headers, so skip it
                continue

            # Adding the column name as now they're a regular column
            row_data = [column] + self[column]
            row_data = Row(row_data)
            _dset.append(row=row_data)

        return _dset

    def stack(self, other):
        """Stack two :class:`Dataset` instances together by
        joining at the row level, and return new combined
        ``Dataset`` instance."""

        if not isinstance(other, Dataset):
            return

        if self.width != other.width:
            raise InvalidDimensions

        # Copy the source data
        _dset = copy(self)

        rows_to_stack = [row for row in _dset._data]
        other_rows = [row for row in other._data]

        rows_to_stack.extend(other_rows)
        _dset._data = rows_to_stack

        return _dset

    def stack_cols(self, other):
        """Stack two :class:`Dataset` instances together by
        joining at the column level, and return a new
        combined ``Dataset`` instance. If either ``Dataset``
        has headers set, than the other must as well."""

        if not isinstance(other, Dataset):
            return

        if self.headers or other.headers:
            if not self.headers or not other.headers:
                raise HeadersNeeded

        if self.height != other.height:
            raise InvalidDimensions

        try:
            new_headers = self.headers + other.headers
        except TypeError:
            new_headers = None

        _dset = Dataset()

        for column in self.headers:
            _dset.append_col(col=self[column])

        for column in other.headers:
            _dset.append_col(col=other[column])

        _dset.headers = new_headers

        return _dset

    def wipe(self):
        """Removes all content and headers from the :class:`Dataset` object."""
        self._data = list()
        self.__headers = None

class Databook(object):
    """A book of :class:`Dataset` objects.
    """

    def __init__(self, sets=None):

        if sets is None:
            self._datasets = list()
        else:
            self._datasets = sets

        self._register_formats()

    def __repr__(self):
        try:
            return '<%s databook>' % (self.title.lower())
        except AttributeError:
            return '<databook object>'

    def wipe(self):
        """Removes all :class:`Dataset` objects from the :class:`Databook`."""
        self._datasets = []

    @classmethod
    def _register_formats(cls):
        """Adds format properties."""
        for fmt in formats.available:
            try:
                try:
                    setattr(cls, fmt.title, property(fmt.export_book, fmt.import_book))
                except AttributeError:
                    setattr(cls, fmt.title, property(fmt.export_book))

            except AttributeError:
                pass

    def sheets(self):
        return self._datasets

    def add_sheet(self, dataset):
        """Adds given :class:`Dataset` to the :class:`Databook`."""
        if isinstance(dataset, Dataset):
            self._datasets.append(dataset)
        else:
            raise InvalidDatasetType

    def _package(self, ordered=True):
        """Packages :class:`Databook` for delivery."""
        collector = []

        if ordered:
            dict_pack = OrderedDict
        else:
            dict_pack = dict

        for dset in self._datasets:
            collector.append(dict_pack(
                title = dset.title,
                data = dset._package(ordered=ordered)
            ))
        return collector

    @property
    def size(self):
        """The number of the :class:`Dataset` objects within :class:`Databook`."""
        return len(self._datasets)

def detect(stream):
    """Return (format, stream) of given stream."""
    for fmt in formats.available:
        try:
            if fmt.detect(stream):
                return (fmt, stream)
        except AttributeError:
            pass
    return (None, stream)

def import_set(stream):
    """Return dataset of given stream."""
    (format, stream) = detect(stream)

    try:
        data = Dataset()
        format.import_set(data, stream)
        return data

    except AttributeError:
        return None

def import_book(stream):
    """Return dataset of given stream."""
    (format, stream) = detect(stream)

    try:
        databook = Databook()
        format.import_book(databook, stream)
        return databook

    except AttributeError:
        return None

class InvalidDatasetType(Exception):
    "Only Datasets can be added to a DataBook"

class InvalidDimensions(Exception):
    "Invalid size"

class InvalidDatasetIndex(Exception):
    "Outside of Dataset size"

class HeadersNeeded(Exception):
    "Header parameter must be given when appending a column in this Dataset."

class UnsupportedFormat(NotImplementedError):
    "Format is not supported"


text:
package me.sven.libz.image;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.imageio.ImageIO;

public class SpriteLoader {

	public static HashMap<String, Sprite> sprites = new HashMap<String, Sprite>();

	public static BufferedImage load(String path) {
		BufferedImage image = null;
		try {
			image = ImageIO.read(SpriteLoader.class.getResourceAsStream(path));
		} catch (IOException e) {
			System.out.println("Could not load image: " + path);
		}
		return image;
	}

	public static BufferedImage load(File file) {
		BufferedImage image = null;
		try {
			image = ImageIO.read(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}

	public static BufferedImage crop(BufferedImage image, int x, int y, int w, int h) {
		return image.getSubimage(x, y, w, h);
	}

	public static BufferedImage resize(BufferedImage image, int w, int h) {
		BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

		Graphics g = newImage.createGraphics();
		g.drawImage(image, 0, 0, w, h, null);
		g.dispose();

		return newImage;
	}
}


text:
        <?php
         global $redux_builder_amp;
        $set_rel_to_noamp=false;

        if( $redux_builder_amp['amp-on-off-support-for-non-amp-home-page'] ) {
                if( $redux_builder_amp['amp-mobile-redirection'] ) {
                  $ampforwp_home_url = trailingslashit( get_bloginfo('url') ).'?nonamp=1';
                  $set_rel_to_noamp = true;
                  } else {
                    $ampforwp_home_url = trailingslashit( get_bloginfo('url') );
                 }
        } else {
                 if($redux_builder_amp['ampforwp-homepage-on-off-support']) {
                    $ampforwp_home_url = user_trailingslashit( trailingslashit( get_bloginfo('url') ) . AMPFORWP_AMP_QUERY_VAR );
                 } else {
                        if( $redux_builder_amp['amp-mobile-redirection'] ) {
                          $ampforwp_home_url = trailingslashit( get_bloginfo('url') ).'?nonamp=1';
                          $set_rel_to_noamp = true;
                         } else {
                          $ampforwp_home_url = trailingslashit( get_bloginfo('url') );
                         }
                }
          }?>

        <?php
         do_action('ampforwp_header_top_design2');
         if (! empty( $redux_builder_amp['opt-media']['url'] ) ) {
          $logo_id =  attachment_url_to_postid($redux_builder_amp['opt-media'] ['url']);
          $logo_alt = get_post_meta( $logo_id, '_wp_attachment_image_alt', true) ;
          if($logo_alt){
            $alt = $logo_alt;
          }
          else {
            $alt = get_bloginfo('name');
          } ?>
          <a href="<?php echo esc_url( $ampforwp_home_url ); ?>" <?php if($set_rel_to_noamp){echo ' rel="nofollow"'; } ?> >

            <?php if($redux_builder_amp['ampforwp-custom-logo-dimensions'] == true)  { ?>

                <amp-img src="<?php echo $redux_builder_amp['opt-media']['url']; ?>" width="<?php echo $redux_builder_amp['opt-media-width']; ?>" height="<?php echo $redux_builder_amp['opt-media-height']; ?>" alt= "<?php echo $alt; ?>" class="amp-logo"></amp-img>

            <?php } else { ?>

                <amp-img src="<?php echo $redux_builder_amp['opt-media']['url']; ?>" width="190" height="36" alt= "<?php echo $alt; ?>" class="amp-logo"></amp-img>

            <?php } ?>

        <?php } else { ?>

<a href="<?php echo esc_url( $ampforwp_home_url ); ?>"  <?php if($set_rel_to_noamp){echo ' rel="nofollow"';} ?>  ><?php bloginfo('name'); ?>

        <?php } ?>
          <?php do_action('ampforwp_header_search'); ?>
          <?php do_action('ampforwp_call_button');
          do_action('ampforwp_header_bottom_design2'); ?>

<?php if(isset($redux_builder_amp['ampforwp-amp-menu']) && $redux_builder_amp['ampforwp-amp-menu']){ ?>

	<?php echo ampforwp_translation( $redux_builder_amp['amp-translator-navigate-text'], 'Navigate' ); ?>

<amp-sidebar id='sidebar'
    layout="nodisplay"
    side="right">

X
 <?php
          $menu = wp_nav_menu( array(
                                    'theme_location' => 'amp-menu' ,
                                    'echo' => false) );
          echo strip_tags( $menu , '

'); ?>

</amp-sidebar>
<?php } ?>


text:
var assert = require('assert');
var should = require('should');
var PCR = require('../lib/pcr');

var PCR_TOKEN = process.env.PCR_AUTH_TOKEN || '';

describe('PCR', () => {
  var pcr = new PCR(PCR_TOKEN);

  it('should find formal logic using course id', () => {
    pcr.course(2041, (err, json) => {
      assert.equal(json.result.name, 'FORMAL LOGIC II');
      assert.equal(json.result.semester, '2003A');
    });
  });

  it('should find formal logic using course url', () => {
    pcr.course('2003A-PHIL-006', (err, json) => {
      assert.equal(json.result.name, 'FORMAL LOGIC II');
      assert.equal(json.result.semester, '2003A');
    });
  });

  it('should find ASTR department', () => {
    pcr.department('ASTR', (err, json) => {
      assert.equal(json.result.name, 'ASTRONOMY');
    });
  });

  it('should get all departments', () => {
    pcr.departments((err, json) => {
      assert(json.result.values.length > 20);
      assert.equal(json.result.values[0].id, 'AAMW');
    });
  });

  it('should get all instructors', () => {
    pcr.instructors((err, json) => {
      assert(json.result.values.length > 20);
      assert.equal(json.result.values[0].id, '1-JACK-TOPIOL');
    });
  });

  it('should find a given instructor with int id', () => {
    pcr.instructor(1, (err, json) => {
      assert.equal(json.result.id, '1-JACK-TOPIOL');
      assert.equal(json.result.reviews.values.length, 6);
    });
  });

  it('should find a given instructor with a long id', () => {
    pcr.instructor('1-JACK-TOPIOL', (err, json) => {
      assert.equal(json.result.id, '1-JACK-TOPIOL');
      assert.equal(json.result.reviews.values.length, 6);
    });
  });

  it('should find a given instructor with a long id (Kearns)', () => {
    pcr.instructor('1356-MICHAEL-KEARNS', (err, json) => {
      assert.equal(json.result.first_name, 'MICHAEL J.');
    });
  });

  it('should get all semesters', () => {
    pcr.semesters((err, json) => {
      assert(json.result.values.length > 10);
      assert.equal(json.result.values[0].id, '2002A');
    });
  });

  it('should find a specific class section based on int ids', () => {
    pcr.section(2795, 401, (err, json) => {
      assert.equal(json.result.name, 'INTRO COGNITIVE SCIENCE');
    });
  });

  it('should find a specific class review based on int ids', () => {
    pcr.review(24765, '001', '1356-MICHAEL-KEARNS', (err, json) => {
      assert.equal(json.result.num_students, 88);
    });
  });

  it ('should find coursehistory based on id', () => {
    pcr.courseHistory(177, (err, json) => {
      assert.equal(json.result.aliases[0], 'ASTR-150');
    });
  });

  it ('should find coursehistory based on alias', () => {
    pcr.courseHistory('ASTR-150', (err, json) => {
      assert.equal(json.result.aliases[0], 'ASTR-150');
    });
  });

  it ('should get the average review of a course', () => {
    pcr.averageReview('ASTR-150', (err, json) => {
      assert(json.rInstructorAccess > 3.5);
    });
  });
});


text:
package org.waveprotocol.wave.model.id;

import org.waveprotocol.wave.model.util.Preconditions;

/**
 * Id serialiser for spec-conforming identifiers.
 *
 * This serialiser throws a runtime exception if an attempt is made to serialise
 * a non-conforming id. This check may be removed once it's no longer possible
 * to construct one.
 *
 * @author anorth@google.com (Alex North)
 */
public class ModernIdSerialiser implements IdSerialiser {

  public static final ModernIdSerialiser INSTANCE = new ModernIdSerialiser();
  private static final String SEP = "/";
  private static final String ELIDE = "~";

  @Override
  public String serialiseWaveId(WaveId id) {
    // These checks will be unnecessary once it's impossible to construct
    // a wave id that violates them.
    Preconditions.checkArgument(WaveIdentifiers.isValidDomain(0, id.getDomain()),
        "Invalid domain %s", id.getDomain());
    Preconditions.checkArgument(WaveIdentifiers.isValidIdentifier(id.getId()),
        "Invalid id %s", id.getId());
    return new StringBuilder(id.getDomain()).append(SEP).append(id.getId()).toString();
  }

  @Override
  public String serialiseWaveletId(WaveletId id) {
    // These checks will be unnecessary once it's impossible to construct
    // a wavelet id that violates them.
    Preconditions.checkArgument(WaveIdentifiers.isValidDomain(0, id.getDomain()),
        "Invalid domain %s", id.getDomain());
    Preconditions.checkArgument(WaveIdentifiers.isValidIdentifier(id.getId()),
        "Invalid id %s", id.getId());
    return new StringBuilder(id.getDomain()).append(SEP).append(id.getId()).toString();
  }

  @Override
  public String serialiseWaveletName(WaveletName name) {
    StringBuilder b = new StringBuilder(serialiseWaveId(name.waveId)).append(SEP);
    if (name.waveletId.getDomain().equals(name.waveId.getDomain())) {
      b.append(ELIDE);
    } else {
      b.append(name.waveletId.getDomain());
    }
    b.append(SEP).append(name.waveletId.getId());
    return b.toString();
  }

  @Override
  public WaveId deserialiseWaveId(String serialisedForm) throws InvalidIdException {
    String[] tokens = serialisedForm.split(SEP);
    if (tokens.length != 2) {
      throw new InvalidIdException(serialisedForm,
          "Required 2 '/'-separated tokens in serialised wave id: " + serialisedForm);
    }
    return WaveId.ofChecked(tokens[0], tokens[1]);
  }

  @Override
  public WaveletId deserialiseWaveletId(String serialisedForm) throws InvalidIdException {
    String[] tokens = serialisedForm.split(SEP);
    if (tokens.length != 2) {
      throw new InvalidIdException(serialisedForm,
          "Required 2 '/'-separated tokens in serialised wavelet id: " + serialisedForm);
    }
    return WaveletId.ofChecked(tokens[0], tokens[1]);
  }

  @Override
  public WaveletName deserialiseWaveletName(String serialisedForm) throws InvalidIdException {
    if (serialisedForm.endsWith("/")) {
      throw new InvalidIdException(serialisedForm, "Serialised wavelet name had trailing '/'");
    }
    String[] tokens = serialisedForm.split(SEP);
    if (tokens.length != 4) {
      throw new InvalidIdException(serialisedForm,
          "Required 4 '/'-separated tokens in serialised wavelet name: " + serialisedForm);
    }
    if (tokens[2].equals(tokens[0])) {
      throw new InvalidIdException(serialisedForm,
          "Serialised wavelet name had un-normalised domains");
    }
    if (tokens[2].equals(ELIDE)) {
      tokens[2] = tokens[0];
    }
    return WaveletName.of(WaveId.ofChecked(tokens[0], tokens[1]),
        WaveletId.ofChecked(tokens[2], tokens[3]));
  }

  private ModernIdSerialiser() {
  }
}


text:
{% load i18n l10n %}
{% load staticfiles %}
{% load autocomplete_light_tags %}
{% load url from future %}

{% block widget_open %}

{% endblock %}

{% block input %}
    {# a text input, that is the 'autocomplete input' #}
    <input type="text" name="{{ name }}-autocomplete" id="{{ widget.html_id }}-autocomplete" value="" {{ attrs }} />
{% endblock %}

{% block deck %}

        <select multiple="multiple" class="box autocomplete-light-widget"></select>

          <button type="button" class="select">→</button>

          <button type="button" class="deselect">←</button>

        {# a deck that should contain the list of selected options #}
        <select multiple="multiple" id="{{ widget.html_id }}-deck" class="sbsdeck autocomplete-light-widget" >
            {% for choice in choices %}
                {{ choice|autocomplete_light_choice_html:autocomplete }}
            {% endfor %}
        </select>

{% endblock %}

{% block select %}
    {# a hidden select, that contains the actual selected values #}
    <select style="display:none" class="value-select" name="{{ name }}" id="{{ widget.html_id }}" multiple="multiple">
        {% for value in values %}
            <option value="{{ value|unlocalize }}" selected="selected">{{ value }}</option>
        {% endfor %}
    </select>
{% endblock %}

{% block choice_template %}
    <option style="display:none"></option>
{% endblock %}

{% block widget_close %}

{% endblock %}


text:
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module      :  Graphics.GL.ARB.SparseTexture
-- Copyright   :  (c) Sven Panne 2019
-- License     :  BSD3
--
-- Maintainer  :  Sven Panne <svenpanne@gmail.com>
-- Stability   :  stable
-- Portability :  portable
--
--------------------------------------------------------------------------------

module Graphics.GL.ARB.SparseTexture (
  -- * Extension Support
  glGetARBSparseTexture,
  gl_ARB_sparse_texture,
  -- * Enums
  pattern GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB,
  pattern GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB,
  pattern GL_MAX_SPARSE_TEXTURE_SIZE_ARB,
  pattern GL_NUM_SPARSE_LEVELS_ARB,
  pattern GL_NUM_VIRTUAL_PAGE_SIZES_ARB,
  pattern GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB,
  pattern GL_TEXTURE_SPARSE_ARB,
  pattern GL_VIRTUAL_PAGE_SIZE_INDEX_ARB,
  pattern GL_VIRTUAL_PAGE_SIZE_X_ARB,
  pattern GL_VIRTUAL_PAGE_SIZE_Y_ARB,
  pattern GL_VIRTUAL_PAGE_SIZE_Z_ARB,
  -- * Functions
  glTexPageCommitmentARB
) where

import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions


text:
import { AbbreviationNode, AbbreviationAttribute, Abbreviation } from '@emmetio/abbreviation';
import { WalkState, WalkNext } from './walk';
import { Config } from '../../config';
/**
 * @description Utility methods for working with indent-based markup languages
 * like HAML, Slim, Pug etc.
 */
interface AttributesCollection {
    /** Primary element attributes: `id` and `class` */
    primary: AbbreviationAttribute[];
    /** Secondary element attributes: everything except `id` and `class` */
    secondary: AbbreviationAttribute[];
}
export interface IndentWalkState extends WalkState {
    options: FormatOptions;
}
export interface FormatOptions {
    /** String to output before tag name */
    beforeName?: string;
    /** String to output after tag name */
    afterName?: string;
    /** String to output before secondary attribute set */
    beforeAttribute?: string;
    /** String to output after secondary attribute set */
    afterAttribute?: string;
    /** String to put between secondary attributes */
    glueAttribute?: string;
    /** Value for boolean attributes */
    booleanValue?: string;
    /** String to put before content line (if value is multiline) */
    beforeTextLine?: string;
    /** String to put after content line (if value is multiline) */
    afterTextLine?: string;
    /** String to put after self-closing elements like `br`. Mostly a `/` character */
    selfClose?: string;
}
export default function indentFormat(abbr: Abbreviation, config: Config, options?: Partial<FormatOptions>): string;
/**
 * Outputs `node` content to output stream of `state`
 * @param node Context node
 * @param index Index of `node` in `items`
 * @param items List of `node`'s siblings
 * @param state Current walk state
 */
export declare function element(node: AbbreviationNode, index: number, items: AbbreviationNode[], state: IndentWalkState, next: WalkNext): void;
/**
 * From given node, collects all attributes as `primary` (id, class) and
 * `secondary` (all the rest) lists. In most indent-based syntaxes, primary attribute
 * has special syntax
 */
export declare function collectAttributes(node: AbbreviationNode): AttributesCollection;
/**
 * Outputs given attributes as primary into output stream
 */
export declare function pushPrimaryAttributes(attrs: AbbreviationAttribute[], state: WalkState): void;
/**
 * Outputs given attributes as secondary into output stream
 */
export declare function pushSecondaryAttributes(attrs: AbbreviationAttribute[], state: IndentWalkState): void;
/**
 * Outputs given node value into state output stream
 */
export declare function pushValue(node: AbbreviationNode, state: IndentWalkState): void;
export {};


text:
==============
SMDC_perftests
==============

This package **SMDC_perftests**, contains python modules that provide decorators
and classes for measuring execution time of function calls. On top of that
specific use cases needed during the Soil Moisture Data Cubes (SMDC) project are
implemented. Results are stored in a
:class:`SMDC_perftests.performance_tests.test_cases.TestResults` object. These
objects can be compared to each other to quickly find out if the measured time
was significantly different using a 95% confidence interval.

The objects can also be stored to and restored from netCDF4 files on disk.
There are also plotting functions for the TestResults object.

Sphinx Documentation
====================

Build the documentation with ``python setup.py docs``.

Unittest & Coverage
===================

Run ``python setup.py test`` to run all unittests defined in the subfolder
``tests`` with the help of `py.test <http://pytest.org/>`_.


text:
struct ProgressObject {
    ICompressProgress p;
    MainWorker *w;
};

static int decompress_update_progress(void *p, UInt64 insize, UInt64 outsize) {
    ProgressObject *po = (ProgressObject *)p;
    po->w->processed_raw_ = outsize;
    return 0;
}

static int compress_update_progress(void *p, UInt64 insize, UInt64 outsize) {
    ProgressObject *po = (ProgressObject *)p;
    po->w->processed_raw_ = insize;
    return 0;
}

int CompressionWorker::do_work()
{
    FileReader file_reader;
    file_reader.obj = new AsyncFileReader(task_->filelist,
            std::min<uint64_t>(32 * 1048576, task_->total_size));
    file_reader.is.Read = file_read_proc;

    FileWriter file_writer;
    file_writer.obj = new AsyncArchiveWriter(*abs_, 8 * 1048576, arc_lock_);
    file_writer.os.Write = file_write_proc;

    CSCProps p;
    CSCEncProps_Init(&p, std::min<uint64_t>(dict_size_, task_->total_size), level_);
    CSCEncHandle h = CSCEnc_Create(&p, (ISeqOutStream*)&file_writer);
    uint8_t buf[CSC_PROP_SIZE];
    CSCEnc_WriteProperties(&p, buf, 0);

    file_reader.obj->Run();
    file_writer.obj->Run();
    file_writer.obj->Write(buf, CSC_PROP_SIZE);

    ProgressObject prog;
    prog.p.Progress = compress_update_progress;
    prog.w = this;

    int ret = CSCEnc_Encode(h, (ISeqInStream*)&file_reader, (ICompressProgress*)&prog);
    CSCEnc_Encode_Flush(h);
    CSCEnc_Destroy(h);
    file_reader.obj->Finish();
    file_writer.obj->Finish();
    delete file_writer.obj;
    delete file_reader.obj;
    return ret;
}

int DecompressionWorker::do_work()
{
    FileReader file_reader;
    file_reader.obj = new AsyncArchiveReader(*abs_, 8 * 1048576);
    file_reader.is.Read = file_read_proc;

    FileWriter file_writer;
    file_writer.obj = new AsyncFileWriter(task_->filelist, 32 * 1048576);
    file_writer.os.Write = file_write_proc;

    file_reader.obj->Run();
    file_writer.obj->Run();

    ProgressObject prog;
    prog.p.Progress = decompress_update_progress;
    prog.w = this;

    CSCProps p;
    uint8_t buf[CSC_PROP_SIZE];
    size_t prop_size = CSC_PROP_SIZE;
    file_reader.obj->Read(buf, &prop_size);
    CSCDec_ReadProperties(&p, buf);
    CSCDecHandle h = CSCDec_Create(&p, (ISeqInStream*)&file_reader);
    int ret = CSCDec_Decode(h, (ISeqOutStream*)&file_writer, (ICompressProgress*)&prog);
    CSCDec_Destroy(h);

    file_reader.obj->Finish();
    file_writer.obj->Finish();
    delete file_reader.obj;
    delete file_writer.obj;
    return ret;
}


text:
[![Build status](https://ci.appveyor.com/api/projects/status/olaoata7qpl7fnk8?svg=true)](https://ci.appveyor.com/project/neutmute/loggly-csharp)
[![NuGet](https://img.shields.io/nuget/v/loggly-csharp.svg)](https://www.nuget.org/packages/loggly-csharp)

A .NET client for loggly. Supporting Https, Syslog UDP and encrypted Syslog TCP transports.
Install via [nuget](https://www.nuget.org/packages/loggly-csharp/) with

	Install-Package loggly-csharp

## Building
This project supports .NET standard and so requires the [latest tooling installed](https://www.microsoft.com/net/core#windowsvs2015)

## Configuration via app.Config
Configuration may be done via your app.config. The minimal amount config you require is to specify your `customerToken`:

```xml
<configuration>
	<configSections>
	<section name="loggly" type="Loggly.Config.LogglyAppConfig, Loggly.Config"/>
	</configSections>
	<loggly xmlns="Loggly" customerToken="your token here" />
</configuration>
```

When you get that working, take the training wheels off and go crazy:

```xml
<loggly
	xmlns="Loggly"
	applicationName="MyAwesomeApp"
	customerToken="your token here"
	isEnabled="true"
	throwExceptions="true">

  	<transport logTransport="Https" endpointHostname="logs-01.loggly.com" endpointPort="443"/>

	<search account="your_loggly_account" username="a_loggly_username" password="myLittleP0ny!"/>

	<tags>
	<simple>
	    <tag value="winforms"/>
	</simple>
	<complex>
	    <tag type="Loggly.HostnameTag" formatter="host-{0}"/>
	    <tag type="Loggly.ApplicationNameTag" formatter="application-{0}"/>
	    <tag type="Loggly.OperatingSystemVersionTag" formatter="os-{0}"/>
	    <tag type="Loggly.OperatingSystemPlatformTag" formatter="platform-{0}"/>
	</complex>
	</tags>
</loggly>
```
## Configuration via Code

The following sample shows how to configure loggly via code - useful for Azure/Asp.NET core scenarios. Be sure to do this very early in the application life cycle in order to capture your early logs.

```csharp
var config = LogglyConfig.Instance;
config.CustomerToken = "1ceb00da-cec7-45cb-8135-d3adbeef";
config.ApplicationName = $"MyApp-{_environmentName}";

config.Transport.EndpointHostname = "logs-01.loggly.com";
config.Transport.EndpointPort = 443;
config.Transport.LogTransport = LogTransport.Https;

var ct = new ApplicationNameTag();
ct.Formatter = "application-{0}";
config.TagConfig.Tags.Add(ct);
```

## Proxy
To set a global proxy for WebRequests used by HTTPS, you can do something like
```csharp
System.Net.WebRequest.DefaultWebProxy = new WebProxy("http://proxy.net:3128");
```

## Configuration Detail

### applicationName
This is an optional attribute. If you leave this attribute out but have `NewRelic.AppName` in your app.config, then it will pick that value up automatically.
Render your application name as a tag by using the `HostnameTag` (keep reading).

### isEnabled
Set it to false on your development machine so that no events are sent to loggly.

### transport
Three different transports may be specified with the `logTransport` attribute in the `transport` element.
The transport element is entirely optional and will default to the Https. The available transports are as follows:

#### logTransport="Https"
The default transport, posting to Loggly on port 443. Note that application and host source group filtering [are not supported by HTTP](https://community.loggly.com/customer/portal/questions/8416949--host-field-for-source-groups?b_id=50), so you may wish to consider a Syslog transport.

#### logTransport="SyslogUdp"
If you specify an `applicationName` in the config, the syslog UDP transport will populate the field so it may be filtered in a source group. Host is also automatically populated by  the client. Udp messages are sent in plain text.

#### logTransport="SyslogTcp"
Uses Syslog over TCP but is not encrypted. Note this needs to be on port 514 for loggly. Port 514 will be selected if not specified.

#### logTransport="SyslogSecure"
Transmits using syslog messages via a secure TLS TCP channel so that your logs are encrypted over the wire. Syslog supports JSON formatted messages just like Https. Port 6514 is required for loggly and will be the default if not specified.

#### ForwardedForIp
When using remote logging from a desktop application, Loggly will record the IP of the machine transmitting logs (HTTP). This may represent PII (Personally Identifiable Information) and may not be desired. In order to override the value Loggly records, you may add the `ForwardedForIp` property to the Transport object's configuration with a dummy value (such as `0.0.0.0`). All messages sent to Loggly with record this Ip in the indexed clientHost property. The property allows for any string, but only a valid IP value will replace the indexed value at Loggly.

#### tags
`simple` tags are string literals added to the app.config. What you see is what you get.

`complex` tags inherit from `ComplexTag`. They have the `formatter` attribute so you may specify your own `string.Format`.
The `Assembly` attribute is available as an optional parameter so you can roll your own tags too.

Loggly has certain restrictions around characters allowed in tags. This library automatically replaces illegal characters with an underscore.

## Usage: LogglyClient
Send simple text messages with something like this.

```csharp
ILogglyClient _loggly = new LogglyClient();
var logEvent = new LogglyEvent();
logEvent.Data.Add("message", "Simple message at {0}", DateTime.Now);
_loggly.Log(logEvent);
```

Or log an entire object and let the client send it as structured JSON

```csharp
logEvent.Data.Add("context", new GlimmerWingPony());
_loggly.Log(logEvent);
```

The `Log` method returns `Task<LogResponse>` so it is asynchronous by default but can be awaited.

## Usage: SearchClient

See example project below in conjunction with the [loggly docs](https://www.loggly.com/docs/api-retrieving-data/)

## Loggly.Example Project
The solution has an example project with sample code to demonstrate the client.
Before starting, copy the example config into the user config, eg:

	C:\loggly-csharp>copy .\source\Loggly.Example\example.loggly.user.config .\source\Loggly.Example\loggly.user.config

And configure the file with your own customer token.

Of course, there is no need to have a config source in your real app, this is just a convenience for this public repository.

## Contributions
Contributions are welcome.

* Open an issue to discuss your proposed changes
* Branch your PR from the `develop` branch
* `.\build.ps1` is compatible with [myget](https://www.myget.org) and [appveyor](https://www.appveyor.com/) build services for dogfooding your modifications
* `.\build.ps1` / Visual Studio 2015 will require VS2015 command prompt / [.NET core tooling](https://www.microsoft.com/net/core#windows) to compile the solution

## Projects using this client
* [nlog-targets-loggly](https://www.nuget.org/packages/NLog.Targets.Loggly) - NLog target
* [Serilog.Sinks.Loggly](https://www.nuget.org/packages/Serilog.Sinks.Loggly/) - Serilog sink
* [Loggly.CompositeC1](https://www.nuget.org/packages/Loggly.CompositeC1) - TraceListener for Composite C1 CMS

## History
### v4.6
* .NET Standard / Core compatible

### v4.5.0.3
* Bug fixes for syslog transports

### v4.5
* Targets framework 4.5
* Log method returns `Task<LogResponse>` for async/await compatibility

### v3.5
* New maintainer [neutmute](https://github.com/neutmute)
* Refactored API with new Config assembly
* Syslog UDP and TCP support added

### v2.0 and prior
* Maintained by [Karl Seguin](https://github.com/karlseguin)


text:
- **класс** `ConnectionResponse` (`php\jsoup\ConnectionResponse`)
- **исходники** `php/jsoup/ConnectionResponse.php`

**Описание**

Class ConnectionResponse

---

#### Методы

- `->`[`headers()`](#method-headers)
- `->`[`cookies()`](#method-cookies)
- `->`[`statusCode()`](#method-statuscode) - _Get the status code of the response._
- `->`[`statusMessage()`](#method-statusmessage) - _Get the status message of the response._
- `->`[`charset()`](#method-charset)
- `->`[`body()`](#method-body)
- `->`[`bodyAsBytes()`](#method-bodyasbytes)
- `->`[`contentType()`](#method-contenttype) - _Get the response content type (e.g. "text/html");_
- `->`[`parse()`](#method-parse)

---
# Методы

### headers()
```php
headers(): array
```

---

### cookies()
```php
cookies(): array
```

---

### statusCode()
```php
statusCode(): int
```
Get the status code of the response.

---

### statusMessage()
```php
statusMessage(): string
```
Get the status message of the response.

---

### charset()
```php
charset(): string
```

---

### body()
```php
body(): string
```

---

### bodyAsBytes()
```php
bodyAsBytes(): string
```

---

### contentType()
```php
contentType(): string
```
Get the response content type (e.g. "text/html");

---

### parse()
```php
parse(): Document
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectEulerSolutions.Models
{
    public class Answer
    {
        public Answer(int number, string mesg, long value, string controller)
        {
            Number = number;
            Message = mesg;
            Value = value;
            Controller = controller;
            StrValue = "";
        }

        public Answer(int number, string mesg, ulong value, string controller) : this(number, mesg, (long) value, controller)
        {
        }

        public Answer(int number, string mesg, string value, string controller) : this(number, mesg, 0, controller)
        {
            StrValue = value;
        }

        public int Number { get; set; }

        public string Message { get; set; }

        public long Value { get; set; }

        public string Controller { get; set; }

        public string StrValue { get; set; }
    }
}


text:
package edu.doane.dugal.dea.kits.general;

import edu.doane.dugal.dea.Individual;
import edu.doane.dugal.dea.Operator;
import edu.doane.dugal.dea.PRNG;

/**
 * Class implementing non-elitist tournament selection.
 *
 * @author Mark M. Meysenburg
 * @version 12/26/2014
 */
public class TournamentSelection implements Operator {

    /**
     * Tournament size. Defaults to 2.
     */
    private int k;

    /**
     * Random number generator used for the selection process.
     */
    final private PRNG prng;

    /**
     * Create a new TournamentSelection operator with default tournament size 2.
     */
    public TournamentSelection() {
        prng = PRNG.getInstance();
        setK(2);
    }

    /**
     * Create a new TournamentSelection operator with the specified tournament
     * size.
     *
     * @param k Tournament size for the operator.
     */
    public TournamentSelection(int k) {
        setK(k);
        prng = PRNG.getInstance();
    }

    /**
     * Perform a tournament selection operation on the population, with
     * tournament size k.
     *
     * @param population Array of Individuals to perform selection on.
     */
    @Override
    public void operate(Individual[] population) {
        int n = population.length;
        Individual[] newPop = new Individual[n];

        // fill new population using k-tournament selection
        for (int i = 0; i < n; i++) {
            // pick a winner for spot i
            double maxFitness = Double.NEGATIVE_INFINITY;
            Individual winner = null;
            // look at k individuals and pick the best one
            for (int j = 0; j < k; j++) {
                Individual c = population[prng.nextInt(0, n - 1)];
                if (c.getFitness() > maxFitness) {
                    maxFitness = c.getFitness();
                    winner = c;
                } // if c is better than our best yet
            } // look at k individuals

            // clone winner into spot i
            newPop[i] = Individual.copy(winner);
        } // fill new population

        // copy new population back to original one
        for(int i = 0; i < population.length; i++) {
            population[i] = null;
            population[i] = newPop[i];
        }
    }

    /**
     * Get the tournament size for this operator.
     *
     * @return the tournament size
     */
    public int getK() {
        return k;
    }

    /**
     * Set the tournament size for this operator.
     *
     * @param k the tournament size to set; must be greater than 0.
     */
    final public void setK(int k) throws IllegalArgumentException {
        if (k <= 0) {
            throw new IllegalArgumentException("Illegal k in setK: " + k);
        }
        this.k = k;
    }

    @Override
    public String toString() {
        return "TournamentSelection, k = " + k;
    }

}


text:
/*
 * MQTTTemperatureListener.cpp
 *
 *  Created on: 21 août 2015
 *      Author: warole
 */

#include <MQTTTemperatureListener.h>

MQTTTemperatureListener::~MQTTTemperatureListener() {
}


text:
require 'uri'

module Voucherify
  module Service
    class AsyncActions
      attr_reader :client

      def initialize(client)
        @client = client
      end

      def get(id)
        @client.get("/async-actions/#{ERB::Util.url_encode(id)}")
      end

      def list(query)
        @client.get('/async-actions', query)
      end

    end
  end
end


text:
package org.glamey.training.collection.queue;

/**
 * @author yang.zhou 2019.11.15.13
 */
public class LinkedQueue<T> implements Queue<T> {

    @Override
    public int size() {
        return 0;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public void enqueue(T t) {

    }

    @Override
    public T dequeue() {
        return null;
    }
}


text:
using System;
using CommandLineParser.Arguments;

namespace CommandLineParser.Exceptions
{
    /// <summary>
    /// General command line exception
    /// </summary>
    public class CommandLineException: Exception
    {
        /// <summary>
        /// Creates new instance of CommandLineException.
        /// </summary>
        /// <param name="message">Exception message</param>
        public CommandLineException(string message) : base(message)
        {
        }

        /// <summary>
        /// Creates new instance of CommandLineException.
        /// </summary>
        /// <param name="message">Exception message</param>
        /// <param name="innerException">The exception that is the cause of the
        /// current exception, or a null reference (Nothing in Visual Basic) if no
        /// inner exception is specified. </param>
        public CommandLineException(string message, Exception innerException)
            : base(message, innerException)
        {
        }
    }

    /// <summary>
    /// Thrown when command line arguments does not followgeneral rules for
    /// command line arguments or rules specific for the particular argument type.
    /// </summary>
    public class CommandLineFormatException: CommandLineException
    {
        /// <summary>
        /// Creates new instance of CommandLineFormatException.
        /// </summary>
        /// <param name="message">Exception message</param>
        public CommandLineFormatException(string message):
            base(message)
        {
        }
    }

    /// <summary>
    /// Thrown when an argument is used in a wrong way
    /// </summary>
    public class CommandLineArgumentException: CommandLineException
    {
        /// <summary>
        /// Creates new instance of CommandLineArgumentException.
        /// </summary>
        /// <param name="message">Exception message</param>
        /// <param name="argument">Name of the argument</param>
        public CommandLineArgumentException(string message, string argument) : base(message)
        {
            _argument = argument;
        }

        private string _argument;

        /// <summary>
        /// Argument used in a wrong way.
        /// </summary>
        public string Argument
        {
            get { return _argument; }
            set { _argument = value; }
        }
    }

    /// <summary>
    /// Thrown when an <see cref="Argument"/> with <see cref="Argument.Optional"/> field
    /// set to false is not used on the parsed command line.
    /// </summary>
    public class MandatoryArgumentNotSetException: CommandLineArgumentException
    {
        /// <summary>
        /// Creates new instance of MandatoryArgumentNotSetException.
        /// </summary>
        /// <param name="message">Exception message</param>
        /// <param name="argument">Name of the argument</param>
        public MandatoryArgumentNotSetException(string message, string argument) :
            base(message, argument)
        {
        }
    }

    /// <summary>
    /// Thrown when <see cref="ValueArgument{TValue}"/> value is not set on the parsed command line.
    /// </summary>
    public class MissingArgumentValueException: CommandLineArgumentException
    {
        /// <summary>
        /// Creates new instance of MissingArgumentValueException.
        /// </summary>
        /// <param name="message">Exception message</param>
        /// <param name="argument">Name of the argument</param>
        public MissingArgumentValueException(string message, string argument) :
            base(message, argument)
        {
        }
    }

    /// <summary>
    /// Thrown when uknown argument is found on the command line
    /// </summary>
    public class UnknownArgumentException: CommandLineArgumentException
    {
        /// <summary>
        /// Creates new instance of UnknownArgumentException.
        /// </summary>
        /// <param name="message">Exception message</param>
        /// <param name="argument">Name of the argument</param>
        public UnknownArgumentException(string message, string argument) :
            base(message, argument)
        {
        }
    }

    /// <summary>
    /// Thrown when parser failed to converse string to arguments value
    /// </summary>
    public class InvalidConversionException: CommandLineArgumentException
    {
        /// <summary>
        /// Creates new instance of InvalidConversionException.
        /// </summary>
        /// <param name="message">Exception message</param>
        /// <param name="argument">Name of the argument</param>
        public InvalidConversionException(string message, string argument) : base(message, argument)
        {
        }
    }

    /// <summary>
    /// Thrown when arguments value does not follow limitations defined by the argument.
    /// </summary>
    public class CommandLineArgumentOutOfRangeException: CommandLineArgumentException
    {
        /// <summary>
        /// Creates new instance of CommandLineArgumentOutOfRangeException.
        /// </summary>
        /// <param name="message">Exception message</param>
        /// <param name="argument">Name of the argument</param>
        public CommandLineArgumentOutOfRangeException(string message, string argument)
            : base(message, argument)
        {
        }
    }

    /// <summary>
    /// Thrown when argument defined group is not valid.
    /// </summary>
    public class InvalidArgumentGroupException: CommandLineException
    {
        /// <summary>
        /// Creates new instance of InvalidArgumentGroupException.
        /// </summary>
        /// <param name="message">reason of the exception</param>
        public InvalidArgumentGroupException(string message)
            : base(message)
        {
        }
    }

	/// <summary>
	/// Thrown when there are not all requested additional arguments found on the
	/// command line
	/// </summary>
	public class MissingAdditionalArgumentsException: CommandLineException
	{
		/// <summary>
		/// Creates new instance of CommandLineException.
		/// </summary>
		/// <param name="message">Exception message</param>
		public MissingAdditionalArgumentsException(string message) : base(message)
		{
		}
	}
}


text:
<?php

namespace LpFactory\Bundle\CoreBundle\Tests;

use LpFactory\Bundle\CoreBundle\Entity\Page;
use LpFactory\Bundle\CoreBundle\Tests\Entity\TestUnitBlock;

/**
 * Class PageBlockHelper
 *
 * @package LpFactory\Bundle\CoreBundle\Tests
 * @author jobou
 */
class PageBlockHelper
{
    /**
     * Create a page with 3 block
     *
     * @return Page
     */
    public static function createPageWithBlock()
    {
        $block1 = new TestUnitBlock();
        $block1->setSort(1);
        $block1->setTitle('block 1');

        $block2 = new TestUnitBlock();
        $block2->setSort(2);
        $block2->setTitle('block 2');

        $block3 = new TestUnitBlock();
        $block3->setSort(3);
        $block3->setTitle('block 3');

        $page = new Page();
        $page->setTitle('Title');
        $page->setSlug('slug-title');
        $page->addBlock($block1);
        $page->addBlock($block2);
        $page->addBlock($block3);

        return $page;
    }

    /**
     * Create a block
     *
     * @return TestUnitBlock
     */
    public static function createBlock()
    {
        $block = new TestUnitBlock();
        $block->setSort(1);
        $block->setTitle('Test block');

        return $block;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>RdToRd</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.function.definition

Class RdToRd

java.lang.Object

org.drip.function.definition.RdToRd

public abstract class RdToRd
extends java.lang.Object

RdToRd provides the evaluation of the R^d To R^d objective function and its derivatives for a specified
        set of R^d variates. Default implementation of the derivatives are for non-analytical black box objective
        functions.

Author:

Lakshmi Krishnamurthy

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

double[]
derivative(double[] adblVariate,
          int iVariateIndex,
          int iOrder)

Calculate the Derivative Array as a double

Differential[]
differential(double[] adblVariate,
            int iVariateIndex,
            int iOrder)

Calculate the Array of Differentials

abstract double[]
evaluate(double[] adblVariate)

Evaluate for the given Input R^d Variates

double[]
integrate(double[] adblLeftEdge,
         double[] adblRightEdge)

Integrate over the given Input Range Using Uniform Monte-Carlo

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

evaluate

public abstract double[] evaluate(double[] adblVariate)

Evaluate for the given Input R^d Variates

Parameters:

adblVariate - Array of Input R^d Variates

Returns:

The Output R^d Variates

differential

public Differential[] differential(double[] adblVariate,
                                   int iVariateIndex,
                                   int iOrder)

Calculate the Array of Differentials

Parameters:

adblVariate - Variate Array at which the derivative is to be calculated

iVariateIndex - Index of the Variate whose Derivative is to be computed

iOrder - Order of the derivative to be computed

Returns:

The Array of Differentials

derivative

public double[] derivative(double[] adblVariate,
                           int iVariateIndex,
                           int iOrder)

Calculate the Derivative Array as a double

Parameters:

adblVariate - Variate Array at which the derivative is to be calculated

iVariateIndex - Index of the Variate whose Derivative is to be computed

iOrder - Order of the derivative to be computed

Returns:

The Derivative Array

integrate

public double[] integrate(double[] adblLeftEdge,
                          double[] adblRightEdge)

Integrate over the given Input Range Using Uniform Monte-Carlo

Parameters:

adblLeftEdge - Array of Input Left Edge

adblRightEdge - Array of Input Right Edge

Returns:

The Array Containing the Result of the Integration over the specified Range

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
ListViewFunctions::<BIG>SelectUnverifiedTextItem</BIG>

RC
TC
DRD
SE2

<short_desc xmlns="">
                Routine to select (single click) an unverifiable item according to its text value.
              </short_desc>

<detailed_desc xmlns="">
                An unverifiable item is one whose READ value is not the same as its SET value.
              </detailed_desc>

Fields: [ ]=Optional with Default Value

SelectTextValue

<short_desc xmlns="">
                 Case-sensitive text of node to select
              </short_desc>

<detailed_desc xmlns="">
                 SelectTextValue should contain the case-sensitive text item to select.
                 The selection will not be verified.
              </detailed_desc>

[ MatchIndex =  ]

<short_desc xmlns="">
                 Optional index of the Nth duplicate item to match.
              </short_desc>

<detailed_desc xmlns="">
                 Allows us to match duplicate item N in a list containing duplicate
                 entries.  For example, match the 2nd (or specified Nth) item whose text matches
                 the provided text value.

                 The value of the parameter can have 2 forms:

A numeric value.  Ex: "3"

Index prefixed value.  Ex: "Index=3"

</detailed_desc>

Examples:

<usage xmlns=""> T, WINDOW, ListView, SelectUnverifiedTextItem ,  "AParticularUserID"   </usage>

<short_desc xmlns="">
                 Selects "AParticularUserID" from the ListView object.
              </short_desc>

<detailed_desc xmlns="">
                 The selection will not (cannot) be verified.
              </detailed_desc>

<usage xmlns=""> T, WINDOW, ListView, SelectUnverifiedTextItem ,  "AParticularUserID", "Index=3"   </usage>

<short_desc xmlns="">
                 Selects the 3rd text item matching "AParticularUserID" from the ListView object.
              </short_desc>

<detailed_desc xmlns="">
                 The selection will not (cannot) be verified.
              </detailed_desc>

[How To Read This Reference]


text:
package cn.nowdo.cloud.base.utils;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;

public class SpringApplicationContext {
    private static Logger logger = Logger.getLogger(SpringApplicationContext.class);
    private static ApplicationContext context;

    public static <T> T getBeanByName(String name, final Class<T> clazz) {
        T bean = null;
        if (!StringUtils.isEmpty(name)) {
            try {
                bean = context.getBean(name, clazz);
            } catch (Exception e) {
                logger.error("getBeanByName " + name + " not found " + e);
            }
        }
        return bean;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBeanByName(String name) {
        T bean = null;
        if (!StringUtils.isEmpty(name)) {
            try {
                bean = (T) context.getBean(name);
            } catch (Exception e) {
                logger.error("getBeanByName " + name + " not found " + e);
            }
        }
        return bean;
    }

    public static <T> T getBeanByClass(final Class<T> clazz) {
        T bean = null;
        try {
            bean = context.getBean(clazz);
        } catch (Exception e) {
            logger.error("getBeanByClass " + clazz + " not found " + e);
        }
        return bean;
    }

    public static synchronized void setApplicationContext(ApplicationContext context) {
        logger.info("setApplicationContext " + context);
        logger.info("setApplicationContext " + SpringApplicationContext.context);
        if (SpringApplicationContext.context == null) {
            SpringApplicationContext.context = context;
        }
    }
}