text:
/*
 *		IP_MASQ_RAUDIO  - Real Audio masquerading module
 *
 *
 * Version:	@(#)$Id: ip_masq_raudio.c,v 1.1.2.1 1997/03/04 12:04:53 davem Exp $
 *
 * Author:	Nigel Metheringham
 *		[strongly based on ftp module by Juan Jose Ciarlante & Wouter Gadeyne]
 *		[Real Audio information taken from Progressive Networks firewall docs]
 *		[Kudos to Progressive Networks for making the protocol specs available]
 *
 *
 *
 *	This program is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU General Public License
 *	as published by the Free Software Foundation; either version
 *	2 of the License, or (at your option) any later version.
 *
 *
 * Limitations
 *	The IP Masquerading proxies at present do not have access to a processed
 *	data stream.  Hence for a protocol like the Real Audio control protocol,
 *	which depends on knowing where you are in the data stream, you either
 *	to keep a *lot* of state in your proxy, or you cheat and simplify the
 *	problem [needless to say I did the latter].
 *
 *	This proxy only handles data in the first packet.  Everything else is
 *	passed transparently.  This means it should work under all normal
 *	circumstances, but it could be fooled by new data formats or a
 *	malicious application!
 *
 *	At present the "first packet" is defined as a packet starting with
 *	the protocol ID string - "PNA".
 *	When the link is up there appears to be enough control data
 *	crossing the control link to keep it open even if a long audio
 *	piece is playing.
 *
 *	The Robust UDP support added in RealAudio 3.0 is supported, but due
 *	to servers/clients not making great use of this has not been greatly
 *	tested.  RealVideo (as used in the Real client version 4.0beta1) is
 *	supported but again is not greatly tested (bandwidth requirements
 *	appear to exceed that available at the sites supporting the protocol).
 *
 * Multiple Port Support
 *	The helper can be made to handle up to MAX_MASQ_APP_PORTS (normally 12)
 *	with the port numbers being defined at module load time.  The module
 *	uses the symbol "ports" to define a list of monitored ports, which can
 *	be specified on the insmod command line as
 *		ports=x1,x2,x3...
 *	where x[n] are integer port numbers.  This option can be put into
 *	/etc/conf.modules (or /etc/modules.conf depending on your config)
 *	where modload will pick it up should you use modload to load your
 *	modules.
 *
 */

#include <linux/module.h>
#include <asm/system.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <net/protocol.h>
#include <net/tcp.h>
#include <net/ip_masq.h>

#ifndef DEBUG_CONFIG_IP_MASQ_RAUDIO
#define DEBUG_CONFIG_IP_MASQ_RAUDIO 0
#endif

struct raudio_priv_data {
	/* Associated data connection - setup but not used at present */
	struct	ip_masq *data_conn;
	/* UDP Error correction connection - setup but not used at present */
	struct	ip_masq *error_conn;
	/* Have we seen and performed setup */
	short	seen_start;
};

/*
 * List of ports (up to MAX_MASQ_APP_PORTS) to be handled by helper
 * First port is set to the default port.
 */
int ports[MAX_MASQ_APP_PORTS] = {7070}; /* I rely on the trailing items being set to zero */
struct ip_masq_app *masq_incarnations[MAX_MASQ_APP_PORTS];

static int
masq_raudio_init_1 (struct ip_masq_app *mapp, struct ip_masq *ms)
{
        MOD_INC_USE_COUNT;
	if ((ms->app_data = kmalloc(sizeof(struct raudio_priv_data),
				    GFP_ATOMIC)) == NULL)
		printk(KERN_INFO "RealAudio: No memory for application data\n");
	else
	{
		struct raudio_priv_data *priv =
			(struct raudio_priv_data *)ms->app_data;
		priv->seen_start = 0;
		priv->data_conn = NULL;
		priv->error_conn = NULL;
	}
        return 0;
}

static int
masq_raudio_done_1 (struct ip_masq_app *mapp, struct ip_masq *ms)
{
        MOD_DEC_USE_COUNT;
	if (ms->app_data)
		kfree_s(ms->app_data, sizeof(struct raudio_priv_data));
        return 0;
}

int
masq_raudio_out (struct ip_masq_app *mapp, struct ip_masq *ms, struct sk_buff **skb_p, struct device *dev)
{
        struct sk_buff *skb;
	struct iphdr *iph;
	struct tcphdr *th;
	char *p, *data, *data_limit;
	struct ip_masq *n_ms;
	unsigned short version, msg_id, msg_len, udp_port;
	struct raudio_priv_data *priv =
		(struct raudio_priv_data *)ms->app_data;

	/* Everything running correctly already */
	if (priv && priv->seen_start)
		return 0;

        skb = *skb_p;
	iph = skb->h.iph;
        th = (struct tcphdr *)&(((char *)iph)[iph->ihl*4]);
        data = (char *)&th[1];

        data_limit = skb->h.raw + skb->len;

	/* Check to see if this is the first packet with protocol ID */
	if (memcmp(data, "PNA", 3)) {
#if DEBUG_CONFIG_IP_MASQ_RAUDIO
		printk("RealAudio: not initial protocol packet - ignored\n");
#endif
		return(0);
	}
	data += 3;
	memcpy(&version, data, 2);

#if DEBUG_CONFIG_IP_MASQ_RAUDIO
	printk("RealAudio: initial seen - protocol version %d\n",
	       ntohs(version));
#endif
	if (priv)
		priv->seen_start = 1;

	if (ntohs(version) >= 256)
	{
		printk(KERN_INFO "RealAudio: version (%d) not supported\n",
		       ntohs(version));
		return 0;
	}

	data += 2;
	while (data+4 < data_limit) {
		memcpy(&msg_id, data, 2);
		data += 2;
		memcpy(&msg_len, data, 2);
		data += 2;
		if (ntohs(msg_id) == 0) {
			/* The zero tag indicates the end of options */
#if DEBUG_CONFIG_IP_MASQ_RAUDIO
			printk("RealAudio: packet end tag seen\n");
#endif
			return 0;
		}
#if DEBUG_CONFIG_IP_MASQ_RAUDIO
		printk("RealAudio: msg %d - %d byte\n",
		       ntohs(msg_id), ntohs(msg_len));
#endif
		if (ntohs(msg_id) == 0) {
			/* The zero tag indicates the end of options */
			return 0;
		}
		p = data;
		data += ntohs(msg_len);
		if (data > data_limit)
		{
			printk(KERN_INFO "RealAudio: Packet too short for data\n");
			return 0;
		}
		if ((ntohs(msg_id) == 1) || (ntohs(msg_id) == 7)) {
			/*
			 * MsgId == 1
			 * Audio UDP data port on client
			 *
			 * MsgId == 7
			 * Robust UDP error correction port number on client
			 *
			 * Since these messages are treated just the same, they
			 * are bundled together here....
			 */
			memcpy(&udp_port, p, 2);

			/*
			 * Sometimes a server sends a message 7 with a zero UDP port
			 * Rather than do anything with this, just ignore it!
			 */
			if (udp_port == 0)
				continue;

			n_ms = ip_masq_new(dev, IPPROTO_UDP,
					   ms->saddr, udp_port,
					   ms->daddr, 0,
					   IP_MASQ_F_NO_DPORT);

			if (n_ms==NULL)
				return 0;

			memcpy(p, &(n_ms->mport), 2);
#if DEBUG_CONFIG_IP_MASQ_RAUDIO
			printk("RealAudio: rewrote UDP port %d -> %d in msg %d\n",
			       ntohs(udp_port), ntohs(n_ms->mport), ntohs(msg_id));
#endif
			ip_masq_set_expire(n_ms, ip_masq_expire->udp_timeout);

			/* Make ref in application data to data connection */
			if (priv) {
				if (ntohs(msg_id) == 1)
					priv->data_conn = n_ms;
				else
					priv->error_conn = n_ms;
			}
		}
	}
	return 0;
}

struct ip_masq_app ip_masq_raudio = {
        NULL,			/* next */
	"RealAudio",	       	/* name */
        0,                      /* type */
        0,                      /* n_attach */
        masq_raudio_init_1,     /* ip_masq_init_1 */
        masq_raudio_done_1,     /* ip_masq_done_1 */
        masq_raudio_out,        /* pkt_out */
        NULL                    /* pkt_in */
};

/*
 * 	ip_masq_raudio initialization
 */

int ip_masq_raudio_init(void)
{
	int i, j;

	for (i=0; (i<MAX_MASQ_APP_PORTS); i++) {
		if (ports[i]) {
			if ((masq_incarnations[i] = kmalloc(sizeof(struct ip_masq_app),
							    GFP_KERNEL)) == NULL)
				return -ENOMEM;
			memcpy(masq_incarnations[i], &ip_masq_raudio, sizeof(struct ip_masq_app));
			if ((j = register_ip_masq_app(masq_incarnations[i],
						      IPPROTO_TCP,
						      ports[i]))) {
				return j;
			}
#if DEBUG_CONFIG_IP_MASQ_RAUDIO
			printk("RealAudio: loaded support on port[%d] = %d\n",
			       i, ports[i]);
#endif
		} else {
			/* To be safe, force the incarnation table entry to NULL */
			masq_incarnations[i] = NULL;
		}
	}
	return 0;
}

/*
 * 	ip_masq_raudio fin.
 */

int ip_masq_raudio_done(void)
{
	int i, j, k;

	k=0;
	for (i=0; (i<MAX_MASQ_APP_PORTS); i++) {
		if (masq_incarnations[i]) {
			if ((j = unregister_ip_masq_app(masq_incarnations[i]))) {
				k = j;
			} else {
				kfree(masq_incarnations[i]);
				masq_incarnations[i] = NULL;
#if DEBUG_CONFIG_IP_MASQ_RAUDIO
				printk("RealAudio: unloaded support on port[%d] = %d\n",
				       i, ports[i]);
#endif
			}
		}
	}
	return k;
}

#ifdef MODULE

int init_module(void)
{
        if (ip_masq_raudio_init() != 0)
                return -EIO;
        register_symtab(0);
        return 0;
}

void cleanup_module(void)
{
        if (ip_masq_raudio_done() != 0)
                printk("ip_masq_raudio: can't remove module");
}

#endif /* MODULE */


text:
'use strict';

var readFile = require( './../lib' );

/* Sync */

var file = readFile.sync( __filename, 'utf8' );
// returns <string>

console.log( file instanceof Error );
// => false

file = readFile.sync( 'beepboop', {
	'encoding': 'utf8'
});
// returns <Error>

console.log( file instanceof Error );
// => true

/* Async */

readFile( __filename, onFile );
readFile( 'beepboop', onFile );

function onFile( error, data ) {
	if ( error ) {
		if ( error.code === 'ENOENT' ) {
			console.error( 'File does not exist.' );
		} else {
			throw error;
		}
	} else {
		console.log( data );
	}
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component, PropTypes } from 'react'
import '../../assets/css/app.css'

class Card extends Component {

  static propTypes = {
    children: PropTypes.node
  }

  render() {
    return (

Title

Blonde

Artist

Frank Ocean

    )
  }

}

class Wrapper extends Component {
  render(){
    return (

        <Card>

            oi

        </Card>

    )
  }
}

export default Card


text:
import {RECEIVE_ARTIST_DATA} from '../actions/index';

const defaultState = {};

export default function artistData(state = defaultState, action) {
  if (action.type === RECEIVE_ARTIST_DATA) {
    return Object.assign({}, state, action.payload);
  }

  return state;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Backpropagation.Core;
using Backpropagation.WinForms;

namespace Backpropagation.Console
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var count = 20;
            var irises = Iris.GetImagesFromFile("iris.data");

            ShowImagesDistribution(irises); //Warning: Thread-blocking method

            //выборка для обучения
            var trainIrises = new List<INeuralImage>();
            trainIrises.AddRange(irises.Where(i => i.ClassId == 0).Take(count));
            trainIrises.AddRange(irises.Where(i => i.ClassId == 1).Take(count));
            trainIrises.AddRange(irises.Where(i => i.ClassId == 2).Take(count));

            //выборка для тестирования
            var testIrises = new List<INeuralImage>();
            testIrises.AddRange(irises.Where(i => i.ClassId == 0).Skip(count));
            testIrises.AddRange(irises.Where(i => i.ClassId == 1).Skip(count));
            testIrises.AddRange(irises.Where(i => i.ClassId == 2).Skip(count));

            var network = new NeuralNetwork(4, 3, NeuralNetwork.SigmoidalActivationFunction);
            System.Console.WriteLine("ANN is being trained:");
            network.TrainNetwork(trainIrises, 50000, DisplayProgress);
            System.Console.WriteLine("");

            var recognAbility = 0;
            var generAbility = 0;
            var startTime = DateTime.Now;
            foreach (var neuralImage in trainIrises)
            {
                var v = network.GetNetworkOutput(neuralImage);
                var result = network.GetClassIdOrDefault(neuralImage);
                recognAbility += result == neuralImage.ClassId ? 1 : 0;
            }
            var trainTime = DateTime.Now - startTime;
            System.Console.WriteLine("Time elapsed: {0}", trainTime);
            foreach (var neuralImage in testIrises)
            {
                var v = network.GetNetworkOutput(neuralImage);
                var result = network.GetClassIdOrDefault(neuralImage);
                generAbility += result == neuralImage.ClassId ? 1 : 0;
            }
            System.Console.WriteLine("Распознающая способность: {0}%", GetPercentage(recognAbility, trainIrises.Count));
            System.Console.WriteLine("Обобщающая способность: {0}%", GetPercentage(generAbility, testIrises.Count));

            System.Console.ReadLine();
        }

        private static void ShowImagesDistribution(ICollection<INeuralImage> irises)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // Создание главного окна и его запуск
            Application.Run(new IrisForm(irises));
        }

        public static Double GetPercentage(int count, int overall)
        {
            var percentage = (Math.Round(count/(double) overall, 4))*100;
            return percentage;
        }

        public static void DisplayProgress(int iterations)
        {
            System.Console.Write("\r{0}", iterations);
        }

        public static IrisClass GetClassByNetworkOutput(Double[] values)
        {
            for (var i = 0; i < values.Count(); i++)
            {
                if ((int) values[i] == 1) return (IrisClass) i;
            }
            throw new FormatException("Bad network output");
        }
    }
}


text:
module DropboxForBusiness
  module Collections
    class Reports

      def initialize(connection)
        @connection = connection
      end

      # https://www.dropbox.com/developers/business/docs#reports-get-storage
      def get_storage(params)
        @connection.post("/reports/get_storage", params)
      end

      # https://www.dropbox.com/developers/business/docs#reports-get-activity
      def get_activity(params)
        @connection.post("/reports/get_activity", params)
      end

      # https://www.dropbox.com/developers/business/docs#reports-get-membership
      def get_membership(params)
        @connection.post("/reports/get_membership", params)
      end

      def get_devices(params)
        @connection.post("/reports/get_devices", params)
      end

    end
  end
end


text:
namespace ash {

VmDiskManagementServiceProvider::VmDiskManagementServiceProvider() = default;

VmDiskManagementServiceProvider::~VmDiskManagementServiceProvider() = default;

void VmDiskManagementServiceProvider::Start(
    scoped_refptr<dbus::ExportedObject> exported_object) {
  exported_object->ExportMethod(
      vm_tools::disk_management::kVmDiskManagementServiceInterface,
      vm_tools::disk_management::kVmDiskManagementServiceGetDiskInfoMethod,
      base::BindRepeating(&VmDiskManagementServiceProvider::GetDiskInfo,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&VmDiskManagementServiceProvider::OnExported,
                     weak_ptr_factory_.GetWeakPtr()));
  exported_object->ExportMethod(
      vm_tools::disk_management::kVmDiskManagementServiceInterface,
      vm_tools::disk_management::kVmDiskManagementServiceRequestSpaceMethod,
      base::BindRepeating(&VmDiskManagementServiceProvider::RequestSpace,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&VmDiskManagementServiceProvider::OnExported,
                     weak_ptr_factory_.GetWeakPtr()));
  exported_object->ExportMethod(
      vm_tools::disk_management::kVmDiskManagementServiceInterface,
      vm_tools::disk_management::kVmDiskManagementServiceReleaseSpaceMethod,
      base::BindRepeating(&VmDiskManagementServiceProvider::ReleaseSpace,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&VmDiskManagementServiceProvider::OnExported,
                     weak_ptr_factory_.GetWeakPtr()));
}

void VmDiskManagementServiceProvider::OnExported(
    const std::string& interface_name,
    const std::string& method_name,
    bool success) {
  LOG_IF(ERROR, !success) << "Failed to export " << interface_name << "."
                          << method_name;
}

void VmDiskManagementServiceProvider::GetDiskInfo(
    dbus::MethodCall* method_call,
    dbus::ExportedObject::ResponseSender response_sender) {
  dbus::MessageReader reader(method_call);

  vm_tools::disk_management::GetDiskInfoRequest request;
  if (!reader.PopArrayOfBytesAsProto(&request)) {
    constexpr char error_message[] =
        "Unable to parse GetDiskInfoRequest from message";
    LOG(ERROR) << error_message;
    std::move(response_sender)
        .Run(dbus::ErrorResponse::FromMethodCall(
            method_call, DBUS_ERROR_INVALID_ARGS, error_message));
    return;
  }

  std::unique_ptr<dbus::Response> response =
      dbus::Response::FromMethodCall(method_call);

  if (request.origin().vm_name().empty() ||
      request.origin().container_name().empty() ||
      request.origin().owner_id().empty()) {
    OnGetDiskInfo(std::move(response), std::move(response_sender),
                  ExpectedGetDiskInfoResponse::Unexpected(
                      borealis::Described<borealis::BorealisGetDiskInfoResult>(
                          borealis::BorealisGetDiskInfoResult::kInvalidRequest,
                          "GetDiskInfoRequest failed: request has missing or "
                          "incomplete origin")));
    return;
  }

  borealis::BorealisService::GetForProfile(
      ProfileManager::GetPrimaryUserProfile())
      ->DiskManagerDispatcher()
      .GetDiskInfo(
          request.origin().vm_name(), request.origin().container_name(),
          base::BindOnce(&VmDiskManagementServiceProvider::OnGetDiskInfo,
                         weak_ptr_factory_.GetWeakPtr(), std::move(response),
                         std::move(response_sender)));
}

void VmDiskManagementServiceProvider::RequestSpace(
    dbus::MethodCall* method_call,
    dbus::ExportedObject::ResponseSender response_sender) {
  dbus::MessageReader reader(method_call);

  vm_tools::disk_management::RequestSpaceRequest request;
  if (!reader.PopArrayOfBytesAsProto(&request)) {
    constexpr char error_message[] =
        "Unable to parse RequestSpaceRequest from message";
    LOG(ERROR) << error_message;
    std::move(response_sender)
        .Run(dbus::ErrorResponse::FromMethodCall(
            method_call, DBUS_ERROR_INVALID_ARGS, error_message));
    return;
  }

  std::unique_ptr<dbus::Response> response =
      dbus::Response::FromMethodCall(method_call);

  if (request.origin().vm_name().empty() ||
      request.origin().container_name().empty() ||
      request.origin().owner_id().empty()) {
    OnRequestSpace(
        std::move(response), std::move(response_sender),
        ExpectedRequestDeltaResponse::Unexpected(
            borealis::Described<borealis::BorealisResizeDiskResult>(
                borealis::BorealisResizeDiskResult::kInvalidRequest,
                "RequestSpaceRequest failed: request has missing or incomplete "
                "origin")));
    return;
  }

  borealis::BorealisService::GetForProfile(
      ProfileManager::GetPrimaryUserProfile())
      ->DiskManagerDispatcher()
      .RequestSpace(
          request.origin().vm_name(), request.origin().container_name(),
          request.space_requested(),
          base::BindOnce(&VmDiskManagementServiceProvider::OnRequestSpace,
                         weak_ptr_factory_.GetWeakPtr(), std::move(response),
                         std::move(response_sender)));
}

void VmDiskManagementServiceProvider::ReleaseSpace(
    dbus::MethodCall* method_call,
    dbus::ExportedObject::ResponseSender response_sender) {
  dbus::MessageReader reader(method_call);

  vm_tools::disk_management::ReleaseSpaceRequest request;
  if (!reader.PopArrayOfBytesAsProto(&request)) {
    constexpr char error_message[] =
        "Unable to parse ReleaseSpaceRequest from message";
    LOG(ERROR) << error_message;
    std::move(response_sender)
        .Run(dbus::ErrorResponse::FromMethodCall(
            method_call, DBUS_ERROR_INVALID_ARGS, error_message));
    return;
  }

  std::unique_ptr<dbus::Response> response =
      dbus::Response::FromMethodCall(method_call);

  if (request.origin().vm_name().empty() ||
      request.origin().container_name().empty() ||
      request.origin().owner_id().empty()) {
    OnReleaseSpace(
        std::move(response), std::move(response_sender),
        ExpectedRequestDeltaResponse::Unexpected(
            borealis::Described<borealis::BorealisResizeDiskResult>(
                borealis::BorealisResizeDiskResult::kInvalidRequest,
                "ReleaseSpaceRequest failed: request has missing or incomplete "
                "origin")));
    return;
  }

  borealis::BorealisService::GetForProfile(
      ProfileManager::GetPrimaryUserProfile())
      ->DiskManagerDispatcher()
      .ReleaseSpace(
          request.origin().vm_name(), request.origin().container_name(),
          request.space_to_release(),
          base::BindOnce(&VmDiskManagementServiceProvider::OnReleaseSpace,
                         weak_ptr_factory_.GetWeakPtr(), std::move(response),
                         std::move(response_sender)));
}

void VmDiskManagementServiceProvider::OnGetDiskInfo(
    std::unique_ptr<dbus::Response> response,
    dbus::ExportedObject::ResponseSender response_sender,
    ExpectedGetDiskInfoResponse response_or_error) {
  vm_tools::disk_management::GetDiskInfoResponse payload;
  if (!response_or_error) {
    LOG(ERROR) << "GetDiskInfoRequest failed: "
               << response_or_error.Error().description();
    payload.set_error(int(response_or_error.Error().error()));
  } else {
    payload.set_available_space(response_or_error.Value().available_bytes);
    payload.set_expandable_space(response_or_error.Value().expandable_bytes);
    payload.set_disk_size(response_or_error.Value().disk_size);
  }
  // Reply to the original D-Bus method call.
  dbus::MessageWriter writer(response.get());
  writer.AppendProtoAsArrayOfBytes(payload);
  std::move(response_sender).Run(std::move(response));
}

void VmDiskManagementServiceProvider::OnRequestSpace(
    std::unique_ptr<dbus::Response> response,
    dbus::ExportedObject::ResponseSender response_sender,
    ExpectedRequestDeltaResponse response_or_error) {
  vm_tools::disk_management::RequestSpaceResponse payload;
  if (!response_or_error) {
    LOG(ERROR) << "RequestSpaceRequest failed: "
               << response_or_error.Error().description();
    payload.set_error(int(response_or_error.Error().error()));
  } else {
    payload.set_space_granted(response_or_error.Value());
  }
  // Reply to the original D-Bus method call.
  dbus::MessageWriter writer(response.get());
  writer.AppendProtoAsArrayOfBytes(payload);
  std::move(response_sender).Run(std::move(response));
}

void VmDiskManagementServiceProvider::OnReleaseSpace(
    std::unique_ptr<dbus::Response> response,
    dbus::ExportedObject::ResponseSender response_sender,
    ExpectedRequestDeltaResponse response_or_error) {
  vm_tools::disk_management::ReleaseSpaceResponse payload;
  if (!response_or_error) {
    LOG(ERROR) << "ReleaseSpaceRequest failed: "
               << response_or_error.Error().description();
    payload.set_error(int(response_or_error.Error().error()));
  } else {
    payload.set_space_released(response_or_error.Value());
  }
  // Reply to the original D-Bus method call.
  dbus::MessageWriter writer(response.get());
  writer.AppendProtoAsArrayOfBytes(payload);
  std::move(response_sender).Run(std::move(response));
}

}  // namespace ash


text:
@implementation UIColor (UIColorCategory)

+(UIColor*) randomColor {
    UIColor* colorForReturn = nil;
    int randomColorNum = arc4random_uniform(13);
    switch (randomColorNum) {
        case 0:
            colorForReturn = [UIColor blackColor];
            break;
        case 1:
            colorForReturn = [UIColor darkGrayColor];
            break;
        case 2:
            colorForReturn = [UIColor lightGrayColor];
            break;
        case 3:
            colorForReturn = [UIColor grayColor];
            break;
        case 4:
            colorForReturn = [UIColor redColor];
            break;
        case 5:
            colorForReturn = [UIColor greenColor];
            break;
        case 6:
            colorForReturn = [UIColor blueColor];
            break;
        case 7:
            colorForReturn = [UIColor cyanColor];
            break;
        case 8:
            colorForReturn = [UIColor yellowColor];
            break;
        case 9:
            colorForReturn = [UIColor magentaColor];
            break;
        case 10:
            colorForReturn = [UIColor orangeColor];
            break;
        case 11:
            colorForReturn = [UIColor purpleColor];
            break;
        case 12:
            colorForReturn = [UIColor brownColor];
            break;

        default:
            colorForReturn = [UIColor greenColor];
            break;
    }

    return colorForReturn;
}

@end


text:
@implementation IOUser

@end


text:
class CreateCuratedPages < ActiveRecord::Migration
  def self.up
    create_table :curated_pages do |t|
      t.string :name
      t.string :description
      t.string :analytics_id
      t.string :image_url
      t.string :video_url

      t.timestamps
    end

    add_column :projects, :curated_page_id, :integer
  end

  def self.down
    drop_table :curated_pages
    remove_column :projects, :curated_page_id
  end
end


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

<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>London 2013
 -  Proposal</title>
<meta name="author" content="Juan Breinlinger" >

<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >

<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">

      Home

      Contact

      Events

      Presentations

      Blog

London 2013
 -  Proposal

Gold sponsors

welcome
propose
program
location
register
sponsor
contact
reactions

Back to proposals overview - program

How do you get releases down to 12 minutes at 12-years-old lastminute.com?

Abstract:

Starting devops from scratch in a startup may be a breeze compared to transforming one of the world's classic dotcom companies saddled with a 12-year-old architecture. Imagine being faced with operations versus development teams, SVN/Perforce/CVS deploys, code copy-and-paste processes, manual configurations and, to make it even more fun, teams across different regions.

But at the same time everyone wants confident software deployments, improved availability, low cost solutions and a good working environment.

What can we do to make that happen? There is no single easy answer.

At lastminute.com we had to change the way we worked at multiple layers. We started with our mobile website and have been extending it organically across interconnected applications and processes. For greenfield development, the process is relatively easy to plan. However, for the majority of systems in such a mature enterprise you are faced with a far greater challenge: transforming applications and processes that are already weighed down with obstacles to automation.

We learned that the key ingredient for this transformation is collaboration. There is also a particular rhythm to expanding continuous delivery system by system in an "island hopping" strategy. We feed off the learnings, momentum, and success of each system to build confidence and convince stakeholders to invest in transforming related systems.

As part of the talk I will illustrate the technical details and toolsets behind our process. I will walk through an application build, starting when a developer submits a single line of code through to the application ending reliably deployed in production.

Speaker:

Juan Breinlinger

Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by Disqus

Gold sponsors

Silver sponsors


text:
numero_magico = 12345679
numero_usuario = int(input('Ingresa un numero entero del 1-9'))

numero_usuario *= 9
numero_magico *= numero_usuario
print(numero_magico)


text:
Sequel.migration do
  up do
    create_table(:users) do
      primary_key :id
      String      :email,      :size => 80,  :null => false, :index => true
      Text        :preferences
      DateTime    :created_at,               :null => false
      DateTime    :updated_at,               :null => false
    end
  end

  down do
    drop_table?(:users)
  end
end


text:
package io.github.zwieback.relef.configs;

import io.github.zwieback.relef.analyzers.MsProductAnalyzer;
import io.github.zwieback.relef.importers.excel.MsProductImporter;
import io.github.zwieback.relef.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.function.Function;

@Configuration
@ComponentScan("io.github.zwieback.relef.analyzers")
public class AnalyzerConfig {

    private final JdbcTemplate jdbcTemplate;
    private final ProductRepository productRepository;
    private final Function<String, MsProductImporter> msProductImporterFactory;

    @Autowired
    public AnalyzerConfig(JdbcTemplate jdbcTemplate,
                          ProductRepository productRepository,
                          Function<String, MsProductImporter> msProductImporterFactory) {
        this.jdbcTemplate = jdbcTemplate;
        this.productRepository = productRepository;
        this.msProductImporterFactory = msProductImporterFactory;
    }

    @Bean
    public Function<String, MsProductAnalyzer> msProductAnalyzerFactory() {
        return this::msProductAnalyzer;
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    MsProductAnalyzer msProductAnalyzer(String fileName) {
        MsProductImporter msProductImporter = msProductImporterFactory.apply(fileName);
        return new MsProductAnalyzer(jdbcTemplate, productRepository, msProductImporter);
    }
}


text:
package com.google.devtools.depan.filesystem;

import com.google.devtools.depan.eclipse.ui.nodes.plugins.NodeElementPlugin;
import com.google.devtools.depan.filesystem.eclipse.FileSystemCategoryTransformer;
import com.google.devtools.depan.filesystem.eclipse.FileSystemIconTransformer;
import com.google.devtools.depan.filesystem.eclipse.FileSystemImageTransformer;
import com.google.devtools.depan.filesystem.eclipse.FileSystemNodeComparator;
import com.google.devtools.depan.filesystem.eclipse.FileSystemNodePainter;
import com.google.devtools.depan.filesystem.graph.FileSystemElements;
import com.google.devtools.depan.model.Element;
import com.google.devtools.depan.model.ElementTransformer;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;

import java.awt.Color;
import java.util.Collection;
import java.util.Comparator;

/**
 * DepAn Plug-in that models the File System. It is intended to be included from
 * other plug-ins that use a file system; however, it is possible to use this
 * plug-in in DepAn as is.
 *
 * @author tugrul@google.com (Tugrul Ince)
 */
public class FileSystemNodePlugin implements NodeElementPlugin {

  @Override
  public Collection<Class<? extends Element>> getElementClasses() {
    return FileSystemElements.NODES;
  }

  @Override
  public ElementTransformer<Color> getElementColorProvider() {
    return FileSystemNodePainter.getInstance();
  }

  @Override
  public ElementTransformer<ImageDescriptor>
      getElementImageDescriptorProvider() {
    return FileSystemIconTransformer.getInstance();
  }

  @Override
  public ElementTransformer<Image> getElementImageProvider() {
    return FileSystemImageTransformer.getInstance();
  }

  @Override
  public Comparator<Element> getElementSorter() {
    return FileSystemNodeComparator.getInstance();
  }

  @Override
  public ElementTransformer<Integer> getElementCategoryProvider() {
    return FileSystemCategoryTransformer.getInstance();
  }
}


text:
describe('Notification', function() {
  var instance;

  beforeEach(function() {
    jQuery.fx.off = true;

    loadFixtures('cells_notification.html');
    Notification.instances = [];
    instance = Cell.findOrCreateInstance($('[data-cell="Notification"]').get(0));
  });

  describe('#initialize', function() {
    it('should define the "initialClassName" property', function() {
      expect(instance.initialClassName).toEqual(instance.target.className);
    });

    it('should define the "$content" property', function() {
      expect(instance.$content).toBeDefined();
    });

    it('should initialize the event handlers', function() {
      spyOn(instance, 'initializeEventHandlers');
      instance.initialize();
      expect(instance.initializeEventHandlers).wasCalled();
    });
  });

  describe('#initializeEventHandlers', function() {
    beforeEach(function() {
      $(window).off();
      instance.initializeEventHandlers();
    });

    it('should bind the showNotification event', function() {
      spyOn(instance, 'show');
      $(window).trigger('showNotification', {'classification': 'foo', 'message': 'bar'});
      expect(instance.show).wasCalledWith('foo', 'bar');
    });

    it('should bind the hideNotification event', function() {
      spyOn(instance, 'hide');
      $(window).trigger('hideNotification');
      expect(instance.hide).wasCalled();
    });
  });

  describe('#show', function() {
    it('should append the classification to the CSS class name', function() {
      instance.show('warning', 'Foo Bar');
      expect(instance.$target.hasClass('warning')).toBeTruthy();
    });

    it('should reset the currently appended CSS class name up front', function() {
      instance.show('warning', 'Foo Bar');
      instance.show('error', 'More Foo Bar');
      expect(instance.$target.hasClass('warning')).toBeFalsy();
    });

    it('should show the notification container', function() {
      instance.show('warning', 'Foo Bar');
      expect(instance.shown()).toBeTruthy();
    });

    it('should set the notification message', function() {
      instance.show('warning', 'Mega Foo');
      expect(instance.$content.html()).toEqual('Mega Foo');
    });

    it("should expand to the '$content' outer height", function() {
      instance.show('warning', 'Foo Bar<br />More Foo');
      expect(instance.$target.height()).toEqual(instance.$content.outerHeight());
    });

    it('should hide automatically after the specified interval', function() {
      spyOn(window, 'setTimeout');
      instance.show('warning', 'Foo Bar');

      expect(window.setTimeout.argsForCall[0][1]).toEqual(Notification.hideAfter);

      spyOn(instance, 'hide');
      window.setTimeout.argsForCall[0][0]();
      expect(instance.hide).wasCalled();
    });

    describe('when a notification is shown', function() {
      it('should hide the current notification before showing the next', function() {
        instance.show('warning', 'Foo Bar');
        spyOn(instance, 'hide');
        instance.show('error', 'More Foo Bar');
        expect(instance.hide).wasCalled();
      });
    });
  });

  describe('#shown', function() {
    it("should verify the $target's current 'display' value", function() {
      spyOn(instance.$target, 'css').andCallThrough();
      instance.shown();
      expect(instance.$target.css).wasCalledWith('display');
    });

    it("should return true if the 'display' value equals 'block'", function() {
      spyOn(instance.$target, 'css').andReturn('block');
      expect(instance.shown()).toBeTruthy();
    });

    it("should return true if the 'display' value does not equal 'block'", function() {
      spyOn(instance.$target, 'css').andReturn('none');
      expect(instance.shown()).toBeFalsy();
    });
  });

  describe('#hide', function() {
    it('should hide the notification', function() {
      instance.show('warning', 'Foo Bar');
      instance.hide();
      expect(instance.shown()).toBeFalsy();
    });
  });

  describe('static #show', function() {
    it("should trigger the 'showNotification' event", function() {
      var stub = {'callback': function(a, b) {}};
      $(window).on('showNotification', function(eventObject, data) { stub.callback(data.classification, data.message); });
      spyOn(stub, 'callback');
      Notification.show('foo', 'bar');
      expect(stub.callback).wasCalledWith('foo', 'bar');
    });
  });

  describe('static #hide', function() {
    it("should trigger the 'hideNotification' event", function() {
      var stub = {'callback': function() {}};
      $(window).on('hideNotification', function() { stub.callback(); });
      spyOn(stub, 'callback');
      Notification.hide();
      expect(stub.callback).wasCalled();
    });
  });
});


text:
from __future__ import print_function
from mindmup_as_attack_trees import *

import sys,json
import re
from collections import OrderedDict
import math
import argparse
parser = argparse.ArgumentParser()

parser.add_argument('mupin', nargs='?', help="the mindmup file that will be processed -- transforming and augmenting the JSON")
args = parser.parse_args()

#import ipdb
def info(type, value, tb):
	ipdb.pm()

sys.excepthook = info

levels_count = dict()
nodes_lookup = dict()
fixups_queue = list()
objective_node = None

if args.mupin is None:
	fd_in=sys.stdin
else:
	fd_in=open(args.mupin, 'r')

data = json.load(fd_in)

if args.mupin is None:
	fd_out = sys.stdout
else:
	fd_in.close()
	fd_out=open(args.mupin,'w')

nodes_context=list()

if 'id' in data and data['id'] == 'root':
	#version 2 mindmup
	root_node = data['ideas']['1']
else:
	root_node = data

dedup_with_references(root_node)

normalize_nodes(root_node)
str = json.dumps(data, indent=2, sort_keys=False)
str = re.sub(r'\s+$', '', str, 0, re.M)
str = re.sub(r'\s+$', '', str, flags=re.M)

fd_out.write(str)

if len(sys.argv) >= 1:
	fd_out.close()


text:
--
-- Version: Each entry describes a drug and the disorder(s) it targets.  Supports Azure SQL Server.
-- URL: http://ostlog.org/schema/Drug_targets.json
--
CREATE TABLE [dbo].[Drug targets] (
	[drug_atc_code] NVARCHAR(50) NOT NULL,
	[disorder_sctid_code] INT NOT NULL,
	[disorder_name] NVARCHAR (50),
	[remarks] NVARCHAR (4000) NULL,
	CONSTRAINT [PK_Drug disorder lookup] PRIMARY KEY CLUSTERED ([drug_atc_code] ASC, [disorder_sctid_code] ASC),

)


text:
package french

import (
	"github.com/kljensen/snowball/snowballword"
)

// Step 2a is the removal of Verb suffixes beginning
// with "i" in the RV region.
//
func step2a(word *snowballword.SnowballWord) bool {

	// Search for the longest among the following suffixes
	// in RV and if found, delete if preceded by a non-vowel.

	suffix, suffixRunes := word.FirstSuffixIn(word.RVstart, len(word.RS),
		"issantes", "issaIent", "issions", "issants", "issante",
		"iraIent", "issons", "issiez", "issent", "issant", "issait",
		"issais", "irions", "issez", "isses", "iront", "irons", "iriez",
		"irent", "irait", "irais", "îtes", "îmes", "isse", "irez",
		"iras", "irai", "ira", "ies", "ît", "it", "is", "ir", "ie", "i",
	)
	if suffix != "" {
		sLen := len(suffixRunes)
		idx := len(word.RS) - sLen - 1
		if idx >= 0 && word.FitsInRV(sLen+1) && isLowerVowel(word.RS[idx]) == false {
			word.RemoveLastNRunes(len(suffixRunes))
			return true
		}
	}
	return false
}


text:
import os
import subprocess
import pprint
import logging

# This module provides a wrapper for subprocess.POpen
# that can be used for debugging

# Internal logger
_logger = logging.getLogger(__name__)

def Popen(*pargs, **kwargs):
    _logger.debug("WLLVM Executing:\n" + pprint.pformat(pargs[0]) + "\nin: " +  os.getcwd())
    try:
        return subprocess.Popen(*pargs, **kwargs)
    except OSError:
        _logger.error("WLLVM Failed to execute: %s", pprint.pformat(pargs[0]))
        raise


text:
"""
    make-release
    ~~~~~~~~~~~~

    Helper script that performs a release.  Does pretty much everything
    automatically for us.

    :copyright: (c) 2015 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.

    This code was adapted from the Flask project. The specific origin including
    commit of the code is here:

    https://raw.githubusercontent.com/mitsuhiko/flask/33534bb4a9937e6faba5ecec4586519f453369b6/scripts/make-release.py

"""
import sys
import os
import re
from datetime import datetime, date
from subprocess import Popen, PIPE

_date_clean_re = re.compile(r'(\d+)(st|nd|rd|th)')

def parse_changelog():
    with open('CHANGELOG.md') as f:
        lineiter = iter(f)
        for line in lineiter:
            match = re.search('^## Version\s+(.*)', line.strip())
            if match is None:
                continue
            version = match.group(1).strip()
            while 1:
                change_info = lineiter.next().strip()
                if change_info:
                    break

            match = re.search(r'released on (\w+\s+\d+\w+\s+\d+)',
                              change_info)

            if match is None:
                continue

            datestr = match.groups(1)[0]
            return version, parse_date(datestr)

def bump_version(version):
    try:
        parts = map(int, version.split('.'))
    except ValueError:
        fail('Current version is not numeric')
    parts[-1] += 1
    return '.'.join(map(str, parts))

def parse_date(string):
    string = _date_clean_re.sub(r'\1', string)
    return datetime.strptime(string, '%B %d %Y')

def set_filename_version(filename, version_number, pattern):
    changed = []

    def inject_version(match):
        before, old, after = match.groups()
        changed.append(True)
        return before + version_number + after
    with open(filename) as f:
        contents = re.sub(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern,
                          inject_version, f.read())

    if not changed:
        fail('Could not find %s in %s', pattern, filename)

    with open(filename, 'w') as f:
        f.write(contents)

def set_init_version(version):
    info('Setting __init__.py version to %s', version)
    set_filename_version('moi/__init__.py', version, '__version__')

def set_setup_version(version):
    info('Setting setup.py version to %s', version)
    set_filename_version('setup.py', version, 'version')

def build_and_upload():
    Popen([sys.executable, 'setup.py', 'sdist', 'upload']).wait()

def fail(message, *args):
    print >> sys.stderr, 'Error:', message % args
    sys.exit(1)

def info(message, *args):
    print >> sys.stderr, message % args

def get_git_tags():
    return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines())

def git_is_clean():
    return Popen(['git', 'diff', '--quiet']).wait() == 0

def make_git_commit(message, *args):
    message = message % args
    Popen(['git', 'commit', '-am', message]).wait()

def make_git_tag(tag):
    info('Tagging "%s"', tag)
    Popen(['git', 'tag', tag]).wait()

def main():
    os.chdir(os.path.join(os.path.dirname(__file__), '..'))

    rv = parse_changelog()
    if rv is None:
        fail('Could not parse changelog')

    version, release_date = rv
    dev_version = bump_version(version) + '-dev'

    info('Releasing %s (release date %s)',
         version, release_date.strftime('%d/%m/%Y'))
    tags = get_git_tags()

    if version in tags:
        fail('Version "%s" is already tagged', version)
    if release_date.date() != date.today():
        fail('Release date is not today (%s != %s)',
             release_date.date(), date.today())

    if not git_is_clean():
        fail('You have uncommitted changes in git')

    set_init_version(version)
    make_git_commit('Bump version number to %s', version)
    make_git_tag(version)
    build_and_upload()
    set_init_version(dev_version)

if __name__ == '__main__':
    main()


text:
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

module CouchDB.DBChallenge where

import qualified Data.ByteString.Char8             as C
import           Data.Conduit
import           Data.Conduit.List                 as CL
import           Data.Maybe                        (fromJust, listToMaybe)
import           Database.CouchDB.Conduit
import           Database.CouchDB.Conduit.Explicit
import           Database.CouchDB.Conduit.View

import           CouchDB.DBCommon

import qualified Model.Challenge                   as Challenge
import qualified Model.UUID                        as UUID

create :: Challenge.Challenge -> IO Challenge.Challenge
create challenge = do
    uuid <- fmap UUID.toByteString' UUID.nextRandom
    runCouch conn $ do
        let rev = ""
        revision <- couchPut dbName uuid rev [] challenge
        return challenge { Challenge.uuid     = UUID.fromByteStringSafe' uuid
                         , Challenge.revision = Just revision }

type ChallengeUUID = UUID.UUID
type ContractUUID = UUID.UUID
type TokenValue = C.ByteString
findChallenge :: ChallengeUUID -> ContractUUID -> IO (Maybe Challenge.Challenge)
findChallenge challengeUUID contractUUID = do
    tokens <- runCouch conn $
        couchView_ dbName "challenge" "listChallengesWithContractUUID"
            [("key", Just $ encodeKeys $ fmap UUID.toByteString' [challengeUUID, contractUUID])] $
            rowValue =$= toType =$ CL.consume
    return $ listToMaybe tokens

setAnswered :: Challenge.Challenge -> IO Challenge.Challenge
setAnswered challenge = runCouch conn $ do
    let uuid = UUID.toByteString' $ fromJust $ Challenge.uuid challenge
        rev  = fromJust $ Challenge.revision challenge
        challenge' = challenge { Challenge.wasAnswered = True }
    revision <- couchPut dbName uuid rev [] challenge'
    return challenge' { Challenge.revision = Just revision }


text:
// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********

#ifndef SRC_CORE_AREA_H_
#define SRC_CORE_AREA_H_

#include "core/animation.h"
#include "core/keyboard.h"
#include "core/tile-grid.h"
#include "core/tile.h"
#include "core/vec.h"
#include "util/hashtable.h"
#include "util/optional.h"
#include "util/rc.h"
#include "util/string-view.h"
#include "util/string.h"

#define ISOMETRIC_ZOFF_PER_TILE 0.001

class AreaJSON;
class Character;
class DataArea;
struct DisplayList;
class Entity;
class NPC;
class Overlay;
class Player;

//! An Area represents one map, or screen, in a World.
/*!
    The Area class manages a three-dimensional structure of Tiles and a set
    of Entities.

    The game's Viewport must be "focused" on an Area. Only one Area can be
    focused on at a time.

    The viewport will not scroll past the edge of an Area. (At least as of
    June 2012. :)
*/
class Area {
 public:
    //! Prepare game state for this Area to be in focus.
    void focus();

    //! Processes keyboard input, calling the Player object when necessary.
    void buttonDown(KeyboardKey key);
    void buttonUp(KeyboardKey key);

    //! Renders all visible Tiles and Entities within this Area.
    void draw(DisplayList* display);

    //! If false, drawing might be skipped. Saves CPU cycles when idle.
    bool needsRedraw();

    //! Inform the Area that a redraw is needed.
    void requestRedraw();

    /**
     * Update the game state within this Area as if dt milliseconds had
     * passed since the last call. Updates Entities, runs scripts, and
     * checks for Tile animation updates.
     */
    void tick(time_t dt);

    /**
     * Updates Entities, runs scripts, and checks for Tile animation
     * updates.
     */
    void turn();

    uint32_t getColorOverlay();
    void setColorOverlay(uint8_t a, uint8_t r, uint8_t g, uint8_t b);

    TileSet* getTileSet(StringView imagePath);

    //! Returns a physical cubic range of Tiles that are visible on-screen.
    //! Takes actual map size into account.
    icube visibleTiles() const;

    //! Returns true if a Tile exists at the specified coordinate.
    bool inBounds(Entity* ent) const;

    // Create an NPC and insert it into the Area.
    Rc<Character> spawnNPC(StringView descriptor,
                           vicoord coord,
                           StringView phase);
    // Create an Overlay and insert it into the Area.
    Rc<Overlay> spawnOverlay(StringView descriptor,
                             vicoord coord,
                             StringView phase);

    DataArea* getDataArea();

    void runScript(TileGrid::ScriptType type,
                   icoord tile,
                   Entity* triggeredBy) noexcept;

 public:
    TileGrid grid;

    bool ok = true;

 protected:
    //! Calculate frame to show for each type of tile
    void drawTiles(DisplayList* display, const icube& tiles, int z);
    void drawEntities(DisplayList* display, const icube& tiles, int z);

 protected:
    Hashmap<String, TileSet> tileSets;

    Vector<Animation> tileGraphics;
    Vector<bool> checkedForAnimation;
    Vector<bool> tilesAnimated;

    Vector<Rc<Character>> characters;
    Vector<Rc<Overlay>> overlays;

    bool beenFocused = false;
    bool redraw = true;
    uint32_t colorOverlayARGB = 0x00000000;

    DataArea* dataArea;

    Player* player;

    // The following contain filenames such that they may be loaded lazily.
    String descriptor;

    String name;
    String author;
    Optional<String> musicPath;

    friend AreaJSON;
};

#endif  // SRC_CORE_AREA_H_


text:
var ol = require('openlayers');
var Backbone = require('backbone');

var imageStyle = new ol.style.Circle({
    radius: 5,
      snapToPixel: false,
      fill: new ol.style.Fill({color: 'yellow'}),
      stroke: new ol.style.Stroke({color: 'red', width: 1})
});

var headInnerImageStyle = new ol.style.Style({
    image: new ol.style.Circle({
                 radius: 2,
          snapToPixel: false,
          fill: new ol.style.Fill({color: 'blue'})
        })
});

var headOuterImageStyle = new ol.style.Circle({
    radius: 5,
      snapToPixel: false,
      fill: new ol.style.Fill({color: 'black'})
});

var n = 30;
var omegaTheta = 30000; // Rotation period in ms
var R = 7e6;
var r = 2e6;
var p = 2e6;

var Transfer = Backbone.Model.extend({
  defaults: {
    start_latlng: [0, 0], //開始座標
    end_latlng: [0, 0], //終了座標
    country: "", //国名
    //Export: 0, //輸出量
    //Import: 0, //輸入量
    distance: 0 //距離
  },
  initialize: function(attrs, options) {
    console.log("Calc");

  }
});
var TransferCollection = Backbone.Collection.extend({
  model: Transfer
});

var TransferManager = function() {
  this.transferCollection;
  this.vectorSource = new ol.source.Vector();

};
TransferManager.prototype = {
  initialize: function(json) {
    this.transferCollection = new TransferCollection();
    //console.log(this.transferCollection);
    var forSearchData = {};
    for (var n=0; n<json.length; n++) {
      forSearchData[json[n].country] = json[n];
    }
    console.log(forSearchData);
    for (var j=0; j<json.length; j++) {
      //if (j > 10) continue;
      var item = json[j];
      var slat = item.lat;
      var slon = item.lon;
      if (item.Rank >= 3) {
        continue;
      }
      var distance_list = item.distance_list;
      var distance_count_list = Array();
      for (var i=0; i<distance_list.length; i++) {
          if (distance_count_list.length <= 3) {
            distance_count_list.push(distance_list[i]);
          } else if (distance_count_list[2].distance > distance_list[i].distance) {
            distance_count_list.push(distance_list[i]);
          }
          distance_count_list.sort(function(value1, value2) {
              if (value1.distance == value2.distance) {
                return 0;
              } else if (value1.distance < value2.distance) {
                return -1;
              }
              return 1;
          });
          if (distance_count_list.length > 3) {
            distance_count_list.pop();
          }
      }

      for (var i=0; i<distance_count_list.length; i++) {
        //if (i > 5) continue;
        var hitCountryData = forSearchData[distance_count_list[i].country];
        if (!hitCountryData) continue;
        var elat = hitCountryData.lat;
        var elon = hitCountryData.lon;
        var transferModel = new Transfer({
          start_latlng: [slat, slon],
          end_latlng: [elat, elon],
          distance: distance_count_list[i].distance,
          country: item.country
        });
        this.transferCollection.push(transferModel);

        /*
        var transferModel2 = new Transfer({
          start_latlng: [slat, slon],
          end_latlng: [elat, elon],
          distance: distance_count_list[i].distance,
          country: distance_count_list[i].country
        });
        this.transferCollection.push(transferModel2);
        */
      }
    }
    console.log(this.transferCollection);// 4000件くらいの国同士のつながりを保持
  },
  makeTransferRoutes: function() {

  },
  paintOneCountry: function(map, countryName) {
    this.vectorSource.clear();
    var showlist = this.transferCollection.where({ country: countryName })
    console.log(showlist);
    var featureList = [];
    for (var i=0; i<showlist.length; i++) {
      featureList.push(this.getFeatureFromModel(showlist[i]));
      featureList.push(this.getCircleFromModel(showlist[i]));
    }
    this.vectorSource = new ol.source.Vector({
      features: featureList
    });
    var layerLines = new ol.layer.Vector({
      source: this.vectorSource
    });
    map.addLayer(layerLines);
  },
  paint: function(map) {
    this.vectorSource.clear();
    var featureList = [];
    //線が多すぎるとアイコンが見えない
    for (var i=0; i<this.transferCollection.models.length; i++) {
      var item = this.transferCollection.models[i];
      var feature = this.getFeatureFromModel(item);
      featureList.push(feature);
    }
    this.vectorSource = new ol.source.Vector({
      features: featureList
    });
    var layerLines = new ol.layer.Vector({
      source: this.vectorSource
    });
    map.addLayer(layerLines);
  },
  getFeatureFromModel: function(model) {
    var sp = ol.proj.transform(
      [model.get("start_latlng")[1], model.get("start_latlng")[0]],
      'EPSG:4326', 'EPSG:3857');
    var ep = ol.proj.transform(
      [model.get("end_latlng")[1], model.get("end_latlng")[0]],
      'EPSG:4326', 'EPSG:3857');
    return new ol.Feature({
      geometry: new ol.geom.LineString([sp, ep]),
      name: 'Line'
    });
  },
  getCircleFromModel: function(model) {
    var ep = ol.proj.transform(
      [model.get("end_latlng")[1], model.get("end_latlng")[0]],
      'EPSG:4326', 'EPSG:3857');
    console.log(ep);
    return new ol.Feature({
      geometry: new ol.geom.Circle(ep, 300000),
      name: 'Circle'
    });
  }
};

module.exports = TransferManager;


text:
package fi.hut.cs.drumbeat.common.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;

public class FileManager {

	public static File createDirectory(String directoryPath) {
		File directory = new File(directoryPath);
		if (!directory.exists()) {
			directory.mkdir();
		}
		return directory;
	}

	public static String createFileName(File directory, String fileName) {
		return String.format("%s%s%s", directory.getAbsolutePath(), File.separatorChar, fileName);
	}

	public static File createFile(String filePath) throws IOException {
		File file = new File(filePath);
		File parentFile = file.getParentFile();
		if (parentFile != null && !parentFile.exists()) {
			parentFile.mkdirs();
		}
		return file;
	}

	public static FileWriter createFileWriter(String filePath) throws IOException {
		File file = new File(filePath);
		File parentFile = file.getParentFile();
		if (parentFile != null) {
			parentFile.mkdirs();
		}
		return new FileWriter(file);
	}

	public static FileOutputStream createFileOutputStream(String filePath) throws IOException {
		File file = new File(filePath);
		file.getParentFile().mkdirs();
		return new FileOutputStream(file);
	}

	public static String getReadableFileSize(long size) {
	    if(size <= 0) return "0";
	    final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
	    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
	    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
	}

	public static String createFileNameWithExtension(String filePath, String extension) {

		String tempFilePath = filePath;

		String[] tokens = extension.split("\\.");

		int firstExtentionToBeAdded = tokens.length;

		for (int i = tokens.length - 1; i >= 0; --i) {
			tokens[i] = "." + tokens[i];
			if (tempFilePath.endsWith(tokens[i])) {
				tempFilePath = tempFilePath.substring(0, tempFilePath.length() - tokens[i].length());
			} else {
				firstExtentionToBeAdded = i;
			}
		}

		for (int i = firstExtentionToBeAdded; i < tokens.length; ++i) {
			filePath += tokens[i];
		}

		return filePath;
	}

}


text:
My talk for [devcon](http://devcon-february.events.co.il/) 2013 about [Clojure](http://clojure.org/) for bigdata processing (using Hadoop and Amazon EMR).

Slides can be viewed [here](http://narkisr.github.com/clojure-bigdata-processing/index.html#/).

## License

Clojure for bigdata processing by Ronen Narkis is licensed under a Creative Commons Attribution 3.0 Unported License.
Based on a work at github.com.

This presentation uses reveal.js, see the LICENSE file for its license


text:
#ifndef FK_ORDER_OPERATOR_H
#define FK_ORDER_OPERATOR_H

#include <functional>
#include <QMap>
#include <QVariant>
#include <QDebug>

//base class allow store description types in single map
//this template provides convinient way to attach order operators to different implementation classes
template <class ImplementationClass>
struct FKDescriptionTypeBase{
    template <typename... Args>
    using checkCall=std::function<bool(ImplementationClass&,Args...)>;
    template <typename... Args>
    using getCall=std::function<QVariant(ImplementationClass&,Args...)>;
    using setCall=std::function<void(ImplementationClass&,const QVariant&)>;
    template <typename... Args>
    using requestCall=std::function<void(ImplementationClass&,Args...)>;
    using Impl=ImplementationClass;
};

//template for description respecialization
template <int r>
struct FKDescriptionType{
};

//use this macro for shorter respecialization typing
#define FKDescriptionDeclaration(id,operatorClass) template<> struct FKDescriptionType<id>:public FKDescriptionTypeBase<operatorClass>
//it is recommended to redefine description declarator macro for special implementation class in .cpp file, for example
//#define FKRequest(id) FKDescriptionDeclaration(id,MyCustomOperatorImplementationClass)

//use this macro inside opeartor implementation class for order declaration
#define FKDeclareOrder(name) template <int r,typename... Args> void name(FKDescriptionType<r>* description,Args... args)

//use this macro outside oprator implementation class for order implementation
#define FKOrder(ClassName,id,name) \
    template <class OperatorClass,int r,typename... Args> \
    struct FKOrderContainer<id,OperatorClass,r,Args...>{ \
        FKOrderContainer(OperatorClass* base,FKDescriptionType<r>* description,Args... args){base->name(description,args...);} \
    }; \
    template <int r,typename... Args> void ClassName::name(FKDescriptionType<r>* description,Args... args)

//template for order respecialization
template <int order,class OperatorClass,int r,typename... Args>
struct FKOrderContainer{
};

//helper sctructure
template<typename OrderOperator,typename... Args>
struct FKOrderCaller{
    FKOrderCaller(OrderOperator* impl,Args... arguments):_impl(impl),arguments(arguments...){}
    template<int order,int r>
    void callOrder()const{
        FKDescriptionType<r> description;
        callOrderInternal<order,r>(&description,std::index_sequence_for<Args...>{});
    }
private:
    template<int order,int r,std::size_t... index>
    void callOrderInternal(FKDescriptionType<r>* description,std::index_sequence<index...>)const{
        FKOrderContainer<order,OrderOperator,r,Args...>(_impl,description,std::get<index>(arguments)...);
    }
    OrderOperator* _impl;
    std::tuple<Args...> arguments;
};

//helper sctructure
template <int... descriptions>
struct FKAllowedDescriptions{
    template<int order,typename Caller>
    void execute(int descriptionId, const Caller& caller)const{
        deduceDescription<order,Caller,descriptions...>(descriptionId,caller);
    }
private:
    template<int order,typename Caller,int description,int... restDescriptions>
    void deduceDescription(int descriptionId,const Caller& caller)const{
        if(descriptionId==description){
            caller.template callOrder<order,description>();
        }else{
            deduceDescription<order,Caller,restDescriptions...>(descriptionId,caller);
        }
    }
    template<int order,typename Caller>
    void deduceDescription(int/* descriptionId*/,const Caller&/* caller*/)const{
        //description not found
    }
};

//helper sctructure
template <int... orders>
struct FKAllowedOrders{
    template<typename AllowedDescriptions,typename Caller>
    void execute(int orderId,int descriptionId,const Caller& caller)const{
        deduceOrder<AllowedDescriptions,Caller,orders...>(orderId,descriptionId,caller);
    }
    template<typename Caller,int r>
    void execute(int orderId,const Caller& caller)const{
        deduceOrder<Caller,r,orders...>(orderId,caller);
    }
private:
    template<typename AllowedDescriptions,typename Caller,int order, int... restOrders>
    void deduceOrder(int orderId,int descriptionId,const Caller& caller)const{
        if(orderId==order){
            AllowedDescriptions descriptions;
            descriptions.execute<order,decltype(caller)>(descriptionId,caller);
        }else{
            deduceOrder<AllowedDescriptions,Caller,restOrders...>(orderId,descriptionId,caller);
        }
    }
    template<typename AllowedDescriptions,typename Caller>
    void deduceOrder(int/* orderId*/,int/* descriptionId*/,const Caller&/* caller*/)const{
        //no order found
    }

    template<typename Caller,int r,int order, int... restOrders>
    void deduceOrder(int orderId,const Caller& caller)const{
        if(orderId==order){
            caller.template callOrder<order,r>();
        }else{
            deduceOrder<Caller,r,restOrders...>(orderId,caller);
        }
    }
    template<typename Caller,int r>
    void deduceOrder(int/* orderId*/,const Caller&/* caller*/)const{
        //no order found
    }
};

template <class Impl,typename AllowedOrders,typename AllowedDescriptions>
class FKOrderOperator:public Impl{
    static_assert(std::has_virtual_destructor<Impl>::value,"Invalid FKOrderOperator template base: implementation should have virtual destructor");

public:
    virtual ~FKOrderOperator(){

    }
    template <int r,int order,typename... Args>
    void execute(Args... args){
        FKOrderCaller<Impl,Args...> caller(this,args...);
        caller.callOrder<r,order>();
    }
    template <int r,typename... Args>
    void executeOrder(void (Impl::*orderPtr)(FKDescriptionType<r>*,Args...), Args... args){
        FKDescriptionType<r> description;
        ((*this).*orderPtr)(&description,args...);
    }
    template <int r,typename... Args>
    void executeOrder(int orderId, Args... args){
        FKOrderCaller<Impl,Args...> caller(this,args...);
        AllowedOrders orders;
        orders.execute<decltype(caller),r>(orderId,caller);
    }
    template <int order,typename... Args>
    void execute(int descriptionId, Args... args){
        FKOrderCaller<Impl,Args...> caller(this,args...);
        AllowedDescriptions descriptions;
        descriptions.execute<order,decltype(caller)>(descriptionId,caller);
    }
    template <typename... Args>
    void execute(int orderId,int descriptionId,Args... args){
        FKOrderCaller<Impl,Args...> caller(this,args...);
        AllowedOrders orders;
        orders.execute<AllowedDescriptions>(orderId,descriptionId,caller);
    }

private:
    template <int orderId,typename Arguments, int allowed, int... other>
    void deduceExecute(int id,Arguments arguments){
        if(allowed==id){
            FKDescriptionType<allowed> description;
            callOrder<orderId>(arguments,&description);
        }else{
            deduceExecute<orderId,other...>(id,arguments);
        }
    }
    template <int orderId,typename Arguments>
    void deduceExecute(int id,Arguments arguments){
        Q_UNUSED(arguments)
        qDebug()<<"not found "<<id;
    }
    template<int orderId,int r,typename Arguments>
    void callOrder(Arguments arguments,FKDescriptionType<r>* description){
        arguments.callOrder<orderId,r>(description,this);
    }
};

#endif // FK_ORDER_OPERATOR_H


text:
                            Upload Cart

            Cancel

                Done
                Edit

    Flight Name
    <input class="form-control" placeholder="AK25" ng-model="newUpload.flightName">

                <input type="radio" name="optionsRadiosInline" id="optionsRadiosInline1" value="Inbound" ng-model="newUpload.optionsRadiosInline">Inbound

                <input type="radio" name="optionsRadiosInline" id="optionsRadiosInline2" value="Outbound" ng-model="newUpload.optionsRadiosInline">Outbound

                <input type="radio" name="optionsRadiosInline" id="optionsRadiosInline3" value="Quick Turn" ng-model="newUpload.optionsRadiosInline">Quick Turn

            <select name="singleSelect" ng-model="item.singleSelect" value="">
                <option ng-repeat="item in carts" value="{{item.id}}">{{item.cartName}}</option>
            </select>

        <input style="width:300px;border-color:#ddd;border-style: solid;border-width: 0px 0px 0px 1px;" ng-model="item.detailadd" placeholder="Left Front Outbound">

              Add Cart

    Cancel

        Done
        Edit


text:
<!DOCTYPE Html>

	<title>Bookings</title>
	<link rel="stylesheet" type="text/css" href="css/styles.css">

Effective Date:

Next Date:

Previous Date:


text:
{% extends "account/base.html" %}

{% load i18n %}
{% load account %}
{% load socialaccount %}
{% load crispy_forms_tags %}

{% block content %}
{% get_providers as socialaccount_providers %}

Sign In

{% if socialaccount_providers %}You can gain access through participating third party authentication services,
or you can{% else %}If you don't have an account you can{% endif %} sign up with us here!

{% if socialaccount_providers %}

{% include "socialaccount/snippets/login_extra.html" %}

External Sign In

Start by clicking one of the icons below.

{% endif %}

Sign In With a BeyondCompare Account

  <form class="login" method="POST" action="{% url 'account_login' %}">
    {% csrf_token %}
    {{ form|crispy }}
    {% if redirect_field_value %}
    <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
    {% endif %}
    <button id="sign-in-button" class="btn btn-primary" type="submit">{% trans "Sign In" %}</button>
    {% trans "Forgot Password?" %}
  </form>

{% endblock %}


text:
pa
==

Pomodoro, To-Do, Notes and what not

To-Do
=====

1. Use Require.js
2. Use less.css or any other css engine
3. ~~takeout timer from pomodoro timer~~


text:
package com.sohu.jafka.consumer;

import static java.lang.String.format;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

import com.sohu.jafka.cluster.Partition;
import com.sohu.jafka.common.ErrorMapping;
import com.sohu.jafka.message.ByteBufferMessageSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author adyliu (imxylz@gmail.com)
 * @since 1.0
 */
public class PartitionTopicInfo {

    private static final Logger logger = LoggerFactory.getLogger(PartitionTopicInfo.class);

    public final String topic;

    public final int brokerId;

    private final BlockingQueue<FetchedDataChunk> chunkQueue;

    private final AtomicLong consumedOffset;

    private final AtomicLong fetchedOffset;

    private final AtomicLong consumedOffsetChanged = new AtomicLong(0);

    final Partition partition;

    public PartitionTopicInfo(String topic, //
            Partition partition,//
            BlockingQueue<FetchedDataChunk> chunkQueue, //
            AtomicLong consumedOffset, //
            AtomicLong fetchedOffset) {
        super();
        this.topic = topic;
        this.partition = partition;
        this.brokerId = partition.brokerId;
        this.chunkQueue = chunkQueue;
        this.consumedOffset = consumedOffset;
        this.fetchedOffset = fetchedOffset;
    }

    public long getConsumedOffset() {
        return consumedOffset.get();
    }

    public AtomicLong getConsumedOffsetChanged() {
        return consumedOffsetChanged;
    }

    public boolean resetComsumedOffsetChanged(long lastChanged) {
        return consumedOffsetChanged.compareAndSet(lastChanged, 0);
    }

    public long getFetchedOffset() {
        return fetchedOffset.get();
    }

    public void resetConsumeOffset(long newConsumeOffset) {
        consumedOffset.set(newConsumeOffset);
        consumedOffsetChanged.incrementAndGet();
    }

    public void resetFetchOffset(long newFetchOffset) {
        fetchedOffset.set(newFetchOffset);
    }

    public long enqueue(ByteBufferMessageSet messages, long fetchOffset) throws InterruptedException {
        long size = messages.getValidBytes();
        if (size > 0) {
            final long oldOffset = fetchedOffset.get();
            chunkQueue.put(new FetchedDataChunk(messages, this, fetchOffset));
            long newOffset = fetchedOffset.addAndGet(size);
            if (logger.isDebugEnabled()) {
                logger.debug(format("updated fetchset (origin+size=newOffset) => %d + %d = %d", oldOffset, size, newOffset));
            }
        }
        return size;
    }

    @Override
    public String toString() {
        return topic + "-" + partition + ", fetched/consumed offset: " + fetchedOffset.get() + "/" + consumedOffset.get();
    }

    public void enqueueError(Exception e, long fetchOffset) throws InterruptedException {
        ByteBufferMessageSet messages = new ByteBufferMessageSet(ErrorMapping.EMPTY_BUFFER, 0, ErrorMapping.valueOf(e));
        chunkQueue.put(new FetchedDataChunk(messages, this, fetchOffset));
    }
}


text:
import moment from 'moment'
import Post from '../model/PostModel'

export const getAll = () => {
  return new Promise((resolve, reject) => {
    Post.find()
      .exec()
      .then((posts) => {
        if (posts) {
          resolve(posts)
        } else {
          reject(`Empty post collection`)
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export const getById = (postId) => {
  return new Promise((resolve, reject) => {
    Post.findOne({ _id: postId })
      .exec()
      .then((post) => {
        if (post) {
          resolve(post)
        } else {
          reject(`Item Not Found`)
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export const getByUrl = (url) => {
  return new Promise((resolve, reject) => {
    Post.findOne({ url: url })
      .exec()
      .then((post) => {
        resolve(post)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export const create = (post) => {
  return new Promise((resolve, reject) => {
    Post.create({
        author: post.author,
        title: post.title,
        url: post.url,
        readLength: post.readLength,
        content: post.content
      })
      .then((post) => {
        resolve(post)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export const update = (post) => {
  return new Promise((resolve, reject) => {
    const timeNow = moment().format("YYYY-MM-DD HH:mm:ss")
    Post.findOneAndUpdate({_id: post._id},
      {$set: {
        author: post.author,
        title: post.title,
        url: post.url,
        readLength: post.readLength,
        content: post.content,
        status: post.status,
        updatedAt: timeNow
      }},
      {new: true})
      .then((post) => {
        resolve(post)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export default ({
  getAll,
  getById,
  getByUrl,
  create,
  update
})


text:
package org.pentaho.osgi.impl;

import org.junit.Assert;
import org.junit.Test;

import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CipherEncryptionServiceImplTest {

  @Test
  public void testCipherDefaultValues() {
    CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "_CyPh3r_", "PBEWithMD5AndDES", "P3ntah0C1ph3r", 19 );
  }

  @Test
  public void testCipherEncryptionWithDefaults() throws Exception {
    CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "_CyPh3r_", "PBEWithMD5AndDES", "P3ntah0C1ph3r", 19 );
    // Everything should be set up now for encryption testing
    String stringToEncrypt = "String To Encrypt";
    String encryptedStringExpected = "R1pxG/vXQU8ezFM5VE644dqQxCKNP+Ap";
    String encryptedStringActual = service.encrypt( stringToEncrypt );
    Assert.assertEquals( encryptedStringExpected, encryptedStringActual );
  }

  @Test
  public void testCipherDecryptionWithDefaults() throws Exception {
    CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "_CyPh3r_", "PBEWithMD5AndDES", "P3ntah0C1ph3r", 19 );
    // Everything should be set up now for encryption testing
    String encryptedString = "R1pxG/vXQU8ezFM5VE644dqQxCKNP+Ap";
    String decryptedStringExpected = "String To Encrypt";
    String decryptedStringActual = service.decrypt( encryptedString );
    Assert.assertEquals( decryptedStringExpected, decryptedStringActual );
  }

  @Test
  public void testSaltEffectOnEncryption() throws Exception {
    CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "DiffSalt", "PBEWithMD5AndDES", "P3ntah0C1ph3r", 19 );
    // Everything should be set up now for encryption testing
    String encryptedStringShouldNotBe = "R1pxG/vXQU8ezFM5VE644dqQxCKNP+Ap";
    String stringToEncrypt = "String To Encrypt";
    String encryptedStringActual = service.encrypt( stringToEncrypt );
    Assert.assertNotSame( encryptedStringShouldNotBe, encryptedStringActual );
  }

  @Test( expected = RuntimeException.class )
  public void testSaltTooLong() throws Exception {
    CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "This Salt Is Too Long And Will Be Truncated", "PBEWithMD5AndDES",
        "P3ntah0C1ph3r", 19 );
  }

  @Test( expected = RuntimeException.class )
  public void testSaltTooShort() throws Exception {
    CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "short", "PBEWithMD5AndDES", "P3ntah0C1ph3r", 19 );
  }

  @Test
  public void testIterationsEffectOnEncryption() throws Exception {
    CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "_CyPh3r_", "PBEWithMD5AndDES", "P3ntah0C1ph3r", 25 );
    // Everything should be set up now for encryption testing
    String encryptedStringShouldNotBe = "R1pxG/vXQU8ezFM5VE644dqQxCKNP+Ap";
    String stringToEncrypt = "String To Encrypt";
    String encryptedStringActual = service.encrypt( stringToEncrypt );
    Assert.assertNotSame( encryptedStringShouldNotBe, encryptedStringActual );
  }

  @Test
  public void testThreadSafetyOfCipherService() throws Exception {
    int threadCount = 30;
    final CipherEncryptionServiceImpl service =
      new CipherEncryptionServiceImpl( "_CyPh3r_", "PBEWithMD5AndDES", "P3ntah0C1ph3r", 19 );
    ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>( threadCount );
    ThreadPoolExecutor executor = new ThreadPoolExecutor( 10, 50, 1, TimeUnit.SECONDS, queue );

    for ( int i = 0; i < threadCount; i++ ) {
      executor.execute( new Runnable() {
        @Override
        public void run() {
          try {
            String s = null;
            String enc = null;
            String dec = null;
            for ( int i = 0; i < 50; i++ ) {
              s = UUID.randomUUID().toString();
              enc = service.encrypt( s );
              dec = service.decrypt( enc );
              Assert.assertEquals( s, dec );
            }
          } catch ( Exception ex ) {
            ex.printStackTrace();
            Assert.fail( ex.toString() );
          }
        }
      } );
    }
    executor.shutdown();
    boolean isTerminated = executor.awaitTermination( 200, TimeUnit.SECONDS );
    if ( !isTerminated ) {
      Assert.fail( "It took too long to run the threading test." );
    }

  }
}