text:
/****************************************
  ==== RESETS
****************************************/

html,body,div,canvas { margin: 0; padding: 0; }
::-moz-selection { color: #333; text-shadow: none; }
::selection {  color: #333; text-shadow: none; }
.clear:after { visibility: hidden; display: block; font-size: 0; content: " "; clear: both; height: 0; }
.clear { display: inline-table; clear: both; }
/* Hides from IE-mac \*/ * html .clear { height: 1%; } .clear { display: block; } /* End hide from IE-mac */

/****************************************
  ==== LAYOUT
****************************************/

html, body { width: 100%; height: 100%; font-family: Open Sans, Helvetica, Verdana, Arial, sans-serif; }
body { }
p.header, p.footer { display: none; }
div.logo { width: 201px; height: 57px; float: left; background: url(logo.png) 0 0 no-repeat; position: relative; z-index: 10; background-size: contain;}
div.title { height: 38px; line-height: 38px; padding: 0 10px; margin: 10px 1px 0 0; float: right; color: #fff; text-align: right; font-size: 18px; position: relative; z-index: 10; }
.template-wrap { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }
.template-wrap canvas { margin: 0 0 10px 0; position: relative; z-index: 9; box-shadow: 0 10px 30px rgba(0,0,0,0.2); -moz-box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
.fullscreen { float: right; position: relative; z-index: 10; padding-top: 10px;}
.title a {color:white; text-decoration: none; font-size: 115%;}

div.rockstarVRContainer {
    background-image: url("vrbackground.jpg"); background-size: cover;
    min-height: 900px;
}
.template .template-wrap { }
.template .template-wrap canvas { }

redpajama_set_name: RedPajamaGithub


text:
package model

import java.util.Date
import com.datastax.driver.core._
import collection.JavaConversions._

class CassandraStorage extends Storage {
  private val cluster = new Cluster.Builder().addContactPoint("localhost").build()
  private val session: Session = cluster.connect("msgstorage")

  private val createUser =
    session.prepare("insert into users (username, name) values (?, ?)").enableTracing()

  private val deleteChatQuery = session.prepare("delete from chats where user = ? and opponent = ?")

  private val createChat = session.prepare("insert into chats (user, opponent, chat, created) values (?, ?, ?, ?) if not exists")

  private val findChatQuery = session.prepare("select * from chats where user = ? and opponent = ?")

  private val createMessage = session.prepare("insert into messages (chat, ts, author, msg) values (?, now(), ?, ?)")

  private val chatMessages = session.prepare("select author, msg, dateOf(ts) as created from messages where chat = ?")

  def findUserOrCreate(username: String) =
    session.execute("select * from users where username = ?", username)
      .map(r => User(r.getString("username"), r.getString("name"))).headOption
      .getOrElse(throw new IllegalArgumentException("User %s has been not found!".format(username)))

  def deleteChat(u1: User, u2: User) = session.execute(deleteChatQuery.bind(u1.username, u2.username))

  def findChat(u1: User, u2: User) = {
    session.execute(findChatQuery.bind(u2.username, u1.username)).headOption.getOrElse(createNewChat(u2, u1))
    session.execute(findChatQuery.bind(u1.username, u2.username)).map(r => Chat(r.getString("chat"))).headOption
  }

  def findChatOrCreate(u1: User, u2: User) = findChat(u1, u2) getOrElse createNewChat(u1, u2)

  def createNewChat(u1: User, u2: User) = {
    val chat = Chat(chatId(u1, u2))
    session.execute(createChat.bind(u1.username, u2.username, chat.id, chat.created))
    println("Chat %s for %s and %s is created".format(chat, u1, u2))
    session.execute(createChat.bind(u2.username, u1.username, chat.id, chat.created))
    println("Chat %s for %s and %s is created".format(chat, u2, u1))
    chat
  }

  def postMessage(chat: Chat, author: User, text: String) = {
    session.execute(createMessage.bind(chat.id, author.username, text))
    Message(author.username, text, new Date)
  }

  def findMessages(u1: User, u2: User) =
    findChat(u1, u2).map(ch =>
      for (r <- session.execute(chatMessages.bind(ch.id)) if ch.created.before(r.getDate("created"))) yield
        Message(r.getString("author"), r.getString("msg"), r.getDate(2))
    ) getOrElse Nil

  def shutdown = {
    println("Shutting down Cassandra session...")
    cluster.shutdown()
  }

  def save(user: User) = {
    session.execute(createUser.bind(user.username, user.name))
    user
  }

  println("CassandraStorage is initialized")
}


text:
@interface TAListResponseModel : MTLModel<MTLJSONSerializing>

@property (nonatomic) NSUInteger page;
@property (nonatomic, strong) NSArray *results;
@property (nonatomic) NSUInteger totalPages;
@property (nonatomic) NSUInteger totalResults;

@end


text:
A consumer group must be created in order to retrieve messages. A maximum of three consumer groups can be created in each queue.

Messages in a queue are retrievable to all consumer groups created in that queue.

## Prerequisites

A queue has been created.

## Procedure

1.  Log in to the management console.
2.  Click  ![](figures/project.png)  in the upper left corner to select a region and a project.
3.  Click  **Service List**, and choose  **Application**  \>  **Distributed Message Service**  to open the DMS console.
4.  In the navigation pane, choose  **Queue Manager**.
5.  Open the  **Create Consumer Group**  dialog box using either of the methods:
    -   Method 1

        In the queue list, choose  **More**  \>  **Create Consumer Group**  in the same row as the queue for which you want to create a consumer group.

    -   Method 2
        1.  Click the name of a queue for which you want to create a consumer group.
        2.  On the queue details page, click the  **Consumer Groups**  tab.
        3.  Click  **Create Consumer Group**.

6.  Specify  **Consumer Group Name**.

    A default consumer group name is generated, which you can change if required. A consumer group name is 1 to 32 characters long. Only letters, digits, underscores \(\_\), and hyphens \(-\) are allowed. Consumer group names must be unique within their queue.

7.  Click  **OK**.


text:
package bigip

import (
	"fmt"

	"github.com/scottdware/go-bigip"
)

// Note: Had to call main something different as the package complained main was in LTM's example
func mainGTM() {
	// Connect to the BIG-IP system.
	f5 := bigip.NewSession("gtm.company.com", "admin", "secret", nil)

	// Get a list of all WideIP's, and print their names to the console.
	result, err := f5.GetGTMWideIPs(bigip.ARecord)
	if err != nil {
		fmt.Println(err)
	}

	for _, wideip := range result.GTMWideIPs {
		fmt.Println(wideip.Name)
	}

	// Ordering here just makes things easier.
	// Since Pools can exist without any other reliance, we start there.
	poolConfig := &bigip.GTMAPool{
		Name:      "sample.company.com_pool",
		Partition: "Common",
	}
	f5.AddGTMAPool(poolConfig)

	// Create a WideIP Pool config using our Pool Config
	wipPoolConfig := bigip.GTMWideIPPool{
		Name:      poolConfig.Name,
		Partition: poolConfig.Partition,
	}

	// right now we only have a 1:1 mapping - but WideIPs can have multiple pools
	wipPools := &[]bigip.GTMWideIPPool{wipPoolConfig}

	wipConfig := &bigip.GTMWideIP{
		Name:      "sample.company.com",
		Partition: "Common",
		Pools:     wipPools,
	}

	// Crate the new WideIP
	f5.AddGTMWideIP(wipConfig, bigip.ARecord)

	// Add Pools
	// This part is faked out - and you will have to provide some information to make this work.
	// Namely you have to know the LTM Server which was setup in the GTM (with VirtualServerDiscovery turned on)
	// And you will also need at least one virtual server by full path  e.g.  /partition/name

	fullPathAPool := fmt.Sprintf("/%s/%s", poolConfig.Partition, poolConfig.Name)
	virtualServerPath := "/Common/baseapp_80_vs"
	serverPath := "/Common/someltm"

	// Add the Virtual Server to the list of members for the pool
	f5.CreateGTMAPoolMember(fullPathAPool, serverPath, virtualServerPath)

	// Unwind all the work
	f5.DeleteGTMAPoolMember(fullPathAPool, serverPath, virtualServerPath)

	wipFullPath := fmt.Sprintf("/%s/%s", wipConfig.Partition, wipConfig.Name)
	f5.DeleteGTMWideIP(wipFullPath, bigip.ARecord)

	f5.DeleteGTMPool(fullPathAPool, bigip.ARecord)
}


text:
package org.infinispan.demo.carmart.session;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.infinispan.demo.carmart.session.CarManager;
import org.infinispan.demo.carmart.session.StatisticsProvider;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.stats.Stats;

@Named("stats")
@RequestScoped
public class LocalStatisticsProvider implements StatisticsProvider {

    @Inject
    private CacheContainerProvider provider;

    private Stats stats;

    @PostConstruct
    public void getStatsObject() {
        stats = ((DefaultCacheManager) provider.getCacheContainer()).getCache(CarManager.CACHE_NAME).getAdvancedCache()
                .getStats();
    }

    public String getRetrievals() {
        return String.valueOf(stats.getRetrievals());
    }

    public String getStores() {
        return String.valueOf(stats.getStores());
    }

    public String getCurrentEntries() {
        return String.valueOf(stats.getCurrentNumberOfEntries());
    }

    public String getHits() {
        return String.valueOf(stats.getHits());
    }

    public String getMisses() {
        return String.valueOf(stats.getMisses());
    }

    public String getRemoveHits() {
        return String.valueOf(stats.getRemoveMisses());
    }
}


text:
NSString * const A0LockNotificationLoginSuccessful = @"A0LockNotificationLoginSuccessful";
NSString * const A0LockNotificationLoginFailed = @"A0LockNotificationLoginFailed";

NSString * const A0LockNotificationSignUpSuccessful = @"A0LockNotificationSignUpSuccessful";
NSString * const A0LockNotificationSignUpFailed = @"A0LockNotificationSignUpFailed";

NSString * const A0LockNotificationChangePasswordSuccessful = @"A0LockNotificationChangePasswordSuccessful";
NSString * const A0LockNotificationChangePasswordFailed = @"A0LockNotificationChangePasswordFailed";

NSString * const A0LockNotificationLockDismissed = @"A0LockNotificationLockDismissed";

NSString * const A0LockNotificationErrorParameterKey = @"A0LockNotificationErrorParameterKey";
NSString * const A0LockNotificationEmailParameterKey = @"A0LockNotificationEmailParameterKey";
NSString * const A0LockNotificationConnectionParameterKey = @"A0LockNotificationConnectionParameterKey";

NSString * const A0LockNotificationUniversalLinkReceived = @"com.auth0.universal-link.received";
NSString * const A0LockNotificationUniversalLinkParameterKey = @"com.auth0.universal-link.url";


text:
package singleton.multithreading;

/**
 * Created by george on 24/2/15.
 */
public class Singleton3 {
    private static Singleton3 instanse;

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        if (instanse == null) {
            synchronized (Singleton3.class) {
                if (instanse == null) {
                    instanse = new Singleton3();
                }
            }
        }
        return instanse;
    }
}


text:
require 'capistrano'
dir = File.dirname(__FILE__)
require File.join(dir, 'rails-recipes', 'console')


text:
package common;

import org.loofer.framework.base.BaseFragment;
import org.loofer.framework.mvp.BasePresenter;
import com.squareup.leakcanary.RefWatcher;

/**
 * Created by jess on 8/5/16 14:11
 * contact with jess.yan.effort@gmail.com
 */
public abstract class WEFragment<P extends BasePresenter> extends BaseFragment<P> {
    protected WEApplication mWeApplication;
    @Override
    protected void ComponentInject() {
        mWeApplication = (WEApplication)mActivity.getApplication();
        setupFragmentComponent(mWeApplication.getAppComponent());
    }

    //提供AppComponent(提供所有的单例对象)给子类,进行Component依赖
    protected abstract void setupFragmentComponent(AppComponent appComponent);

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher watcher = WEApplication.getRefWatcher(getActivity());//使用leakCanary检测fragment的内存泄漏
        if (watcher != null) {
            watcher.watch(this);
        }
        this.mWeApplication =null;
    }
}


text:
from pymongo import MongoClient
from bson.objectid import ObjectId
import gridfs
from BeautifulSoup import BeautifulSoup, SoupStrainer
from dot_utils import get_title_from_url, get_date
import os

mongo_host = os.environ.get('MONGODB_PORT_27017_TCP_ADDR')
mongo_port = os.environ.get('MONGODB_PORT_27017_TCP_PORT')
MONGO_URL = 'mongodb://' + mongo_host + ":" + mongo_port + '/'

client = MongoClient(MONGO_URL)

db = client.eve
fs = gridfs.GridFS(db)
dks = db.dotmarks
users = db.users

LAST_UPDATED = '_updated'

def parse_html(oid):
    cursor = db.attachments.find({'_id': ObjectId(oid)})
    for attachment in cursor:
        html = fs.get(attachment['file']).read()
        # print html
        for link in BeautifulSoup(html, parseOnlyThese=SoupStrainer('a')):
            if link:
                # print link.contents
                dk = {}
                dk['url'] = link['href']
                print "parsing " + link['href']
                if ',' in link['tags']:
                    tags = link['tags'].strip().split(',')
                    if tags:
                        dk['tags'] = tags
                dk['username'] = attachment['user']
                if link.contents[0]:
                    title = link.contents[0]
                    print title
                    if 'http' != title[:4]:
                        dk['title'] = title
                if 'title' not in dk:
                    dk['title'] = get_title_from_url(dk['url'])
                new_id = dks.insert(dk)
                if new_id:
                    users.update({'username': attachment['user']},
                                 {"$inc": {"dots": 1},
                                  "$set": {LAST_UPDATED: get_date()}},
                                 upsert=False)


text:
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WorkflowServices;
using System;

namespace OfficeDevPnP.PowerShell.Commands.Base.PipeBinds
{
    public sealed class WorkflowInstancePipeBind
    {
        private WorkflowInstance _instance;
        private Guid _id;

        public WorkflowInstancePipeBind()
        {
            _instance = null;
            _id = Guid.Empty;
        }

        public WorkflowInstancePipeBind(WorkflowInstance instance)
        {
            this._instance = instance;
        }

        public WorkflowInstancePipeBind(Guid guid)
        {
            this._id = guid;
        }

        public WorkflowInstancePipeBind(string id)
        {
            this._id = Guid.Parse(id);
        }

        public Guid Id
        {
            get { return _id; }
        }

        public WorkflowInstance Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2002-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.beans

/** When attached to a field, this annotation adds a setter and a getter
 *  method following the Java Bean convention. For example:
 *  {{{
 *    @BeanProperty
 *    var status = ""
 *  }}}
 *  adds the following methods to the class:
 *  {{{
 *    def setStatus(s: String) { this.status = s }
 *    def getStatus: String = this.status
 *  }}}
 *  For fields of type `Boolean`, if you need a getter named `isStatus`,
 *  use the `scala.beans.BooleanBeanProperty` annotation instead.
 */
@scala.annotation.meta.field
class BeanProperty extends scala.annotation.StaticAnnotation


text:
import Component from '@ember/component';
import layout from '../../../templates/components/base/db-divider/divider-navigation';

export default Component.extend({
  layout,

  tagName: 'ul',
  classNames: 'nav nav-pills hr-divider-content hr-divider-nav'
});


text:
'use strict';

var crequest = require("../lib/cached_request");

module.exports.get = function(req, res) {
	var settings = {
    title: 'FSTO 2015 Demo',
    name: 'Home',
    selection: 'header-home'
	};

	var headerUrl = "http://"+req.headers.host+"/header?selection=header-home";

  crequest.get(headerUrl, null, function (err, body) {
  	if (err)
  		console.log(err);
  	settings.header = body;
  	res.render('home.dust', settings);
	});
}


text:
/*
 * ProjectEuler/src/c/Problem062.c
 *
 * Cubic permutations
 * ==================
 * Published on Friday, 30th January 2004, 06:00 pm
 *
 * The cube, 41063625 (3453), can be permuted to produce two other cubes:
 * 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube
 * which has exactly three permutations of its digits which are also cube. Find
 * the smallest cube for which exactly five permutations of its digits are cube.
 */

#include <stdio.h>
#include "ProjectEuler/ProjectEuler.h"
#include "ProjectEuler/Problem062.h"

int main(int argc, char** argv) {

    return 0;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Belonidium hysterinum Speg.

### Remarks
null


text:
package org.hisp.dhis.dxf2.metadata.sync;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.hisp.dhis.dxf2.metadata.jobs.MetadataRetryContext;
import org.hisp.dhis.dxf2.metadata.jobs.MetadataSyncJob;
import org.hisp.dhis.dxf2.metadata.sync.exception.MetadataSyncServiceException;
import org.hisp.dhis.dxf2.metadata.version.MetadataVersionDelegate;
import org.hisp.dhis.dxf2.metadata.version.exception.MetadataVersionServiceException;
import org.hisp.dhis.dxf2.sync.*;
import org.hisp.dhis.metadata.version.MetadataVersion;
import org.hisp.dhis.metadata.version.MetadataVersionService;
import org.hisp.dhis.scheduling.JobProgress;
import org.hisp.dhis.scheduling.parameters.MetadataSyncJobParameters;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.util.DateUtils;
import org.springframework.stereotype.Component;

/**
 * Performs the tasks before metadata sync happens
 *
 * @author aamerm
 * @author David Katuscak <katuscak.d@gmail.com>
 */
@Slf4j
@Component
@AllArgsConstructor
public class MetadataSyncPreProcessor
{
    private final SystemSettingManager systemSettingManager;

    private final MetadataVersionService metadataVersionService;

    private final MetadataVersionDelegate metadataVersionDelegate;

    private final TrackerSynchronization trackerSync;

    private final EventSynchronization eventSync;

    private final DataValueSynchronization dataValueSync;

    private final CompleteDataSetRegistrationSynchronization completeDataSetRegistrationSync;

    public void setUp( MetadataRetryContext context, JobProgress progress )
    {
        progress.startingStage( "Setting up metadata synchronisation" );
        progress.runStage( () -> systemSettingManager.saveSystemSetting( SettingKey.METADATAVERSION_ENABLED, true ) );
    }

    public void handleDataValuePush( MetadataRetryContext context, MetadataSyncJobParameters syncParams,
        JobProgress progress )
    {
        SynchronizationResult result = dataValueSync.synchronizeData( syncParams.getDataValuesPageSize(), progress );

        if ( result.status == SynchronizationStatus.FAILURE )
        {
            context.updateRetryContext( MetadataSyncJob.DATA_PUSH_SUMMARY, result.message, null, null );
            throw new MetadataSyncServiceException( result.message );
        }
    }

    public void handleTrackerProgramsDataPush( MetadataRetryContext context, MetadataSyncJobParameters syncParams,
        JobProgress progress )
    {
        SynchronizationResult result = trackerSync.synchronizeData( syncParams.getTrackerProgramPageSize(), progress );

        if ( result.status == SynchronizationStatus.FAILURE )
        {
            context.updateRetryContext( MetadataSyncJob.TRACKER_PUSH_SUMMARY, result.message, null, null );
            throw new MetadataSyncServiceException( result.message );
        }
    }

    public void handleEventProgramsDataPush( MetadataRetryContext context, MetadataSyncJobParameters syncParams,
        JobProgress progress )
    {
        SynchronizationResult result = eventSync.synchronizeData( syncParams.getEventProgramPageSize(), progress );

        if ( result.status == SynchronizationStatus.FAILURE )
        {
            context.updateRetryContext( MetadataSyncJob.EVENT_PUSH_SUMMARY, result.message, null, null );
            throw new MetadataSyncServiceException( result.message );
        }
    }

    public List<MetadataVersion> handleMetadataVersionsList( MetadataRetryContext context, MetadataVersion version,
        JobProgress progress )
    {
        progress.startingStage( "Fetching the list of remote versions"
            + (version == null ? "There is no initial version in the system" : "") );
        try
        {
            List<MetadataVersion> versions = metadataVersionDelegate.getMetaDataDifference( version );

            if ( isRemoteVersionEmpty( version, versions ) )
            {
                progress.completedStage( "There are no metadata versions created in the remote instance." );
                return versions;
            }

            if ( isUsingLatestVersion( version, versions ) )
            {
                progress.completedStage( "Your instance is already using the latest version:" + version );
                return versions;
            }

            MetadataVersion latestVersion = getLatestVersion( versions );
            assert latestVersion != null;

            systemSettingManager.saveSystemSetting( SettingKey.REMOTE_METADATA_VERSION, latestVersion.getName() );
            progress.completedStage( "Remote system is at version: " + latestVersion.getName() );
            return versions;
        }
        catch ( MetadataVersionServiceException e )
        {
            String message = setVersionListErrorInfoInContext( context, version, e );
            progress.failedStage( message );
            throw new MetadataSyncServiceException( message, e );
        }
        catch ( Exception ex )
        {
            if ( ex instanceof MetadataSyncServiceException )
            {
                progress.failedStage( ex );
                throw ex;
            }

            String message = setVersionListErrorInfoInContext( context, version, ex );
            progress.failedStage( ex );
            throw new MetadataSyncServiceException( message, ex );
        }
    }

    private String setVersionListErrorInfoInContext( MetadataRetryContext context, MetadataVersion version,
        Exception e )
    {
        String message = "Exception happened while trying to get remote metadata versions difference " + e.getMessage();
        context.updateRetryContext( MetadataSyncJob.GET_METADATAVERSIONSLIST, e.getMessage(), version, null );
        return message;
    }

    private boolean isUsingLatestVersion( MetadataVersion metadataVersion, List<MetadataVersion> versions )
    {
        return metadataVersion != null && versions.isEmpty();
    }

    private boolean isRemoteVersionEmpty( MetadataVersion metadataVersion, List<MetadataVersion> versions )
    {
        return metadataVersion == null && versions.isEmpty();
    }

    public MetadataVersion handleCurrentMetadataVersion( MetadataRetryContext context, JobProgress progress )
    {
        progress.startingStage( "Getting the current version of the system" );

        try
        {
            MetadataVersion version = metadataVersionService.getCurrentVersion();
            progress.completedStage( "Current Metadata Version of the system: " + version );
            return version;
        }
        catch ( MetadataVersionServiceException ex )
        {
            context.updateRetryContext( MetadataSyncJob.GET_METADATAVERSION, ex.getMessage(), null, null );
            progress.failedStage( ex );
            throw new MetadataSyncServiceException( ex.getMessage(), ex );
        }
    }

    // ----------------------------------------------------------------------------------------
    // Private Methods
    // ----------------------------------------------------------------------------------------

    private MetadataVersion getLatestVersion( List<MetadataVersion> metadataVersionList )
    {
        Collection<Date> dateCollection = new ArrayList<>();

        for ( MetadataVersion metadataVersion : metadataVersionList )
        {
            dateCollection.add( metadataVersion.getCreated() );
        }

        Date maxDate = DateUtils.max( dateCollection );

        for ( MetadataVersion metadataVersion : metadataVersionList )
        {
            if ( metadataVersion.getCreated().equals( maxDate ) )
            {
                return metadataVersion;
            }
        }
        return null;
    }

    public void handleCompleteDataSetRegistrationDataPush( MetadataRetryContext context, JobProgress progress )
    {
        SynchronizationResult result = completeDataSetRegistrationSync.synchronizeData( progress );

        if ( result.status == SynchronizationStatus.FAILURE )
        {
            context.updateRetryContext( MetadataSyncJob.DATA_PUSH_SUMMARY, result.message, null, null );
            throw new MetadataSyncServiceException( result.message );
        }
    }
}


text:
@implementation SPSportsPageBaseModel

+ (JSONKeyMapper *)keyMapper {
    return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{@"sportId":@"id"}];
}

@end


text:
@interface UIResponder (Router)

- (void)routeEvent:(NSString *)eventName userInfo:(NSDictionary *)userInfo;

@end


text:
namespace {

static const int            NUM_CHANNELS = 1;
static const PaSampleFormat SAMPLE_TYPE  = paFloat32;

struct CbUserData {
    std::promise<bool>        done;
    std::size_t               processed;
    const std::vector<float>& signal;
};

class AutoClose {
  private:
    PaStream *m_audioStream_p;

  public:
    AutoClose(PaStream *audioStream);
    AutoClose(const AutoClose&) = delete;
    AutoClose& operator=(const AutoClose&) = delete;
    ~AutoClose();
};

int paCallback(const void                     *input,
               void                           *output,
               unsigned long                   frameCount,
               const PaStreamCallbackTimeInfo *timeInfo,
               PaStreamCallbackFlags           statusFlags,
               void                           *userData);

void paFinishedCallback(void *userData);

}  // anonymous namespace

namespace stinkee {

Diffuser::Diffuser()
: m_initialized(false)
{
}

Diffuser::~Diffuser()
{
    if (m_initialized) {
        Pa_Terminate();
    }
}

int Diffuser::init()
{
    PaError rc = Pa_Initialize();
    if (rc != paNoError) {
        std::cerr << "Failed to initialize portaudio: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
    } else {
        m_initialized = true;
    }

    return rc;
}

int Diffuser::process(const std::vector<float>& signal) const
{
    assert(m_initialized);

    PaError rc;
    CbUserData userData = { std::promise<bool>(), 0, signal };

    PaStreamParameters outputParams;
    outputParams.device = Pa_GetDefaultOutputDevice();
    if (outputParams.device == paNoDevice) {
        std::cerr << "No audio output device available" << std::endl;
        return paNoDevice;                                            // RETURN
    }

    const PaDeviceInfo *deviceInfo = Pa_GetDeviceInfo(outputParams.device);
    outputParams.channelCount = NUM_CHANNELS;
    outputParams.sampleFormat = SAMPLE_TYPE;
    outputParams.suggestedLatency = deviceInfo->defaultLowOutputLatency;
    outputParams.hostApiSpecificStreamInfo = nullptr;

    PaStream *audioStream;
    rc = Pa_OpenStream(
            &audioStream,
            nullptr,
            &outputParams,
            SAMPLING_RATE,
            paFramesPerBufferUnspecified,
            paClipOff | paDitherOff,
            paCallback,
            &userData);

    if (rc != paNoError) {
        std::cerr << "Failed to open output stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;                                                    // RETURN
    }

    // Will close the stream no matter what happens next...
    AutoClose scopeGuard(audioStream);

    rc = Pa_SetStreamFinishedCallback(audioStream, paFinishedCallback);
    if (rc != paNoError) {
        std::cerr << "Failed to set finished callback: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;                                                    // RETURN
    }

    rc = Pa_StartStream(audioStream);
    if (rc != paNoError) {
        std::cerr << "Failed to start stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
        return rc;                                                    // RETURN
    }

    // Wait for the signal to be completely played
    bool finished = userData.done.get_future().get();
    assert(finished);

    return userData.processed == signal.size() ? 0 : 1;
}

}  // library namespace

namespace {

AutoClose::AutoClose(PaStream *audioStream)
: m_audioStream_p(audioStream)
{
}

AutoClose::~AutoClose()
{
    PaError rc = Pa_CloseStream(m_audioStream_p);
    if (rc != paNoError) {
        std::cerr << "Failed to close stream: "
                  << Pa_GetErrorText(rc)
                  << std::endl;
    }
}

int paCallback(const void                     *input,
               void                           *output,
               unsigned long                   frameCount,
               const PaStreamCallbackTimeInfo *timeInfo,
               PaStreamCallbackFlags           statusFlags,
               void                           *userData)
{
    CbUserData *data = (CbUserData *)userData;
    const std::vector<float>& frames = data->signal;
    float *out = (float *)output;

    // Caller may request more frames than there is left in the signal buffer
    // once the end is reached
    std::size_t framesCopied = std::min((std::size_t)frameCount,
                                        frames.size() - data->processed);

    std::memcpy(out,
                &frames[data->processed],
                framesCopied * sizeof (float));

    // At the end of the signal, fill the rest of the buffer with silence
    std::memset(out + framesCopied,
                0,
                (frameCount - framesCopied) * sizeof (float));

    data->processed += framesCopied;
    return data->processed < frames.size() ? paContinue : paComplete;
}

void paFinishedCallback(void *userData)
{
    ((CbUserData *)userData)->done.set_value(true);
}

}  // anonymous namespace


text:
@interface MediaModel : NSManagedObject

@property (nonatomic, retain) NSDate * timeStamp;
@property (nonatomic, retain) NSData * data;
@property (nonatomic, retain) NSString * url;
@property (nonatomic, retain) NSNumber * size;

@end


text: node-debug %appdata%\npm\node_modules\gulp\bin\gulp.js default


text:
<?php

/*
 * Member Registration Page
 * @author Anton Fedianin aka Tony Air <tony@twma.pro>
 * https://tony.twma.pro/
 *
*/

//namespace Members\Accounts;

class MemberRegistrationPage extends Page
{
    private static $defaults = [
        'URLSegment' => 'register',
        'ShowInMenus' => 0,
        'ShowInSearch' => 0,
    ];

    public function canCreate($member = null)
    {
        if (self::get()->count() > 0) {
            return false;
        }

        return true;
    }

    public function requireDefaultRecords()
    {
        if ($this->canCreate()) {
            $className = get_class($this);
            $page = new $className();
            $page->setField('Title', _t($className.'DEFAULTTITLE', 'Register'));
            $page->setField('Content', _t($className.'DEFAULTCONTENT', '
Default registration page content. You can change it in the CMS
'));
            $page->write();
            $page->publish('Stage', 'Live');
            $page->flushCache();
            DB::alteration_message($className.' page created', 'created');
        }
    }

    /**
     * Returns the link or the URLSegment to the account page on this site.
     *
     * @param bool $urlSegment Return the URLSegment only
     *
     * @return string Page Link
     */
    public static function find_link($urlSegment = false)
    {
        $page = self::get_if_account_page_exists();

        return ($urlSegment) ? $page->URLSegment : $page->Link();
    }

    /**
     * Returns the title of the account page on this site.
     *
     * @param bool $urlSegment Return the URLSegment only
     *
     * @return string page Title
     */
    public static function find_title()
    {
        $page = self::get_if_account_page_exists();

        return $page->Title;
    }

    protected static function get_if_account_page_exists()
    {
        $page = self::get();
        if ($page) {
            return $page->first();
        }
        user_error('No Member Registration Page was found. Please create one in the CMS!', E_USER_ERROR);
    }
}

class MemberRegistrationPage_Controller extends Page_Controller
{
    private static $allowed_actions = [
        'LoginForm',
        'Form',
    ];
    private static $url_segment = 'register';

    public function Link($action = null)
    {
        return Controller::join_links(
            Director::baseURL(), self::config()->url_segment, $action
        );
    }

    public function init()
    {
        $backurl = $this->getRequest()->getVar('BackURL');
        if ($backurl) {
            Session::set('BackURL', $backurl);
        }
        parent::init();
    }

    public function Form()
    {
        return MemberRegistrationForm::create($this, 'Form');
    }

    public function LoginForm()
    {
        $form = parent::LoginForm();

        $this->extend('updateLoginForm', $form);

        return $form;
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<parameters>
  <parameter name="appsetting endpoint"
    description="."
    defaultValue="__documentdb_endpoint__"
    tags="">
    <parameterEntry
      kind="XmlFile"
      scope="Web\.config$"
      match="//appSettings[@key='endpoint']/@value" />
  </parameter>
  <parameter name="appsetting authkey"
  description="."
  defaultValue="__documentdb_authkey__"
  tags="">
    <parameterEntry
      kind="XmlFile"
      scope="Web\.config$"
      match="//appSettings[@key='authKey']/@value" />
  </parameter>
</parameters>


text:
(function(){
	var Inception = window.Inception = {

		socket : null,
		identifier: null,
		iframe: null,
		send : null,
		local : null,
		target: null,
		window : window,

		_construct : function(params){
			if (params.level == "top" && window == window.top) Inception.top(params);
			else if (params.level== "child") Inception.child(params);
			else if (params.level== "channel") Inception.channel(params);

			//// if page's get params, use them
			var getParams = Inception.get(window.location.href);
			if (getParams.length) Inception.command(getParams.value);
		},

		_event : function(element,event,listener){
			if(element.addEventListener) {
			 	element.addEventListener(event, listener, false);
			}
			else {
				 element.attachEvent("on" + event, listener);
			}
		},

		get : function(path){

			var ret = {};
			if (path.indexOf('?') > -1) {
				var uri = path.substring((path.indexOf('?') + 1),path.length);
				var split = uri.split('&');
				var hasVals = false;
				for(var i =0; i<split.length; i++){
					var vals = split[i].split('=');
					ret[vals[0]] = vals[1];
					hasVals = true;
				}
				return {length: split.length, value: ret};
			}
			else return {length: 0, value:ret}

		},

		setSocket : function(socket){
			Inception.socket = socket;
		},

		createFrame: function(url){
			Inception.iframe = document.createElement("iframe");
			Inception.iframe.src = url;
			Inception.iframe.width='1px';
			Inception.iframe.height='1px';
			Inception.iframe.style.position="absolute"
			Inception.iframe.style.left="-100px"
			Inception.iframe.style.top="-100px"
			return Inception.iframe;
		},

		top : function(params){
			Inception.identifier = window.location.href;
			Inception.send = Inception.bubbleDown;
		},

		child : function(params){
			Inception.identifier = window.location.href;
			//window.Inception = Inception.bubbleUp;
			if(params.target) {
				Inception.target = params.target;
				Inception.iframe = Inception.createFrame(params.target);
				document.body.appendChild(Inception.iframe);
			}
			Inception.send = Inception.bubbleFrame;
		},

		channel: function(params){
			Inception.identifier = window.location.href;
			if(params.target) {
				Inception.target = params.target;
				Inception.iframe = Inception.createFrame(params.target)
				document.body.appendChild(Inception.iframe);

				Inception.send = Inception.bubbleOne;
			}
			else {
				Inception.send = Inception.bubbleUp;
			}

			window.parent.parent.window.Inception.setSocket(Inception);
		},

		bubbleUp : function(params){
			window.parent.parent.Inception.command(params);
		},

		bubbleDown: function(params){
			params.command='bubbleUp';
			params.next=false;
			Inception.socket.send(params)
		},

		bubbleFrame: function(params){
			params.command='bubbleUp';
			params.next=false;
			Inception.bubbleOne(params)
		},

		bubbleOne: function(params){
			params.level = 'channel';
			if (Inception.target) params.target = Inception.target;
			Inception.iframe.src=Inception.target + '?' + Inception.convert(params);
		},

		convert: function(params){
			var arr = [];
			for(var a in params) {
				arr.push(a + '=' + params[a]);
			}
			return arr.join("&");
		},

		log: function(params){
			console.log(['log',params]);
		},

		command: function(params){
			if (params.command && params.command !== "false") {
				key = params.command;
				if (typeof params.next !== 'undefined') {

					params.command=params.next;
					params.next=false;
				}

				Inception[key](params);
			}
			else {

				if (params.execute) {
				window[params.execute](params);
				}
				//else Inception.send(params);
			}
		}

	}
})();


text:
// @COPYRIGHT@
// Licensed under MIT license (LICENSE.txt)

/** // doc: clxx/cl/mem.cpp {{{
 * \file clxx/cl/mem.cpp
 * \brief Implements the \ref clxx::mem "mem" class
 */ // }}}
#include <clxx/cl/mem.hpp>
#include <clxx/cl/context.hpp>
#include <clxx/cl/clobj_impl.hpp>

namespace clxx {
/* ------------------------------------------------------------------------ */
// Instantiate the base class
template class clobj<cl_mem>;
static_assert(
    sizeof(clobj<cl_mem>) == sizeof(cl_mem),
    "sizeof(clobj<cl_mem>) differs from sizeof(cl_mem)"
);
/* ----------------------------------------------------------------------- */
mem::
mem(context const& ctx, mem_flags_t flags, size_t size, void* host_ptr)
  :Base((cl_mem)NULL)
{
  this->_set_handle(create_buffer(ctx.chk_get(), flags, size, host_ptr), false, false);
}
/* ----------------------------------------------------------------------- */
mem_object_type_t mem::
get_type() const
{
  return _get_pod_info<mem_object_type_t>(*this, mem_info_t::type);
}
/* ----------------------------------------------------------------------- */
mem_flags_t mem::
get_flags() const
{
  return _get_pod_info<mem_flags_t>(*this, mem_info_t::flags);
}
/* ----------------------------------------------------------------------- */
size_t mem::
get_size() const
{
  return _get_pod_info<size_t>(*this, mem_info_t::size);
}
/* ----------------------------------------------------------------------- */
void* mem::
get_host_ptr() const
{
  return _get_pod_info<void*>(*this, mem_info_t::host_ptr);
}
/* ----------------------------------------------------------------------- */
cl_uint mem::
get_map_count() const
{
  return _get_pod_info<cl_uint>(*this, mem_info_t::map_count);
}
/* ----------------------------------------------------------------------- */
context mem::
get_context() const
{
  return context(_get_pod_info<cl_context>(*this, mem_info_t::context));
}
/* ----------------------------------------------------------------------- */
mem mem::
get_associated_memobject() const
{
  return mem(_get_pod_info<cl_mem>(*this, mem_info_t::associated_memobject));
}
/* ----------------------------------------------------------------------- */
size_t mem::
get_offset() const
{
  return _get_pod_info<size_t>(*this, mem_info_t::offset);
}
/* ----------------------------------------------------------------------- */
#if CLXX_CL_H_VERSION_2_0
cl_bool mem::
get_uses_svm_pointer() const
{
  return _get_pod_info<cl_bool>(*this, mem_info_t::uses_svm_pointer);
}
#endif
/* ----------------------------------------------------------------------- */
} // end namespace clxx

// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:


text:
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;

namespace System.Collections.Specialized.Tests
{
    public class ResetTests
    {
        public const int MAX_LEN = 50;          // max length of random strings

        [Fact]
        public void Test01()
        {
            StringCollection sc;
            StringEnumerator en;
            string curr;        // Eumerator.Current value
            bool res;           // boolean result of MoveNext()
            // simple string values
            string[] values =
            {
                "a",
                "aa",
                "",
                " ",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // [] StringEnumerator.Reset()
            //-----------------------------------------------------------------

            sc = new StringCollection();

            //
            // [] on Empty Collection
            //

            //
            //  no exception
            //
            en = sc.GetEnumerator();
            en.Reset();

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = en.Current; });

            //
            // [] Add item to collection and Reset()
            //
            int cnt = sc.Count;
            sc.Add(values[0]);
            if (sc.Count != 1)
            {
                Assert.False(true, string.Format("Error, failed to add item"));
            }

            Assert.Throws<InvalidOperationException>(() => { en.Reset(); });

            //
            // [] on Filled collection
            //
            sc.AddRange(values);
            en = sc.GetEnumerator();

            //
            //  Reset() should not result in any exceptions
            //
            en.Reset();
            en.Reset();

            //
            // [] Move to 0th item and Reset()
            //
            if (!en.MoveNext())
            {
                Assert.False(true, string.Format("Error, MoveNext() returned false"));
            }
            curr = en.Current;
            if (String.Compare(curr, values[0]) != 0)
            {
                Assert.False(true, string.Format("Error, Current returned wrong value"));
            }

            // Reset() and repeat two checks
            en.Reset();
            if (!en.MoveNext())
            {
                Assert.False(true, string.Format("Error, MoveNext() returned false"));
            }
            if (String.Compare(en.Current, curr) != 0)
            {
                Assert.False(true, string.Format("Error, Current returned wrong value"));
            }

            //
            // [] Move to Count/2 item and Reset()
            //
            int ind = sc.Count / 2;

            en.Reset();
            for (int i = 0; i < ind + 1; i++)
            {
                res = en.MoveNext();
                if (!res)
                {
                    Assert.False(true, string.Format("Error, MoveNext returned false", i));
                }

                curr = en.Current;
                if (String.Compare(curr, sc[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i]));
                }
                // while we didn't MoveNext, Current should return the same value
                string curr1 = en.Current;
                if (String.Compare(curr, curr1) != 0)
                {
                    Assert.False(true, string.Format("Error, second call of Current returned different result", i));
                }
            }

            // Reset() and check 0th item
            en.Reset();
            if (!en.MoveNext())
            {
                Assert.False(true, string.Format("Error, MoveNext() returned false"));
            }
            if (String.Compare(en.Current, sc[0]) != 0)
            {
                Assert.False(true, string.Format("Error, Current returned wrong value"));
            }

            //
            // [] Move to the last item and Reset()
            //
            ind = sc.Count;

            en.Reset();
            for (int i = 0; i < ind; i++)
            {
                res = en.MoveNext();
                if (!res)
                {
                    Assert.False(true, string.Format("Error, MoveNext returned false", i));
                }

                curr = en.Current;
                if (String.Compare(curr, sc[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i]));
                }
                // while we didn't MoveNext, Current should return the same value
                string curr1 = en.Current;
                if (String.Compare(curr, curr1) != 0)
                {
                    Assert.False(true, string.Format("Error, second call of Current returned different result", i));
                }
            }

            // Reset() and check 0th item
            en.Reset();
            if (!en.MoveNext())
            {
                Assert.False(true, string.Format("Error, MoveNext() returned false"));
            }
            if (String.Compare(en.Current, sc[0]) != 0)
            {
                Assert.False(true, string.Format("Error, Current returned wrong value"));
            }

            //
            // [] Move beyond the last item and Reset()
            //
            en.Reset();
            for (int i = 0; i < ind; i++)
            {
                res = en.MoveNext();
            }
            // next MoveNext should bring us outside of the collection
            //
            res = en.MoveNext();
            res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }
            // Reset() and check 0th item
            en.Reset();
            if (!en.MoveNext())
            {
                Assert.False(true, string.Format("Error, MoveNext() returned false"));
            }
            if (String.Compare(en.Current, sc[0]) != 0)
            {
                Assert.False(true, string.Format("Error, Current returned wrong value"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            en.Reset();
            Assert.Throws<InvalidOperationException>(() => { curr = en.Current; });

            //
            // [] Modify collection when enumerating
            //
            if (sc.Count < 1)
                sc.AddRange(values);

            //
            // modify the collection and call Reset() before first MoveNext()
            //
            en = sc.GetEnumerator();
            sc.RemoveAt(0);
            Assert.Throws<InvalidOperationException>(() => { en.Reset(); });

            //
            // Enumerate to the middle item of the collection, modify the collection,
            //  and call Reset()
            //
            // create valid enumerator
            //
            en = sc.GetEnumerator();
            for (int i = 0; i < sc.Count / 2; i++)
            {
                res = en.MoveNext();
            }
            curr = en.Current;
            sc.RemoveAt(0);

            // will return previous current
            if (String.Compare(curr, en.Current) != 0)
            {
                Assert.False(true, string.Format("Error, current returned {0} instead of {1}", en.Current, curr));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { en.Reset(); });

            //
            // Enumerate to the last item of the collection, modify the collection,
            //  and call Reset()
            //
            // create valid enumerator
            //
            en = sc.GetEnumerator();
            for (int i = 0; i < sc.Count; i++)
            {
                res = en.MoveNext();
            }
            sc.RemoveAt(0);

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { en.Reset(); });

            //
            // [] Modify collection after enumerating beyond the end
            //
            if (sc.Count < 1)
                sc.AddRange(values);

            en = sc.GetEnumerator();
            for (int i = 0; i < sc.Count; i++)
            {
                res = en.MoveNext();
            }
            res = en.MoveNext();              // should be beyond the end
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true after moving beyond the end"));
            }

            cnt = sc.Count;
            sc.RemoveAt(0);
            if (sc.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove 0-item"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { en.Reset(); });
        }
    }
}


text:
In case you need to check for over- and underflow.

    CREATE OR REPLACE LIBRARY OverflowOpsLib
      AS '/tmp/liboverflowops.so'
      LANGUAGE 'C++';

    CREATE OR REPLACE FUNCTION add
      AS LANGUAGE 'C++'
      NAME 'OverflowAddFactory'
      LIBRARY OverflowOpsLib
      FENCED;

    \set MAX_VINT 9223372036854775807

    SELECT add(:MAX_VINT, 1) AS result;
    ERROR 3399:  Failure in UDx RPC call InvokeProcessBlock(): Error calling processBlock()
    in User Defined Object [add] at [overflowops.cpp:29], error code: 0, message: int out of range

    SELECT add(-:MAX_VINT, -1) AS result;
    ERROR 3399:  Failure in UDx RPC call InvokeProcessBlock(): Error calling processBlock()
    in User Defined Object [add] at [overflowops.cpp:29], error code: 0, message: int out of range


text:
var SinglePolicyCriteria = require('./single-policy-criteria.js');
var SearchCriteria = require('./../../../../core/search/common-criteria.js');

module.exports = AntiAffinityPolicyCriteria;

/**
 * Class that used to filter anti-affinity policies
 * @typedef AntiAffinityPolicyCriteria
 * @type {(SingleAntiAffinityPolicyCriteria|CompositeCriteria)}
 *
 */
function AntiAffinityPolicyCriteria (criteria) {
    return new SearchCriteria(criteria, SinglePolicyCriteria);
}


text:
<?php

namespace Adyen\Payment\Model\Ui;

use Adyen\Payment\Exception\PaymentMethodException;
use Adyen\Payment\Helper\Data;
use Adyen\Payment\Helper\PaymentMethods\PaymentMethodFactory;
use Adyen\Payment\Helper\Recurring;
use Adyen\Payment\Helper\Vault;
use Exception;
use Magento\Vault\Api\Data\PaymentTokenInterface;
use Magento\Vault\Model\Ui\TokenUiComponentInterface;
use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface;
use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory;

class PaymentMethodUiComponentProvider extends AdyenUiComponentProvider implements TokenUiComponentProviderInterface
{

    private $vaultHelper;
    private $paymentMethodFactory;

    /**
     * @param TokenUiComponentInterfaceFactory $componentFactory
     * @param Data $dataHelper
     * @param Vault $vaultHelper
     * @param PaymentMethodFactory $paymentMethodFactory
     */
    public function __construct(
        TokenUiComponentInterfaceFactory $componentFactory,
        Data $dataHelper,
        Vault $vaultHelper,
        PaymentMethodFactory $paymentMethodFactory
    ) {
        parent::__construct($componentFactory, $dataHelper);
        $this->vaultHelper = $vaultHelper;
        $this->paymentMethodFactory = $paymentMethodFactory;
    }

    /**
     * Get UI component for token
     *
     * @param PaymentTokenInterface $paymentToken
     * @return TokenUiComponentInterface
     * @throws PaymentMethodException
     * @throws Exception
     */
    public function getComponentForToken(PaymentTokenInterface $paymentToken): TokenUiComponentInterface
    {
        $tokenType = $this->vaultHelper->getAdyenTokenType($paymentToken);
        $details = json_decode($paymentToken->getTokenDetails() ?: '{}', true);
        // If payment method cannot be created based on the type, this implies that a card token was created using
        // a wallet method (googlepay/applepay etc.). Hence, return the card component for this token.
        try {
            $adyenPaymentMethod = $this->paymentMethodFactory::createAdyenPaymentMethod($details['type']);
        } catch (PaymentMethodException $exception) {
            return $this->getCardComponentForToken($paymentToken);
        }

        $details['icon'] = $this->dataHelper->getVariantIcon($details['type']);
        $createdAt = new \DateTime($paymentToken->getCreatedAt());
        $details['created'] = $createdAt->format('Y-m-d');
        $details['displayToken'] = $tokenType === Recurring::CARD_ON_FILE;
        $details['label'] = $adyenPaymentMethod->getPaymentMethodName();

        return $this->componentFactory->create(
            [
                'config' => [
                    'code' => AdyenHppConfigProvider::HPP_VAULT_CODE,
                    TokenUiComponentProviderInterface::COMPONENT_DETAILS => $details,
                    TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash()
                ],
                'name' => 'Adyen_Payment/js/view/payment/method-renderer/payment_method_vault'
            ]
        );
    }
}


text:
package com.stanleyidesis.quotograph;

import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.StrictMode;
import android.support.annotation.NonNull;

import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.core.CrashlyticsCore;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orm.SugarApp;
import com.stanleyidesis.quotograph.api.LWQError;
import com.stanleyidesis.quotograph.api.controller.LWQImageControllerHelper;
import com.stanleyidesis.quotograph.api.controller.LWQLoggerHelper;
import com.stanleyidesis.quotograph.api.event.IabPurchaseEvent;
import com.stanleyidesis.quotograph.api.receiver.LWQReceiver;
import com.stanleyidesis.quotograph.api.service.LWQWallpaperService;
import com.stanleyidesis.quotograph.billing.util.IabBroadcastReceiver;
import com.stanleyidesis.quotograph.billing.util.IabHelper;
import com.stanleyidesis.quotograph.billing.util.IabLic;
import com.stanleyidesis.quotograph.billing.util.IabResult;
import com.stanleyidesis.quotograph.billing.util.Inventory;
import com.stanleyidesis.quotograph.billing.util.Purchase;
import com.stanleyidesis.quotograph.billing.util.SkuDetails;
import com.stanleyidesis.quotograph.ui.activity.LWQSettingsActivity;
import com.stanleyidesis.quotograph.ui.adapter.ImageMultiSelectAdapter;

import org.greenrobot.eventbus.EventBus;

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

import io.fabric.sdk.android.Fabric;
import io.fabric.sdk.android.services.concurrency.AsyncTask;

public class LWQApplication extends SugarApp implements IabHelper.OnIabSetupFinishedListener,
        IabBroadcastReceiver.IabBroadcastListener,
        IabHelper.QueryInventoryFinishedListener,
        IabHelper.OnIabPurchaseFinishedListener {

    /**
     * Performs asynchronous work to prepare any
     * application components that require disk writes
     * and network access during initialization.
     */
    private class LoadApplicationTask extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            // Bug tracking
            CrashlyticsCore core = new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build();
            Fabric.with(LWQApplication.get(), new Crashlytics.Builder().core(core).build());

            // ImageLoader Requires Disk Access to Initialize
            LWQImageControllerHelper.get();

            // Remote Config
            FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                    .setDeveloperModeEnabled(BuildConfig.DEBUG)
                    .build();
            FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
            firebaseRemoteConfig.setConfigSettings(configSettings);
            firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);

            // Firebase Analytics
            FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics.getInstance(LWQApplication.get());
            firebaseAnalytics.setAnalyticsCollectionEnabled(!BuildConfig.DEBUG);
            firebaseAnalytics.setMinimumSessionDuration(1000);

            // AdMob
            MobileAds.initialize(getApplicationContext(), getString(R.string.admob_app_id));
            MobileAds.setAppMuted(true);

            // Enable
            setComponentsEnabled(!LWQPreferences.isFirstLaunch());

            // Cache images if FTUETask completed
            if (!LWQPreferences.isFirstLaunch()) {
                cacheRemoteImageAssets();
            }
            return null;
        }
    }

    static LWQApplication sApplication;

    IabHelper iabHelper;
    IabBroadcastReceiver iabBroadcastReceiver;
    Set<IabConst.Product> ownedProducts = new HashSet<>();
    Map<IabConst.Product, SkuDetails> productDetails = new HashMap<>();

    @Override
    public void onCreate() {
        if (BuildConfig.DEBUG && !AdMobUtils.adsEnabled()) {
                setStrictMode(true);
        }

        super.onCreate();
        sApplication = this;

        // Billing
        iabHelper = new IabHelper(this, IabLic.retrieveLic());
        iabHelper.enableDebugLogging(BuildConfig.DEBUG, getString(R.string.app_name) + ".BILLING");
        iabHelper.startSetup(this);

        // Asynch Application Dependencies
        new LoadApplicationTask().execute();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        if (getIabHelper() != null) {
            getIabHelper().dispose();
        }
    }

    public static LWQApplication get() {
        return sApplication;
    }

    public static IabHelper getIabHelper() {
        return get().iabHelper;
    }

    public static void fetchRemoteConfig() {
        FirebaseRemoteConfig.getInstance().fetch()
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (!task.isSuccessful()) {
                            return;
                        }
                        FirebaseRemoteConfig.getInstance().activateFetched();
                    }
                });
    }

    public static boolean ownsProduct(IabConst.Product product) {
        return get().ownedProducts.contains(product);
    }

    public static SkuDetails getProductDetails(IabConst.Product product) {
        return get().productDetails.get(product);
    }

    public static void purchaseProduct(Activity activity, IabConst.Product product) {
        getIabHelper().launchPurchaseFlow(activity, product.sku,
                IabConst.PURCHASE_REQUEST_CODE, get());
    }

    public static void setStrictMode(boolean enabled) {
        if (enabled) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());
        } else {
            StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
            StrictMode.setVmPolicy(StrictMode.VmPolicy.LAX);
        }
    }

    public static boolean isWallpaperActivated() {
        final WallpaperManager wallpaperManager = WallpaperManager.getInstance(sApplication);
        final WallpaperInfo wallpaperInfo = wallpaperManager.getWallpaperInfo();
        boolean active = wallpaperInfo != null && sApplication.getPackageName().equalsIgnoreCase(wallpaperInfo.getPackageName());
        LWQLoggerHelper.get().logWallpaperActive(active);
        return active;
    }

    public static void setComponentsEnabled(boolean enabled) {
        ComponentName receiver = new ComponentName(LWQApplication.get(), LWQReceiver.class);
        ComponentName wallpaperService = new ComponentName(LWQApplication.get(), LWQWallpaperService.class);
        ComponentName settingsActivity = new ComponentName(LWQApplication.get(), LWQSettingsActivity.class);
        PackageManager pm = LWQApplication.get().getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(wallpaperService,
                enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(settingsActivity,
                enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    public static int getVersionCode() {
        try {
            return get().getPackageManager()
                    .getPackageInfo(get().getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * Download additional images before the user needs to see them.
     * This is critical when displaying the store and the image selection dialog.
     */
    public static void cacheRemoteImageAssets() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (ImageMultiSelectAdapter.KnownUnsplashCategories category :
                        ImageMultiSelectAdapter.KnownUnsplashCategories.values()) {
                    if (ImageLoader.getInstance().getDiskCache().get(category.imgSource) == null) {
                        ImageLoader.getInstance().loadImage(category.imgSource, null);
                    }
                }
            }
        }).start();
    }

    ////////////////////////////////////////////////////////////
    // IAB Interfaces
    ////////////////////////////////////////////////////////////

    @Override
    public void onIabSetupFinished(IabResult result) {
        // Check for failure
        if (result.isFailure()) {
            LWQError.log(result.getMessage());
            return;
        }
        // If we've detached, return
        if (iabHelper == null) {
            return;
        }
        // Register a receiver
        iabBroadcastReceiver = new IabBroadcastReceiver(this);
        IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
        registerReceiver(iabBroadcastReceiver, broadcastFilter);
        // Query inventory
        receivedBroadcast();
    }

    @Override
    public void receivedBroadcast() {
        // Something has changed, refresh inventory
        List<String> skus = new ArrayList<>(IabConst.Product.values().length);
        for (IabConst.Product product : IabConst.Product.values()) {
            skus.add(product.sku);
        }
        getIabHelper().queryInventoryAsync(true, skus, this);
    }

    @Override
    public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
        if (result.isFailure()) {
            LWQError.log(result.getMessage());
            return;
        }
        ownedProducts.clear();
        for (IabConst.Product product : IabConst.Product.values()) {
            if (inventory.hasPurchase(product.sku)) {
                ownedProducts.add(product);
            }
            productDetails.put(product, inventory.getSkuDetails(product.sku));
        }
    }

    @Override
    public void onIabPurchaseFinished(IabResult result, Purchase info) {
        if (getIabHelper() == null) {
            return;
        }
        if (result.isFailure()) {
            EventBus.getDefault().post(IabPurchaseEvent.failed(result.getMessage()));
            return;
        }
        String purchasedSku = info.getSku();
        IabConst.Product purchased = null;
        for (IabConst.Product product : IabConst.Product.values()) {
            if (product.sku.equalsIgnoreCase(purchasedSku)) {
                purchased = product;
                ownedProducts.add(product);
            }
        }
        if (purchased == null) {
            // Huh?
            return;
        }
        EventBus.getDefault().post(IabPurchaseEvent.success(purchased));
    }
}


text: SELECT x FROM t1 WHERE x REGEXP '^abc' ORDER BY 1;


text:
function OnEnter(element,callback){
    $(element).addClass("boxanimated");
    setTimeout(callback, 2000);
}

function OnClose(callback, element){
    $(element).removeClass("boxanimated");
	setTimeout(callback, 2000);
}


text:
require 'json'
require 'securerandom'
require 'logger'
require 'bunny'
require 'time'
require 'active_support/notifications'

require 'songkick_queue/version'
require 'songkick_queue/client'
require 'songkick_queue/consumer'
require 'songkick_queue/producer'
require 'songkick_queue/worker'
require 'songkick_queue/cli'

module SongkickQueue
  Configuration = Struct.new(
    :logger,
    :host,
    :port,
    :username,
    :password,
    :vhost,
    :max_reconnect_attempts,
    :network_recovery_interval,
    :requeue_rejected_messages,
    :heartbeat_interval
  )

  TooManyReconnectAttemptsError = Class.new(StandardError)

  # Retrieve configuration for SongkickQueue
  #
  # @return [Configuration]
  def self.configuration
    @configuration ||= Configuration.new.tap do |config|
      config.logger = Logger.new(STDOUT)
      config.port = 5672
      config.max_reconnect_attempts = 10
      config.network_recovery_interval = 1.0
      config.requeue_rejected_messages = false
      config.heartbeat_interval = 10
    end
  end

  # Yields a block, passing the memoized configuration instance
  #
  # @yield [Configuration]
  def self.configure
    yield(configuration)

    configuration
  end

  # Publishes the given message to the given queue
  #
  # @see SongkickQueue::Producer#publish for argument documentation
  def self.publish(queue_name, message, options = {})
    producer.publish(queue_name, message, options = {})
  end

  private

  def self.producer
    @producer ||= Producer.new
  end
end


text:
package com.vaadin.v7.data.validator;

import java.io.Serializable;
import java.util.Locale;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator.Context;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.metadata.ConstraintDescriptor;

import com.vaadin.data.BeanValidationBinder;
import com.vaadin.v7.data.Validator;

/**
 * Vaadin {@link Validator} using the JSR-303 (javax.validation)
 * annotation-based bean validation.
 *
 * The annotations of the fields of the beans are used to determine the
 * validation to perform.
 *
 * Note that a JSR-303 implementation (e.g. Hibernate Validator or Apache Bean
 * Validation - formerly agimatec validation) must be present on the project
 * classpath when using bean validation.
 *
 * @since 7.0
 *
 * @author Petri Hakala
 * @author Henri Sara
 *
 * @deprecated See {@link BeanValidationBinder} and {@link com.vaadin.data.validator.BeanValidator}
 */
@Deprecated
public class BeanValidator implements Validator {

    private static final long serialVersionUID = 1L;
    private static ValidatorFactory factory;

    private transient javax.validation.Validator javaxBeanValidator;
    private String propertyName;
    private Class<?> beanClass;
    private Locale locale;

    /**
     * Simple implementation of a message interpolator context that returns
     * fixed values.
     */
    @Deprecated
    protected static class SimpleContext implements Context, Serializable {

        private final Object value;
        private final ConstraintDescriptor<?> descriptor;

        /**
         * Create a simple immutable message interpolator context.
         *
         * @param value
         *            value being validated
         * @param descriptor
         *            ConstraintDescriptor corresponding to the constraint being
         *            validated
         */
        public SimpleContext(Object value, ConstraintDescriptor<?> descriptor) {
            this.value = value;
            this.descriptor = descriptor;
        }

        @Override
        public ConstraintDescriptor<?> getConstraintDescriptor() {
            return descriptor;
        }

        @Override
        public Object getValidatedValue() {
            return value;
        }

    }

    /**
     * Creates a Vaadin {@link Validator} utilizing JSR-303 bean validation.
     *
     * @param beanClass
     *            bean class based on which the validation should be performed
     * @param propertyName
     *            property to validate
     */
    public BeanValidator(Class<?> beanClass, String propertyName) {
        this.beanClass = beanClass;
        this.propertyName = propertyName;
        locale = Locale.getDefault();
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.data.Validator#validate(java.lang.Object)
     */
    @Override
    public void validate(final Object value) throws InvalidValueException {
        Set<?> violations = getJavaxBeanValidator().validateValue(beanClass,
                propertyName, value);
        if (violations.size() > 0) {
            InvalidValueException[] causes = new InvalidValueException[violations
                    .size()];
            int i = 0;
            for (Object v : violations) {
                final ConstraintViolation<?> violation = (ConstraintViolation<?>) v;
                String msg = getJavaxBeanValidatorFactory()
                        .getMessageInterpolator()
                        .interpolate(violation.getMessageTemplate(),
                                new SimpleContext(value,
                                        violation.getConstraintDescriptor()),
                                locale);
                causes[i] = new InvalidValueException(msg);
                ++i;
            }

            throw new InvalidValueException(null, causes);
        }
    }

    /**
     * Sets the locale used for validation error messages.
     *
     * Revalidation is not automatically triggered by setting the locale.
     *
     * @param locale
     */
    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    /**
     * Gets the locale used for validation error messages.
     *
     * @return locale used for validation
     */
    public Locale getLocale() {
        return locale;
    }

    /**
     * Returns the underlying JSR-303 bean validator factory used. A factory is
     * created using {@link Validation} if necessary.
     *
     * @return {@link ValidatorFactory} to use
     */
    protected static ValidatorFactory getJavaxBeanValidatorFactory() {
        if (factory == null) {
            factory = Validation.buildDefaultValidatorFactory();
        }

        return factory;
    }

    /**
     * Returns a shared Validator instance to use. An instance is created using
     * the validator factory if necessary and thereafter reused by the
     * {@link BeanValidator} instance.
     *
     * @return the JSR-303 {@link javax.validation.Validator} to use
     */
    protected javax.validation.Validator getJavaxBeanValidator() {
        if (javaxBeanValidator == null) {
            javaxBeanValidator = getJavaxBeanValidatorFactory().getValidator();
        }

        return javaxBeanValidator;
    }

}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="20dp"
    android:height="20dp"
    android:viewportWidth="20"
    android:viewportHeight="20"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M2.021,17.125V12.229L9.479,9.979L2.021,7.75V2.833L18.833,9.979Z"/>
</vector>


text:
// Class header file.
#include "XString.hpp"

namespace XALAN_CPP_NAMESPACE {

XString::XString(
            const XalanDOMString&   val,
            MemoryManager&          theManager) :
    XStringBase(theManager),
    m_value(val,theManager)
{
}

XString::XString(
            const XalanDOMChar*     val,
            MemoryManager&          theManager) :
    XStringBase(theManager),
    m_value(val, theManager)
{
}

XString::XString(
            const XalanDOMChar*     val,
            XalanSize_t             len,
            MemoryManager&          theManager) :
    XStringBase(theManager),
    m_value(val, theManager, len)
{
}

XString::XString(
            const XString&      source,
            MemoryManager&      theManager) :
    XStringBase(source, theManager),
    m_value(source.m_value, theManager)
{
}

XString::~XString()
{
}

const XalanDOMString&
XString::str(XPathExecutionContext&     /* executionContext */) const
{
    return m_value;
}

const XalanDOMString&
XString::str() const
{
    return m_value;
}

void
XString::str(
            XPathExecutionContext&  /* executionContext */,
            FormatterListener&      formatterListener,
            MemberFunctionPtr       function) const
{
    string(m_value, formatterListener, function);
}

void
XString::str(
            FormatterListener&      formatterListener,
            MemberFunctionPtr       function) const
{
    string(m_value, formatterListener, function);
}

void
XString::str(
            XPathExecutionContext&  /* executionContext */,
            XalanDOMString&         theBuffer) const
{
    theBuffer.append(m_value);
}

void
XString::str(XalanDOMString&    theBuffer) const
{
    theBuffer.append(m_value);
}

double
XString::stringLength(XPathExecutionContext&    /* executionContext */) const
{
    return static_cast<double>(m_value.length());
}

}


text:
@interface PodsDummy_PWAlertController : NSObject
@end
@implementation PodsDummy_PWAlertController
@end


text:
//
// Novell.Directory.Ldap.Utilclass.IntermediateResponseFactory.cs
//
// Author:
//   Anil Bhatia (banil@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//

using System;
using System.Reflection;
using Novell.Directory.Ldap.Rfc2251;

namespace Novell.Directory.Ldap.Utilclass
{
    ///
    ///     Takes an LDAPIntermediateResponse and returns an object
    ///     (that implements the base class LDAPIntermediateResponse)
    ///     based on the OID.
    ///     You can then call methods defined in the child
    ///     class to parse the contents of the response.  The methods available
    ///     depend on the child class. All child classes inherit from the
    ///     LdapIntermediateResponse.
    ///
    public class IntermediateResponseFactory
    {
        /**
             * Used to Convert an RfcLDAPMessage object to the appropriate
             * LDAPIntermediateResponse object depending on the operation being performed.
             *
             * @param inResponse   The LDAPIntermediateResponse object as returned by the
             *                     extendedOperation method in the LDAPConnection object.
             *

             * @return An object of base class LDAPIntermediateResponse.  The actual child
             *         class of this returned object depends on the operation being
             *         performed.
             *
             * @exception LDAPException A general exception which includes an error message
             *                          and an LDAP error code.
             */

        public static LdapIntermediateResponse convertToIntermediateResponse(RfcLdapMessage inResponse)
            //          throws LDAPException
        {
            var tempResponse = new LdapIntermediateResponse(inResponse);
            // Get the oid stored in the Extended response
            var inOID = tempResponse.getID();

            var regExtResponses =
                LdapIntermediateResponse.getRegisteredResponses();
            try
            {
                var extRespClass = regExtResponses.findResponseExtension(inOID);
                if (extRespClass == null)
                {
                    return tempResponse;
                }

                Type[] argsClass = {typeof(RfcLdapMessage)};
                object[] args = {inResponse};
                Exception ex;
                try
                {
                    var extConstructor = extRespClass.GetConstructor(argsClass);

                    try
                    {
                        object resp = null;
                        resp = extConstructor.Invoke(args);
                        return (LdapIntermediateResponse) resp;
                    }
                    catch (UnauthorizedAccessException e)
                    {
                        ex = e;
                    }
                    catch (TargetInvocationException e)
                    {
                        ex = e;
                    }
                }
                catch (MissingMethodException e)
                {
                    // bad class was specified, fall through and return a
                    // default  LDAPIntermediateResponse object
                    ex = e;
                }
            }
            catch (MissingFieldException ex)
            {
                // No match with the OID
                // Do nothing. Fall through and construct a default LDAPControl object.
                Logger.Log.LogWarning("Exception swallowed", ex);
            }
            // If we get here we did not have a registered extendedresponse
            // for this oid.  Return a default LDAPIntermediateResponse object.
            return tempResponse;
        }
    }
}


text:
package org.fiware.apps.marketplace.model.validators;

import org.apache.commons.validator.GenericValidator;
import org.fiware.apps.marketplace.exceptions.ValidationException;

public class BasicValidator {

	private static final int DISPLAY_NAME_MIN_LENGTH = 3;
	private static final int DISPLAY_NAME_MAX_LENGTH = 100;
	private static final int COMMENT_MIN_LENGTH = 0;
	private static final int COMMENT_MAX_LENGTH = 200;
	private static final String DISPLAY_NAME_FIELD = "displayName";
	private static final String COMMENT_FIELD = "comment";

	private static BasicValidator INSTANCE = new BasicValidator();

	private BasicValidator() {

	}

	public static BasicValidator getInstance() {
		return INSTANCE;
	}

	public static int getDisplayNameMaxLength() {
		return DISPLAY_NAME_MAX_LENGTH;
	}

	public static int getCommentMaxLength() {
		return COMMENT_MAX_LENGTH;
	}

	public static int getDisplayNameMinLength() {
		return DISPLAY_NAME_MIN_LENGTH;
	}

	public static int getCommentMinLength() {
		return COMMENT_MIN_LENGTH;
	}

	// BASIC VALIDATORS
	public void validateRequired(String fieldName, String fieldValue) throws ValidationException {
		if (fieldValue == null || fieldValue.length() == 0) {
			throw new ValidationException(fieldName, "This field is required.");
		}
	}

	public void validatePattern(String fieldName, String fieldValue, String regex, String errorMessage)
			throws ValidationException {

		if (fieldValue == null || !fieldValue.matches(regex)) {
			throw new ValidationException(fieldName, errorMessage);
		}
	}

	public void validateDisplayNamePattern(String displayName) throws ValidationException {
		this.validatePattern(DISPLAY_NAME_FIELD, displayName, "^[a-zA-Z0-9. -]+$",
				"This field only accepts letters, numbers, white spaces, dots and hyphens.");
	}

	public void validateURL(String fieldName, String fieldValue) throws ValidationException {
		if (fieldValue == null || !GenericValidator.isUrl(fieldValue)) {
			throw new ValidationException(fieldName, "This field must be a valid URL.");
		}
	}

	public void validateMinLength(String fieldName, String fieldValue, int minLength) throws ValidationException {
		if (fieldValue == null || fieldValue.length() < minLength) {
			throw new ValidationException(fieldName,
					String.format("This field must be at least %d chars.", minLength));
		}
	}

	public void validateMaxLength(String fieldName, String fieldValue, int maxLength) throws ValidationException {
		if (fieldValue == null || fieldValue.length() > maxLength) {
			throw new ValidationException(fieldName,
					String.format("This field must not exceed %d chars.", maxLength));
		}
	}

	public void validateLength(String fieldName, String fieldValue, int minLength, int maxLength) throws ValidationException {
		this.validateMinLength(fieldName, fieldValue, minLength);
		this.validateMaxLength(fieldName, fieldValue, maxLength);

	}

	public void validateEMail(String fieldName, String email) throws ValidationException {
		if (email == null || !GenericValidator.isEmail(email)) {
			throw new ValidationException(fieldName, "This field must be a valid email.");
		}
	}

	// VALIDATORS FOR SPECIFIC FIELDS
	public void validateDisplayNameMinLength(String displayName) throws ValidationException {
		validateMinLength(DISPLAY_NAME_FIELD, displayName, DISPLAY_NAME_MIN_LENGTH);
	}

	public void validateCommentMinLength(String description) throws ValidationException {
		validateMaxLength(COMMENT_FIELD, description, COMMENT_MAX_LENGTH);
	}

	public void validateDisplayNameMaxLength(String displayName) throws ValidationException {
		validateMaxLength(DISPLAY_NAME_FIELD, displayName, DISPLAY_NAME_MAX_LENGTH);
	}

	public void validateCommentMaxLength(String description) throws ValidationException {
		validateMaxLength(COMMENT_FIELD, description, COMMENT_MAX_LENGTH);
	}

	public void validateDisplayName(String displayName) throws ValidationException {
		this.validateDisplayNamePattern(displayName);
		this.validateDisplayNameMinLength(displayName);
		this.validateDisplayNameMaxLength(displayName);
	}

	public void validateComment(String comment) throws ValidationException {
		this.validateCommentMinLength(comment);
		this.validateCommentMaxLength(comment);
	}

}


text:
// Includes
Engine.include("/engine/engine.baseobject.js");
Engine.include("/engine/engine.hostobject.js");

Engine.initObject("BaseComponent", "BaseObject", function() {

/**
 * @class All components extend from this object class.  A component is one
 *        part of an operating whole object (a {@link HostObject}) which is
 *        responsible for only a portion of the overall operation of an in-
 *        game object.  Components are broken down into five major categories:
 *

 *
TYPE_INPUT - Input from controllers (keyboard, mouse, etc.)

 *
TYPE_TRANSFORM - Performs transformations on the host object

 *
TYPE_LOGIC - Handles logical operations that are not related to
 *              input and collision

 *
TYPE_COLLIDER - Determines what this object is possibly colliding
 *              with, and reports those collisions via callbacks to the host.

 *
TYPE_RENDER - Performs some sort of rendering operation to the context

 *

 *        Components are executed in the order listed.  First, all inputs are
 *        checked, then logic is performed.  Logic may be internal to a host object
 *        itself, but some components perform an object-centric type of logic that
 *        can be reused.  Next, collisions are checked.  And finally, rendering can
 *        occur.
 *

 *        Within each component type set, components can be prioritized so that
 *        one component will execute before others.  Such an ordering allows for
 *        multiple components of each type to perform their tasks in an order
 *        that the host defines.
 *
 *
 * @extends BaseObject
 * @constructor
 * @description Create a new instance of a component, setting the name, type, and
 *              update priority of this component compared to all other components
 *              within the host.
 * @param name {String} The name of the component
 * @param type {Number} The type of the component
 * @param priority {Number} A value between 0.0 and 1.0.  Default: 0.5
 */
var BaseComponent = BaseObject.extend(/** @scope BaseComponent.prototype */{

   priority: 0,

   type: -1,

   host: null,

   /**
    * @private
    */
   constructor: function(name, type, priority) {
      Assert((name != null), "You must assign a name to every Component.");
      name = name.toUpperCase();

      Assert((type != null && (type >= BaseComponent.TYPE_INPUT && type <= BaseComponent.TYPE_RENDERING)),
             "You must specify a type for BaseComponent");

      this.type = type;

      Assert((priority != null && (priority >= 0.0 && priority <= 1.0)),
             "Priority must be between 0.0 and 1.0 for BaseComponent");

      this.priority = priority || 0.5;
      this.base(name);
   },

   /**
    * Releases the object back into the object pool.  See {@link PooledObject#release}
    * for more information.
    */
   release: function() {
      this.base();
      this.priority = 0;
      this.type = -1;
      this.host = null;
   },

   /**
    * Establishes the link between this component and its host object.
    * When you assign components to a host object, it will call this method
    * so that each component can refer to its host object, the same way
    * a host object can refer to a component with {@link HostObject#getComponent}.
    *
    * @param hostObject {HostObject} The object which hosts this component
    */
   setHostObject: function(hostObject) {
      this.host = hostObject;
   },

   /**
    * Gets the host object this component is a part of.  When the component was
    * assigned to a host object, the host object will have set itself as the container
    * via {@link #setHostObject}.
    *
    * @return {HostObject}
    */
   getHostObject: function() {
      return this.host;
   },

   /**
    * Get the type of this component.  The value will be one of:
    * {@link #TYPE_INPUT}, {@link #TYPE_TRANSFORM}, {@link #TYPE_LOGIC},
    * {@link #TYPE_COLLIDER}, or {@link #TYPE_RENDERING}
    *
    * @type Number
    */
   getType: function() {
      return this.type;
   },

   /**
    * Set the execution priority of this component with
    * 1.0 being the highest priority and 0.0 being the lowest.  Components
    * within a host object are sorted by type, and then priority.  As such,
    * two components with the same type will be sorted by priority with the
    * higer value executing before the lower value.  This allows you to layer
    * components like the {@link #TYPE_RENDER} componenent so that one effect
    * is drawn before another.
    *
    * @param priority {Number} A value between 0.0 and 1.0
    */
   setPriority: function(priority) {
      this.priority = priority;
      this.getHost().sort();
   },

   /**
    * Returns the priority of this component.
    *
    * @return {Number} A value between 0.0 and 1.0
    */
   getPriority: function() {
      return this.priority;
   },

   /**
    * [ABSTRACT] This method is called by the host object to run the component,
    * updating its state.  Not all components will need an execute
    * method.  However, it is important to include one if you need to
    * update the state of the component each engine cycle.
    *
    * @param renderContext {RenderContext} The context the component will render within.
    * @param time {Number} The global engine time
    */
   execute: function(renderContext, time) {
      // ABSTRACT METHOD DECLARATION
   },

   /**
    * Get the type of the component as a string.
    * @return {String}
    */
   getTypeString: function() {
      var ts = "";
      switch (this.getType()) {
         case BaseComponent.TYPE_INPUT: ts = "TYPE_INPUT"; break;
         case BaseComponent.TYPE_TRANSFORM: ts = "TYPE_TRANSFORM"; break;
         case BaseComponent.TYPE_LOGIC: ts = "TYPE_LOGIC"; break;
         case BaseComponent.TYPE_COLLIDER: ts = "TYPE_COLLIDER"; break;
         case BaseComponent.TYPE_RENDERING: ts = "TYPE_RENDERING"; break;
         default: ts = "TYPE_UNKNOWN";
      }

      return ts;
   }

}, /** @scope BaseComponent.prototype */{

   /**
    * Get the class name of this object
    *
    * @return {String} The string "BaseComponent"
    */
   getClassName: function() {
      return "BaseComponent";
   },

   /**
    * The constant value for INPUT components.
    * @type {Number}
    */
   TYPE_INPUT:          1,

   /**
    * The constant value for TRANSFORM (movement) components.
    * @type {Number}
    */
   TYPE_TRANSFORM:      2,

   /**
    * The constant value for LOGIC components.
    * @type {Number}
    */
   TYPE_LOGIC:          3,

   /**
    * The constant value for COLLIDER components.
    * @type {Number}
    */
   TYPE_COLLIDER:       4,

   /**
    * The constant value for RENDERING components.
    * @type {Number}
    */
   TYPE_RENDERING:      5
});

return BaseComponent;

});


text:
require 'forwardable'

# A rectangular box
class Box
  extend Forwardable
  def_delegators(:@app, :push_matrix, :pop_matrix, :fill, :rotate, :box2d,
                 :stroke_weight, :translate, :rect_mode, :stroke, :rect)
  # We need to keep track of a Body and a width and height
  attr_reader :body, :w, :h

  # Constructor
  def initialize(x, y, w, h, lock)
    @w, @h = w, h
    @app = $app
    # Define and create the body
    bd = BodyDef.new
    bd.position.set(box2d.processing_to_world(Vec2.new(x, y)))
    bd.type = lock ? BodyType::STATIC : BodyType::DYNAMIC

    @body = box2d.createBody(bd)

    # Define the shape -- a  (this is what we use for a rectangle)
    sd = PolygonShape.new
    box2dW = box2d.scale_to_world(w / 2)
    box2dH = box2d.scale_to_world(h / 2)
    sd.setAsBox(box2dW, box2dH)

    # Define a fixture
    fd = FixtureDef.new
    fd.shape = sd
    # Parameters that affect physics
    fd.density = 1
    fd.friction = 0.3
    fd.restitution = 0.5

    body.createFixture(fd)

    # Give it some initial random velocity
    body.setLinearVelocity(Vec2.new(rand(-5..5),rand(2..5)))
    body.setAngularVelocity(rand(-5..5))
  end

  # This function removes the particle from the box2d world
  def killBody
    box2d.destroyBody(body)
  end

  # Drawing the box
  def display
    # We look at each body and get its screen position
    pos = box2d.body_coord(body)
    # Get its angle of rotation
    a = body.getAngle

    rect_mode(Java::ProcessingCore::PConstants::CENTER)
    push_matrix
    translate(pos.x,pos.y)
    rotate(-a)
    fill(127)
    stroke(0)
    stroke_weight(2)
    rect(0,0,w,h)
    pop_matrix
  end
end


text:
package com.crossover.trial.weather.domain;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

import com.fasterxml.jackson.annotation.JsonIgnore;

/** Sensor information for a particular location */
public class Weather {

	/** temperature in degrees celsius */
	private DataPoint temperature;

	/** wind speed in km/h */
	private DataPoint wind;

	/** humidity in percent */
	private DataPoint humidity;

	/** precipitation in cm */
	private DataPoint precipitation;

	/** pressure in mmHg */
	private DataPoint pressure;

	/** cloud cover percent from 0 - 100 (integer) */
	private DataPoint cloudCover;

	/** the last time this data was updated, in milliseconds since UTC epoch */
	private long lastUpdateTime;

	@JsonIgnore
	public boolean isEmpty() {
		return cloudCover == null && //
				humidity == null && //
				precipitation == null && //
				pressure == null && //
				temperature == null && //
				wind == null;
	}

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

	public DataPoint getTemperature() {
		return temperature;
	}

	public void setTemperature(DataPoint temperature) {
		this.temperature = temperature;
	}

	public DataPoint getWind() {
		return wind;
	}

	public void setWind(DataPoint wind) {
		this.wind = wind;
	}

	public DataPoint getHumidity() {
		return humidity;
	}

	public void setHumidity(DataPoint humidity) {
		this.humidity = humidity;
	}

	public DataPoint getPrecipitation() {
		return precipitation;
	}

	public void setPrecipitation(DataPoint precipitation) {
		this.precipitation = precipitation;
	}

	public DataPoint getPressure() {
		return pressure;
	}

	public void setPressure(DataPoint pressure) {
		this.pressure = pressure;
	}

	public DataPoint getCloudCover() {
		return cloudCover;
	}

	public void setCloudCover(DataPoint cloudCover) {
		this.cloudCover = cloudCover;
	}

	public long getLastUpdateTime() {
		return this.lastUpdateTime;
	}

	public void setLastUpdateTime(long lastUpdateTime) {
		this.lastUpdateTime = lastUpdateTime;
	}
}


text:
module Crumpet
  class Railtie < Rails::Railtie
    initializer 'crumpet.setup_action_controller' do |app|
      ActiveSupport.on_load :action_controller do
        self.class_eval do
          include Crumpet::ControllerAdditions
        end
      end
    end

    initializer 'crumpet.setup_action_view' do |app|
      ActiveSupport.on_load :action_view do
        self.class_eval do
          include Crumpet::ViewHelpers
        end
      end
    end
  end
end