text:
package org.elasticsearch.xpack.sql.cli;

import com.carrotsearch.randomizedtesting.annotations.Listeners;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;

import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TimeUnits;
import org.elasticsearch.test.junit.listeners.LoggingListener;
import org.elasticsearch.test.junit.listeners.ReproduceInfoPrinter;

import static com.carrotsearch.randomizedtesting.RandomizedTest.randomAsciiLettersOfLength;

@Listeners({ ReproduceInfoPrinter.class, LoggingListener.class })
@ThreadLeakScope(ThreadLeakScope.Scope.SUITE)
@ThreadLeakLingering(linger = 5000) // 5 sec lingering
@TimeoutSuite(millis = 20 * TimeUnits.MINUTE)
@LuceneTestCase.SuppressSysoutChecks(bugUrl = "we log a lot on purpose")
// we suppress pretty much all the lucene codecs for now, except asserting
// assertingcodec is the winner for a codec here: it finds bugs and gives clear exceptions.
@LuceneTestCase.SuppressCodecs(
    {
        "SimpleText",
        "Memory",
        "CheapBastard",
        "Direct",
        "Compressing",
        "FST50",
        "FSTOrd50",
        "TestBloomFilteredLucenePostings",
        "MockRandom",
        "BlockTreeOrds",
        "LuceneFixedGap",
        "LuceneVarGapFixedInterval",
        "LuceneVarGapDocFreqInterval",
        "Lucene50" }
)
@LuceneTestCase.SuppressReproduceLine
public abstract class SqlCliTestCase extends LuceneTestCase {

    public boolean randomBoolean() {
        return random().nextBoolean();
    }

    public String randomAlphaOfLength(int length) {
        return randomAsciiLettersOfLength(length);
    }
}


text:
package com.github.ckwen.je.spring.boot.multi.datasource.model.s;

import org.springframework.data.jpa.repository.JpaRepository;

public interface MessageRepository extends JpaRepository<Message, Long> {

}

redpajama_set_name: RedPajamaGithub


text:
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six

# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
    import builtins as __builtin__

    long = int
elif six.PY2:
    import __builtin__

from . import config
from . import state
from . import vlan
from . import ipv4
from . import ipv6

class subinterface(PybindBase):
    """
  This class was auto-generated by the PythonClass plugin for PYANG
  from YANG module openconfig-interfaces - based on the path /interfaces/interface/subinterfaces/subinterface. Each member element of
  the container is represented as a class variable - with a specific
  YANG type.

  YANG Description: The list of subinterfaces (logical interfaces) associated
with a physical interface
  """
    __slots__ = (
        "_path_helper",
        "_extmethods",
        "__index",
        "__config",
        "__state",
        "__vlan",
        "__ipv4",
        "__ipv6",
    )

    _yang_name = "subinterface"

    _pybind_generated_by = "container"

    def __init__(self, *args, **kwargs):

        self._path_helper = False

        self._extmethods = False
        self.__index = YANGDynClass(
            base=six.text_type,
            is_leaf=True,
            yang_name="index",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            is_keyval=True,
            namespace="http://openconfig.net/yang/interfaces",
            defining_module="openconfig-interfaces",
            yang_type="leafref",
            is_config=True,
        )
        self.__config = YANGDynClass(
            base=config.config,
            is_container="container",
            yang_name="config",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces",
            defining_module="openconfig-interfaces",
            yang_type="container",
            is_config=True,
        )
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces",
            defining_module="openconfig-interfaces",
            yang_type="container",
            is_config=True,
        )
        self.__vlan = YANGDynClass(
            base=vlan.vlan,
            is_container="container",
            yang_name="vlan",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/vlan",
            defining_module="openconfig-vlan",
            yang_type="container",
            is_config=True,
        )
        self.__ipv4 = YANGDynClass(
            base=ipv4.ipv4,
            is_container="container",
            yang_name="ipv4",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces/ip",
            defining_module="openconfig-if-ip",
            yang_type="container",
            is_config=True,
        )
        self.__ipv6 = YANGDynClass(
            base=ipv6.ipv6,
            is_container="container",
            yang_name="ipv6",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces/ip",
            defining_module="openconfig-if-ip",
            yang_type="container",
            is_config=True,
        )

        load = kwargs.pop("load", None)
        if args:
            if len(args) > 1:
                raise TypeError("cannot create a YANG container with >1 argument")
            all_attr = True
            for e in self._pyangbind_elements:
                if not hasattr(args[0], e):
                    all_attr = False
                    break
            if not all_attr:
                raise ValueError("Supplied object did not have the correct attributes")
            for e in self._pyangbind_elements:
                nobj = getattr(args[0], e)
                if nobj._changed() is False:
                    continue
                setmethod = getattr(self, "_set_%s" % e)
                if load is None:
                    setmethod(getattr(args[0], e))
                else:
                    setmethod(getattr(args[0], e), load=load)

    def _path(self):
        if hasattr(self, "_parent"):
            return self._parent._path() + [self._yang_name]
        else:
            return ["interfaces", "interface", "subinterfaces", "subinterface"]

    def _get_index(self):
        """
    Getter method for index, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/index (leafref)

    YANG Description: The index number of the subinterface -- used to address
the logical interface
    """
        return self.__index

    def _set_index(self, v, load=False):
        """
    Setter method for index, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/index (leafref)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_index is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_index() directly.

    YANG Description: The index number of the subinterface -- used to address
the logical interface
    """
        parent = getattr(self, "_parent", None)
        if parent is not None and load is False:
            raise AttributeError(
                "Cannot set keys directly when" + " within an instantiated list"
            )

        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=six.text_type,
                is_leaf=True,
                yang_name="index",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                is_keyval=True,
                namespace="http://openconfig.net/yang/interfaces",
                defining_module="openconfig-interfaces",
                yang_type="leafref",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """index must be of a type compatible with leafref""",
                    "defined-type": "leafref",
                    "generated-type": """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="index", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/interfaces', defining_module='openconfig-interfaces', yang_type='leafref', is_config=True)""",
                }
            )

        self.__index = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_index(self):
        self.__index = YANGDynClass(
            base=six.text_type,
            is_leaf=True,
            yang_name="index",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            is_keyval=True,
            namespace="http://openconfig.net/yang/interfaces",
            defining_module="openconfig-interfaces",
            yang_type="leafref",
            is_config=True,
        )

    def _get_config(self):
        """
    Getter method for config, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/config (container)

    YANG Description: Configurable items at the subinterface level
    """
        return self.__config

    def _set_config(self, v, load=False):
        """
    Setter method for config, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/config (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_config is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_config() directly.

    YANG Description: Configurable items at the subinterface level
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=config.config,
                is_container="container",
                yang_name="config",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/interfaces",
                defining_module="openconfig-interfaces",
                yang_type="container",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """config must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=config.config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/interfaces', defining_module='openconfig-interfaces', yang_type='container', is_config=True)""",
                }
            )

        self.__config = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_config(self):
        self.__config = YANGDynClass(
            base=config.config,
            is_container="container",
            yang_name="config",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces",
            defining_module="openconfig-interfaces",
            yang_type="container",
            is_config=True,
        )

    def _get_state(self):
        """
    Getter method for state, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/state (container)

    YANG Description: Operational state data for logical interfaces
    """
        return self.__state

    def _set_state(self, v, load=False):
        """
    Setter method for state, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/state (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_state is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_state() directly.

    YANG Description: Operational state data for logical interfaces
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=state.state,
                is_container="container",
                yang_name="state",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/interfaces",
                defining_module="openconfig-interfaces",
                yang_type="container",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """state must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/interfaces', defining_module='openconfig-interfaces', yang_type='container', is_config=True)""",
                }
            )

        self.__state = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_state(self):
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces",
            defining_module="openconfig-interfaces",
            yang_type="container",
            is_config=True,
        )

    def _get_vlan(self):
        """
    Getter method for vlan, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/vlan (container)

    YANG Description: Enclosing container for VLAN interface-specific
data on subinterfaces
    """
        return self.__vlan

    def _set_vlan(self, v, load=False):
        """
    Setter method for vlan, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/vlan (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_vlan is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_vlan() directly.

    YANG Description: Enclosing container for VLAN interface-specific
data on subinterfaces
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=vlan.vlan,
                is_container="container",
                yang_name="vlan",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/vlan",
                defining_module="openconfig-vlan",
                yang_type="container",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """vlan must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=vlan.vlan, is_container='container', yang_name="vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/vlan', defining_module='openconfig-vlan', yang_type='container', is_config=True)""",
                }
            )

        self.__vlan = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_vlan(self):
        self.__vlan = YANGDynClass(
            base=vlan.vlan,
            is_container="container",
            yang_name="vlan",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/vlan",
            defining_module="openconfig-vlan",
            yang_type="container",
            is_config=True,
        )

    def _get_ipv4(self):
        """
    Getter method for ipv4, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/ipv4 (container)

    YANG Description: Parameters for the IPv4 address family.
    """
        return self.__ipv4

    def _set_ipv4(self, v, load=False):
        """
    Setter method for ipv4, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/ipv4 (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_ipv4 is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_ipv4() directly.

    YANG Description: Parameters for the IPv4 address family.
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=ipv4.ipv4,
                is_container="container",
                yang_name="ipv4",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/interfaces/ip",
                defining_module="openconfig-if-ip",
                yang_type="container",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """ipv4 must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=ipv4.ipv4, is_container='container', yang_name="ipv4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='container', is_config=True)""",
                }
            )

        self.__ipv4 = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_ipv4(self):
        self.__ipv4 = YANGDynClass(
            base=ipv4.ipv4,
            is_container="container",
            yang_name="ipv4",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces/ip",
            defining_module="openconfig-if-ip",
            yang_type="container",
            is_config=True,
        )

    def _get_ipv6(self):
        """
    Getter method for ipv6, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/ipv6 (container)

    YANG Description: Parameters for the IPv6 address family.
    """
        return self.__ipv6

    def _set_ipv6(self, v, load=False):
        """
    Setter method for ipv6, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/ipv6 (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_ipv6 is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_ipv6() directly.

    YANG Description: Parameters for the IPv6 address family.
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=ipv6.ipv6,
                is_container="container",
                yang_name="ipv6",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/interfaces/ip",
                defining_module="openconfig-if-ip",
                yang_type="container",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """ipv6 must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=ipv6.ipv6, is_container='container', yang_name="ipv6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='container', is_config=True)""",
                }
            )

        self.__ipv6 = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_ipv6(self):
        self.__ipv6 = YANGDynClass(
            base=ipv6.ipv6,
            is_container="container",
            yang_name="ipv6",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/interfaces/ip",
            defining_module="openconfig-if-ip",
            yang_type="container",
            is_config=True,
        )

    index = __builtin__.property(_get_index, _set_index)
    config = __builtin__.property(_get_config, _set_config)
    state = __builtin__.property(_get_state, _set_state)
    vlan = __builtin__.property(_get_vlan, _set_vlan)
    ipv4 = __builtin__.property(_get_ipv4, _set_ipv4)
    ipv6 = __builtin__.property(_get_ipv6, _set_ipv6)

    _pyangbind_elements = OrderedDict(
        [
            ("index", index),
            ("config", config),
            ("state", state),
            ("vlan", vlan),
            ("ipv4", ipv4),
            ("ipv6", ipv6),
        ]
    )


text:
@interface PDDatabaseDomain ()
//Commands

@end

@implementation PDDatabaseDomain

@dynamic delegate;

+ (NSString *)domainName;
{
    return @"Database";
}

// Events
- (void)addDatabaseWithDatabase:(PDDatabaseDatabase *)database;
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:1];

    if (database != nil) {
        [params setObject:[database PD_JSONObject] forKey:@"database"];
    }

    [self.debuggingServer sendEventWithName:@"Database.addDatabase" parameters:params];
}
- (void)sqlTransactionSucceededWithTransactionId:(NSNumber *)transactionId columnNames:(NSArray *)columnNames values:(NSArray *)values;
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:3];

    if (transactionId != nil) {
        [params setObject:[transactionId PD_JSONObject] forKey:@"transactionId"];
    }
    if (columnNames != nil) {
        [params setObject:[columnNames PD_JSONObject] forKey:@"columnNames"];
    }
    if (values != nil) {
        [params setObject:[values PD_JSONObject] forKey:@"values"];
    }

    [self.debuggingServer sendEventWithName:@"Database.sqlTransactionSucceeded" parameters:params];
}
- (void)sqlTransactionFailedWithTransactionId:(NSNumber *)transactionId sqlError:(NSDictionary *)sqlError;
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:2];

    if (transactionId != nil) {
        [params setObject:[transactionId PD_JSONObject] forKey:@"transactionId"];
    }
    if (sqlError != nil) {
        [params setObject:[sqlError PD_JSONObject] forKey:@"sqlError"];
    }

    [self.debuggingServer sendEventWithName:@"Database.sqlTransactionFailed" parameters:params];
}

- (void)handleMethodWithName:(NSString *)methodName parameters:(NSDictionary *)params responseCallback:(PDResponseCallback)responseCallback;
{
    if ([methodName isEqualToString:@"enable"] && [self.delegate respondsToSelector:@selector(domain:enableWithCallback:)]) {
        [self.delegate domain:self enableWithCallback:^(id error) {
            responseCallback(nil, error);
        }];
    } else if ([methodName isEqualToString:@"disable"] && [self.delegate respondsToSelector:@selector(domain:disableWithCallback:)]) {
        [self.delegate domain:self disableWithCallback:^(id error) {
            responseCallback(nil, error);
        }];
    } else if ([methodName isEqualToString:@"getDatabaseTableNames"] && [self.delegate respondsToSelector:@selector(domain:getDatabaseTableNamesWithDatabaseId:callback:)]) {
        [self.delegate domain:self getDatabaseTableNamesWithDatabaseId:[params objectForKey:@"databaseId"] callback:^(NSArray *tableNames, id error) {
            NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:1];

            if (tableNames != nil) {
                [params setObject:tableNames forKey:@"tableNames"];
            }

            responseCallback(params, error);
        }];
    } else if ([methodName isEqualToString:@"executeSQL"] && [self.delegate respondsToSelector:@selector(domain:executeSQLWithDatabaseId:query:callback:)]) {
        [self.delegate domain:self executeSQLWithDatabaseId:[params objectForKey:@"databaseId"] query:[params objectForKey:@"query"] callback:^(NSNumber *success, NSNumber *transactionId, id error) {
            NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:2];

            if (success != nil) {
                [params setObject:success forKey:@"success"];
            }
            if (transactionId != nil) {
                [params setObject:transactionId forKey:@"transactionId"];
            }

            responseCallback(params, error);
        }];
    } else {
        [super handleMethodWithName:methodName parameters:params responseCallback:responseCallback];
    }
}

@end

@implementation PDDebugger (PDDatabaseDomain)

- (PDDatabaseDomain *)databaseDomain;
{
    return [self domainForName:@"Database"];
}

@end


text:
<?php
/**
 * @license see LICENSE
 */

namespace UForm\Test\Validator;

use UForm\Test\ValidatorTestCase;
use UForm\Validator\AlphaNum;

/**
 * @covers UForm\Validator\AlphaNum
 */
class AlphaNumTest extends ValidatorTestCase
{

    public function testValid()
    {
        $validation = $this->generateValidationItem(['firstname' => 'bart1']);
        $validator = new AlphaNum();
        $validator->validate($validation);
        $this->assertTrue($validation->isValid());

        $validation = $this->generateValidationItem(['firstname' => 'bart 1']);
        $validator = new AlphaNum(true);
        $validator->validate($validation);
        $this->assertTrue($validation->isValid());
    }

    public function testNotValid()
    {
        $validation = $this->generateValidationItem(['firstname' => 'bart-1']);
        $validator = new AlphaNum();
        $validator->validate($validation);
        $this->assertFalse($validation->isValid());

        $validation = $this->generateValidationItem(['firstname' => 'bart 1']);
        $validator = new AlphaNum();
        $validator->validate($validation);
        $this->assertFalse($validation->isValid());
    }

    public function testEmpty()
    {

        $validation = $this->generateValidationItem(['firstname' => '']);
        $validator = new AlphaNum();
        $validator->validate($validation);
        $this->assertTrue($validation->isValid());
    }
}


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

  // Codesnips controller
  angular
    .module('codesnips')
    .controller('CodesnipsController', CodesnipsController);

  CodesnipsController.$inject = ['$scope', '$state', 'Authentication', 'codesnipResolve'];

  function CodesnipsController ($scope, $state, Authentication, codesnip) {
    var vm = this;

    vm.authentication = Authentication;
    vm.codesnip = codesnip;
    vm.error = null;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;

    // Remove existing Codesnip
    function remove() {
      if (confirm('Are you sure you want to delete?')) {
        vm.codesnip.$remove($state.go('codesnips.list'));
      }
    }

    // Save Codesnip
    function save(isValid) {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.codesnipForm');
        return false;
      }

      // TODO: move create/update logic to service
      if (vm.codesnip._id) {
        vm.codesnip.$update(successCallback, errorCallback);
      } else {
        vm.codesnip.$save(successCallback, errorCallback);
      }

      function successCallback(res) {
        $state.go('codesnips.view', {
          codesnipId: res._id
        });
      }

      function errorCallback(res) {
        vm.error = res.data.message;
      }
    }
  }
})();


text:
package aural

import (
	"net/http"
)

// Doer is an interface for an object that can make HTTP requests
type Doer interface {
	Do(req *http.Request) (resp *http.Response, err error)
}


text:
<?php

namespace AsyncSockets\RequestExecutor\Pipeline;

use AsyncSockets\Event\WriteEvent;
use AsyncSockets\Operation\InProgressWriteOperation;
use AsyncSockets\Operation\OperationInterface;
use AsyncSockets\Operation\WriteOperation;
use AsyncSockets\RequestExecutor\EventHandlerInterface;
use AsyncSockets\RequestExecutor\ExecutionContext;
use AsyncSockets\RequestExecutor\Metadata\RequestDescriptor;
use AsyncSockets\RequestExecutor\RequestExecutorInterface;
use AsyncSockets\Socket\Io\IoInterface;
use AsyncSockets\Socket\SocketInterface;

/**
 * Class WriteIoHandler
 */
class WriteIoHandler extends AbstractOobHandler
{
    /** {@inheritdoc} */
    public function supports(OperationInterface $operation)
    {
        return ($operation instanceof WriteOperation) || ($operation instanceof InProgressWriteOperation);
    }

    /** {@inheritdoc} */
    protected function handleOperation(
        OperationInterface $operation,
        RequestDescriptor $descriptor,
        RequestExecutorInterface $executor,
        EventHandlerInterface $eventHandler,
        ExecutionContext $executionContext
    ) {
        $socket = $descriptor->getSocket();

        /** @var WriteOperation $operation */
        $fireEvent = !($operation instanceof InProgressWriteOperation);

        if ($fireEvent) {
            $meta  = $executor->socketBag()->getSocketMetaData($socket);
            $event = new WriteEvent(
                $operation,
                $executor,
                $socket,
                $meta[ RequestExecutorInterface::META_USER_CONTEXT ]
            );
            $eventHandler->invokeEvent($event, $executor, $descriptor->getSocket(), $executionContext);
            $nextOperation = $event->getNextOperation();
        } else {
            $nextOperation = $operation;
        }

        $result = $this->writeDataToSocket($operation, $socket, $nextOperation, $bytesWritten);
        $this->handleTransferCounter(RequestDescriptor::COUNTER_SEND_MIN_RATE, $descriptor, $bytesWritten);

        return $result;
    }

    /**
     * Perform data writing to socket and return suitable next socket operation
     *
     * @param WriteOperation     $operation Current write operation instance
     * @param SocketInterface    $socket Socket object
     * @param OperationInterface $nextOperation Desirable next operation
     * @param int                $bytesWritten Amount of written bytes
     *
     * @return OperationInterface Actual next operation
     */
    private function writeDataToSocket(
        WriteOperation $operation,
        SocketInterface $socket,
        OperationInterface $nextOperation = null,
        &$bytesWritten = null
    ) {
        $result               = $nextOperation;
        $extractNextOperation = true;
        $bytesWritten         = 0;

        $iterator = $this->resolveDataIterator($operation);
        if ($iterator->valid()) {
            $data     = $iterator->current();
            $length   = strlen($data);
            $written  = $socket->write($data, $operation->isOutOfBand());
            if ($length !== $written) {
                $iterator->unread($length - $written);
            }

            $bytesWritten = $written;
            $iterator->next();

            if ($iterator->valid()) {
                $extractNextOperation = false;
                $operation = $this->makeInProgressWriteOperation($operation, $nextOperation);
                $result    = $operation;
            }
        }

        if ($extractNextOperation && ($operation instanceof InProgressWriteOperation)) {
            /** @var InProgressWriteOperation $operation */
            $result = $operation->getNextOperation();
        }

        return $result;
    }

    /**
     * Marks write operation as in progress
     *
     * @param WriteOperation     $operation Current operation object
     * @param OperationInterface $nextOperation Next planned operation
     *
     * @return InProgressWriteOperation Next operation object
     */
    private function makeInProgressWriteOperation(WriteOperation $operation, OperationInterface $nextOperation = null)
    {
        $result = $operation;
        if (!($result instanceof InProgressWriteOperation)) {
            $result = new InProgressWriteOperation($nextOperation, $operation->getData());
        }

        return $result;
    }

    /**
     * Return iterator for writing operation
     *
     * @param WriteOperation $operation The operation
     *
     * @return PushbackIterator
     */
    private function resolveDataIterator(WriteOperation $operation)
    {
        $result = $operation->getData();
        if (!($result instanceof PushbackIterator)) {
            $result = new PushbackIterator(
                $this->dataToIterator($result),
                IoInterface::SOCKET_BUFFER_SIZE
            );

            $result->rewind();

            $operation->setData($result);
        }

        return $result;
    }

    /**
     * Converts data to Traversable object
     *
     * @param mixed $data Data to convert into object
     *
     * @return \Iterator
     * @throws \LogicException If data can not be converted to \Traversable
     */
    private function dataToIterator($data)
    {
        switch (true) {
            case !is_object($data):
                return new \ArrayIterator((array) $data);
            case $data instanceof \Iterator:
                return $data;
            case $data instanceof \Traversable:
                return new \IteratorIterator($data);
            default:
                throw new \LogicException(
                    sprintf(
                        'Trying to send unexpected data type %s',
                        is_object($data) ? get_class($data) : gettype($data)
                    )
                );
        }
    }

    /**
     * @inheritDoc
     */
    protected function getHandlerType()
    {
        return RequestDescriptor::RDS_WRITE;
    }
}


text:
package com.raizlabs.android.dbflow.test.sql.inherited;

import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.InheritedColumn;
import com.raizlabs.android.dbflow.annotation.InheritedPrimaryKey;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.structure.Model;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.raizlabs.android.dbflow.test.TestDatabase;

/**
 * Description:
 */
@Table(database = TestDatabase.class,
        inheritedColumns = {@InheritedColumn(column = @Column, fieldName = "name"),
                @InheritedColumn(column = @Column, fieldName = "number")},
        inheritedPrimaryKeys = {@InheritedPrimaryKey(column = @Column,
                primaryKey = @PrimaryKey,
                fieldName = "inherited_primary_key")})
public class InheritorModel extends InheritedModel implements Model {

    private final ModelAdapter<InheritorModel> modelAdapter = FlowManager.getModelAdapter(InheritorModel.class);

    @Column
    @PrimaryKey
    String primary_key;

    @Override
    public void save() {
        modelAdapter.save(this);
    }

    @Override
    public void delete() {
        modelAdapter.delete(this);
    }

    @Override
    public void update() {
        modelAdapter.update(this);
    }

    @Override
    public void insert() {
        modelAdapter.insert(this);
    }

    @Override
    public boolean exists() {
        return modelAdapter.exists(this);
    }
}


text:
Examples
========

Generate a Migration File
-------------------------

Creating a new migration file.

```
cake Migrations.migration generate
```

If you want import all tables regardless if it has a model or not you can use ```-f``` (force) parameter.

```
cake Migrations.migration generate -f
```

Running All Pending Migrations
-----------------------------

Get all pending changes into your database run.

```
cake Migrations.migration run all
```

Resetting Your Database
-----------------------

Reset your database to the initial state of your first migration run.

```
cake Migrations.migration run reset
```

Downgrade to Previous Version
-----------------------------

Downgrades your database to the previous migration.

```
cake Migrations.migration run down
```

Upgrade to Next Version
-----------------------

Applies the next migration to your database.

```
cake Migrations.migration run up
```

Running Migrations for Plugins
------------------------------

Running a migration of a plugin you can use the plugin option.

```
cake Migrations.migration run all --plugin Users
```

Getting the Status of Available/Applied Migrations
--------------------------------------------------

Gets the status of all migrations.

```
cake Migrations.migration status
```


text:
require File.expand_path('../test_helper', __FILE__)

describe Gitdocs::Repository::Path do
  let(:path) { Gitdocs::Repository::Path.new(repository, "/#{relative_path}") }
  let(:repository) { stub(root: GitFactory.expand_path(:local)) }
  let(:relative_path) { 'directory/file' }

  before do
    FileUtils.rm_rf('tmp/unit')
    GitFactory.init(:local)
  end

  describe '#relative_dirname' do
    subject { path.relative_dirname }

    describe 'root' do
      let(:relative_path) { '' }
      it { subject.must_equal('') }
    end

    describe 'root filename' do
      let(:relative_path) { 'directory' }
      it { subject.must_equal('') }
    end

    describe 'non-root filename' do
      let(:relative_path) { 'directory1/directory2/file' }
      it { subject.must_equal('directory1/directory2') }
    end
  end

  describe '#join' do
    subject { path.join('new_file') }
    before { subject }
    it { path.relative_path.must_equal(File.join(relative_path, 'new_file')) }
    it { path.absolute_path.must_equal(GitFactory.expand_path(:local, relative_path, 'new_file')) }
  end

  describe '#write' do
    subject { path.write('foobar') }

    describe 'directory missing' do
      before { subject }
      it { GitInspector.file_content(:local, relative_path).must_equal "foobar\n" }
    end

    describe 'directory exists' do
      before do
        mkdir(File.dirname(relative_path))
        subject
      end
      it { GitInspector.file_content(:local, relative_path).must_equal "foobar\n" }
    end

    describe 'file exists' do
      before do
        write(relative_path, 'deadbeef')
        subject
      end
      it { GitInspector.file_content(:local, relative_path).must_equal "foobar\n" }
    end
  end

  describe '#touch' do
    subject { path.touch }

    describe 'when directory does not exist' do
      before { subject }
      it { GitInspector.file_content(:local, relative_path).must_equal '' }
    end

    describe 'when directory already exists' do
      before do
        mkdir(File.dirname(relative_path))
        subject
      end
      it { GitInspector.file_content(:local, relative_path).must_equal '' }
    end

    describe 'when file already exists' do
      before do
        write(relative_path, 'test')
        subject
      end
      it { GitInspector.file_content(:local, relative_path).must_equal 'test' }
    end
  end

  describe '#mkdir' do
    subject { path.mkdir }

    describe 'directory does not exist' do
      before { subject }
      it { File.directory?(GitFactory.expand_path(:local, relative_path)) }
    end

    describe 'directory does exist' do
      before do
        mkdir(relative_path)
        subject
      end
      it { File.directory?(GitFactory.expand_path(:local, relative_path)) }
    end

    describe 'already exists as a file' do
      before { write(relative_path, 'foobar') }
      it { assert_raises(Errno::EEXIST) { subject } }
    end
  end

  describe '#mv' do
    subject { path.mv(source_filename) }
    let(:source_filename) { File.join(GitFactory.working_directory, 'move_me') }
    before do
      FileUtils.mkdir_p(File.dirname(source_filename))
      File.write(source_filename, 'foobar')

      subject
    end
    it { GitInspector.file_content(:local, relative_path).must_equal('foobar') }
  end

  describe '#remove' do
    subject { path.remove }

    describe 'missing' do
      it { subject.must_be_nil }
    end

    describe 'directory' do
      before { mkdir(relative_path) }
      it { subject.must_be_nil }
    end

    describe 'file' do
      before do
        write(relative_path, 'foobar')
        subject
      end
      it { GitInspector.file_exist?(:local, relative_path).must_equal false }
    end
  end

  describe '#text?' do
    subject { path.text? }

    describe 'missing' do
      it { subject.must_equal false }
    end

    describe 'directory' do
      before { mkdir(relative_path) }
      it { subject.must_equal false }
    end

    describe 'not a text file' do
      let(:relative_path) { 'file.png' }
      it { subject.must_equal false }
    end

    describe 'empty file' do
      before { write(relative_path, '') }
      it { subject.must_equal true }
    end

    describe 'text file' do
      before { write(relative_path, 'foobar') }
      it { subject.must_equal true }
    end
  end

  describe '#meta' do
    subject { path.meta }
    before do
      repository.stubs(:last_commit_for).with(relative_path).returns(commit)
    end

    describe 'when missing' do
      let(:commit) { nil }
      it { assert_raises(RuntimeError) { subject } }
    end

    describe 'on a ' do
      let(:commit) { stub(author: { name: :name, time: :time }) }
      before do
        write(File.join(%w(directory0 file0)), '')
        write(File.join(%w(directory file1)), 'foo')
        write(File.join(%w(directory file2)), 'bar')
      end

      describe 'file size 0' do
        let(:relative_path) { File.join(%w(directory0 file0)) }
        it { subject[:author].must_equal :name }
        it { subject[:size].must_equal(-1) }
        it { subject[:modified].must_equal :time }
      end

      describe 'file non-zero size' do
        let(:relative_path) { File.join(%w(directory file1)) }
        it { subject[:author].must_equal :name }
        it { subject[:size].must_equal(3) }
        it { subject[:modified].must_equal :time }
      end

      describe 'directory size 0' do
        let(:relative_path) { 'directory0' }
        it { subject[:author].must_equal :name }
        it { subject[:size].must_equal(-1) }
        it { subject[:modified].must_equal :time }
      end

      describe 'directory non-zero size' do
        let(:relative_path) { 'directory' }
        it { subject[:author].must_equal :name }
        it { subject[:size].must_equal(6) }
        it { subject[:modified].must_equal :time }
      end
    end
  end

  describe '#exist?' do
    subject { path.exist? }

    describe 'missing' do
      it { subject.must_equal false }
    end

    describe 'directory' do
      before { mkdir(relative_path) }
      it { subject.must_equal true }
    end

    describe 'file' do
      before { write(relative_path, 'foobar') }
      it { subject.must_equal true }
    end
  end

  describe '#directory?' do
    subject { path.directory? }

    describe 'missing' do
      it { subject.must_equal false }
    end

    describe 'directory' do
      before { mkdir(relative_path) }
      it { subject.must_equal true }
    end

    describe 'file' do
      before { write(relative_path, 'foobar') }
      it { subject.must_equal false }
    end
  end

  describe '#absolute_path' do
    subject { path.absolute_path(ref) }

    describe 'no revision' do
      let(:ref) { nil }
      it { subject.must_equal GitFactory.expand_path(:local, relative_path) }
    end

    describe 'with revision' do
      let(:ref) { :ref }
      before { repository.stubs(:blob_at).with(relative_path, :ref).returns(blob) }

      describe 'no blob' do
        let(:blob) { nil }
        it { File.read(subject).must_equal "\n" }
      end

      describe 'has blob' do
        let(:blob) { stub(text: 'beef') }
        it { File.read(subject).must_equal "beef\n" }
      end
    end
  end

  describe '#readme_path' do
    subject { path.readme_path }

    describe 'no directory' do
      it { subject.must_be_nil }
    end

    describe 'no README' do
      before { mkdir(relative_path) }
      it { subject.must_be_nil }
    end

    describe 'with README.md' do
      before { write(File.join(relative_path, 'README.md'), 'foobar') }
      it { subject.must_equal GitFactory.expand_path(:local, relative_path, 'README.md') }
    end
  end

  describe '#file_listing' do
    subject { path.file_listing }

    describe 'missing' do
      it { subject.must_be_nil }
    end

    describe 'file' do
      before { write(relative_path, 'foobar') }
      it { subject.must_be_nil }
    end

    describe 'directory' do
      before do
        write(File.join(relative_path, '.hidden'), 'beef')
        mkdir(File.join(relative_path, 'dir1'))
        write(File.join(relative_path, 'file1'), 'foo')
        write(File.join(relative_path, 'file2'), 'bar')

        # Paths which should not be included
        write(File.join(relative_path, '.gitignore'), 'test')
        write(File.join(relative_path, '.gitmessage~'), 'test')
      end

      it { subject.size.must_equal 4 }
      it { subject.map(&:name).must_equal %w(dir1 file1 file2 .hidden) }
      it { subject.map(&:is_directory).must_equal [true, false, false, false] }
    end
  end

  describe '#content' do
    subject { path.content }

    describe 'missing' do
      it { subject.must_be_nil }
    end

    describe 'directory' do
      before { mkdir(relative_path) }
      it { subject.must_be_nil }
    end

    describe 'file' do
      before { write(relative_path, 'foobar') }
      it { subject.must_equal 'foobar' }
    end
  end

  describe '#revisions' do
    subject { path.revisions }

    before do
      repository.stubs(:commits_for).returns(
        [
          stub(oid: '1234567890', message: "short1\nlong", author: { name: :name1, time: :time1 }),
          stub(oid: '0987654321', message: "short2\nlong", author: { name: :name2, time: :time2 })
        ]
      )
    end
    it { subject.size.must_equal(2) }
    it { subject[0].must_equal(commit: '1234567', subject: 'short1', author: :name1, date: :time1) }
    it { subject[1].must_equal(commit: '0987654', subject: 'short2', author: :name2, date: :time2) }
  end

  describe '#revert' do
    subject { path.revert('ref') }
    before { repository.expects(:blob_at).with(relative_path, 'ref').returns(blob) }

    describe 'blob missing' do
      let(:blob) { nil }
      it { subject.must_equal(nil) }
    end

    describe 'blob present' do
      let(:blob) { stub(text: 'deadbeef') }
      before { path.expects(:write).with('deadbeef') }
      it { subject }
    end
  end

  #############################################################################

  private

  def write(filename, content)
    GitFactory.write(:local, filename, content)
  end

  def mkdir(path)
    GitFactory.mkdir(:local, path)
  end
end


text:
var chai = require('chai')
chai.Should()
chai.use(require('chai-things'))
chai.use(require('@signalk/signalk-schema').chaiModule)

var mapper = require('./testMapper')

describe('129285 Route Information', function () {
  it('complete sentence converts', function () {
    var msg = JSON.parse(
      '{"timestamp":"2017-04-15T21:50:57.780Z","prio":6,"pgn":129285,"src":3,"dst":255,"fields":{"Start RPS#":12,"nItems":3,"Database ID":0,"Route ID":0,"Navigation direction in route":3,"Supplementary Route/WP data available":1,"Route Name":"Route","list":[{"WP ID":12,"WP Name":"Waypoint 240","WP Latitude":39.1525868,"WP Longitude":-76.1811988},{"WP ID":13,"WP Name":"Waypoint 241","WP Latitude":39.1568741,"WP Longitude":-76.1834715},{"WP ID":14,"WP Name":"Waypoint 242","WP Latitude":39.159168,"WP Longitude":-76.182178}]},"description":"Navigation - Route/WP Information"}'
    )
    var tree = mapper.toNested(msg)
    console.log(JSON.stringify(tree))
    tree.should.have.nested.property(
      'navigation.currentRoute.name.value',
      'Route'
    )
    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[0].name',
      'Waypoint 240'
    )
    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[0].position.value.latitude',
      39.1525868
    )
    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[0].position.value.longitude',
      -76.1811988
    )

    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[1].name',
      'Waypoint 241'
    )
    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[1].position.value.latitude',
      39.1568741
    )
    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[1].position.value.longitude',
      -76.1834715
    )

    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[2].name',
      'Waypoint 242'
    )
    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[2].position.value.latitude',
      39.159168
    )
    tree.should.have.nested.property(
      'navigation.currentRoute.waypoints.value[2].position.value.longitude',
      -76.182178
    )
  })
})


text:
layout: post
title: 'SpeedHack #3 is coming to Berlin'
url: /2015/03/20/speedhack-3-is-coming-to-berlin/
source: /2015/03/20/speedhack-3-is-coming-to-berlin/
domain: apistrat.com
image:
---

After two successful editions in Chicago and in Paris, we are bringing SpeedHack to APIDays+APIStrat Berlin.

SpeedHack is a new franchise of hackathons of a new genre as we wrote in an earlier post here. Hackers have only 3 hours to solve code challenges suggested by our API partners. The team that solves all the challenges -- plus some extra challenges -- wins the global prize!

SpeedHack events are a great opportunity for hackers to get exposed to different sets of APIs, that they may use in their projects. API partners also take advantage of SpeedHack by meeting the local community of hackers and getting exposure and feedback. It's a great way to see how the API is perceived by the community.

Participation in as a hacker in the SpeedHack is free.

Register HERE

For this third edition we are happy to receive support from great sponsors:

Twitter

With Twitter's Fabric, you have a range of tools at your immediate disposal. Crashlytics to get crash reports from apps, Beta to distribute app to beta users, Digits to authenticate users with phone numbers, and Mopub to generate revenue with ads.

Developer Resources:

Twitter new SDK : Fabric

@TwitterDev

Google

Google will come along to the SpeedHack with brand-new technology. It is so hot we have to wait announcing it till after GoogleIO which is just shortly before our SpeedHack.

Developer Resources:

Google Developer

@googledevs

Twilio

Twilio has an awesome API that makes it easy to embed, VoIP or messaging services into web, desktop, and mobile apps. Twilio takes care of the messy telecom hardware and expose a globally available cloud API that developers can interact with to build intelligent & complex communications systems.

Developer Resources:

Twilio API documentation

@twilio

Context.io

Context.IO provide a unique email API that makes it easy for developers to retrieve that information and leverage it in applications such as CRM, document management, collaboration, productivity tools and project management..

Developer Resources:

Contextio API documentation

@ContextIO

Apidaze

Apidaze lets web developers add voice, messaging or WebRTC to web & mobile apps. Free for individual developers. No more cables, carriers, no hidden costs. Simple and pay as you go.

Developer Resources:

Apidaze API documentation

@apidaze

Streamdata.io

Transform any JSON API into a real-time push API with streamdata.io without a single line of server side code, and an easy integration in client applications thanks to our SDKs.

Developer Resources:

Streamdata API documentation

@StreamdataIO

Cronofy

Allowing any developer to interact with their customers' calendars, no matter which calendar service they've chosen or had forced upon them.

Developer Resources:

Cronofy API documentation

@cronofy

Stamplay

Stamplay brings together powerful components and services API in a way that you just need to define rules like: "when a user signs up, send him a welcome email and add him on my newsletter"

Developer Resources:

Stamplay API documentation

@Stamplay

Algolia

Search as a Service. We enable developers to deliver an outstanding search experience.

Developer Resources:

Algolia API documentation

@Algolia

Rules

Rules of SpeedHack are pretty simple

3 hours long hackathon

Challenges are revealed at the beginning on the SpeedHack page

Teams of maximum 2 hackers

All code should be written during the event

fun :)

Prizes

In good old SpeedHack tradition we have cash prizes to win, which are broken down the following way:

1st Place: EUR 1.500

2nd Place: EUR 250

3rd Place: EUR 150

In addition API partners will give away certain prices if you solve their challenge particularly well. And we may have some extra swag too. Both TBD, so stay tuned.

For more questions get in touch with the SpeedHack organisers directly.


text:
package org.gradle.api.artifacts.repositories;

import org.gradle.api.attributes.Attribute;

/**
 *
Descriptor of a repository content, used to avoid reaching to
 * an external repository when not needed.

 *
 *
Excludes are applied after includes. This means that by default, everything is included and nothing excluded.
 * If includes are added, then if the module doesn't match any of the includes, it's excluded. Then if it does, but
 * it also matches one of the excludes, it's also excluded.

 *
 * @since 5.1
 */
public interface RepositoryContentDescriptor extends InclusiveRepositoryContentDescriptor {

    /**
     * Declares that an entire group should be searched for in this repository.
     *
     * @param group the group name
     */
    @Override
    void includeGroup(String group);

    /**
     * Declares that an entire group should be searched for in this repository.
     *
     * @param groupRegex a regular expression of the group name
     */
    @Override
    void includeGroupByRegex(String groupRegex);

    /**
     * Declares that an entire module should be searched for in this repository.
     *
     * @param group the group name
     * @param moduleName the module name
     */
    @Override
    void includeModule(String group, String moduleName);

    /**
     * Declares that an entire module should be searched for in this repository, using regular expressions.
     *
     * @param groupRegex the group name regular expression
     * @param moduleNameRegex the module name regular expression
     */
    @Override
    void includeModuleByRegex(String groupRegex, String moduleNameRegex);

    /**
     * Declares that a specific module version should be searched for in this repository.
     *

     * The version notation supports range notations like {@code [1.0,2.0[}.
     *
     * @param group the group name
     * @param moduleName the module name
     * @param version the module version
     */
    @Override
    void includeVersion(String group, String moduleName, String version);

    /**
     * Declares that a specific module version should be searched for in this repository, using regular expressions.
     *

     * The version notation for a regex will be matched against a single version and does not support range notations.
     *
     * @param groupRegex the group name regular expression
     * @param moduleNameRegex the module name regular expression
     * @param versionRegex the module version regular expression
     */
    @Override
    void includeVersionByRegex(String groupRegex, String moduleNameRegex, String versionRegex);

    /**
     * Declares that an entire group shouldn't be searched for in this repository.
     *
     * @param group the group name
     */
    void excludeGroup(String group);

    /**
     * Declares that an entire group shouldn't be searched for in this repository.
     *
     * @param groupRegex the group name regular expression
     */
    void excludeGroupByRegex(String groupRegex);

    /**
     * Declares that an entire module shouldn't be searched for in this repository.
     *
     * @param group the group name
     * @param moduleName the module name
     */
    void excludeModule(String group, String moduleName);

    /**
     * Declares that an entire module shouldn't be searched for in this repository, using regular expressions.
     *
     * @param groupRegex the group name regular expression
     * @param moduleNameRegex the module name regular expression
     */
    void excludeModuleByRegex(String groupRegex, String moduleNameRegex);

    /**
     * Declares that a specific module version shouldn't be searched for in this repository.
     *

     * The version notation for a regex will be matched against a single version and does not support range notations.
     *
     * @param group the group name
     * @param moduleName the module name
     * @param version the module version
     */
    void excludeVersion(String group, String moduleName, String version);

    /**
     * Declares that a specific module version shouldn't be searched for in this repository, using regular expressions.
     *

     * The version notation for a regex will be matched against a single version and does not support range notations.
     *
     * @param groupRegex the group name
     * @param moduleNameRegex the module name
     * @param versionRegex the module version
     */
    void excludeVersionByRegex(String groupRegex, String moduleNameRegex, String versionRegex);

    /**
     * Declares that this repository should only be used for a specific
     * set of configurations. Defaults to any configuration
     *
     * @param configurationNames the names of the configurations the repository will be used for
     */
    void onlyForConfigurations(String... configurationNames);

    /**
     * Declares that this repository should not be used for a specific
     * set of configurations. Defaults to any configuration
     *
     * @param configurationNames the names of the configurations the repository will not be used for
     */
    void notForConfigurations(String... configurationNames);

    /**
     * Declares that this repository will only be searched if the consumer requires a
     * specific attribute.
     * @param attribute the attribute
     * @param validValues the list of accepted values
     * @param <T> the type of the attribute
     */
    @SuppressWarnings("unchecked")
    <T> void onlyForAttribute(Attribute<T> attribute, T... validValues);
}


text:
package com.stvn.nscreen.common;

/**
 * Created by leejunghoon on 15. 10. 9..
 */

public class SearchVodDataObject {

    public String HDAssetCount;
    public String SDAssetCount;
    public String UHDAssetCount;
    public String assetBundle;
    public String assetFree;
    public String assetHot;
    public String assetNew;
    public String assetSeriesLink;
    public String categoryId;
    public String contentGroupId;
    public String director;
    public String episodePeerExistence;
    public String genre;
    public String imageFileName;
    public String isFavorite;
    public String isLiked;
    public String likedCount;
    public String mobilePublicationRight;
    public String primaryAssetId;
    public String production;
    public String promotionSticker;
    public String rating;
    public String reviewRating;
    public String runningTime;
    public String smallImageFileName;
    public String starring;
    public String synopsis;
    public String title;
    public String eventTargetId;
    public String eventTargetType;
    public String isNew;
    public String hot;

    @Override
    public String toString() {
        return "SearchVodDataObject{" +
                "HDAssetCount='" + HDAssetCount + '\'' +
                ", SDAssetCount='" + SDAssetCount + '\'' +
                ", UHDAssetCount='" + UHDAssetCount + '\'' +
                ", assetBundle='" + assetBundle + '\'' +
                ", assetFree='" + assetFree + '\'' +
                ", assetHot='" + assetHot + '\'' +
                ", assetNew='" + assetNew + '\'' +
                ", assetSeriesLink='" + assetSeriesLink + '\'' +
                ", categoryId='" + categoryId + '\'' +
                ", contentGroupId='" + contentGroupId + '\'' +
                ", director='" + director + '\'' +
                ", episodePeerExistence='" + episodePeerExistence + '\'' +
                ", genre='" + genre + '\'' +
                ", imageFileName='" + imageFileName + '\'' +
                ", isFavorite='" + isFavorite + '\'' +
                ", isLiked='" + isLiked + '\'' +
                ", likedCount='" + likedCount + '\'' +
                ", mobilePublicationRight='" + mobilePublicationRight + '\'' +
                ", primaryAssetId='" + primaryAssetId + '\'' +
                ", production='" + production + '\'' +
                ", promotionSticker='" + promotionSticker + '\'' +
                ", rating='" + rating + '\'' +
                ", reviewRating='" + reviewRating + '\'' +
                ", runningTime='" + runningTime + '\'' +
                ", smallImageFileName='" + smallImageFileName + '\'' +
                ", starring='" + starring + '\'' +
                ", synopsis='" + synopsis + '\'' +
                ", title='" + title + '\'' +
                ", eventTargetId='" + eventTargetId + '\'' +
                ", eventTargetType='" + eventTargetType + '\'' +
                ", isNew='" + isNew + '\'' +
                ", hot='" + hot + '\'' +
                '}';
    }
}


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Model;

use Oro\Bundle\WorkflowBundle\Configuration\WorkflowConfiguration;
use Oro\Bundle\WorkflowBundle\Form\Type\WorkflowTransitionType;
use Oro\Bundle\WorkflowBundle\Model\Transition;
use Oro\Bundle\WorkflowBundle\Model\TransitionAssembler;
use Oro\Bundle\WorkflowBundle\Model\Condition\Configurable as ConfigurableCondition;
use Oro\Bundle\WorkflowBundle\Model\Action\Configurable as ConfigurableAction;

class TransitionAssemblerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $formOptionsAssembler;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $conditionFactory;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $actionFactory;

    /**
     * @var TransitionAssembler
     */
    protected $assembler;

    /**
     * @var array
     */
    protected $transitionDefinitions = array(
        'empty_definition' => array(),
        'with_pre_condition' => array(
            'pre_conditions' => array('@true' => null)
        ),
        'with_condition' => array(
            'conditions' => array('@true' => null)
        ),
        'with_post_actions' => array(
            'post_actions' => array('@assign_value' => array('parameters' => array('$attribute', 'first_value')))
        ),
        'full_definition' => array(
            'page_template' => 'Test:Page:template',
            'dialog_template' => 'Test:Dialog:template',
            'pre_conditions' => array('@true' => null),
            'conditions' => array('@true' => null),
            'post_actions' => array('@assign_value' => array('parameters' => array('$attribute', 'first_value'))),
        )
    );

    protected function setUp()
    {
        $this->formOptionsAssembler = $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\FormOptionsAssembler')
            ->disableOriginalConstructor()
            ->setMethods(array('assemble'))
            ->getMock();

        $this->conditionFactory = $this->getMockBuilder('Oro\Component\ConfigExpression\ExpressionFactory')
            ->disableOriginalConstructor()
            ->getMock();
        $this->actionFactory = $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\Action\ActionFactory')
            ->disableOriginalConstructor()
            ->getMock();
        $this->assembler = new TransitionAssembler(
            $this->formOptionsAssembler,
            $this->conditionFactory,
            $this->actionFactory
        );
    }

    /**
     * @expectedException \Oro\Bundle\WorkflowBundle\Exception\AssemblerException
     * @dataProvider missedTransitionDefinitionDataProvider
     * @param array $configuration
     */
    public function testAssembleNoRequiredTransitionDefinitionException($configuration)
    {
        $this->assembler->assemble($configuration, array(), array(), array());
    }

    public function missedTransitionDefinitionDataProvider()
    {
        return array(
            'no options' => array(
                array(
                    'name' => array()
                )
            ),
            'no transition_definition' => array(
                array(
                    'name' => array(
                        '' => 'test'
                    )
                )
            )
        );
    }

    /**
     * @expectedException \Oro\Bundle\WorkflowBundle\Exception\AssemblerException
     * @dataProvider incorrectTransitionDefinitionDataProvider
     * @param array $definitions
     */
    public function testUnknownTransitionDefinitionAssembler($definitions)
    {
        $configuration = array(
            'test' => array(
                'transition_definition' => 'unknown'
            )
        );
        $this->assembler->assemble($configuration, $definitions, array(), array());
    }

    public function incorrectTransitionDefinitionDataProvider()
    {
        return array(
            'no definitions' => array(
                array()
            ),
            'definitions as null' => array(
                array('some' => null)
            ),
            'unknown definition' => array(
                array('known' => array())
            )
        );
    }

    /**
     * @expectedException \Oro\Bundle\WorkflowBundle\Exception\AssemblerException
     * @dataProvider incorrectStepsDataProvider
     * @param array $steps
     */
    public function testUnknownStepException($steps)
    {
        $configuration = array(
            'test' => array(
                'transition_definition' => 'transition_definition',
                'label' => 'label',
                'step_to' => 'unknown'
            )
        );
        $definitions = array('transition_definition' => array());
        $this->assembler->assemble($configuration, $definitions, $steps, array());
    }

    public function incorrectStepsDataProvider()
    {
        return array(
            'no steps' => array(
                array()
            ),
            'unknown step' => array(
                array('known' => $this->createStep())
            )
        );
    }

    /**
     * @dataProvider configurationDataProvider
     * @param array $configuration
     * @param array $transitionDefinition
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function testAssemble(array $configuration, array $transitionDefinition)
    {
        $steps = array(
            'step' => $this->createStep()
        );

        $attributes = array(
            'attribute' => $this->createAttribute()
        );

        $expectedCondition      = null;
        $expectedPreCondition   = $this->createCondition();
        $expectedAction         = null;
        $defaultAclPrecondition = array();
        $preConditions          = array();

        if (isset($configuration['acl_resource'])) {
            $defaultAclPrecondition = array(
                '@acl_granted' => array(
                    'parameters' => array($configuration['acl_resource'])
                )
            );

            if (isset($configuration['acl_message'])) {
                $defaultAclPrecondition['@acl_granted']['message'] = $configuration['acl_message'];
            }
        }

        if (isset($transitionDefinition['pre_conditions']) && $defaultAclPrecondition) {
            $preConditions = array(
                '@and' => array(
                    $defaultAclPrecondition,
                    $transitionDefinition['pre_conditions']
                )
            );
        } elseif (isset($transitionDefinition['pre_conditions'])) {
            $preConditions = $transitionDefinition['pre_conditions'];
        }

        $count = 0;

        if ($preConditions) {
            $this->conditionFactory->expects($this->at($count))
                ->method('create')
                ->with(ConfigurableCondition::ALIAS, $preConditions)
                ->will($this->returnValue($expectedPreCondition));
            $count++;
        }

        if (array_key_exists('conditions', $transitionDefinition)) {
            $expectedCondition = $this->createCondition();
            $this->conditionFactory->expects($this->at($count))
                ->method('create')
                ->with(ConfigurableCondition::ALIAS, $transitionDefinition['conditions'])
                ->will($this->returnValue($expectedCondition));
        }

        $actionFactoryCallCount = 0;

        if (array_key_exists('post_actions', $transitionDefinition)) {
            $actionFactoryCallCount++;
        }

        if (array_key_exists('init_actions', $transitionDefinition)) {
            $actionFactoryCallCount++;
        }

        if ($actionFactoryCallCount) {
            $expectedAction = $this->createAction();
            $this->actionFactory->expects($this->exactly($actionFactoryCallCount))
                ->method('create')
                ->with(ConfigurableAction::ALIAS, $transitionDefinition['post_actions'])
                ->will($this->returnValue($this->createAction()));
        }

        $this->formOptionsAssembler->expects($this->once())
            ->method('assemble')
            ->with(
                isset($configuration['form_options']) ? $configuration['form_options'] : array(),
                $attributes,
                'transition',
                'test'
            )
            ->will($this->returnArgument(0));

        $transitions = $this->assembler->assemble(
            array('test' => $configuration),
            $this->transitionDefinitions,
            $steps,
            $attributes
        );

        $configuration = array_merge(
            array(
                'is_start' => false,
                'form_type' => WorkflowTransitionType::NAME,
                'form_options' => array(),
                'frontend_options' => array(),
            ),
            $configuration
        );

        $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $transitions);
        $this->assertCount(1, $transitions);
        $this->assertTrue($transitions->containsKey('test'));

        /** @var Transition $actualTransition */
        $actualTransition = $transitions->get('test');
        $this->assertEquals('test', $actualTransition->getName(), 'Incorrect name');
        $this->assertEquals($steps['step'], $actualTransition->getStepTo(), 'Incorrect step_to');
        $this->assertEquals($configuration['label'], $actualTransition->getLabel(), 'Incorrect label');

        $expectedDisplayType = WorkflowConfiguration::DEFAULT_TRANSITION_DISPLAY_TYPE;

        if (isset($configuration['display_type'])) {
            $expectedDisplayType = $configuration['display_type'];
        }

        $this->assertEquals($expectedDisplayType, $actualTransition->getDisplayType(), 'Incorrect display type');
        $this->assertEquals(
            $configuration['frontend_options'],
            $actualTransition->getFrontendOptions(),
            'Incorrect frontend_options'
        );
        $this->assertEquals($configuration['is_start'], $actualTransition->isStart(), 'Incorrect is_start');
        $this->assertEquals($configuration['form_type'], $actualTransition->getFormType(), 'Incorrect form_type');
        $this->assertEquals(
            $configuration['form_options'],
            $actualTransition->getFormOptions(),
            'Incorrect form_options'
        );

        $this->assertTemplate('page', $configuration, $actualTransition);
        $this->assertTemplate('dialog', $configuration, $actualTransition);

        if ($preConditions) {
            $this->assertEquals($expectedPreCondition, $actualTransition->getPreCondition(), 'Incorrect Precondition');
        } else {
            $this->assertNull($actualTransition->getPreCondition(), 'Incorrect Precondition');
        }

        $this->assertEquals($expectedCondition, $actualTransition->getCondition(), 'Incorrect condition');
        $this->assertEquals($expectedAction, $actualTransition->getPostAction(), 'Incorrect post_action');
    }

    /**
     * @param string $templateType
     * @param array $configuration
     * @param $actualTransition
     */
    protected function assertTemplate($templateType, $configuration, $actualTransition)
    {
        $configKey = $templateType . '_template';
        $getter    = 'get' . ucfirst($templateType) . 'Template';

        if (array_key_exists($configKey, $configuration)) {
            $this->assertEquals($configuration[$configKey], $actualTransition->$getter());
        } else {
            $this->assertNull($actualTransition->$getter());
        }
    }

    public function configurationDataProvider()
    {
        return array(
            'empty_definition' => array(
                'configuration' => array(
                    'transition_definition' => 'empty_definition',
                    'label' => 'label',
                    'step_to' => 'step',
                    'form_type' => 'custom_workflow_transition',
                    'display_type' => 'page',
                    'form_options' => array(
                        'attribute_fields' => array(
                            'attribute_on_be' => array('type' => 'text')
                        )
                    ),
                    'frontend_options' => array('class' => 'foo', 'icon' => 'bar'),
                ),
                'transitionDefinition' => $this->transitionDefinitions['empty_definition'],
            ),
            'with_condition' => array(
                'configuration' => array(
                    'transition_definition' => 'with_condition',
                    'label' => 'label',
                    'step_to' => 'step',
                ),
                'transitionDefinition' => $this->transitionDefinitions['with_condition'],
            ),
            'with_post_actions' => array(
                'configuration' => array(
                    'transition_definition' => 'with_post_actions',
                    'label' => 'label',
                    'step_to' => 'step',
                ),
                'transitionDefinition' => $this->transitionDefinitions['with_post_actions'],
            ),
            'full_definition' => array(
                'configuration' => array(
                    'transition_definition' => 'full_definition',
                    'acl_resource' => 'test_acl',
                    'acl_message' => 'test acl message',
                    'label' => 'label',
                    'step_to' => 'step',
                ),
                'transitionDefinition' => $this->transitionDefinitions['full_definition'],
            ),
            'start_transition' => array(
                'configuration' => array(
                    'transition_definition' => 'empty_definition',
                    'acl_resource' => 'test_acl',
                    'acl_message' => 'test acl message',
                    'label' => 'label',
                    'step_to' => 'step',
                    'is_start' => true,
                ),
                'transitionDefinition' => $this->transitionDefinitions['empty_definition'],
            ),
        );
    }

    protected function createStep()
    {
        return $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\Step')
            ->disableOriginalConstructor()
            ->getMock();
    }

    protected function createAttribute()
    {
        return $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\Attribute')
            ->disableOriginalConstructor()
            ->getMock();
    }

    protected function createCondition()
    {
        return $this->getMockBuilder('Oro\Component\ConfigExpression\ExpressionInterface')
            ->getMockForAbstractClass();
    }

    protected function createAction()
    {
        return $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\Action\ActionInterface')
            ->getMockForAbstractClass();
    }
}


text:
'use strict';

angular.module('myApp.business', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/business', {
    templateUrl: 'business/business.html',
    controller: 'BusinessCtrl',
  });
}])

.controller('BusinessCtrl', ['$http', function($http) {
	var self=this;
	self.source = 'bloomberg';
	self.currentSource = 'Bloomberg';
    self.select = '#!/business';
    self.currentPage = function(href){
        window.location.href=href;
    }

	self.sources = [
        {source: 'bloomberg',name:'Bloomberg'},
        {source: 'business-insider',name:'Business Insider'},
        {source: 'cnbc',name:'CNBC'},
        {source: 'financial-times',name:'Financial Times'},
        {source: 'fortune', name:'Fortune' },
        {source: 'the-economist', name:'The Economist' },
        {source: 'the-wall-street-journal', name:'Wall Street Journal' },
      ];

    self.initial = self.sources[0].source;

    self.check = 'Bloomberg';
	self.addClass = function(link){
		self.check=link;
	};

    self.changeSource = function(source,name){
    	$http.get('https://newsapi.org/v1/articles?source='+source+'&apiKey=22480be10ea14a548027c1172f4beee6').then(function(response) {
    		self.headlines = response.data.articles;
    		angular.forEach(self.sources, function(value, key) {
    			if(source === value.source){
    				self.currentSource = value.name;
    			}
			});
			self.addClass(name);
		});
    }

	$http.get('https://newsapi.org/v1/articles?source='+self.sources[0].source+'&apiKey=22480be10ea14a548027c1172f4beee6').then(function(response) {
    	self.headlines = response.data.articles;
	});

}]);


text:
\hypertarget{_forward_8php}{}\section{C\+:/wamp/www/polecat/public/core/\+Command/\+Forward.php File Reference}
\label{_forward_8php}\index{C\+:/wamp/www/polecat/public/core/\+Command/\+Forward.\+php@{C\+:/wamp/www/polecat/public/core/\+Command/\+Forward.\+php}}

Encapsulates a command, which is passed from highest ranking to lowest target along Co\+R.

\subsection*{Data Structures}
\begin{DoxyCompactItemize}
\item
interface \hyperlink{interface_able_polecat___command___forward_interface}{Able\+Polecat\+\_\+\+Command\+\_\+\+Forward\+Interface}
\item
class \hyperlink{class_able_polecat___command___forward_abstract}{Able\+Polecat\+\_\+\+Command\+\_\+\+Forward\+Abstract}
\end{DoxyCompactItemize}

\subsection{Detailed Description}
Encapsulates a command, which is passed from highest ranking to lowest target along Co\+R.

\begin{DoxyAuthor}{Author}
Karl Kuhrman
\end{DoxyAuthor}
\begin{DoxyCopyright}{Copyright}
https\+://github.com/kkuhrman/\+Able\+Polecat/blob/master/\+L\+I\+C\+E\+N\+S\+E.\+md \char`\"{}\+B\+D\+S I\+I License\char`\"{}
\end{DoxyCopyright}
\begin{DoxyVersion}{Version}
0.\+7.\+0
\end{DoxyVersion}


text:
package com.quakearts.syshub.test;

import com.quakearts.appbase.Main;

public class TestMain {
	public static void main(String[] args) {
		Main.main(new String[] {TestSysHubMain.class.getName()});
	}
}


text:
package com.asigbe.view;

import java.util.Calendar;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TimePicker;
import android.widget.ViewSwitcher;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker.OnTimeChangedListener;

import com.asigbe.R;

public class DateTimePicker extends RelativeLayout implements
		View.OnClickListener, OnDateChangedListener, OnTimeChangedListener {

	// DatePicker reference
	private DatePicker datePicker;
	// TimePicker reference
	private TimePicker timePicker;
	// ViewSwitcher reference
	private ViewSwitcher viewSwitcher;
	// Calendar reference
	private Calendar mCalendar;
	private Button switchToTimeButton;
	private Button switchToDateButton;
	private Button lastButtonEnabled;

	// Constructor start
	public DateTimePicker(Context context) {
		this(context, null);
	}

	public DateTimePicker(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public DateTimePicker(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		// Get LayoutInflater instance
		final LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		// Inflate myself
		inflater.inflate(R.layout.datetimepicker, this, true);

		// Inflate the date and time picker views
		final LinearLayout datePickerView = (LinearLayout) inflater.inflate(
				R.layout.datepicker, null);
		final LinearLayout timePickerView = (LinearLayout) inflater.inflate(
				R.layout.timepicker, null);

		// Grab a Calendar instance
		this.mCalendar = Calendar.getInstance();
		// Grab the ViewSwitcher so we can attach our picker views to it
		this.viewSwitcher = (ViewSwitcher) this
				.findViewById(R.id.DateTimePickerVS);

		// Init date picker
		this.datePicker = (DatePicker) datePickerView
				.findViewById(R.id.DatePicker);
		this.datePicker.init(this.mCalendar.get(Calendar.YEAR), this.mCalendar
				.get(Calendar.MONTH),
				this.mCalendar.get(Calendar.DAY_OF_MONTH), this);

		// Init time picker
		this.timePicker = (TimePicker) timePickerView
				.findViewById(R.id.TimePicker);
		this.timePicker.setOnTimeChangedListener(this);

		this.switchToTimeButton = (Button) findViewById(R.id.SwitchToTime);
		this.switchToTimeButton.setOnClickListener(this); // shows the time
															// picker
		this.lastButtonEnabled = this.switchToTimeButton;
		this.switchToDateButton = (Button) findViewById(R.id.SwitchToDate);
		this.switchToDateButton.setOnClickListener(this); // shows the date
															// picker

		// Populate ViewSwitcher
		this.viewSwitcher.addView(datePickerView, 0);
		this.viewSwitcher.addView(timePickerView, 1);
	}

	// Constructor end

	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);

		this.timePicker.setEnabled(enabled);
		this.datePicker.setEnabled(enabled);
		if (!enabled) {
			if (this.switchToDateButton.isEnabled()) {
				this.lastButtonEnabled = this.switchToDateButton;
			} else {
				this.lastButtonEnabled = this.switchToTimeButton;
			}
			this.switchToDateButton.setEnabled(enabled);
			this.switchToTimeButton.setEnabled(enabled);
		} else {
			this.lastButtonEnabled.setEnabled(enabled);
		}
	}

	// Called every time the user changes DatePicker values
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		// Update the internal Calendar instance
		this.mCalendar
				.set(year, monthOfYear, dayOfMonth, this.mCalendar
						.get(Calendar.HOUR_OF_DAY), this.mCalendar
						.get(Calendar.MINUTE));
	}

	// Called every time the user changes TimePicker values
	public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
		// Update the internal Calendar instance
		this.mCalendar.set(this.mCalendar.get(Calendar.YEAR), this.mCalendar
				.get(Calendar.MONTH),
				this.mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
	}

	// Handle button clicks
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.SwitchToDate:
			v.setEnabled(false);
			findViewById(R.id.SwitchToTime).setEnabled(true);
			this.viewSwitcher.showPrevious();
			break;

		case R.id.SwitchToTime:
			v.setEnabled(false);
			findViewById(R.id.SwitchToDate).setEnabled(true);
			this.viewSwitcher.showNext();
			break;
		}
	}

	// Convenience wrapper for internal Calendar instance
	public int get(final int field) {
		return this.mCalendar.get(field);
	}

	// Reset DatePicker, TimePicker and internal Calendar instance
	public void reset() {
		final Calendar c = Calendar.getInstance();
		updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c
				.get(Calendar.DAY_OF_MONTH));
		updateTime(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
	}

	// Convenience wrapper for internal Calendar instance
	public long getDateTimeMillis() {
		return this.mCalendar.getTimeInMillis();
	}

	// Convenience wrapper for internal TimePicker instance
	public void setIs24HourView(boolean is24HourView) {
		this.timePicker.setIs24HourView(is24HourView);
	}

	// Convenience wrapper for internal TimePicker instance
	public boolean is24HourView() {
		return this.timePicker.is24HourView();
	}

	// Convenience wrapper for internal DatePicker instance
	public void updateDate(int year, int monthOfYear, int dayOfMonth) {
		this.datePicker.updateDate(year, monthOfYear, dayOfMonth);
	}

	// Convenience wrapper for internal TimePicker instance
	public void updateTime(int currentHour, int currentMinute) {
		this.timePicker.setCurrentHour(currentHour);
		this.timePicker.setCurrentMinute(currentMinute);
	}
}


text:
package com.google.cloud.translate.automl;

import static com.google.common.truth.Truth.assertThat;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for translation "Model API" sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class ModelApiIT {
  private static final String PROJECT_ID = "java-docs-samples-testing";
  private static final String COMPUTE_REGION = "us-central1";
  private ByteArrayOutputStream bout;
  private PrintStream out;
  private PrintStream originalPrintStream;
  private String modelId;

  @Before
  public void setUp() {

    bout = new ByteArrayOutputStream();
    out = new PrintStream(bout);
    originalPrintStream = System.out;
    System.setOut(out);
  }

  @After
  public void tearDown() {
    // restores print statements in the original method
    System.out.flush();
    System.setOut(originalPrintStream);
  }

  @Test
  public void testModelApi() throws Exception {
    // Act
    ModelApi.listModels(PROJECT_ID, COMPUTE_REGION, "");

    // Assert
    String got = bout.toString();
    modelId = got.split("\n")[1].split("/")[got.split("\n")[1].split("/").length - 1];
    assertThat(got).contains("Model id:");
  }
}


text:
using System.Linq;
using System.Management.Instrumentation;

namespace Plugin_Replace
{
    class LineHistory
    {
        private string[] _history;

        public LineHistory(int size)
        {
            _history = new string[size];
            for (var i = 0; i < _history.Length ; i++)
            {
                _history[i] = string.Empty;
            }
        }

        public bool HasMatch(string text)
        {
            return _history.Any(line => line.Contains(text));
        }

        public void AddLine(string line)
        {
            //move all entries in _history down one
            for (var i = 0; i < _history.Length -1; i++)
            {
                _history[i] = _history[i+1];
            }

            //add new line
            _history[_history.Length-1] = line;
        }

        public string GetLine(string text)
        {
            foreach (var line in _history.Reverse())
            {
                if (line.Contains(text))
                {
                    return line;
                }
            }

            throw new InstanceNotFoundException("Could not find " + text + " in History");
        }

    }
}


text:
require("./globals")
_ = require("underscore")
$ = require("jQuery")
d3 = require("d3")

require("./env-assert")

data = require("../lib/ggdata")


text:
class MainMenu : public State
{
public:
	virtual void Enter(shared_ptr<StateParams>& params) { init(params); }
	virtual void Exit() { }
	virtual bool handleEvents(const Control& controls);
	virtual void Update(Controller& ctrl, float elapsedTime);
	virtual void Render(Controller& ctrl);

private:
	shared_ptr<Menu> _menu;

	void init(shared_ptr<StateParams>& params);

};


text:
const webpack = require('webpack');
const WebpackMd5Hash = require('webpack-md5-hash');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');
const path = require('path');

const GLOBALS = {
  'process.env.NODE_ENV': JSON.stringify('production'),
  __DEV__: false
};

module.exports = {
  devtool: 'source-map',
  entry: {
    vendor: path.resolve(__dirname, 'src/vendor'),
    main: path.resolve(__dirname, 'src/index')
  },
  target: 'web',
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].[chunkhash].js'
  },
  plugins: [
    new webpack.ProvidePlugin({
      fetch: 'exports-loader?self.fetch!whatwg-fetch'
    }),
    new WebpackMd5Hash(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor'
    }),
    new webpack.DefinePlugin(GLOBALS),
    new HtmlWebpackPlugin({
      template: 'src/index.ejs',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
      },
      inject: true
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true
    }),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new OfflinePlugin({
      relativePaths: false,
      publicPath: '/',
      autoUpdate: 1000 * 60 * 60 * 4
    })
  ],
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules']
  },
  module: {
    rules: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
      {
        test: /\.(jpe?g|png|gif)$/i,
        loader: 'file-loader',
        options: { name: 'assets/[name].[ext]' }
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          mimetype: 'application/font-woff',
          name: 'assets/[name].[ext]'
        }
      },
      {
        test: /\.ico$/,
        loader: 'file-loader',
        options: { name: '[name].[ext]' }
      },
      { test: /(\.css)$/, use: ['style-loader', 'css-loader'] }
    ]
  }
};