text:
FILE(REMOVE_RECURSE
  "CMakeFiles/misc05_picking_slow_easy.dir/misc05_picking/misc05_picking_slow_easy.cpp.o"
  "CMakeFiles/misc05_picking_slow_easy.dir/common/shader.cpp.o"
  "CMakeFiles/misc05_picking_slow_easy.dir/common/controls.cpp.o"
  "CMakeFiles/misc05_picking_slow_easy.dir/common/texture.cpp.o"
  "CMakeFiles/misc05_picking_slow_easy.dir/common/objloader.cpp.o"
  "CMakeFiles/misc05_picking_slow_easy.dir/common/vboindexer.cpp.o"
  "misc05_picking_slow_easy.pdb"
  "misc05_picking_slow_easy"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/misc05_picking_slow_easy.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)

redpajama_set_name: RedPajamaGithub


text:
body {
    background-color: #777779;
}

h1 {
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    background-color: aliceblue;
    color: #777779;
    text-align: center;
    font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
    font-size : 500%;
    vertical-align: middle;
    line-height: normal;
    margin-left: 10%;
    margin-right: 10%;
}

p {
    color: aliceblue;
    text-align: center;
    margin: 5%;
    font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
}

nav, a {
    font-family: "Lucinda Grande", "Lucinda Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
    color: aliceblue;
    position: fixed;
    right: 10px;
    top: 10px;
    font-size: 125%;
}

#title {
    border: none;
    background-color: aliceblue;
    font-size: 120%;
    color: transparent;
    text-shadow: 0 0 0 #777779;
    text-align: center;
}

#content {
    border: none;
    background-color: #777779;
    font-size: 120%;
    color: transparent;
    text-shadow: 0 0 0 aliceblue;
    text-align: center;
}

#submit {
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    background-color: aliceblue;
    color: #777779;
    font-size: 20px;
    text-decoration: none;
    border:none;
}


text:
module.exports = {
  method: function() {
    return false;
  }
}


text:
<!-- @import "[TOC]" {cmd="toc" depthFrom=1 depthTo=6 orderedList=false} -->

<!-- code_chunk_output -->

* [Mechanism design thoughts](#mechanism-design-thoughts)
	* [Application Components](#application-components)
		* [Architecture](#architecture)
			* [Server](#server)
			* [Worker](#worker)
		* [Back End/Service Layer](#back-endservice-layer)
			* [REST API](#rest-api)
			* [Message Flow](#message-flow)
			* [Data Storage](#data-storage)
			* [Plugins](#plugins)
			* [Client/User creation](#clientuser-creation)
			* [Client Authentication](#client-authentication)
		* [Front End/Website](#front-endwebsite)
			* [Design](#design)
			* [Back-End Interaction](#back-end-interaction)
			* [User Login/Logout](#user-loginlogout)

<!-- /code_chunk_output -->

# Mechanism design thoughts

## Application Components

### Architecture
Voluble is implemented in a server/worker fashion whereby the 'server' component is responsible for all of the central organisation of the system that the workers may depend upon, and the workers simply handle the process of sending messages with a given service. The two communicate through a Redis-backed messaging system.

#### Server
The server has three primary roles: firstly to implement the REST API which allows websites and other user service layers to interact with the Voluble system; secondly to keep track of the messages that are being processed within the system; and thirdly to assert that any parts of the Voluble system that workers may depend upon but it would be inefficient to re-evaluate upon each usage (such as plugins) are working as expected.

The server does not handle the actual mechanism of message-sending, which is delegated to workers, but does co-ordinate the messages that flow through the system.

#### Worker
The worker has a simple function: to attempt to send a given message with a given service (or rather, using a given plugin) naively and report back whether or not the attempt was successful. The inherent naivity of the system is designed that any worker must be able to attempt to send any given message with any given plugin without having to concern itself with whether or not the plugin is functioning as it should. It is the responsibility of the server to validate the available plugins before messages are handed to workers and to choose to refuse to utilise a given plugin if it does not appear to be functioning or unable to be correctly instantiated, so as to save messaging attempts with plugins that do not work.

Once a worker has attempted to send a message with a given plugin, the worker should simply respond to the server (through the messaging interface) the success or failure state of the message-sending attempt.

### Back End/Service Layer
#### REST API
This is the primary way that Voluble server instances interact with outside clients. All client-facing Voluble operations should be accessible through the REST API. This includes managing contacts, sending messages and defining how messages can be sent.

The design and implementation of this section is arguably the largest part of the whole project. It forms the bulk of the work that needs to be done, since it is effectively the basis of the software - it does the heavy lifting.

Points to consider:
* The API design/URL scheme itself
    * Presumably, this will take the standard object-oriented-esque REST style
    * Think:
        * https://<SERVER_URL>/messages/<MESSAGE_ID>
        * https://<SERVER_URL>/contacts/<MESSAGE_ID>
        * https://<SERVER_URL>/blasts/<MESSAGE_ID>
        * etc.
* In what format and in what structure information will be transmitted between Voluble and a client
* The structure of and information that relates to each of the core concepts in Voluble (`message`s, `blast`s, `service`s, `servicechain`s, etc.) and how they relate to each other.
    * Perhaps, a `GET` request for a particular `message` (i.e. a request to the endpoint `https://<SERVER_URL>/messages/01234567890123456789`) might return the following:

```
{
    message:
    {
        id: 01234567890123456789,
        content: "Hi Steve, how's things?"
        contact_id: 987654321
        service_state:
        {
            service: "telegram",
            direction: "incoming", /* "incoming" | "outgoing"
            state: "MSG_RECIEVED",
            reply_to: None
        }
    }

    metadata:
    {
        http_code: 200,
        method: "GET",
        unique_url: "https://<SERVER_URL>/messages/01234567890123456789"
        auth_token: "BEARER_TOKEN_RECIEVED"
    }
}
```

though it may be important in the future that server-worker and server-client messages follow a scheme such as the JRESP standard.

#### Message Flow

A `message` once it has been created has one of the following states:
| State                 | Meaning
|-----------------------|--------
| MSG_PENDING           | Voluble has queued the message for sending.
| MSG_SENDING           | Voluble is in the process of sending the message via the relevant plugin.
| MSG_DELIVERED_SERVICE | In the case of messages that use an intermediate delivery serice (e.g. Facebook Messenger, Telegram, etc.), the message has been confirmed as delivered to the intermediary, but the user has not necessarily recieved it. Does not apply in the case of SMS messages.
| MSG_DELIVERED_USER    | The message has been delivered to the user through a given service. Cannot confirm that the message has been read. Final state for SMS messages, unless they are replied to.
| MSG_READ              | The message has been confirmed as read by the user. Does not apply to SMS messages.
| MSG_REPLIED           | The user has sent a reply to the message through a given channel.
| MSG_FAILED            | Voluble could not send the message to the delivery provider.

How do we deal with replies? The most straightforward method might be to store the reply as a standard `message`, with a `reply_to` field. The downside of this is that by default, every message sent from a contact to an organization would be a reply to the previous message sent (assuming the contact had not already replied). Perhaps an implementation with a `direction` parameter stored in the message would be helpful, so we know whether or not the message was sent by a contact, and if so, whether it was a reply to a message sent out or an unsolicited message. Doing this would allow contacts to contact an organization without the organization sending a message to the contact first, and also allow Voluble to keep track of conversations, regardless of who initiated it.

The process of sending a message is as follows:

|Server|Worker|
|---|---|
| INIT | INIT |
| Init all plugins to validate that they work, blacklist any plugins that fail | |
| Join message queue | Join message queue |
| **ON POST /messages** | |
| Receive message | |
| Create message entry in database with `MSG_PENDING` state | |
| Send `send-message` message to queue with message details | |
| Update message database entry to `MSG_SENDING` state | |
| | **ON `send-message` MESSAGE** |
| | Recieve message from queue with message details |
| | Retrieve relevant plugin API details from Auth0 |
| | Attempt to init plugin with relevant API details for user |
| | If plugin fails, send `attempt-failed` message to message queue |
| | If plugin inits, attempt to send message with the given plugin |
| | If attempt is successful, send `message-sent` message to the message queue |
| | If attempt is unsuccessful, send `attempt-failed` message to the message queue |
| **ON `attempt-failed` MESSAGE** | |
| Iterate through the servicechain that the message was sent with to find the next plugin in the servicechain | |
| If there is a next plugin in the servicechain, send `send-message` message to the queue using the new plugin | |
| If this the last plugin in the servicechain, update the message database entry to the `MSG_FAILED` state | |
| **ON `message-sent` MESSAGE** | |
| Update the message database entry to the `MSG_DELIVERED_USER` state and set the message entry's `sent_time` to the current time. |

#### Data Storage

Questions:
* Given that all users on voluble must also exist on Auth0, why can we not simply use the same UIDs on Voluble as the ones generated on Auth0? This reduces lookups between Voluble and Auth0 users
All of the contacts and messages that are sent by Voluble are stored somewhere. This is the somewhere.

Centrally, the messages, plugin status data, organization data, as well as ancillary data about users than needn't be stored on Auth0 is stored in a MariaDB database.

#### Plugins

The actual mechanism of sending a message (via a worker) is delegated to a `plugin`, which represents a way of Voluble interacting with a given service. For example, if a user wished to be able to send an SMS using the Esendex platform (considered a `service` in Voluble terminology), then Voluble will delegate this responsibility to an Esendex plugin. The plugin will attempt to send the message and notify the calling worker of the success or failure of the attempt.

This way, if Voluble needs to be able to support a new system for sending messages, then all that needs to happen is for a plugin to be installed and added to a `servicechain` (a system for sending messages). Voluble itself doesn't need a new version-release or code update.

How should a plugin work? If Voluble needs to work with it in a predictable way, then it needs to expose a certain set of interfaces/methods and not break when it's used. How can we ensure this? How do we define what the plugin needs to make available for Voluble to be able to use it?

#### Client/User creation
* User responsibility delegation
    * How do we decide how we structure users in Voluble?
        * Should Voluble be able to support multiple 'Organizations', each with it's own set of Users and Contacts, that are completely separate within Voluble?
            * This would be closest to replicating the current functionality of Info2Text and would avoid having multiple instances running for multiple clients
            * In this case, the responsibility structure might look like this:

                    voluble_instance:
                        sysadmin
                            organization
                            {
                                organization_admin
                                [...]
                                    organization_regular_user
                                    [...]
                            }
                            organization
                            {
                                organization_admin
                                [...]
                                    organization_regular_user
                                    [...]
                            }
                            etc...

* For each level of client/user, Voluble will also need to be able to implement the following basic features:
    * User creation
    * Login/logout + cookie management
    * Password reset

Though, most of these features will be handed off to Auth0 to take place more securely.

#### Client Authentication
* As with all API-based systems, we need a way of making sure that only the right people have access to the right information. There are a number of ways to accomplish this, and several mechanisms for each.

Likely options:
* OAuth?
    * Widely supported, and well-known to be a secure infrastructure for user authentication.
    * Can be quite complicated to set up
    * There are a few mechanisms to authenticate users:
        * Bearer token?
            * Authenticate a given client when they supply a unique key that we have supplied
            * Provides a way of identifying a client without them having to provide their sensitive information every time they make a request
            * Means that we don't have to store user/password information, which could present a security vulnerability without expert secure implementation

* User/Password
    * Most obvious and straightforward system to set up
    * Requires us to store password information, which must be done in a very particular manner to prevent common security vulnerabilities
    * Requires the user to transmit their username and password hash every time they make a request, which could present security vulnerabilities

### Front End/Website
The website is effectively a pleasnt-looking wrapper around the API functions. While this sounds straightforward, it will still take a considerable amount of time to implement.

#### Design

#### Back-End Interaction

#### User Login/Logout


text:
package org.postgresql.java.model.types.builtin;

import org.postgresql.java.model.annotations.Stringable;
import org.postgresql.java.model.types.TypeDesc;

/*

https://www.postgresql.org/docs/current/static/datatype-money.html

* */

@Stringable
public class MONEY extends BuiltIn {

    private Double value;

    public MONEY() {
        javaClass = Double.class;
        typeDesc = TypeDesc.MONEY;
    }

    @Override
    public void setValue(Object value) {
        this.value = (Double) value;
    }

    @Override
    public Double getValue() {
        return value;
    }
}


text:
class Password
  attr_reader :parts

  def initialize
    @parts = Word.random(amount: 4).map(&:value)
  end
end


text:
package com.lh.android.com.lh.android.utils;

public class LHUtil
{

}


text:
package TerrariaClone;

import java.util.HashMap;
import java.util.Map;

public enum Item {

Empty(0,"Empty"),
    CopperHelmet(105, "Copper Helmet", ItemKind.Helmet, MetalType.Copper),
    IronHelmet(109, "Iron Helmet", ItemKind.Helmet, MetalType.Iron),
    SilverHelmet(113, "Silver Helmet", ItemKind.Helmet, MetalType.Silver),
    GoldHelmet(117, "Gold Helmet", ItemKind.Helmet, MetalType.Gold),
    ZincHelmet(121, "Zinc Helmet", ItemKind.Helmet, MetalType.Zinc),
    RhymestoneHelmet(125, "Rhymestone Helmet", ItemKind.Helmet, MetalType.Rhymestone),
    ObduriteHelmet(129, "Obdurite Helmet", ItemKind.Helmet, MetalType.Obdurite),
    AluminumHelmet(133, "Aluminum Helmet", ItemKind.Helmet, MetalType.Aluminium),
    LeadHelmet(137, "Lead Helmet", ItemKind.Helmet, MetalType.Lead),
    ZythiumHelmet(141, "Zythium Helmet", ItemKind.Helmet, MetalType.Zythium),

    CopperChestplate(106, "Copper Chestplate", ItemKind.Chestplate, MetalType.Copper),
    IronChestplate(110, "Iron Chestplate", ItemKind.Chestplate, MetalType.Iron),
    SilverChestplate(114, "Silver Chestplate", ItemKind.Chestplate, MetalType.Silver),
    GoldChestplate(118, "Gold Chestplate", ItemKind.Chestplate, MetalType.Gold),
    ZincChestplate(122, "Zinc Chestplate", ItemKind.Chestplate, MetalType.Zinc),
    RhymestoneChestplate(126, "Rhymestone Chestplate", ItemKind.Chestplate, MetalType.Rhymestone),
    ObduriteChestplate(130, "Obdurite Chestplate", ItemKind.Chestplate, MetalType.Obdurite),
    AluminumChestplate(134, "Aluminum Chestplate", ItemKind.Chestplate, MetalType.Aluminium),
    LeadChestplate(138, "Lead Chestplate", ItemKind.Chestplate, MetalType.Aluminium),
    ZythiumChestplate(142, "Zythium Chestplate", ItemKind.Chestplate, MetalType.Zythium),

    CopperLeggings(107, "Copper Leggings", ItemKind.Jeggings, MetalType.Copper),
    IronLeggings(111, "Iron Leggings", ItemKind.Jeggings, MetalType.Iron),
    SilverLeggings(115, "Silver Leggings", ItemKind.Jeggings, MetalType.Silver),
    GoldLeggings(119, "Gold Leggings", ItemKind.Jeggings, MetalType.Gold),
    ZincLeggings(123, "Zinc Leggings", ItemKind.Jeggings, MetalType.Zinc),
    RhymestoneLeggings(127, "Rhymestone Leggings", ItemKind.Jeggings, MetalType.Rhymestone),
    ObduriteLeggings(131, "Obdurite Leggings", ItemKind.Jeggings, MetalType.Obdurite),
    AluminumLeggings(135, "Aluminum Leggings", ItemKind.Jeggings, MetalType.Aluminium),
    LeadLeggings(139, "Lead Leggings", ItemKind.Jeggings, MetalType.Lead),
    ZythiumLeggings(143, "Zythium Leggings", ItemKind.Jeggings, MetalType.Zythium),

    CopperGreaves(108, "Copper Greaves", ItemKind.Greaves, MetalType.Copper),
    IronGreaves(112, "Iron Greaves", ItemKind.Greaves, MetalType.Iron),
    SilverGreaves(116, "Silver Greaves", ItemKind.Greaves, MetalType.Silver),
    GoldGreaves(120, "Gold Greaves", ItemKind.Greaves, MetalType.Gold),
    ZincGreaves(124, "Zinc Greaves", ItemKind.Greaves, MetalType.Zinc),
    RhymestoneGreaves(128, "Rhymestone Greaves", ItemKind.Greaves, MetalType.Rhymestone),
    ObduriteGreaves(132, "Obdurite Greaves", ItemKind.Greaves, MetalType.Obdurite),
    AluminumGreaves(136, "Aluminum Greaves", ItemKind.Greaves, MetalType.Aluminium),
    LeadGreaves(140, "Lead Greaves", ItemKind.Greaves, MetalType.Lead),
    ZythiumGreaves(144, "Zythium Greaves", ItemKind.Greaves, MetalType.Zythium),

    MagnetitePick(169, "Magnetite Pick", ItemKind.HandTool, MetalType.Magnetite),
MagnetiteAxe(170, "Magnetite Axe", ItemKind.HandTool, MetalType.Magnetite),
MagnetiteSword(171, "Magnetite Sword", ItemKind.HandTool, MetalType.Magnetite),
ZythiumDelayer1(186, "Zythium Delayer (1)"),

    WoodenPick(154, "Wooden Pick", ItemKind.Pick, MetalType.Wooden, 0.100),
    WoodenAxe(155, "Wooden Axe", ItemKind.Axe, MetalType.Wooden, 0.100),
    WoodenSword(156, "Wooden Sword", ItemKind.Sword, MetalType.Wooden, 0.100),
    StonePick(157, "Stone Pick", ItemKind.Pick, MetalType.Stone, 0.110),
    StoneAxe(158, "Stone Axe", ItemKind.Axe, MetalType.Stone, 0.110),
    StoneSword(159, "Stone Sword", ItemKind.Sword, MetalType.Stone, 0.105),

    CopperPick(7, "Copper Pick", ItemKind.Pick, MetalType.Copper, 0.120);

    public static short getDefaultDurability()
    {
        return 0;
    }

    public static final double NormalToolSpeedInferredFromHorrificProvider = 0.175;
    double toolSpeed;

    public short getCode() {
        return blockCode.shortValue();
    }

    Integer blockCode;
    String lookupLabel;
    ItemKind itemKind;

    public boolean isTool() {
        return itemKind == ItemKind.HandTool;
    }

    public MetalType getMetalType() {
        return metalType;
    }

    MetalType metalType;

    Item(Integer code)
    {
        blockCode = code;
        lookupLabel = "";
        itemKind = ItemKind.Applesauce;
        metalType = MetalType.Applesauce;
        toolSpeed = NormalToolSpeedInferredFromHorrificProvider;
    }

    static Map<Integer, Item> itemCodeCache;

    Item(Integer code, String lookup)
    {
        this(code);
        lookupLabel = lookup;
    }

    Item(Integer code, String lookup, ItemKind kind, MetalType type)
    {
        this(code, lookup);
        metalType = type;
        itemKind = kind;
    }

    Item(Integer code, String lookup, ItemKind kind, MetalType type, double toolSpeed)
    {
        this(code, lookup, kind, type);
        this.toolSpeed = toolSpeed;

    }

    static void populateItemCodeCache()
    {
        itemCodeCache = new HashMap<Integer,Item>();
        for(Item b : values())
        {
            itemCodeCache.put((int) b.getCode(), b);
        }
    }

    public static Item lookupItemCode(short itemCode)
    {
        if (itemCodeCache == null || itemCodeCache.size() == 0)
        {
            populateItemCodeCache();
        }

        // YOLO.
        // TODO: Resolve this sin later.
        Item result = itemCodeCache.get((int) itemCode);
        if(result == null){
            throw new RuntimeException("Item Code " + String.valueOf(itemCode) + " is not defined in the items data");
        }
        return result;
    }

    public double getToolSpeed() {
        return toolSpeed;
    }
}


text:
package ca.uhn.fhir.jpa.config;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.*;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import ca.uhn.fhir.jpa.dao.DaoConfig;
import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor;
import ca.uhn.fhir.validation.ResultSeverityEnum;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;

import static org.junit.Assert.fail;

@Configuration
@EnableTransactionManagement()
public class TestDstu3Config extends BaseJavaConfigDstu3 {

	static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(TestDstu3Config.class);

	@Bean()
	public DaoConfig daoConfig() {
		return new DaoConfig();
	}

	private Exception myLastStackTrace;

	@Bean()
	public DataSource dataSource() {
		BasicDataSource retVal = new BasicDataSource() {

			@Override
			public Connection getConnection() throws SQLException {
				ConnectionWrapper retVal;
				try {
					retVal = new ConnectionWrapper(super.getConnection());
				} catch (Exception e) {
					ourLog.error("Exceeded maximum wait for connection", e);
					logGetConnectionStackTrace();
					if ("true".equals(System.getProperty("ci"))) {
						fail("Exceeded maximum wait for connection: "+ e.toString());
					}
					System.exit(1);
					retVal = null;
				}

				try {
					throw new Exception();
				} catch (Exception e) {
					myLastStackTrace = e;
				}

				return retVal;
			}

			private void logGetConnectionStackTrace() {
					StringBuilder b = new StringBuilder();
					b.append("Last connection request stack trace:");
					for (StackTraceElement next : myLastStackTrace.getStackTrace()) {
							b.append("\n   ");
							b.append(next.getClassName());
							b.append(".");
							b.append(next.getMethodName());
							b.append("(");
							b.append(next.getFileName());
							b.append(":");
							b.append(next.getLineNumber());
							b.append(")");
					}
					ourLog.info(b.toString());
			}

		};
		retVal.setDriver(new org.apache.derby.jdbc.EmbeddedDriver());
		retVal.setUrl("jdbc:derby:memory:myUnitTestDB;create=true");
		retVal.setMaxWaitMillis(10000);
		retVal.setUsername("");
		retVal.setPassword("");

		/*
		 * We use a randomized number of maximum threads in order to try
		 * and catch any potential deadlocks caused by database connection
		 * starvation
		 */
		int maxThreads = (int) (Math.random() * 6) + 1;
		retVal.setMaxTotal(maxThreads);

		DataSource dataSource = ProxyDataSourceBuilder
				.create(retVal)
				// .logQueryBySlf4j(SLF4JLogLevel.INFO, "SQL")
				.logSlowQueryBySlf4j(10, TimeUnit.SECONDS)
				.countQuery()
				.build();

		return dataSource;
	}

	@Bean()
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		LocalContainerEntityManagerFactoryBean retVal = new LocalContainerEntityManagerFactoryBean();
		retVal.setPersistenceUnitName("PU_HapiFhirJpaDstu3");
		retVal.setDataSource(dataSource());
		retVal.setPackagesToScan("ca.uhn.fhir.jpa.entity");
		retVal.setPersistenceProvider(new HibernatePersistenceProvider());
		retVal.setJpaProperties(jpaProperties());
		return retVal;
	}

	private Properties jpaProperties() {
		Properties extraProperties = new Properties();
		extraProperties.put("hibernate.jdbc.batch_size", "50");
		extraProperties.put("hibernate.format_sql", "false");
		extraProperties.put("hibernate.show_sql", "false");
		extraProperties.put("hibernate.hbm2ddl.auto", "update");
		extraProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyTenSevenDialect");
		extraProperties.put("hibernate.search.default.directory_provider", "ram");
		extraProperties.put("hibernate.search.lucene_version", "LUCENE_CURRENT");
		extraProperties.put("hibernate.search.autoregister_listeners", "true");
		return extraProperties;
	}

	/**
	 * Bean which validates incoming requests
	 */
	@Bean
	@Lazy
	public RequestValidatingInterceptor requestValidatingInterceptor() {
		RequestValidatingInterceptor requestValidator = new RequestValidatingInterceptor();
		requestValidator.setFailOnSeverity(ResultSeverityEnum.ERROR);
		requestValidator.setAddResponseHeaderOnSeverity(null);
		requestValidator.setAddResponseOutcomeHeaderOnSeverity(ResultSeverityEnum.INFORMATION);
		requestValidator.addValidatorModule(instanceValidatorDstu3());

		return requestValidator;
	}

	@Bean()
	public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
		JpaTransactionManager retVal = new JpaTransactionManager();
		retVal.setEntityManagerFactory(entityManagerFactory);
		return retVal;
	}

}


text:
//
//  State.h
//  StoreExample
//
//  Created by David House on 8/18/12.
//  Copyright (c) 2012 David House. All rights reserved.
//
#import "NSObject+DHMambaObject.h"

@interface State : NSObject<DHMambaObjectProperties>

/* {"attributes":{"name":"ALABAMA","abbreviation":"AL","capital":"Montgomery","most-populous-city":"Birmingham","population":"4708708","square-miles":"52423","time-zone-1":"CST (UTC-6)","time-zone-2":"EST (UTC-5)","dst":"YES"}}
*/

#pragma mark - Properties
@property (nonatomic,retain) NSString *name;
@property (nonatomic,retain) NSString *abbreviation;
@property (nonatomic,retain) NSString *population;
@property (nonatomic,retain) NSString *squareMiles;
@property (nonatomic,strong) NSString *capital;
@property (nonatomic,strong) NSString *mostPopulousCity;

#pragma mark - Public Methods
+ (void)loadTestStates;

@end


text:
import logging

from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon import tabs
from horizon import workflows

from openstack_dashboard.api import sahara as saharaclient
from openstack_dashboard.dashboards.project.data_processing. \
    cluster_templates import forms as cluster_forms
import openstack_dashboard.dashboards.project.data_processing. \
    cluster_templates.tables as ct_tables
import openstack_dashboard.dashboards.project.data_processing. \
    cluster_templates.tabs as _tabs
import openstack_dashboard.dashboards.project.data_processing. \
    cluster_templates.workflows.copy as copy_flow
import openstack_dashboard.dashboards.project.data_processing. \
    cluster_templates.workflows.create as create_flow

LOG = logging.getLogger(__name__)

class ClusterTemplatesView(tables.DataTableView):
    table_class = ct_tables.ClusterTemplatesTable
    template_name = (
        'project/data_processing.cluster_templates/cluster_templates.html')

    def get_data(self):
        try:
            cluster_templates = saharaclient.cluster_template_list(
                self.request)
        except Exception:
            cluster_templates = []
            exceptions.handle(self.request,
                              _("Unable to fetch cluster template list"))
        return cluster_templates

class ClusterTemplateDetailsView(tabs.TabView):
    tab_group_class = _tabs.ClusterTemplateDetailsTabs
    template_name = 'project/data_processing.cluster_templates/details.html'

    def get_context_data(self, **kwargs):
        context = super(ClusterTemplateDetailsView, self)\
            .get_context_data(**kwargs)
        return context

    def get_data(self):
        pass

class UploadFileView(forms.ModalFormView):
    form_class = cluster_forms.UploadFileForm
    template_name = (
        'project/data_processing.cluster_templates/upload_file.html')
    success_url = reverse_lazy(
        'horizon:project:data_processing.cluster_templates:index')

class CreateClusterTemplateView(workflows.WorkflowView):
    workflow_class = create_flow.CreateClusterTemplate
    success_url = ("horizon:project:data_processing.cluster_templates"
                   ":create-cluster-template")
    classes = ("ajax-modal")
    template_name = "project/data_processing.cluster_templates/create.html"

class ConfigureClusterTemplateView(workflows.WorkflowView):
    workflow_class = create_flow.ConfigureClusterTemplate
    success_url = "horizon:project:data_processing.cluster_templates"
    template_name = "project/data_processing.cluster_templates/configure.html"

class CopyClusterTemplateView(workflows.WorkflowView):
    workflow_class = copy_flow.CopyClusterTemplate
    success_url = "horizon:project:data_processing.cluster_templates"
    template_name = "project/data_processing.cluster_templates/configure.html"

    def get_context_data(self, **kwargs):
        context = super(CopyClusterTemplateView, self)\
            .get_context_data(**kwargs)

        context["template_id"] = kwargs["template_id"]
        return context

    def get_object(self, *args, **kwargs):
        if not hasattr(self, "_object"):
            template_id = self.kwargs['template_id']
            try:
                template = saharaclient.cluster_template_get(self.request,
                                                             template_id)
            except Exception:
                template = {}
                exceptions.handle(self.request,
                                  _("Unable to fetch cluster template."))
            self._object = template
        return self._object

    def get_initial(self):
        initial = super(CopyClusterTemplateView, self).get_initial()
        initial['template_id'] = self.kwargs['template_id']
        return initial


text:
package uk.co.cbray.msc.nhsdsp.utils;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;

import java.math.BigDecimal;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import uk.co.cbray.msc.nhsdsp.dao.AssessmentRepository;
import uk.co.cbray.msc.nhsdsp.dao.DataAccessObject;
import uk.co.cbray.msc.nhsdsp.dao.DrugRepository;
import uk.co.cbray.msc.nhsdsp.dao.EffectRepository;
import uk.co.cbray.msc.nhsdsp.dao.IllnessRepository;
import uk.co.cbray.msc.nhsdsp.dao.IncidentRepository;
import uk.co.cbray.msc.nhsdsp.dao.UserRepository;
import uk.co.cbray.msc.nhsdsp.entity.Drug;
import uk.co.cbray.msc.nhsdsp.entity.DrugUserSuitability;
import uk.co.cbray.msc.nhsdsp.entity.Effect;
import uk.co.cbray.msc.nhsdsp.entity.Illness;
import uk.co.cbray.msc.nhsdsp.forms.NewAssessmentForm;
import uk.co.cbray.msc.nhsdsp.test.utils.ClassificationFactory;
import uk.co.cbray.msc.nhsdsp.test.utils.TestFactory;

public class AssessmentHelperTest {

	@Mock
	private UserRepository userRepo;
	@Mock
	private IllnessRepository illnessRepo;
	@Mock
	private DrugRepository drugRepo;
	@Mock
	private DataAccessObject dao;
	@Mock
	private IncidentRepository incidentRepo;
	@Mock
	private EffectRepository effectRepo;
	@Mock
	private AssessmentRepository assessmentRepo;

	@Before
	public void SetUp() {
		MockitoAnnotations.initMocks(this);

		Mockito.when(userRepo.findById((BigDecimal) anyObject())).thenReturn(
				ClassificationFactory.getUserBeingAssessed());
		Mockito.when(illnessRepo.findByName(anyString())).thenReturn(
				TestFactory.getIllnessListInstance());
		Mockito.when(
				drugRepo.findAllDrugsForIllnesses(anyListOf(Illness.class)))
				.thenReturn(ClassificationFactory.getDrugList());
		Mockito.when(incidentRepo.findAllForDrug((Drug) anyObject()))
				.thenReturn(ClassificationFactory.getIncidentListInstance());
		Mockito.when(effectRepo.findByName(eq("effect 1"))).thenReturn(
				ClassificationFactory.getEffectOne());
		Mockito.when(effectRepo.findByName(eq("effect 2"))).thenReturn(
				ClassificationFactory.getEffectTwo());
		Mockito.when(effectRepo.findByName(eq("effect 3"))).thenReturn(
				ClassificationFactory.getEffectThree());
		Mockito.when(effectRepo.findByName(eq("effect 4"))).thenReturn(
				ClassificationFactory.getEffectFour());
		Mockito.when(dao.executeNamedQuery("Effect.findAll", Effect.class))
				.thenReturn(ClassificationFactory.getEffectList());
	}

	@Test
	public void testSuccessScenarioForAssessmentHelperAssessMethod() {

		NewAssessmentForm form = new NewAssessmentForm();

		form.setIllnessName("test name");
		form.setUserId(1);

		List<DrugUserSuitability> results = AssessmentHelper.assess(form,
				userRepo, illnessRepo, drugRepo, dao, incidentRepo, effectRepo,
				assessmentRepo);

		// Verify the correct number of results exist
		assertEquals(4, results.size());
		// Verify the results have been saved to the database
		verify(assessmentRepo).createAll(anyListOf(DrugUserSuitability.class));

	}

	@Test
	public void testExceptionIsCaughtAndNoResultsAreReturned() {

		NewAssessmentForm form = new NewAssessmentForm();

		form.setIllnessName("test name");
		form.setUserId(1);

		Mockito.when(incidentRepo.findAllForDrug((Drug) anyObject()))
				.thenThrow(Exception.class);

		List<DrugUserSuitability> results = AssessmentHelper.assess(form,
				userRepo, illnessRepo, drugRepo, dao, incidentRepo, effectRepo,
				assessmentRepo);

		assertEquals(0, results.size());

	}
}


text:
/*
 creating a Express app initializing it with the HelloWorld message
 */
'use strict';

var PORT_LISTENER = 3001;
console.log('I am listening to this port: http://localhost:%s', PORT_LISTENER);

var express = require('express'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    errorhandler = require('errorhandler'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    http = require('http'),
    path = require('path');

var appConfig = require('./config/appConfig.json');
var router = require('./routes/index');

var app = express();

// all environments
app.set('port', process.env.PORT || PORT_LISTENER);
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.use(favicon(__dirname + '/public/bootstrap-3.3.1/docs/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser({ keepExtensions: true, uploadDir: path.join(__dirname, appConfig.directories.publicDir) }));
app.use(methodOverride());
app.use(cookieParser('my v3ry s3cr3t C00k1e k3y d0nt y0u th1nk?'));
app.use(session({ resave: true,
                  saveUninitialized: true,
                  secret: 'my l1ttl3 s3cret s3ss10n k3y isnt it?' }));

//routes
app.use('/', router);

app.use(express.static(path.join(__dirname, appConfig.directories.publicDir)));

app.use(function (req, res, next) {
    console.log('req.body: ' + JSON.stringify(req.body));
    next();
});

// development only
if ('development' === app.get('env')) {
    app.use(errorhandler());
}

http.createServer(app).listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});


text:
import {Behavior} from 'aurelia-framework';

export class Msg {
  static metadata(){ return Behavior.withProperty('router'); }
}


text:
#ifndef MOCK_ENDPOINT_H
#define MOCK_ENDPOINT_H

#include "src/core/lib/iomgr/endpoint.h"

void grpc_passthru_endpoint_create(grpc_endpoint **client,
                                   grpc_endpoint **server);

#endif


text:
import uuid

from designateclient.tests import v2

class TestBlacklists(v2.APIV2TestCase, v2.CrudMixin):
    RESOURCE = 'blacklists'

    def new_ref(self, **kwargs):
        ref = super(TestBlacklists, self).new_ref(**kwargs)
        ref.setdefault("pattern", uuid.uuid4().hex)
        return ref

    def test_create(self):
        ref = self.new_ref()

        self.stub_url("POST", parts=[self.RESOURCE], json=ref)

        values = ref.copy()
        del values["id"]

        self.client.blacklists.create(**values)
        self.assertRequestBodyIs(json=values)

    def test_create_with_description(self):
        ref = self.new_ref(description="My Blacklist")

        self.stub_url("POST", parts=[self.RESOURCE], json=ref)

        values = ref.copy()
        del values["id"]

        self.client.blacklists.create(**values)
        self.assertRequestBodyIs(json=values)

    def test_get(self):
        ref = self.new_ref()

        self.stub_entity("GET", entity=ref, id=ref["id"])

        response = self.client.blacklists.get(ref["id"])
        self.assertEqual(ref, response)

    def test_list(self):
        items = [
            self.new_ref(),
            self.new_ref()
        ]

        self.stub_url("GET", parts=[self.RESOURCE], json={"blacklists": items})

        listed = self.client.blacklists.list()
        self.assertList(items, listed)
        self.assertQueryStringIs("")

    def test_update(self):
        ref = self.new_ref()

        self.stub_entity("PATCH", entity=ref, id=ref["id"])

        values = ref.copy()
        del values["id"]

        self.client.blacklists.update(ref["id"], values)
        self.assertRequestBodyIs(json=values)

    def test_delete(self):
        ref = self.new_ref()

        self.stub_entity("DELETE", id=ref["id"])

        self.client.blacklists.delete(ref["id"])
        self.assertRequestBodyIs(None)


text:
using System.Collections.Generic;

using Company.Data;
using Company.Utilities.Contracts;
using Company.Utilities.DataGenerators.Contracts;

namespace Company.Utilities.DataGenerators
{
    public class DepartmentGenerator : IDepartmentGenerator
    {
        private const int MinNameLength = 10;
        private const int MaxNameLength = 50;

        private readonly IStringGenerator stringGenerator;

        public DepartmentGenerator(IStringGenerator stringGenerator)
        {
            this.stringGenerator = stringGenerator;
        }

        public IEnumerable<Department> GetDepartments(int count)
        {
            ICollection<Department> departments = new List<Department>(count);

            for (int i = 0; i < count; i++)
            {
                var departmentName = this.stringGenerator.GetRandomString(MinNameLength, MaxNameLength);
                var department = new Department { Name = departmentName };

                departments.Add(department);
            }

            return departments;
        }
    }
}


text:
require 'rubygems'
require 'xmpp4r'
require 'xmpp4r/roster/iq/roster'
require 'xmpp4r-simple'

require './loopfunctions.rb'

# config parameters all default to nil
@username = nil
@password = nil
@modules = nil
@pause = 1

# read in the config file
@configfile = "./hungryconfig.txt"
file = File.new(@configfile, "r")
file.each { |line|
	if line =~ /^username/ then
		@username = line.split("=",2)[1].strip
	elsif line=~ /^password/ then
		@password = line.split("=",2)[1].strip
	elsif line=~ /^modules/ then
		@modules = line.split("=",2)[1].strip
	elsif line=~ /^pause/ then
		@pause = line.split("=",2)[1].strip.to_i
	end
}
file.close

# dynamically load all modules from the given directory
@loaded = Array.new
# how many iterations to loop for before reseting counter to 0
@maxcount = 1
Dir.new(@modules).entries.each { |file|
	if file =~ /.+\.rb$/ then
		require "./#{@modules}/#{file}"
		# for each module find the object name and initialize it
		modnum = 0
		modulefile = File.new("#{@modules}/#{file}", "r")
		modulefile.each { |line|
			if line =~ /^class (\w+)/ then
				mod = $1
				mod = Module.const_get(mod).new
				mod.times.each { |time|
					if (time > @maxcount) then
						@maxcount = time
					end
				}
				@loaded << mod
				break
			end
		}
	end
}

# Connect
@im = Jabber::Simple.new(@username, @password)
@im.status(nil,"Available")
@im.accept_subscriptions = true
# create query for contacts TODO: fix this - it doesn't work
@friends = Array.new
@im.client.add_iq_callback { |i|
    @friends = Array.new
    if i.type == :result and i.query.kind_of?(Jabber::Roster::IqQueryRoster)
        i.query.each_element { |e|
            @friends << e.jid.to_s
        }
    end
}

sleep 5

# the bot loop
count = 0
loop do

    count += 1
    #puts count

    # respond to user commands
    @im.received_messages do |message|
        processMessage(message)
    end

	doTimeTrigger(count)

	if count == @maxcount
		count = 0
	end

	# Every 20 seconds ensure we remain connected
    if count.divmod(20)[1] == 0 then
        @im.status(nil,"Available")
    end

    # pause in loop
    sleep @pause
end