text:
[![Build Status](https://travis-ci.org/openforcefield/smarty.svg?branch=master)](https://travis-ci.org/openforcefield/smarty?branch=master)
[![DOI](https://zenodo.org/badge/60921138.svg)](https://zenodo.org/badge/latestdoi/60921138)

# `smarty`: Exploring Bayesian atom type sampling

This is a simple example of how Bayesian atom type sampling using reversible-jump Markov chain Monte Carlo (RJMCMC) [1] over SMARTS types might work.

All tools for implementation of the SMIRNOFF in OpenMM have been moved to the [openforcefield repository](https://github.com/openforcefield/openforcefield)

## Manifest

* `examples/` - some toy examples - look here to get started
* `smarty/` - simple toolkit illustrating the use of RJMCMC to sample over SMARTS-specified atom types and SMIRKS-specified bonded and non-bonded parameter types.
* `devtools/` - continuous integration and packaging scripts and utilities
* `oe_license.txt.enc` - encrypted OpenEye license for continuous integration testing
* `.travis.yml` - travis-ci continuous integration file
* `utilities/` - some utility functionality relating to the project, specifically testing the speed of ChemicalEnvironments for sampling in SMIRKY.

## Prerequisites

Install [miniconda](http://conda.pydata.org/miniconda.html) first. On `osx` with `bash`, this is:
```
wget https://repo.continuum.io/miniconda/Miniconda2-latest-MacOSX-x86_64.sh
bash Miniconda2-latest-MacOSX-x86_64.sh -b -p $HOME/miniconda
export PATH="$HOME/miniconda/bin:${PATH}""
```

You must first install the OpenEye toolkit:
```
pip install -i https://pypi.anaconda.org/OpenEye/simple OpenEye-toolkits
```

You can then use conda to install smarty:
```
conda config --add channels omnia
conda install -c omnia smarty
```

## Installation

Install `smarty` from the `smarty/` directory with:
```bash
pip install .
```
If you modify the `smarty` source code (rather than the examples), reinstall with
```bash
pip install . --upgrade
```

## Documentation

## SMARTY atom type sampler

Check out the example in `examples/smarty/`:

Atom types are specified by SMARTS matches with corresponding parameter names.

First, we start with a number of initial "base types" which are essentially indestructible (often generic) atom types, specified in `atomtypes/basetypes.smarts`:
```
% atom types
[#1]    hydrogen
[#6]    carbon
[#7]    nitrogen
[#8]    oxygen
[#9]    fluorine
[#15]   phosphorous
[#16]   sulfur
[#17]   chlorine
[#35]   bromine
[#53]   iodine
```
Note that lines beginning with `%` are comment lines.

We also specify a number of starting types, "initial types" which can be the same or different from the base types. These follow the same format, and `atomtypes/basetypes.smarts` can be reused unless alternate behavior is desired (such as starting from more sophisticated initial types).

We have two sampler options for SMARTY which differ in how focused the sampling is. The original sampler samples over all elements/patterns at once, whereas the elemental sampler focuses on sampling only one specific element. The principle of sampling is the same; the only change is in which elements we sample over. To sample only over a single element, such as oxygen, for example, we use the elemental sampler to focus on that element.

### Generating New SMARTS patterns

There are two options for how to change SMARTS patterns when creating new atom types.
One is using combinatorial decorators (default) and the other is using simple decorators (`--decoratorbehavior=simple-decorators`). However, it should be noted that we have found the simple decorators insufficient at distinguishing atomtypes even for the most simple sets of molecules.

**Combinatorial Decorators**

The first option (combinatorial-decorator) attempt to create the new atomtype adding an Alpha or Beta substituent to a basetype or an atomtype.
This decorators are different from the simple-decorator option and do not have atom types or bond information on it.
The new decorators are listed in `AlkEthOH/atomtypes/new-decorators.smarts` and `parm@frosst/atomtypes/new-decorators.smarts`:

 ```
 % total connectivity
 X1             connections-1
 X2             connections-2
 X3             connections-3
 X4             connections-4
 % total-h-count
 H0             total-h-count-0
 H1             total-h-count-1
 H2             total-h-count-2
 H3             total-h-count-3
 % formal charge
 +0             neutral
 +1             cationic+1
 -1             anionic-1
 % aromatic/aliphatic
 a              aromatic
 A              aliphatic
 ```
Each decorator has a corresponding string token (no spaces allowed!) that is used to create human-readable versions of the corresponding atom types.

For example, we may find the atom type ```[#6]&H3``` which is `carbon total-h-count-3` for a C atom bonded to three hydrogens.

**Simple Decorators**
The second option (simple-decorators) attempts to split off a new atom type from a parent atom type by combining (via an "and" operator, `&`) the parent atom type with a "decorator".
The decorators are listed in `AlkEthOH/atomtypes/decorators.smarts` or `parm@frosst/atomtypes/decorators.smarts`:
```
% bond order
$([*]=[*])     double-bonded
$([*]#[*])     triple-bonded
$([*]:[*])     aromatic-bonded
% bonded to atoms
$(*~[#1])      hydrogen-adjacent
$(*~[#6])      carbon-adjacent
$(*~[#7])      nitrogen-adjacent
$(*~[#8])      oxygen-adjacent
$(*~[#9])      fluorine-adjacent
$(*~[#15])     phosphorous-adjacent
$(*~[#16])     sulfur-adjacent
$(*~[#17])     chlorine-adjacent
$(*~[#35])     bromine-adjacent
$(*~[#53])     iodine-adjacent
% degree
D1             degree-1
D2             degree-2
D3             degree-3
D4             degree-4
D5             degree-5
D6             degree-6
% valence
v1             valence-1
v2             valence-2
v3             valence-3
v4             valence-4
v5             valence-5
v6             valence-6
% total-h-count
H1             total-h-count-1
H2             total-h-count-2
H3             total-h-count-3
% aromatic/aliphatic
a              atomatic
A              aliphatic
```
This option also has the corresponding string tokens.

Newly proposed atom types are added to the end of the list.
After a new atom type is proposed, all molecules are reparameterized using the new set of atom types.
Atom type matching proceeds by trying to see if each SMARTS match can be applied working from top to bottom of the list.
This means the atom type list is hierarchical, with more general types appearing at the top of the list and more specific subtypes appearing at the bottom.

If a proposed type matches zero atoms, the RJMCMC move is rejected.

Currently, the acceptance criteria does not include the full Metropolis-Hastings acceptance criteria that would include the reverse probability.  This needs to be added in.

### Elemental Decomposition

The input option `--element` allows a user to specify which atoms types to sample based on atomic number. The default input is 0 (corresponding to no specified atomic number) and will attempt to match all atom types. If an element number is given (i.e. `--element=1` for hydrogen) only atoms with that atomic number are considered. Specifying an element number does not affect any other smarty behavior.

Finally, here is a complete list of input options for smarty. Under `usage` all bracketed parameters are optional.
```
Usage:     Sample over atom types, optionally attempting to match atom types in a reference typed set of molecules.

    usage: smarty --basetypes smartsfile --initialtypes smartsfile
            --decorators smartsfile --molecules molfile
            [--element atomicnumber --substitutions smartsfile --reference molfile
            --decoratorbehavior combinatorial-decorators/simple-decorators
            --iterations niterations --temperature temperature --trajectory trajectorfile
            --plot plotfile]

    example:
    python smarty --basetypes=atomtypes/basetypes.smarts --initialtypes=atomtypes/initialtypes.smarts \
            --decorators=atomtypes/decorators.smarts --substitutions=atomtypes/substitutions.smarts \
            --molecules=molecules/zinc-subset-tripos.mol2.gz --reference=molecules/zinc-subset-parm@frosst.mol2.gz \
            --iterations 1000 --temperature=0.1

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -e ELEMENT, --element=ELEMENT
                        By default the element value is 0 corresponding to
                        sampling all atomtypes. If another atomic number is
                        specified only atoms with that atomic number are
                        sampled (i.e. --element=8 will only sample atomtypes
                        for oxygen atoms).
  -b BASETYPES, --basetypes=BASETYPES
                        Filename defining base or generic atom types as SMARTS
                        atom matches; these are indestructible and normally
                        are elemental atom types.
  -f BASETYPES, --initialtypes=BASETYPES
                        Filename defining initial (first) atom types as SMARTS
                        atom matches.
  -d DECORATORS, --decorators=DECORATORS
                        Filename defining decorator atom types as SMARTS atom
                        matches.
  -s SUBSTITUTIONS, --substitutions=SUBSTITUTIONS
                        Filename defining substitution definitions for SMARTS
                        atom matches (OPTIONAL).
  -r REFMOL, --reference=REFMOL
                        Reference typed molecules for computing likelihood
                        (must match same molecule and atom ordering in
                        molecules file) (OPTIONAL).
  -m MOLECULES, --molecules=MOLECULES
                        Small molecule set (in any OpenEye compatible file
                        format) containing 'dG(exp)' fields with experimental
                        hydration free energies.
  -i ITERATIONS, --iterations=ITERATIONS
                        MCMC iterations.
  -t TEMPERATURE, --temperature=TEMPERATURE
                        Effective temperature for Monte Carlo acceptance,
                        indicating fractional tolerance of mismatched atoms
                        (default: 0.1). If 0 is specified, will behave in a
                        greedy manner.
  -l TRAJECTORY_FILE, --trajectory=TRAJECTORY_FILE
                        Name for trajectory file output, trajectory saves only
                        changes to the list of 'atomtypes' for each iteration.
                        If the file already exists, it is overwritten.
  -p PLOT_FILE, --plot=PLOT_FILE
                        Name for output file of a plot of the score versus
                        time. If not specified, none will be written. If
                        provided, needs to use a file extension suitable for
                        matplotlib/pylab. Currently requires a trajectory file
                        to be written using -l or --trajectory.
  -x DECORATOR_BEHAVIOR, --decoratorbehavior=DECORATOR_BEHAVIOR
                        Choose between simple-decorators or combinatorial-
                        decorators (default = combinatorial-decorators).
```

---

## smirky

Check out examples in `examples/smirky/`:

This tool can sample any chemical environment type relevant to SMIRNOFFs, that is atoms, bonds, angles, and proper and improper torsions, one at a time
Scoring is analous to smarty (explained above), but uses a SMIRNOFF with existing parameters as a reference insteady of atomtyped molecules.

Input for this tool can require up to four different file types
* MOLECULES - any file that are readable in openeye, mol2, sdf, oeb, etc.
* ODDSFILES - File with the form "smarts     odds" for the different decorator or bond options
* SMARTS - .smarts file type with the form "smarts/smirks      label/typename"
* REFERENCE - a SMIRNOFF file with reference atoms, bonts, angles, torsions, and impropers

```
Usage:     Sample over fragment types (atoms, bonds, angles, torsions, or impropers)
    optionally attempting to match created types to an established SMIRNOFF.
    For all files left blank, they will be taken from this module's
    data/odds_files/ subdirectory.

    usage smirky --molecules molfile --typetag fragmentType
            [--atomORbases AtomORbaseFile --atomORdecors AtomORdecorFile
            --atomANDdecors AtomANDdecorFile --bondORbase BondORbaseFile
            --bondANDdecors BondANDdecorFile --atomIndexOdds AtomIndexFile
            --bondIndexOdds BondIndexFile --replacements substitutions
            --initialFragments initialFragments --SMIRNOFF referenceSMIRNOFF
            --temperature float --verbose verbose
            --iterations iterations --output outputFile]

    example:
    smirky -molecules AlkEthOH_test_filt1_ff.mol2 --typetag Angle

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -m MOLECULES, --molecules=MOLECULES
                        Small molecule set (in any OpenEye compatible file
                        format) containing 'dG(exp)' fields with experimental
                        hydration free energies. This filename can also be an
                        option in this module's data/molecules sub-directory
  -T TYPETAG, --typetag=TYPETAG
                        type of fragment being sampled, options are 'VdW',
                        'Bond', 'Angle', 'Torsion', 'Improper'
  -e ODDFILES, --atomORbases=ODDFILES
                        Filename defining atom OR bases and associated
                        probabilities. These are combined with atom OR
                        decorators in SMIRKS, for example in
                        '[#6X4,#7X3;R2:2]' '#6' and '#7' are atom OR bases.
                        (OPTIONAL)
  -O ODDFILES, --atomORdecors=ODDFILES
                        Filename defining atom OR decorators and associated
                        probabilities. These are combined with atom bases in
                        SMIRKS, for example in '[#6X4,#7X3;R2:2]' 'X4' and
                        'X3' are ORdecorators. (OPTIONAL)
  -A ODDFILES, --atomANDdecors=ODDFILES
                        Filename defining atom AND decorators and associated
                        probabilities. These are added to the end of an atom's
                        SMIRKS, for example in '[#6X4,#7X3;R2:2]' 'R2' is an
                        AND decorator. (OPTIONAL)
  -o ODDFILES, --bondORbase=ODDFILES
                        Filename defining bond OR bases and their associated
                        probabilities. These are OR'd together to describe a
                        bond, for example in '[#6]-,=;@[#6]' '-' and '=' are
                        OR bases. (OPTIONAL)
  -a ODDFILES, --bondANDdecors=ODDFILES
                        Filename defining bond AND decorators and their
                        associated probabilities. These are AND'd to the end
                        of a bond, for example in '[#6]-,=;@[#7]' '@' is an
                        AND decorator.(OPTIONAL)
  -D ODDSFILE, --atomOddsFile=ODDSFILE
                        Filename defining atom descriptors and probabilities
                        with making changes to that kind of atom. Options for
                        descriptors are integers corresponding to that indexed
                        atom, 'Indexed', 'Unindexed', 'Alpha', 'Beta', 'All'.
                        (OPTIONAL)
  -d ODDSFILE, --bondOddsFile=ODDSFILE
                        Filename defining bond descriptors and probabilities
                        with making changes to that kind of bond. Options for
                        descriptors are integers corresponding to that indexed
                        bond, 'Indexed', 'Unindexed', 'Alpha', 'Beta', 'All'.
                        (OPTIONAL)
  -s SMARTS, --substitutions=SMARTS
                        Filename defining substitution definitions for SMARTS
                        atom matches. (OPTIONAL).
  -f SMARTS, --initialtypes=SMARTS
                        Filename defining initial (first) fragment types as
                        'SMIRKS    typename'. If this is left blank the
                        initial type will be a generic form of the given
                        fragment, for example '[*:1]~[*:2]' for a bond
                        (OPTIONAL)
  -r REFERENCE, --smirff=REFERENCE
                        Filename defining a SMIRNOFF force fielce used to
                        determine reference fragment types in provided set of
                        molecules. It may be an absolute file path, a path
                        relative to the current working directory, or a path
                        relative to this module's data subdirectory (for built
                        in force fields). (OPTIONAL)
  -i ITERATIONS, --iterations=ITERATIONS
                        MCMC iterations.
  -t TEMPERATURE, --temperature=TEMPERATURE
                        Effective temperature for Monte Carlo acceptance,
                        indicating fractional tolerance of mismatched atoms
                        (default: 0.1). If 0 is specified, will behave in a
                        greedy manner.
  -p OUTPUT, --output=OUTPUT
                        Filename base for output information. This same base
                        will be used for all output files created. If None
                        provided then it is set to 'typetag_temperature'
                        (OPTIONAL).
  -v VERBOSE, --verbose=VERBOSE
                        If True prints minimal information to the commandline
                        during iterations. (OPTIONAL)
``

## The SMIRNOFF force field format

The SMIRNOFF force field format is documented [here](https://github.com/openforcefield/openforcefield/blob/master/The-SMIRNOFF-force-field-format.md).
It was previously avaialbe in this repository, but has been moved.
SMIRNOFF99Frosst, a version of SMIRNOFF mirroring the parameters found in the parm@Frosst force field, is now housed in its own [repository](https://github.com/openforcefield/smirnoff99Frosst).
`forcefield.py` and other modules required to implement the SMIRNOFF format for simulations in OpenMM have also been moved. These scripts and examples on how to use them can be found at [openforcefield/openforcefield](https://github.com/openforcefield/openforcefield).

## References

[1] Green PJ. Reversible jump Markov chain Monte Carlo computation and Bayesian model determination. Biometrika 82:711, 1995.
http://dx.doi.org/10.1093/biomet/82.4.711


text:
function php_ipro_record() {
  local url="$1"
  local max_cache_bytes="$2"
  local cache_bytes_op="$3"
  local cache_bytes_cmp="$4"
  echo http_proxy=$SECONDARY_HOSTNAME $WGET_DUMP --save-headers $url
  OUT=$(http_proxy=$SECONDARY_HOSTNAME $WGET_DUMP --save-headers $url)
  check_from "$OUT" egrep -iq 'Content-Encoding: gzip'
  # Now check that we receive the optimized content from cache (not double
  # zipped). When the resource is optimized, "peachpuff" is rewritten to its
  # hex equivalent.
  http_proxy=$SECONDARY_HOSTNAME fetch_until $url 'fgrep -c ffdab9' 1
  # The gzipped size is 175 with the default compression. Our compressed
  # cache uses gzip -9, which will compress even better (below 150).
  OUT=$(http_proxy=$SECONDARY_HOSTNAME $WGET -O - \
    --header="Accept-Encoding: gzip" $url)
  # TODO(jcrowell): clean up when ngx_pagespeed stops chunk-encoding static
  # resources.
  bytes_from_cache=$(echo "$OUT" | wc -c)
  check [ $bytes_from_cache -lt $max_cache_bytes ]
  check [ $bytes_from_cache $cache_bytes_op $cache_bytes_cmp ]
  # Ensure that the Content-Encoding header matches the data that is sent.
  OUT=$(http_proxy=$SECONDARY_HOSTNAME $WGET_DUMP \
    --header='Accept-Encoding: gzip' $url \
    | scrape_header 'Content-Encoding')
  check_from "$OUT" fgrep -q 'gzip'
  OUT=$(http_proxy=$SECONDARY_HOSTNAME $WGET -O - $url)
  bytes_from_cache_uncompressed=$(echo "$OUT" | wc -c)
  # The data should uncompressed, but minified at this point.
  check [ $bytes_from_cache_uncompressed -gt 10000 ]
  check_from "$OUT" grep -q "ffdab9"
  # Ensure that the Content-Encoding header matches the data that is sent.
  # In this case we didn't sent the Accept-Encoding header, so we don't
  # expect the data to have any Content-Encoding header.
  OUT=$(http_proxy=$SECONDARY_HOSTNAME $WGET_DUMP $url)
  check_not_from "$OUT" egrep -q 'Content-Encoding'
}
start_test Cache Compression On: PHP Pre-Gzipping does not get destroyed by the cache.
URL="http://compressedcache.example.com/mod_pagespeed_test/php_gzip.php"
# The gzipped size is 175 with the default compression. Our compressed
# cache uses gzip -9, which will compress even better (below 150).
php_ipro_record "$URL" 150 "-lt" 175
start_test Cache Compression Off: PHP Pre-Gzipping does not get destroyed by the cache.
# With cache compression off, we should see about 175 for both the pre and
# post optimized resource.
URL="http://uncompressedcache.example.com/mod_pagespeed_test/php_gzip.php"
php_ipro_record "$URL" 200 "-gt" 150

redpajama_set_name: RedPajamaGithub


text:
using System;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NodaMoney.UnitTests
{
    public class CurrencyBuilderTests
    {
        [TestClass]
        public class GivenIWantToCreateCustomCurrency
        {
            [TestMethod]
            public void WhenRegisterBitCoinInIsoNamespace_ThenShouldBeAvailable()
            {
                var builder = new CurrencyBuilder("BTC", "ISO-4217");
                builder.EnglishName = "Bitcoin";
                builder.Symbol = "฿";
                builder.ISONumber = "123"; // iso number
                builder.DecimalDigits = 8;
                builder.IsObsolete = false;

                Currency result = builder.Register();

                Currency bitcoin = Currency.FromCode("BTC");
                bitcoin.Symbol.Should().Be("฿");
                bitcoin.ShouldBeEquivalentTo(result);
            }

            [TestMethod]
            public void WhenRegisterBitCoin_ThenShouldBeAvailableByExplicitNamespace()
            {
                var builder = new CurrencyBuilder("BTC1", "virtual");
                builder.EnglishName = "Bitcoin";
                builder.Symbol = "฿";
                builder.ISONumber = "123"; // iso number
                builder.DecimalDigits = 8;
                builder.IsObsolete = false;

                Currency result = builder.Register();

                Currency bitcoin = Currency.FromCode("BTC1", "virtual");
                bitcoin.Symbol.Should().Be("฿");
                bitcoin.ShouldBeEquivalentTo(result);
            }

            [TestMethod]
            public void WhenBuildBitCoin_ThenItShouldSuccedButNotBeRegistered()
            {
                var builder = new CurrencyBuilder("BTC2", "virtual");
                builder.EnglishName = "Bitcoin";
                builder.Symbol = "฿";
                builder.ISONumber = "123"; // iso number
                builder.DecimalDigits = 8;
                builder.IsObsolete = false;

                Currency result = builder.Build();
                result.Symbol.Should().Be("฿");

                Action action = () => Currency.FromCode("BTC2", "virtual");
                action.ShouldThrow<ArgumentException>().WithMessage("BTC2 is an unknown virtual currency code!");
            }

            [TestMethod]
            public void WhenFromExistingCurrency_ThenThisShouldSucceed()
            {
                var builder = new CurrencyBuilder("BTC3", "virtual");

                var euro = Currency.FromCode("EUR");
                builder.LoadDataFromCurrency(euro);

                builder.Code.Should().Be("BTC3");
                builder.Namespace.Should().Be("virtual");
                builder.EnglishName.Should().Be(euro.EnglishName);
                builder.Symbol.Should().Be(euro.Symbol);
                builder.ISONumber.Should().Be(euro.Number);
                builder.DecimalDigits.Should().Be(euro.DecimalDigits);
                builder.IsObsolete.Should().Be(euro.IsObsolete);
                builder.ValidFrom.Should().Be(euro.ValidFrom);
                builder.ValidTo.Should().Be(euro.ValidTo);
            }
        }

        [TestClass]
        public class GivenIWantToUnregisterCurrency
        {
            [TestMethod]
            public void WhenUnregisterIsoCurrency_ThenThisMustSucceed()
            {
                var euro = Currency.FromCode("EUR"); // should work

                CurrencyBuilder.Unregister("EUR", "ISO-4217");
                Action action = () => Currency.FromCode("EUR");

                action.ShouldThrow<ArgumentException>().WithMessage("*unknown*currency*");

                // register again for other unit-tests
                var builder = new CurrencyBuilder("EUR", "ISO-4217");
                builder.LoadDataFromCurrency(euro);
                builder.Register();
            }

            [TestMethod]
            public void WhenUnregisterCustomCurrency_ThenThisMustSucceed()
            {
                var builder = new CurrencyBuilder("XYZ", "virtual");
                builder.EnglishName = "Xyz";
                builder.Symbol = "฿";
                builder.ISONumber = "123"; // iso number
                builder.DecimalDigits = 4;
                builder.IsObsolete = false;

                builder.Register();
                Currency xyz = Currency.FromCode("XYZ", "virtual"); // should work

                CurrencyBuilder.Unregister("XYZ", "virtual");
                Action action = () => Currency.FromCode("XYZ", "virtual");

                action.ShouldThrow<ArgumentException>().WithMessage("*unknown*currency*");
            }

            [TestMethod]
            public void WhenCurrencyDoesntExist_ThenThisShouldThrow()
            {
                Action action = () => CurrencyBuilder.Unregister("ABC", "virtual");

                action.ShouldThrow<ArgumentException>().WithMessage("*specifies a currency that is not found*");
            }
        }

        [TestClass]
        public class GivenIWantToReplaceIsoCurrencyWithOwnVersion
        {
            [TestMethod]
            public void WhenReplacingEuroWithCustom_ThenThisShouldSucceed()
            {
                Currency oldEuro = CurrencyBuilder.Unregister("EUR", "ISO-4217");

                var builder = new CurrencyBuilder("EUR", "ISO-4217");
                builder.LoadDataFromCurrency(oldEuro);
                builder.EnglishName = "New Euro";
                builder.DecimalDigits = 1;

                builder.Register();

                Currency newEuro = Currency.FromCode("EUR");
                newEuro.Symbol.Should().Be("€");
                newEuro.EnglishName.Should().Be("New Euro");
                newEuro.DecimalDigits.Should().Be(1);
            }
        }
    }
}


text:
/*
 * PathNetwork.hpp
 *
 *  Created on: Jun 15, 2015
 *      Author: jcassidy
 */

#ifndef PATHNETWORK_HPP_
#define PATHNETWORK_HPP_

#include <vector>
#include <string>
#include <unordered_map>

#include <boost/range/algorithm.hpp>

#include <iomanip>
#include <iostream>

#include <boost/container/flat_set.hpp>

#include <unordered_map>

#include <boost/range/algorithm.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/filtered.hpp>

#include <boost/graph/adjacency_list.hpp>

#include "OSMEntity.hpp"
#include "OSMNode.hpp"
#include "OSMWay.hpp"

#include "KeyValueTable.hpp"
#include "OSMEntityFilter.hpp"

#include "OSMDatabase.hpp"

/** Specialization to pick out roads */

class OSMWayFilterRoads : public OSMEntityFilter<OSMWay> {
public:

    OSMWayFilterRoads(const OSMDatabase& db, const std::vector<OSMNode>& nodes) :
    OSMEntityFilter<OSMWay>(db),
    kvt_(db.wayTags()),
    kiName_(db.wayTags().getIndexForKeyString("name")),
    kiHighway_(db.wayTags().getIndexForKeyString("highway")) {
        for (const char * const *s = includeHighwayTagValueStrings_; *s != nullptr; ++s)
            includeHighwayTagValues_.insert(kvt_.getIndexForValueString(*s));
    }

    virtual bool operator()(const OSMWay& e) const override
    {
        unsigned vi = e.getValueForKey(kiHighway_);
        return vi != -1U && includeHighwayTagValues_.count(vi);
    }

private:
    const KeyValueTable& kvt_;
    unsigned kiName_ = -1U;
    unsigned kiHighway_ = -1U;

    boost::container::flat_set<unsigned> includeHighwayTagValues_;

    static const char * includeHighwayTagValueStrings_[];
};

struct NodeInfo {
    OSMID osmid = -1ULL;
    LatLon latlon;

private:
    friend boost::serialization::access;

    template<class Archive>void serialize(Archive& ar, const unsigned ver) {
        ar & osmid & latlon;
    }
};

struct EdgeProperties {
    std::vector<LatLon> curvePoints;
    unsigned long long wayOSMID = -1U;

    unsigned streetVectorIndex = -1U;
    unsigned streetSegmentVectorIndex = -1U; // <=== NOT SERIALIZED! MUST BE REBUILT BY PATHNETWORK
    float maxspeed = 50.0;

    enum Oneway : uint8_t {
        Bidir = 0, ToGreaterVertexNumber = 1, ToLesserVertexNumber = 2
    };

    Oneway oneWay = Bidir;

private:
    friend boost::serialization::access;

    template<class Archive>void serialize(Archive& ar, const unsigned ver) {
        ar & curvePoints & wayOSMID & streetVectorIndex & maxspeed & oneWay;
    }
};

typedef boost::adjacency_list<
boost::vecS, // outedgelist
boost::vecS, // vertex list
boost::undirectedS, // dir/undir/bidir
NodeInfo,
EdgeProperties,
boost::no_property,
boost::vecS> PathNetwork;

#ifdef CLANG
#define STDPAIR std::__1::pair
#else
#define STDPAIR std::pair
#endif

template<class Iterator>Iterator begin(STDPAIR<Iterator, Iterator> p,
        typename std::iterator_traits<Iterator>::difference_type __sfinae = 0) {
    return p.first;
}

template<class Iterator>Iterator end(STDPAIR<Iterator, Iterator> p,
        typename std::iterator_traits<Iterator>::difference_type __sfinae = 0) {
    return p.second;
}

PathNetwork buildNetwork(const OSMDatabase& db, const OSMEntityFilter<OSMWay>& wayFilter);

// build street names for network
class OSMDatabase;
std::vector<std::string> assignStreets(OSMDatabase* db, PathNetwork& G);

void nameIntersections(PathNetwork& G);

#endif /* PATHNETWORK_HPP_ */


text:
package org.rapidoid.annotation;

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)
@Authors("Nikolche Mihajlovski")
@Since("5.3.0")
public @interface Desc {

    String value();

}


text:
package com.example.sephiroth.coolweather.gson;

import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
 * Created by Sephiroth on 17/2/13.
 */

public class Weather {
    public String status;

    public Basic basic;

    public AQI aqi;

    public Now now;

    public Suggestion suggestion;

    @SerializedName("daily_forecast")
    public List<Forecast>forecastList;

}


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include <Siv3D/Physics2D/P2Body.hpp>
# include <Siv3D/Physics2D/P2MouseJoint.hpp>
# include "P2Common.hpp"

namespace s3d
{
	class detail::P2MouseJointDetail
	{
	public:

		SIV3D_NODISCARD_CXX20
		P2MouseJointDetail(const std::shared_ptr<detail::P2WorldDetail>& world, const P2Body& body, const Vec2& worldTargetPos);

		~P2MouseJointDetail();

		[[nodiscard]]
		b2MouseJoint& getJoint();

		[[nodiscard]]
		const b2MouseJoint& getJoint() const;

		void setLinearStiffness(double frequencyHz, double dampingRatio) noexcept;

	private:

		b2MouseJoint* m_joint = nullptr;

		std::shared_ptr<detail::P2WorldDetail> m_world;

		std::weak_ptr<P2Body::P2BodyDetail> m_body;

		b2Body* m_placeholderBody = nullptr;
	};
}


text:
package org.apache.hadoop.hive.metastore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import junit.framework.TestCase;

import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsData;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.SetPartitionsStatsRequest;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.StringColumnStatsData;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.events.AddPartitionEvent;
import org.apache.hadoop.hive.metastore.events.AlterTableEvent;
import org.apache.hadoop.hive.metastore.events.CreateDatabaseEvent;
import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
import org.apache.hadoop.hive.metastore.events.DropDatabaseEvent;
import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
import org.apache.hadoop.hive.metastore.events.DropTableEvent;
import org.apache.hadoop.hive.metastore.events.ListenerEvent;
import org.apache.hadoop.hive.ql.io.HiveInputFormat;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.shims.ShimLoader;

/**
 * TestHiveMetaStoreStatsMerge.
 * calls in {@link org.apache.hadoop.hive.metastore.HiveMetaStore}
 */
public class TestHiveMetaStoreStatsMerge extends TestCase {

  private HiveConf hiveConf;
  private HiveMetaStoreClient msc;
  private final Database db = new Database();
  private Table table = new Table();

  private static final String dbName = "hive3253";
  private static final String tblName = "tmptbl";

  @Override
  protected void setUp() throws Exception {
    super.setUp();

    System.setProperty("hive.metastore.event.listeners",
        DummyListener.class.getName());

    int port = MetaStoreUtils.findFreePort();
    MetaStoreUtils.startMetaStore(port, ShimLoader.getHadoopThriftAuthBridge());

    hiveConf = new HiveConf(this.getClass());
    hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, "thrift://localhost:" + port);
    hiveConf.setIntVar(HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES, 3);
    hiveConf.set(HiveConf.ConfVars.PREEXECHOOKS.varname, "");
    hiveConf.set(HiveConf.ConfVars.POSTEXECHOOKS.varname, "");
    hiveConf.set(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname, "false");
    SessionState.start(new CliSessionState(hiveConf));
    msc = new HiveMetaStoreClient(hiveConf);

    msc.dropDatabase(dbName, true, true);

    db.setName(dbName);

    Map<String, String> tableParams = new HashMap<String, String>();
    tableParams.put("a", "string");

    List<FieldSchema> cols = new ArrayList<FieldSchema>();
    cols.add(new FieldSchema("a", "string", ""));
    StorageDescriptor sd = new StorageDescriptor();
    sd.setCols(cols);
    sd.setCompressed(false);
    sd.setParameters(tableParams);
    sd.setSerdeInfo(new SerDeInfo());
    sd.getSerdeInfo().setName(tblName);
    sd.getSerdeInfo().setParameters(new HashMap<String, String>());
    sd.getSerdeInfo().getParameters().put(serdeConstants.SERIALIZATION_FORMAT, "1");
    sd.getSerdeInfo().setSerializationLib(LazySimpleSerDe.class.getName());
    sd.setInputFormat(HiveInputFormat.class.getName());
    sd.setOutputFormat(HiveOutputFormat.class.getName());

    table.setDbName(dbName);
    table.setTableName(tblName);
    table.setParameters(tableParams);
    table.setSd(sd);

    DummyListener.notifyList.clear();
  }

  @Override
  protected void tearDown() throws Exception {
    super.tearDown();
  }

  public void testStatsMerge() throws Exception {
    int listSize = 0;

    List<ListenerEvent> notifyList = DummyListener.notifyList;
    assertEquals(notifyList.size(), listSize);
    msc.createDatabase(db);
    listSize++;
    assertEquals(listSize, notifyList.size());
    CreateDatabaseEvent dbEvent = (CreateDatabaseEvent)(notifyList.get(listSize - 1));
    assert dbEvent.getStatus();

    msc.createTable(table);
    listSize++;
    assertEquals(notifyList.size(), listSize);
    CreateTableEvent tblEvent = (CreateTableEvent)(notifyList.get(listSize - 1));
    assert tblEvent.getStatus();

    table = msc.getTable(dbName, tblName);

    ColumnStatistics cs = new ColumnStatistics();
    ColumnStatisticsDesc desc = new ColumnStatisticsDesc(true, dbName, tblName);
    cs.setStatsDesc(desc);
    ColumnStatisticsObj obj = new ColumnStatisticsObj();
    obj.setColName("a");
    obj.setColType("string");
    ColumnStatisticsData data = new ColumnStatisticsData();
    StringColumnStatsData scsd = new StringColumnStatsData();
    scsd.setAvgColLen(10);
    scsd.setMaxColLen(20);
    scsd.setNumNulls(30);
    scsd.setNumDVs(123);
    scsd.setBitVectors("{0, 4, 5, 7}{0, 1}{0, 1, 2}{0, 1, 4}{0}{0, 2}{0, 3}{0, 2, 3, 4}{0, 1, 4}{0, 1}{0}{0, 1, 3, 8}{0, 2}{0, 2}{0, 9}{0, 1, 4}");
    data.setStringStats(scsd);
    obj.setStatsData(data);
    cs.addToStatsObj(obj);

    List<ColumnStatistics> colStats = new ArrayList<>();
    colStats.add(cs);

    SetPartitionsStatsRequest request = new SetPartitionsStatsRequest(colStats);
    msc.setPartitionColumnStatistics(request);

    List<String> colNames = new ArrayList<>();
    colNames.add("a");

    StringColumnStatsData getScsd = msc.getTableColumnStatistics(dbName, tblName, colNames).get(0)
        .getStatsData().getStringStats();
    assertEquals(getScsd.getNumDVs(), 123);

    cs = new ColumnStatistics();
    scsd = new StringColumnStatsData();
    scsd.setAvgColLen(20);
    scsd.setMaxColLen(5);
    scsd.setNumNulls(70);
    scsd.setNumDVs(456);
    scsd.setBitVectors("{0, 1}{0, 1}{1, 2, 4}{0, 1, 2}{0, 1, 2}{0, 2}{0, 1, 3, 4}{0, 1}{0, 1}{3, 4, 6}{2}{0, 1}{0, 3}{0}{0, 1}{0, 1, 4}");
    data.setStringStats(scsd);
    obj.setStatsData(data);
    cs.addToStatsObj(obj);

    request = new SetPartitionsStatsRequest(colStats);
    request.setNeedMerge(true);
    msc.setPartitionColumnStatistics(request);

    getScsd = msc.getTableColumnStatistics(dbName, tblName, colNames).get(0)
        .getStatsData().getStringStats();
    assertEquals(getScsd.getAvgColLen(), 20.0);
    assertEquals(getScsd.getMaxColLen(), 20);
    assertEquals(getScsd.getNumNulls(), 100);
    // since metastore is ObjectStore, we use the max function to merge.
    assertEquals(getScsd.getNumDVs(), 456);

  }

}


text:
package apple.scenekit;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.uikit.*;
import apple.coreanimation.*;
import apple.dispatch.*;
import apple.glkit.*;
import apple.spritekit.*;
import apple.opengles.*;

/*<javadoc>*/
/*</javadoc>*/
@Library("SceneKit/SceneKit.h")
public class SCNError
    extends Todo
     {

    @GlobalConstant("SCNErrorDomain")
    public static native String getClassDomain();

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 48: 1023 (1970)

#### Original name
Potebniamyces balsamicola var. boycei A. Funk, 1970

### Remarks
null


text:
name "authconfig-setup"
version "1.0.0"
license 'Apache v2.0'
maintainer 'Manabu ISHII'


text:
'use strict';

var database = {};
database.uri = 'mongodb://localhost/--DATABASENAME--';
database.options = {
  db: { native_parser: true },
  server: { poolSize: 5, socketOptions: { keepAlive: 1 } }
  // user: '--user--',
  // pass: '--pass--'
};

module.exports = database;


text:
package org.hibernate.validator.test.constraints.composition.lazyevaluation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.Validator;

import org.testng.annotations.Test;

import org.hibernate.validator.testutil.TestForIssue;
import org.hibernate.validator.testutil.ValidatorUtil;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.testng.Assert.assertEquals;

/**
 * @author Hardy Ferentschik
 */
public class LazyEvaluationOfComposingConstraintsTest {

	@Test
	@TestForIssue(jiraKey = "HV-639")
	public void testComposedConstraintWithReportAsSingleViolationStopsEvaluatingOnFirstViolation() {
		Validator validator = ValidatorUtil.getValidator();

		Foo foo = new Foo();
		validator.validate( foo );
		assertEquals(
				InvocationCounter.getInvocationCount( foo ),
				1,
				"There should have been only one single invocation due to @ReportAsSingleViolation"
		);
	}

	@MyComposedConstraint
	public class Foo {
	}

	@Constraint(validatedBy = { MyComposedConstraintValidator.class })
	@Target({ METHOD, FIELD, TYPE })
	@Retention(RUNTIME)
	@ReportAsSingleViolation
	@InvocationCounting.List(value = { @InvocationCounting })
	public @interface MyComposedConstraint {
		String message() default "my composed constraint failed";

		Class<?>[] groups() default { };

		Class<? extends Payload>[] payload() default { };
	}

	public static class MyComposedConstraintValidator extends InvocationCounter
			implements ConstraintValidator<MyComposedConstraint, Object> {
		@Override
		public void initialize(MyComposedConstraint constraintAnnotation) {
		}

		@Override
		public boolean isValid(Object value, ConstraintValidatorContext context) {
			incrementCount( value );
			return false;
		}
	}
}


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

 -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="wallpaper_instructions" msgid="3524143401182707094">"Definir plano de fundo"</string>
    <string name="image_load_fail" msgid="7538534580694411837">"Não foi possível carregar a imagem"</string>
    <string name="wallpaper_load_fail" msgid="4800700444605404650">"Não foi possível carregar a imagem como plano de fundo"</string>
  <plurals name="number_of_items_selected">
    <item quantity="zero" msgid="9015111147509924344">"%1$d selecionados"</item>
    <item quantity="one" msgid="8409622005831789373">"%1$d selecionado"</item>
    <item quantity="other" msgid="479468347731745357">"%1$d selecionados"</item>
  </plurals>
    <string name="wallpaper_accessibility_name" msgid="4093221025304876354">"Plano de fundo %1$d de %2$d"</string>
    <string name="announce_selection" msgid="123723511662250539">"<xliff:g id="LABEL">%1$s</xliff:g> selecionado"</string>
    <string name="wallpaper_delete" msgid="1459353972739215344">"Excluir"</string>
    <string name="pick_image" msgid="6704438906027442697">"Escolher imagem"</string>
    <string name="pick_wallpaper" msgid="4628969645948454559">"Planos de fundo"</string>
    <string name="crop_wallpaper" msgid="4882870800623585836">"Cortar plano de fundo"</string>
</resources>


text:
+++
title = "Development"
weight = 40
+++
These pages explain the internals of the system and contains the guidelines on how to extend it with your own rules.

{{% children  %}}


text:
package com.faforever.client.preferences;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class NewsPrefs {
  private final StringProperty lastReadNewsUrl;

  public NewsPrefs() {
    lastReadNewsUrl = new SimpleStringProperty();
  }

  public String getLastReadNewsUrl() {
    return lastReadNewsUrl.get();
  }

  public void setLastReadNewsUrl(String lastReadNewsUrl) {
    this.lastReadNewsUrl.set(lastReadNewsUrl);
  }

  public StringProperty lastReadNewsUrlProperty() {
    return lastReadNewsUrl;
  }
}


text:
{% extends 'pages/base.html' %}

{% block maintitle %}
  {{ exploration_title }} - Oppia
{% endblock maintitle %}

{% block header_js %}
  {{ super() }}
  {% if exploration_version %}

  {% endif %}

  {{dependencies_html}}

{% endblock header_js %}

{% block navbar_breadcrumb %}

{{exploration_title}}

    <li ng-click="showInformationCard()" tooltip="<['I18N_PLAYER_INFO_TOOLTIP' | translate]>" tooltip-placement="bottom" style="cursor: pointer;" class="oppia-exploration-info-icon protractor-test-exploration-info-icon" tabindex="0">
      
      <['I18N_PLAYER_INFO_TOOLTIP' | translate]>

{% endblock navbar_breadcrumb %}

{% block local_top_nav_options %}

  {% include 'pages/exploration_player/learner_local_nav.html' %}
{% endblock local_top_nav_options %}

{% block content %}

    <background-banner></background-banner>
    <conversation-skin></conversation-skin>
    {% if not iframed %}
      <attribution-guide></attribution-guide>
    {% endif %}

  {% include 'components/attribution_guide/attribution_guide_directive.html' %}
  {% include 'components/embed_modal/embed_exploration_modal_directive.html' %}
  {% include 'components/gadget/gadget_directive.html' %}
  {% include 'components/gadget/gadget_panel_directive.html' %}
  {% include 'components/profile_link/profile_link_image_directive.html' %}

  {% if iframed %}
    {% include 'pages/exploration_player/conversation_skin_embed_directive.html' %}
  {% else %}
    {% include 'pages/exploration_player/conversation_skin_directive.html' %}
  {% endif %}

  {% include 'pages/exploration_player/tutor_card_directive.html' %}
  {% include 'pages/exploration_player/supplemental_card_directive.html' %}
  {% include 'pages/exploration_player/answer_feedback_pair_directive.html' %}
  {% include 'pages/exploration_player/exploration_successfully_flagged_modal.html' %}
  {% include 'pages/exploration_player/feedback_popup_directive.html' %}
  {% include 'pages/exploration_player/flag_exploration_modal.html' %}
  {% include 'pages/exploration_player/information_card_modal.html' %}
  {% include 'pages/exploration_player/progress_dots_directive.html' %}

{% endblock %}

{% block footer %}
  {% if not iframed %}
    {% include 'pages/exploration_player/exploration_footer_directive.html' %}
    {% include 'components/share/sharing_links_directive.html' %}
    <exploration-footer twitter-text="{{DEFAULT_TWITTER_SHARE_MESSAGE_PLAYER}}"></exploration-footer>
  {% endif %}
{% endblock %}

{% block footer_js %}
  {{ super() }}

  {{ interaction_templates }}
  {{ gadget_templates }}
{% endblock footer_js %}


text:
var app = require('http').createServer(handler),
	io = require('socket.io').listen(app),
	fs = require('fs')
	mongo = require('mongoskin'),
	db = mongo.db('mongodb://localhost:27017/crawled'),
	collection = db.collection('channels');

io.set('browser client minification', true);
// io.set('browser client gzip', true);
io.set('log level', 0);

app.listen(8002);

function handler (req, res) {
	fs.readFile(__dirname + '/crawler/index.html', function (err, data) {
		if (err) {
			res.writeHead(500);
			return res.end('Error loading index.html');
		}
		res.writeHead(200);
		res.end(data);
	});
}

io.sockets.on('connection', function (socket) {
	var emitCount = function () {
		collection.count(function (err, count) {
			if (err) return console.dir(err);
			io.sockets.emit('count', count);
		});
	};
	socket.on('count', emitCount);
	socket.on('insert', function (data) {
		collection.insert(data, function (err) {
			if (err && err.code === 11000) return console.log('duplicate');
			if (err) return console.dir(err);
			console.log('Inserted ' + data.username);
			emitCount();
		});
	});
	socket.on('error', function (err) {
		console.dir(err);
	});
});


text:
package com.demandware.studio.isml;

import com.demandware.studio.DWIcons;
import com.intellij.ide.IconProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

public class ISMLIconProvider extends IconProvider {
    @Nullable
    @Override
    public Icon getIcon(@NotNull PsiElement element, int flags) {
        PsiFile containingFile = element.getContainingFile();
        if (containingFile != null) {
            if (containingFile.getName() != null && containingFile.getName().endsWith(".isml")) {
                return DWIcons.DW_ISML_ICON;
            }
        }
        return null;
    }
}


text:
<?php

namespace Pterodactyl\Models;

use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property int $id
 * @property int $server_id
 * @property string $uuid
 * @property bool $is_successful
 * @property bool $is_locked
 * @property string $name
 * @property string[] $ignored_files
 * @property string $disk
 * @property string|null $checksum
 * @property int $bytes
 * @property string|null $upload_id
 * @property \Carbon\CarbonImmutable|null $completed_at
 * @property \Carbon\CarbonImmutable $created_at
 * @property \Carbon\CarbonImmutable $updated_at
 * @property \Carbon\CarbonImmutable|null $deleted_at
 * @property \Pterodactyl\Models\Server $server
 * @property \Pterodactyl\Models\AuditLog[] $audits
 */
class Backup extends Model
{
    use SoftDeletes;

    public const RESOURCE_NAME = 'backup';

    public const ADAPTER_WINGS = 'wings';
    public const ADAPTER_AWS_S3 = 's3';

    /**
     * @var string
     */
    protected $table = 'backups';

    /**
     * @var bool
     */
    protected $immutableDates = true;

    /**
     * @var array
     */
    protected $casts = [
        'id' => 'int',
        'is_successful' => 'bool',
        'is_locked' => 'bool',
        'ignored_files' => 'array',
        'bytes' => 'int',
    ];

    /**
     * @var array
     */
    protected $dates = [
        'completed_at',
    ];

    /**
     * @var array
     */
    protected $attributes = [
        'is_successful' => false,
        'is_locked' => false,
        'checksum' => null,
        'bytes' => 0,
        'upload_id' => null,
    ];

    /**
     * @var string[]
     */
    protected $guarded = ['id', 'created_at', 'updated_at', 'deleted_at'];

    /**
     * @var array
     */
    public static $validationRules = [
        'server_id' => 'bail|required|numeric|exists:servers,id',
        'uuid' => 'required|uuid',
        'is_successful' => 'boolean',
        'is_locked' => 'boolean',
        'name' => 'required|string',
        'ignored_files' => 'array',
        'disk' => 'required|string',
        'checksum' => 'nullable|string',
        'bytes' => 'numeric',
        'upload_id' => 'nullable|string',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function server()
    {
        return $this->belongsTo(Server::class);
    }
}


text:
/* Set endianness for tile.  */

#ifndef _ENDIAN_H
# error "Never use <bits/endian.h> directly; include <endian.h> instead."
#endif

#if defined __BIG_ENDIAN__
# define __BYTE_ORDER __BIG_ENDIAN
#elif defined __LITTLE_ENDIAN__
# define __BYTE_ORDER __LITTLE_ENDIAN
#else
# error "Endianness not declared!!"
#endif


text:
  {% if params.hair != 1  %}
    Previous Hair
  {% endif %}

  {% if params.hair != 4  %}
    Next Hair
  {% endif %}

  {% if params.eyes != 1 %}
    Previous Eyes
  {% endif %}

  {% if params.eyes != 9  %}
    Next Eyes
  {% endif %}

  {% if params.mouth != 1 %}
    Previous Mouth
  {% endif %}

  {% if params.mouth != 9  %}
    Next Mouth
  {% endif %}


text:
require 'rubygems/test_case'

class TestGemSourceFetchProblem < Gem::TestCase

  def test_exception
    source = Gem::Source.new @gem_repo
    error  = RuntimeError.new 'test'

    sf = Gem::SourceFetchProblem.new source, error

    e = assert_raises RuntimeError do
      raise sf
    end

    assert_equal 'test', e.message
  end

  def test_password_redacted
    source = Gem::Source.new 'https://username:secret@gemsource.com'
    error  = RuntimeError.new 'test'

    sf = Gem::SourceFetchProblem.new source, error

    refute_match sf.wordy, 'secret'
  end

end


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\CarritoSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Carritos';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Carrito', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'idCarrito',
            'total',
            'estado',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
<?php

namespace Kunstmaan\NodeBundle\Router;

use Kunstmaan\NodeBundle\Repository\NodeTranslationRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;

/**
 * The SlugRouter takes care of routing the paths for slugs. It should have the lowest priority as it's a
 * catch-all router that routes (almost) all requests to the SlugController
 */
class SlugRouter implements RouterInterface
{

    /** @var RequestContext */
    private $context;

    /** @var RouteCollection */
    private $routeCollection;

    /** @var UrlGenerator */
    private $urlGenerator;

    /** @var ContainerInterface */
    private $container;

    /**
     * The constructor for this service
     *
     * @param ContainerInterface $container
     */
    public function __construct($container)
    {
        $this->container       = $container;
        $this->routeCollection = new RouteCollection();

        $multilanguage = $this->container->getParameter('multilanguage');
        $defaultlocale = $this->container->getParameter('defaultlocale');

        if ($multilanguage) {
            // the website is multilingual so the language is the first parameter
            $requiredLocales = $this->container->getParameter('requiredlocales');

            $this->routeCollection->add(
                '_slug_preview',
                new Route(
                    '/{_locale}/admin/preview/{url}',
                    array(
                        '_controller' => 'KunstmaanNodeBundle:Slug:slug',
                        'preview'     => true,
                        'url'         => ''
                    ),
                    array(
                        '_locale' => $requiredLocales,
                        'url'     => "[a-zA-Z0-9\-_\/]*"
                    ) // override default validation of url to accept /, - and _
                )
            );
            $this->routeCollection->add(
                '_slug',
                new Route(
                    '/{_locale}/{url}',
                    array(
                        '_controller' => 'KunstmaanNodeBundle:Slug:slug',
                        'preview'     => false,
                        'url'         => ''
                    ),
                    array('_locale' => $requiredLocales, 'url' => "[a-zA-Z0-9\-_\/]*")
                )
            );
        } else {
            // the website is not multilingual, _locale must do a fallback to the default locale
            $this->routeCollection->add(
                '_slug_preview',
                new Route(
                    '/admin/preview/{url}',
                    array(
                        '_controller' => 'KunstmaanNodeBundle:Slug:slug',
                        'preview'     => true,
                        'url'         => '',
                        '_locale'     => $defaultlocale
                    ),
                    array('url' => "[a-zA-Z0-9\-_\/]*")
                )
            );
            $this->routeCollection->add(
                '_slug',
                new Route(
                    '/{url}',
                    array(
                        '_controller' => 'KunstmaanNodeBundle:Slug:slug',
                        'preview'     => false,
                        'url'         => '',
                        '_locale'     => $defaultlocale
                    ),
                    array('url' => "[a-zA-Z0-9\-_\/]*")
                )
            );
        }
    }

    /**
     * Match given urls via the context to the routes we defined.
     * This functionality re-uses the default Symfony way of routing and its components
     *
     * @param string $pathinfo
     * @throws ResourceNotFoundException
     *
     * @return array
     */
    public function match($pathinfo)
    {
        $urlMatcher = new UrlMatcher($this->routeCollection, $this->getContext());
        $result = $urlMatcher->match($pathinfo);

        if (!empty($result)) {
            // The route matches, now check if it actually exists (needed for proper chain router chaining!)
            $em = $this->container->get('doctrine.orm.entity_manager');

            /* @var NodeTranslationRepository $nodeTranslationRepo */
            $nodeTranslationRepo = $em->getRepository('KunstmaanNodeBundle:NodeTranslation');
            /* @var NodeTranslation $nodeTranslation */
            $nodeTranslation = $nodeTranslationRepo->getNodeTranslationForUrl($result['url'], $result['_locale']);

            if (is_null($nodeTranslation)) {
                throw new ResourceNotFoundException('No page found for slug ' . $pathinfo);
            }
            $result['_nodeTranslation'] = $nodeTranslation;
        }

        return $result;
    }

    /**
     * Gets the request context.
     *
     * @return RequestContext The context
     *
     * @api
     */
    public function getContext()
    {
        if (!isset($this->context)) {
            /* @var Request $request */
            $request = $this->container->get('request');

            $this->context = new RequestContext();
            $this->context->fromRequest($request);
        }

        return $this->context;
    }

    /**
     * Sets the request context.
     *
     * @param RequestContext $context The context
     *
     * @api
     */
    public function setContext(RequestContext $context)
    {
        $this->context = $context;
    }

    /**
     * Generate an url for a supplied route
     *
     * @param string $name       The path
     * @param array  $parameters The route parameters
     * @param bool   $absolute   Absolute url or not
     *
     * @return null|string
     */
    public function generate($name, $parameters = array(), $absolute = false)
    {
        $this->urlGenerator = new UrlGenerator($this->routeCollection, $this->context);

        return $this->urlGenerator->generate($name, $parameters, $absolute);
    }

    /**
     * Getter for routeCollection
     *
     * @return \Symfony\Component\Routing\RouteCollection
     */
    public function getRouteCollection()
    {
        return $this->routeCollection;
    }
}


text:
/**
 * A simple, fast array of bits, represented compactly by an array of ints internally.
 */

@interface ZXBitArray : NSObject

@property (nonatomic, readonly) int size;
@property (nonatomic, readonly) int *bits;

- (id)initWithSize:(int)size;
- (int)sizeInBytes;
- (BOOL)get:(int)i;
- (void)set:(int)i;
- (void)flip:(int)i;
- (int)nextSet:(int)from;
- (int)nextUnset:(int)from;
- (void)setBulk:(int)i newBits:(int)newBits;
- (void)setRange:(int)start end:(int)end;
- (void)clear;
- (BOOL)isRange:(int)start end:(int)end value:(BOOL)value;
- (void)appendBit:(BOOL)bit;
- (void)appendBits:(int)value numBits:(int)numBits;
- (void)appendBitArray:(ZXBitArray *)other;
- (void)xor:(ZXBitArray *)other;
- (void)toBytes:(int)bitOffset array:(unsigned char *)array offset:(int)offset numBytes:(int)numBytes;
- (void)reverse;

@end


text:
package org.dawnsci.prototype.nano.model.table;

import java.util.EventObject;

import org.eclipse.january.dataset.SliceND;

public class SliceChangeEvent extends EventObject {

	private static final long serialVersionUID = 1L;
	private NDimensions nDimension;
	private boolean optionsChanged;

	public SliceChangeEvent(NDimensions nDimensions, boolean optionsChanged) {
		super(nDimensions);
		this.nDimension = nDimensions;
		this.optionsChanged = optionsChanged;
	}

	public boolean isOptionsChanged() {
		return optionsChanged;
	}

	public String[] getAxesNames() {
		return nDimension.buildAxesNames();
	}

	public Object[] getOptions() {
		return nDimension.getOptions();
	}

	public SliceND getSlice() {
		return  nDimension.buildSliceND();
	}

	public NDimensions getSource() {
		return nDimension;
	}

}


text:
var MarchingAnts = require('../geom/rectangle/MarchingAnts');
var RotateLeft = require('../utils/array/RotateLeft');
var RotateRight = require('../utils/array/RotateRight');

//  Place the items in the array around the perimeter of the given rectangle.

//  Placement starts from the top-left of the rectangle, and proceeds in a
//  clockwise direction. If the shift parameter is given you can offset where
//  placement begins.

/**
 * [description]
 *
 * @function Phaser.Actions.PlaceOnRectangle
 * @since 3.0.0
 *
 * @generic {Phaser.GameObjects.GameObject[]} G - [items,$return]
 *
 * @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action.
 * @param {Phaser.Geom.Rectangle} rect - [description]
 * @param {integer} [shift=1] - [description]
 *
 * @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action.
 */
var PlaceOnRectangle = function (items, rect, shift)
{
    if (shift === undefined) { shift = 0; }

    var points = MarchingAnts(rect, false, items.length);

    if (shift > 0)
    {
        RotateLeft(points, shift);
    }
    else if (shift < 0)
    {
        RotateRight(points, Math.abs(shift));
    }

    for (var i = 0; i < items.length; i++)
    {
        items[i].x = points[i].x;
        items[i].y = points[i].y;
    }

    return items;
};

module.exports = PlaceOnRectangle;


text:
namespace download {

DownloadCreateInfo::DownloadCreateInfo(
    const base::Time& start_time,
    std::unique_ptr<DownloadSaveInfo> save_info)
    : is_new_download(true),
      referrer_policy(
          net::ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
      start_time(start_time),
      total_bytes(0),
      offset(0),
      has_user_gesture(false),
      transient(false),
      require_safety_checks(true),
      result(DOWNLOAD_INTERRUPT_REASON_NONE),
      save_info(std::move(save_info)),
      render_process_id(-1),
      render_frame_id(-1),
      accept_range(RangeRequestSupportType::kNoSupport),
      connection_info(net::HttpResponseInfo::CONNECTION_INFO_UNKNOWN),
      method("GET"),
      ukm_source_id(ukm::kInvalidSourceId),
      is_content_initiated(false),
      credentials_mode(::network::mojom::CredentialsMode::kInclude),
      isolation_info(absl::nullopt) {}

DownloadCreateInfo::DownloadCreateInfo()
    : DownloadCreateInfo(base::Time(), std::make_unique<DownloadSaveInfo>()) {}

DownloadCreateInfo::~DownloadCreateInfo() {}

const GURL& DownloadCreateInfo::url() const {
  return url_chain.empty() ? GURL::EmptyGURL() : url_chain.back();
}

}  // namespace download


text:
package io.requery.query;

/**
 * Represents a Unary or Binary operation/condition. If a unary operation the right operand is
 * undefined. Separation between unary/binary may be made more explicit in the future.
 *
 * @param <L> left operand type
 * @param <R> right operand type
 */
public interface Condition<L, R> {

    L getLeftOperand();

    Operator getOperator();

    R getRightOperand();
}


text:
#ifndef PG_OPERATOR_H
#define PG_OPERATOR_H

#include "catalog/genbki.h"
#include "catalog/pg_operator_d.h"

#include "catalog/objectaddress.h"
#include "nodes/pg_list.h"

/* ----------------
 *		pg_operator definition.  cpp turns this into
 *		typedef struct FormData_pg_operator
 * ----------------
 */
CATALOG(pg_operator,2617,OperatorRelationId)
{
	Oid			oid;			/* oid */

	/* name of operator */
	NameData	oprname;

	/* OID of namespace containing this oper */
	Oid			oprnamespace BKI_DEFAULT(PGNSP);

	/* operator owner */
	Oid			oprowner BKI_DEFAULT(PGUID);

	/* 'l', 'r', or 'b' */
	char		oprkind BKI_DEFAULT(b);

	/* can be used in merge join? */
	bool		oprcanmerge BKI_DEFAULT(f);

	/* can be used in hash join? */
	bool		oprcanhash BKI_DEFAULT(f);

	/* left arg type, or 0 if 'l' oprkind */
	Oid			oprleft BKI_LOOKUP(pg_type);

	/* right arg type, or 0 if 'r' oprkind */
	Oid			oprright BKI_LOOKUP(pg_type);

	/* result datatype */
	Oid			oprresult BKI_LOOKUP(pg_type);

	/* OID of commutator oper, or 0 if none */
	Oid			oprcom BKI_DEFAULT(0) BKI_LOOKUP(pg_operator);

	/* OID of negator oper, or 0 if none */
	Oid			oprnegate BKI_DEFAULT(0) BKI_LOOKUP(pg_operator);

	/* OID of underlying function */
	regproc		oprcode BKI_LOOKUP(pg_proc);

	/* OID of restriction estimator, or 0 */
	regproc		oprrest BKI_DEFAULT(-) BKI_LOOKUP(pg_proc);

	/* OID of join estimator, or 0 */
	regproc		oprjoin BKI_DEFAULT(-) BKI_LOOKUP(pg_proc);
} FormData_pg_operator;

/* ----------------
 *		Form_pg_operator corresponds to a pointer to a tuple with
 *		the format of pg_operator relation.
 * ----------------
 */
typedef FormData_pg_operator *Form_pg_operator;

extern ObjectAddress OperatorCreate(const char *operatorName,
									Oid operatorNamespace,
									Oid leftTypeId,
									Oid rightTypeId,
									Oid procedureId,
									List *commutatorName,
									List *negatorName,
									Oid restrictionId,
									Oid joinId,
									bool canMerge,
									bool canHash);

extern ObjectAddress makeOperatorDependencies(HeapTuple tuple, bool isUpdate);

extern void OperatorUpd(Oid baseId, Oid commId, Oid negId, bool isDelete);

#endif							/* PG_OPERATOR_H */


text:
namespace ExampleApp
{
    namespace Automation
    {
        class OpenSearchMenuSectionMessage
        {
                const std::function<bool(const Menu::View::IMenuSectionViewModel&)> m_shouldOpenMenuSection;
        public:
            OpenSearchMenuSectionMessage(const std::function<bool(const Menu::View::IMenuSectionViewModel&)> shouldOpenMenuSection)
                : m_shouldOpenMenuSection(shouldOpenMenuSection)
            {}

            const bool ShouldOpenMenuSectionMessage(const Menu::View::IMenuSectionViewModel& menuSection) const
            {
                return m_shouldOpenMenuSection(menuSection);
            }
        };
    }
}


text:
using System;
using SpiceSharp.Attributes;
using SpiceSharp.Behaviors;
using SpiceSharp.Circuits;
using SpiceSharp.Components.MutualInductanceBehaviors;
using SpiceSharp.Simulations;

namespace SpiceSharp.Components
{
    /// <summary>
    /// A mutual inductance
    /// </summary>
    public class MutualInductance : Component
    {
        static MutualInductance()
        {
            RegisterBehaviorFactory(typeof(MutualInductance), new BehaviorFactoryDictionary
            {
                {typeof(TransientBehavior), e => new TransientBehavior(e.Name)},
                {typeof(FrequencyBehavior), e => new FrequencyBehavior(e.Name)}
            });
        }

        /// <summary>
        /// Gets or sets the name of the primary inductor.
        /// </summary>
        [ParameterName("inductor1"), ParameterName("primary"), ParameterInfo("First coupled inductor")]
        public string InductorName1 { get; set; }

        /// <summary>
        /// Gets or sets the name of the secondary inductor.
        /// </summary>
        [ParameterName("inductor2"), ParameterName("secondary"), ParameterInfo("Second coupled inductor")]
        public string InductorName2 { get; set; }

        /// <summary>
        /// Create a new instance of the <see cref="MutualInductance"/> class.
        /// </summary>
        /// <param name="name">The name of the mutual inductance</param>
        public MutualInductance(string name) : base(name, 0)
        {
            ParameterSets.Add(new BaseParameters());
        }

        /// <summary>
        /// Create a new instance of the <see cref="MutualInductance"/> class.
        /// </summary>
        /// <param name="name">Name</param>
        /// <param name="inductorName1">Inductor 1</param>
        /// <param name="inductorName2">Inductor 2</param>
        /// <param name="coupling">Mutual inductance</param>
        public MutualInductance(string name, string inductorName1, string inductorName2, double coupling)
            : base(name, 0)
        {
            ParameterSets.Add(new BaseParameters(coupling));
            InductorName1 = inductorName1;
            InductorName2 = inductorName2;
        }

        /// <summary>
        /// Create the behaviors.
        /// </summary>
        /// <param name="types">The behavior types.</param>
        /// <param name="simulation">The simulation.</param>
        /// <param name="entities">The entities.</param>
        public override void CreateBehaviors(Type[] types, Simulation simulation, EntityCollection entities)
        {
            entities[InductorName1.ThrowIfNull("primary inductor")].CreateBehaviors(types, simulation, entities);
            entities[InductorName2.ThrowIfNull("secondary inductor")].CreateBehaviors(types, simulation, entities);
            base.CreateBehaviors(types, simulation, entities);
        }

        /// <summary>
        /// Build the binding context.
        /// </summary>
        /// <param name="simulation">The simulation.</param>
        /// <returns></returns>
        protected override ComponentBindingContext BuildBindingContext(Simulation simulation)
        {
            var context = base.BuildBindingContext(simulation);

            // Register inductor 1
            context.Add("inductor1", simulation.EntityParameters[InductorName1]);
            context.Add("inductor1", simulation.EntityBehaviors[InductorName1]);

            // Register inductor 2
            context.Add("inductor2", simulation.EntityParameters[InductorName2]);
            context.Add("inductor2", simulation.EntityBehaviors[InductorName2]);

            return context;
        }

        /// <summary>
        /// Clone the mutual inductance
        /// </summary>
        /// <param name="data">Instance data.</param>
        /// <returns></returns>
        public override Entity Clone(InstanceData data)
        {
            var clone = (MutualInductance) base.Clone(data);
            if (data is ComponentInstanceData cid)
            {
                if (clone.InductorName1 != null)
                    clone.InductorName1 = cid.GenerateIdentifier(clone.InductorName1);
                if (clone.InductorName2 != null)
                    clone.InductorName2 = cid.GenerateIdentifier(clone.InductorName2);
            }
            return clone;
        }
    }
}


text:
package org.apache.ambari.server.view;

import org.apache.ambari.server.api.resources.BaseResourceDefinition;
import org.apache.ambari.server.api.resources.SubResourceDefinition;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.orm.entities.ViewEntity;
import org.apache.ambari.server.view.configuration.ResourceConfig;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * View sub-resource definition based on a view resource configuration.
 */
public class ViewSubResourceDefinition extends BaseResourceDefinition {
  /**
   * The associated view definition.
   */
  private final ViewEntity viewDefinition;

  /**
   * The configuration.
   */
  private final ResourceConfig resourceConfiguration;

  /**
   * The sub resource definitions.
   */
  Set<SubResourceDefinition> definitions;

  // ----- Constructors ------------------------------------------------------

  /**
   * Construct a sub-resource definition.
   *
   * @param viewDefinition         the view definition
   * @param resourceConfiguration  the resource configuration
   */
  public ViewSubResourceDefinition(ViewEntity viewDefinition, ResourceConfig resourceConfiguration) {
    super(new Resource.Type(viewDefinition.getQualifiedResourceTypeName(resourceConfiguration.getName())));

    this.viewDefinition        = viewDefinition;
    this.resourceConfiguration = resourceConfiguration;
  }

  // ----- ResourceDefinition ------------------------------------------------

  @Override
  public String getPluralName() {
    return resourceConfiguration.getPluralName();
  }

  @Override
  public String getSingularName() {
    return resourceConfiguration.getName();
  }

  @Override
  public synchronized Set<SubResourceDefinition> getSubResourceDefinitions() {
    if (definitions == null) {
      definitions = new HashSet<SubResourceDefinition>();
      List<String> subResourceNames = resourceConfiguration.getSubResourceNames();
      if (subResourceNames != null) {
        for (String subType : subResourceNames) {
          Resource.Type type = Resource.Type.valueOf(
              viewDefinition.getQualifiedResourceTypeName(subType));
          definitions.add(new SubResourceDefinition(type));
        }
      }
    }
    return definitions;
  }

  // ----- helper methods ----------------------------------------------------

  /**
   * Get the associated resource configuration.
   *
   * @return the resource configuration
   */
  public ResourceConfig getResourceConfiguration() {
    return resourceConfiguration;
  }
}


text:
[![Version](https://img.shields.io/cocoapods/v/ContentfulDeliveryAPI.svg?style=flat)](http://cocoadocs.org/docsets/ContentfulDeliveryAPI)
[![License](https://img.shields.io/cocoapods/l/ContentfulDeliveryAPI.svg?style=flat)](http://cocoadocs.org/docsets/ContentfulDeliveryAPI)
[![Platform](https://img.shields.io/cocoapods/p/ContentfulDeliveryAPI.svg?style=flat)](http://cocoadocs.org/docsets/ContentfulDeliveryAPI)
[![Build Status](https://img.shields.io/travis/contentful/contentful.objc/master.svg?style=flat)](https://travis-ci.org/contentful/contentful.objc)
[![Coverage Status](https://img.shields.io/coveralls/contentful/contentful.objc.svg)](https://coveralls.io/github/contentful/contentful.objc)

Objective-C SDK for [Contentful's][1] Content Delivery API.

[Contentful][1] is a content management platform for web applications, mobile apps and connected devices. It allows you to create, edit & manage content in the cloud and publish it anywhere via powerful API. Contentful offers tools for managing editorial teams and enabling cooperation between organizations.

## Usage

The `CDAClient` manages all your interaction with the Contentful Delivery API.

```objective-c
CDAClient* client = [[CDAClient alloc] initWithSpaceKey:@"cfexampleapi" accessToken:@"b4c0n73n7fu1"];
[client fetchEntryWithIdentifier:@"nyancat"
                         success:^(CDAResponse *response, CDAEntry *entry) {
                             NSLog(@"%@", entry.fields);
                         }
                         failure:^(CDAResponse *response, NSError *error) {
                             NSLog(@"%@", error);
                         }];
```

You can query for entries, assets, etc. with query options similar to what is described in the [Delivery API Documentation][6]:

```objective-c
[client fetchEntriesMatching:@{ @"content_type": @"cat" }
                     success:^(CDAResponse *response, CDAArray *entries) {
                         NSLog(@"%@", [[entries.items firstObject] fields]);
                     }
                     failure:^(CDAResponse *response, NSError *error) {
                         NSLog(@"%@", error);
                     }];
```

Results are returned as object of classes `CDAEntry`, `CDAAsset`, `CDAContentType` or `CDASpace`, depending on the fetch method being called. If there are multiple results, they will be returned as a `CDAArray` instance, which encapsulates the actual resources in the *items* property.

This repository contains multiple examples, demonstrating the use in common real world
scenarios and also showing the different ways you can integrate the SDK into your own project.

### Using Custom Entry Classes

You might want to subclass `CDAEntry` to store additional data alongside Entries or to decouple the rest of your app from the Contentful SDK's API. For this purpose, it is possible to register your own custom classes for specific Content Types, like this:

```objective-c
[client registerClass:[MYSuperCoolClass class] forContentTypeWithIdentifier:@"MyContentType"];
```

Each time, the receiver needs to create a new Entry object of the given Content Type, it will create instances of `MYSuperCoolClass`. Make sure that the class inherits from `CDAEntry` or this mechanism will break at runtime.

### Offline Support

Mobile devices will not always have a data connection, so it makes sense to cache data received from Contentful for offline use. The SDK brings two mechanisms which can help with that:

All Resource classes support `NSCoding` and bring convenience methods for storing and loading from flat files:

```objective-c
[someEntry writeToFile:@"/some/path"];
CDAEntry* readEntry = [CDAEntry readFromFile:@"/some/path" client:client];
```

Most of the UIKit extensions have an `offlineCaching` property which transparently uses this mechanism for showing content when offline.

If you rather use another solution, there is the abstract `CDAPersistenceManager` class with a [sample implementation](https://github.com/contentful/contentful-persistence.objc/blob/master/Code/CoreDataManager.m) for Core Data. It supports mapping Resources to another method for managing your object graph easily and ties this to the Contentful synchronization API. Check out the Core Data example app for integrating it yourself.

In both cases, you can use the `offlineCaching_cda` property of the SDK's `UIImageView` category to make any image view transparently cache its contents in a flat file on disk. This will only cache images that the user has viewed once while the app was online.

### Preview Mode

The Content Delivery API only returns published Entries. However, you might want to preview content in your app before making it public for your users. For this, you can use the preview mode, which will return **all** Entries, regardless of their published status:

```objective-c
CDAConfiguration* configuration = [CDAConfiguration defaultConfiguration];
configuration.previewMode = YES;

CDAClient* client = [[CDAClient alloc] initWithSpaceKey:@"YourSpaceKey"
                                            accessToken:@"YourAccessToken"
                                          configuration:configuration];
```

Apart from the configuration option, you can use the SDK without modifications with one exception: you need to obtain a preview access token, which you can get in the "API" tab of the Contentful app. In preview mode, data can be invalid, because no validation is performed on unpublished entries. Your app needs to deal with that. Be aware that the access token should in no case be shipped with a production app.

### UIKit Extensions

The SDK contains some extensions of UIKit classes for common use cases. You can see a lot of them in action in the examples or read [this blog post][11] with details on some of them.

## Documentation

For further information, check out the [Developer Documentation][6] or browse the [API documentation][7]. The latter can also be loaded into Xcode as a Docset.

## Installation

### CocoaPods

[CocoaPods][2] is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like the Contentful Delivery API in your projects.

```ruby
platform :ios, '7.0'
pod 'ContentfulDeliveryAPI'
```

This is the easiest way to keep your copy of the Contentful Delivery API updated.

For Swift support using iOS 8, you can enable framework support usage in [CocoaPods][2]:

```ruby
platform :ios, '8.0'
use_frameworks!
pod 'ContentfulDeliveryAPI'
```

### Manual integration

In the case you prefer to manage your dependencies manually, you can just drag all files from the `Code` subdirectory into your project or integrate the `ContentfulDeliveryAPI` static library target into your build process. It might be a good idea to add this repository as a [Git submodule][5] if you choose this path.

Be aware that the Contentful Delivery API requires both [AFNetworking][3] and [ISO8601DateFormatter][4] to compile successfully, so you need to provide these dependencies if you do manual integration.

### Static Framework

You can [download][8] the Contentful Delivery API as an universal static framework for iOS. Integrate it into your project by unzipping and dragging the `ContentfulDeliveryAPI.framework` into the `Frameworks` group of your project. You can also [download][9] the UFO example application including the static framework, as an example of integrating it into an Xcode project.

The static framework contains [AFNetworking][3] and [ISO8601DateFormatter][4], but they are prefixed so that they do not clash with any copies that might already be part of your application.

It depends on the `SystemConfiguration.framework` not included by default in iOS projects, so open your project file on the `General` tab.

![](Screenshots/GeneralTab.png)

Click the `+` button in the `Linked Frameworks and Libraries` section at the bottom.

![](Screenshots/Frameworks.png)

Search for *SystemConfiguration* and add the framework to your project.

![](Screenshots/SearchForFramework.png)

Repeat that with *MobileCoreServices*, as that framework is also required to be in your project.

## Unit Tests

The Contentful Delivery API is fully unit tested.

To run the tests, do the following steps:

    $ gem install xcpretty cocoapods cocoapods-testing
    $ make test

or run them directly from Xcode.

## License

Copyright (c) 2014, 2015 Contentful GmbH. See LICENSE for further details.

[1]: https://www.contentful.com
[2]: https://cocoapods.org/
[3]: https://github.com/AFNetworking/AFNetworking
[4]: http://boredzo.org/iso8601dateformatter/
[5]: http://git-scm.com/docs/git-submodule
[6]: http://docs.contentfulcda.apiary.io/
[7]: http://cocoadocs.org/docsets/ContentfulDeliveryAPI/1.9.2/
[8]: http://static.contentful.com/downloads/iOS/ContentfulDeliveryAPI-1.9.2.zip
[9]: http://static.contentful.com/downloads/iOS/UFO.zip
[11]: https://www.contentful.com/blog/2014/04/04/contentful-ios-sdk/


text:
<?php

namespace Test\Phinx\Console\Command;

use Phinx\Config\Config;
use Phinx\Config\ConfigInterface;
use Phinx\Console\Command\SeedRun;
use Phinx\Console\PhinxApplication;
use Phinx\Migration\Manager;
use PHPUnit_Framework_MockObject_MockObject;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Tester\CommandTester;

class SeedRunTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ConfigInterface|array
     */
    protected $config = [];

    /**
     * @var InputInterface $input
     */
    protected $input;

    /**
     * @var OutputInterface $output
     */
    protected $output;

    protected function setUp()
    {
        $this->config = new Config([
            'paths' => [
                'migrations' => __FILE__,
                'seeds' => __FILE__,
            ],
            'environments' => [
                'default_migration_table' => 'phinxlog',
                'default_database' => 'development',
                'development' => [
                    'adapter' => 'mysql',
                    'host' => 'fakehost',
                    'name' => 'development',
                    'user' => '',
                    'pass' => '',
                    'port' => 3006,
                ]
            ]
        ]);

        $this->input = new ArrayInput([]);
        $this->output = new StreamOutput(fopen('php://memory', 'a', false));
    }

    public function testExecute()
    {
        $application = new PhinxApplication('testing');
        $application->add(new SeedRun());

        /** @var SeedRun $command */
        $command = $application->find('seed:run');

        // mock the manager class
        /** @var Manager|PHPUnit_Framework_MockObject_MockObject $managerStub */
        $managerStub = $this->getMockBuilder('\Phinx\Migration\Manager')
            ->setConstructorArgs([$this->config, $this->input, $this->output])
            ->getMock();
        $managerStub->expects($this->once())
                    ->method('seed')->with($this->identicalTo('development'), $this->identicalTo(null));

        $command->setConfig($this->config);
        $command->setManager($managerStub);

        $commandTester = new CommandTester($command);
        $commandTester->execute(['command' => $command->getName()], ['decorated' => false]);

        $this->assertRegExp('/no environment specified/', $commandTester->getDisplay());
    }

    public function testExecuteWithEnvironmentOption()
    {
        $application = new PhinxApplication('testing');
        $application->add(new SeedRun());

        /** @var SeedRun $command */
        $command = $application->find('seed:run');

        // mock the manager class
        /** @var Manager|PHPUnit_Framework_MockObject_MockObject $managerStub */
        $managerStub = $this->getMockBuilder('\Phinx\Migration\Manager')
            ->setConstructorArgs([$this->config, $this->input, $this->output])
            ->getMock();
        $managerStub->expects($this->any())
                    ->method('migrate');

        $command->setConfig($this->config);
        $command->setManager($managerStub);

        $commandTester = new CommandTester($command);
        $commandTester->execute(['command' => $command->getName(), '--environment' => 'fakeenv'], ['decorated' => false]);
        $this->assertRegExp('/using environment fakeenv/', $commandTester->getDisplay());
    }

    public function testDatabaseNameSpecified()
    {
        $application = new PhinxApplication('testing');
        $application->add(new SeedRun());

        /** @var SeedRun $command */
        $command = $application->find('seed:run');

        // mock the manager class
        /** @var Manager|PHPUnit_Framework_MockObject_MockObject $managerStub */
        $managerStub = $this->getMockBuilder('\Phinx\Migration\Manager')
            ->setConstructorArgs([$this->config, $this->input, $this->output])
            ->getMock();
        $managerStub->expects($this->once())
                    ->method('seed');

        $command->setConfig($this->config);
        $command->setManager($managerStub);

        $commandTester = new CommandTester($command);
        $commandTester->execute(['command' => $command->getName()], ['decorated' => false]);
        $this->assertRegExp('/using database development/', $commandTester->getDisplay());
    }

    public function testExecuteMultipleSeeders()
    {
        $application = new PhinxApplication('testing');
        $application->add(new SeedRun());

        /** @var SeedRun $command */
        $command = $application->find('seed:run');

        // mock the manager class
        /** @var Manager|PHPUnit_Framework_MockObject_MockObject $managerStub */
        $managerStub = $this->getMockBuilder('\Phinx\Migration\Manager')
            ->setConstructorArgs([$this->config, $this->input, $this->output])
            ->getMock();
        $managerStub->expects($this->exactly(3))
                    ->method('seed')->withConsecutive(
                        [$this->identicalTo('development'), $this->identicalTo('One')],
                        [$this->identicalTo('development'), $this->identicalTo('Two')],
                        [$this->identicalTo('development'), $this->identicalTo('Three')]
                    );

        $command->setConfig($this->config);
        $command->setManager($managerStub);

        $commandTester = new CommandTester($command);
        $commandTester->execute(
            [
                'command' => $command->getName(),
                '--seed' => ['One', 'Two', 'Three'],
            ],
            ['decorated' => false]
        );

        $this->assertRegExp('/no environment specified/', $commandTester->getDisplay());
    }
}


text:
FactoryGirl.define do
  factory :politician_like do
    liker_id 1
    liked_id 1
    value false
  end
end


text:
void ejoy2d_game(lua_State *L);
void ejoy2d_game_exit();
lua_State *  ejoy2d_game_lua();
void ejoy2d_handle_error(lua_State *L, const char *err_type, const char *msg);
void ejoy2d_game_start();
void ejoy2d_game_drawframe();
int ejoy2d_game_touch(int id, float x, float y, int status);
void ejoy2d_game_gesture(int type,
                         double x1, double y1, double x2, double y2, int s);
void
ejoy2d_game_message(int id_, const char* state, const char* data, lua_Number n);
void ejoy2d_game_pause();
void ejoy2d_game_resume();
void ejoy2d_game_wininit();

#endif


text:
@interface WSRunOnce : NSObject

+ (void)runOnceByVersionWithKey:(NSString *)key action:(BOOL (^)(NSString *version))action;
+ (void)runOnceAsyncByVersionWithKey:(NSString *)key action:(BOOL (^)(NSString *version))action;

+ (void)runOnceByBuildWithKey:(NSString *)key action:(BOOL (^)(NSString *build))action;
+ (void)runOnceAsyncByBuildWithKey:(NSString *)key action:(BOOL (^)(NSString *build))action;

+ (void)runOnceWithKey:(NSString *)key action:(void (^)(void))action;
+ (void)runOnceAsyncWithKey:(NSString *)key action:(void (^)(void))action;

@end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CanvasActivity" >

    <LinearLayout
        android:id="@+id/canvas_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >

    </LinearLayout>

</RelativeLayout>


text:
var Mongodb = require("mongodb");

module.exports.findAll = function(db, collectionName, query, projection){
    return new Promise(function(res, rej){
      var collection = db.collection(collectionName);

      if(!collection){
        rej(new Error(`Collection "${collectionName}" was not found`));
        return;
      }

      collection.find(query || {}, projection || {}, function(err, cursor){
        if(err){
          rej(err);
          return;
        }

        cursor.toArray(function(err2, docs){
            if(err2){
              rej(err);
              return;
            }

            res(docs);
        });
      })
    })
}

module.exports.findOne = function(db, collectionName, query, projection){
  return new Promise(function(res, rej){
    var collection = db.collection(collectionName);

    if(!collection){
      rej(new Error(`Collection "${collectionName}" was not found`));
      return;
    }

    collection.findOne(query || {}, projection || {}, function(err, doc){
      if(err){
        rej(err);
        return;
      }

      res(doc);
    });
  });
}

module.exports.findCursor = function(db, collectionName, query, projection){
    return new Promise(function(res, rej){
      var collection = db.collection(collectionName);

      if(!collection){
        rej(new Error(`Collection "${collectionName}" was not found`));
        return;
      }

      collection.find(query || {}, projection || {}, function(err, cursor){
        if(err){
          rej(err);
          return;
        }

        res(cursor);
      });
    });
}

module.exports.findTailableStream = function(db, collectionName, query, projection){
    return new Promise(function(res, rej){
      var collection = db.collection(collectionName);

      if(!collection){
        rej(new Error(`Collection "${collectionName}" was not found`));
        return;
      }

      collection.find(query || {}, projection || {}, function(err, cursor){
        if(err){
          rej(err);
          return;
        }
        var latestCursor = cursor.sort({$natural:-1}).limit(1);
        latestCursor.nextObject(function(err2, latest){
          if(err2){
            rej(err2);
            return;
          }
          if (latest) {
            query._id = {$gt: latest._id}
          }
          options = {
            tailable: true,
            await_data: true,
            numberOfRetries: -1
          };
          res(collection.find(query, projection, options).stream());
        });
      });
    });
}

module.exports.insertMany = function(db, collectionName, docs){
  return new Promise(function(res, rej){
    var collection = db.collection(collectionName);

    if(!collection){
      rej(new Error(`Collection "${collectionName}" was not found`));
      return;
    }

    collection.insert(docs, function(err){
      if(err){
        rej(err);
        return;
      }

      res();
    });
  });
}

module.exports.insertOne = function(db, collectionName, doc){
  return new Promise(function(res, rej){
    var collection = db.collection(collectionName);

    if(!collection){
      rej(new Error(`Collection "${collectionName}" was not found`));
      return;
    }

    collection.insert([doc], function(err){
      if(err){
        rej(err);
        return;
      }

      res();
    });
  });
}

module.exports.upsertOne = function(db, collectionName, doc, selector){
  return new Promise(function(res, rej){
    var collection = db.collection(collectionName);

    if(!collection){
      rej(new Error(`Collection "${collectionName}" was not found`));
      return;
    }

    collection.update(selector || {}, doc, true, function(err){
      if(err){
        rej(err);
        return;
      }

      res();
    });
  });
}

module.exports.connectToMongo = function(connectionString){
  return new Promise(function(res, rej){
    Mongodb.connect(connectionString, function(err, db){
      if(err){
        rej(err);
        return;
      }

      res(db);
    });
  });
}