text:
Release Notes                                              {#release_notes}
====================

[TOC]

Available since 6.6.0                                                                              {#release_notes_1}
=====================
- Added new ISO C++ DCPS API, called isocpp2.

Known Issues and Currently Unsupported Features                                                                    {#release_notes_known_issues}
=====================================

Although the ISO C++ DCPS API implements the majority of commonly used features, some functionality
of the OMG DDS specification and DDS-PSM-Cxx is not currently supported. Below is a list of known
issues and features that are not currently supported:

- [Find and Discovery functions](#release_notes_us_find_discovery)
- [OpenSplice API extensions](#release_notes_us_extensions)
- [Other known issues] (#release_notes_other_known_issues)

Find and Discovery functions                                                {#release_notes_us_find_discovery}
-------------------------
The following discovery functions are not currently supported:

- [dds/domain/discovery.hpp](@ref dds/domain/discovery.hpp)
- [dds/topic/discovery.hpp](@ref dds/topic/discovery.hpp)

OpenSplice API extensions                                                                        {#release_notes_us_extensions}
-------------------------
The implementation contains only API features that are present in the OMG DCPS specification at this time.
Other OpenSplice language bindings contain extensions to the specification such as additional QoS,
Entity operations, and Entities. These features are not yet available.

Other Known Issues                                                                        {#release_notes_other_known_issues}
------------------

- dds::topic::MultiTopic
    - MultiTopics are not currently supported.

- Release/Debug DLL mismatch issue
    - In order to build applications in DEBUG mode on Windows the ISO C++ library must match, this can be done by recompiling the custom lib as documented @ref isocpp2_customlibs "here"

redpajama_set_name: RedPajamaGithub


text:
using namespace hilti;
using namespace codegen;

DebugInfoBuilder::DebugInfoBuilder(CodeGen* cg)
    : CGVisitor<llvm::MDNode*>(cg, "codegen::DebugInfoBuilderInfoBuilder")
{
}

DebugInfoBuilder::~DebugInfoBuilder()
{
}


text:
package com.amazonaws.services.datapipeline.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.datapipeline.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * PipelineIdNameMarshaller
 */
public class PipelineIdNameJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(PipelineIdName pipelineIdName,
            SdkJsonGenerator jsonGenerator) {
        if (pipelineIdName == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (pipelineIdName.getId() != null) {
                jsonGenerator.writeFieldName("id").writeValue(
                        pipelineIdName.getId());
            }
            if (pipelineIdName.getName() != null) {
                jsonGenerator.writeFieldName("name").writeValue(
                        pipelineIdName.getName());
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static PipelineIdNameJsonMarshaller instance;

    public static PipelineIdNameJsonMarshaller getInstance() {
        if (instance == null)
            instance = new PipelineIdNameJsonMarshaller();
        return instance;
    }

}


text:
package org.kohsuke.stapler.jelly;

import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.XMLOutput;

import java.io.StringWriter;

/**
 * Body is evaluated and is used as an argument for the surrounding {@code <structuredMessageFormat>} element.
 *
 * @author Kohsuke Kawaguchi
 */
public class StructuredMessageArgumentTag extends AbstractStaplerTag {
    public void doTag(XMLOutput output) throws JellyTagException {
        StructuredMessageFormatTag tag = (StructuredMessageFormatTag)findAncestorWithClass(StructuredMessageFormatTag.class);
        if(tag == null)
            throw new JellyTagException("This tag must be enclosed inside a <structuredMessageFormat> tag" );

        StringWriter sw = new StringWriter();
        XMLOutput o = XMLOutput.createXMLOutput(sw);
        invokeBody(o);

        tag.addArgument(sw);
    }
}


text:
<?php

namespace Doctrine\Tests\ORM\Tools;

use Doctrine\ORM\Tools\EntityGenerator;
use Doctrine\ORM\Tools\EntityRepositoryGenerator;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\Tests\OrmTestCase;

class EntityRepositoryGeneratorTest extends OrmTestCase
{
    /**
     * @var EntityGenerator
     */
    private $_generator;

    /**
     * @var EntityRepositoryGenerator
     */
    private $_repositoryGenerator;

    private $_tmpDir;
    private $_namespace;

    /**
     * @inheritdoc
     */
    public function setUp()
    {
        $this->_namespace   = uniqid('doctrine_');
        $this->_tmpDir      = \sys_get_temp_dir() . DIRECTORY_SEPARATOR . $this->_namespace;
        \mkdir($this->_tmpDir);

        $this->_generator = new EntityGenerator();
        $this->_generator->setAnnotationPrefix("");
        $this->_generator->setGenerateAnnotations(true);
        $this->_generator->setGenerateStubMethods(true);
        $this->_generator->setRegenerateEntityIfExists(false);
        $this->_generator->setUpdateEntityIfExists(true);
        $this->_generator->setFieldVisibility(EntityGenerator::FIELD_VISIBLE_PROTECTED);

        $this->_repositoryGenerator = new EntityRepositoryGenerator();
    }

    /**
     * @inheritdoc
     */
    public function tearDown()
    {
        $dirs = array();

        $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->_tmpDir));
        foreach ($ri AS $file) {
            /* @var $file \SplFileInfo */
            if ($file->isFile()) {
                \unlink($file->getPathname());
            } elseif ($file->getBasename() === '.') {
                $dirs[] = $file->getRealPath();
            }
        }

        arsort($dirs);

        foreach ($dirs as $dir) {
            \rmdir($dir);
        }
    }

    /**
     * @group DDC-3231
     */
    public function testGeneratedEntityRepositoryClass()
    {
        $em = $this->_getTestEntityManager();
        $ns = $this->_namespace;

        require_once __DIR__ . '/../../Models/DDC3231/DDC3231User1.php';

        $className = $ns . '\DDC3231User1Tmp';
        $this->writeEntityClass('Doctrine\Tests\Models\DDC3231\DDC3231User1', $className);

        $rpath = $this->writeRepositoryClass($className);

        $this->assertFileExists($rpath);

        require $rpath;

        $repo = new \ReflectionClass($em->getRepository($className));

        $this->assertTrue($repo->inNamespace());
        $this->assertSame($className . 'Repository', $repo->getName());
        $this->assertSame('Doctrine\ORM\EntityRepository', $repo->getParentClass()->getName());

        require_once __DIR__ . '/../../Models/DDC3231/DDC3231User1NoNamespace.php';

        $className2 = 'DDC3231User1NoNamespaceTmp';
        $this->writeEntityClass('DDC3231User1NoNamespace', $className2);

        $rpath2 = $this->writeRepositoryClass($className2);

        $this->assertFileExists($rpath2);

        require $rpath2;

        $repo2 = new \ReflectionClass($em->getRepository($className2));

        $this->assertFalse($repo2->inNamespace());
        $this->assertSame($className2 . 'Repository', $repo2->getName());
        $this->assertSame('Doctrine\ORM\EntityRepository', $repo2->getParentClass()->getName());
    }

    /**
     * @group DDC-3231
     */
    public function testGeneratedEntityRepositoryClassCustomDefaultRepository()
    {
        $em = $this->_getTestEntityManager();
        $ns = $this->_namespace;

        require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2.php';

        $className = $ns . '\DDC3231User2Tmp';
        $this->writeEntityClass('Doctrine\Tests\Models\DDC3231\DDC3231User2', $className);

        $rpath = $this->writeRepositoryClass($className, 'Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository');

        $this->assertNotNull($rpath);
        $this->assertFileExists($rpath);

        require $rpath;

        $repo = new \ReflectionClass($em->getRepository($className));

        $this->assertTrue($repo->inNamespace());
        $this->assertSame($className . 'Repository', $repo->getName());
        $this->assertSame('Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository', $repo->getParentClass()->getName());

        require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2NoNamespace.php';

        $className2 = 'DDC3231User2NoNamespaceTmp';
        $this->writeEntityClass('DDC3231User2NoNamespace', $className2);

        $rpath2 = $this->writeRepositoryClass($className2, 'Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository');

        $this->assertNotNull($rpath2);
        $this->assertFileExists($rpath2);

        require $rpath2;

        $repo2 = new \ReflectionClass($em->getRepository($className2));

        $this->assertFalse($repo2->inNamespace());
        $this->assertSame($className2 . 'Repository', $repo2->getName());
        $this->assertSame('Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository', $repo2->getParentClass()->getName());
    }

    /**
     * @param string $className
     * @param string $newClassName
     * @return string
     */
    private function writeEntityClass($className, $newClassName)
    {
        $cmf    = new ClassMetadataFactory();
        $em     = $this->_getTestEntityManager();

        $cmf->setEntityManager($em);

        $metadata               = $cmf->getMetadataFor($className);
        $metadata->namespace    = $this->_namespace;
        $metadata->name         = $newClassName;
        $metadata->customRepositoryClassName = $newClassName . "Repository";

        $this->_generator->writeEntityClass($metadata, $this->_tmpDir);

        require $this->_tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $newClassName) . ".php";
    }

    /**
     * @param string $className
     * @param string $defaultRepository
     * @return string
     */
    private function writeRepositoryClass($className, $defaultRepository = null)
    {
        $this->_repositoryGenerator->setDefaultRepositoryName($defaultRepository);

        $this->_repositoryGenerator->writeEntityRepositoryClass($className . 'Repository', $this->_tmpDir);

        return $this->_tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . 'Repository.php';
    }

}


text:
using UnityEngine;
using System.Collections;

public class Sense : MonoBehaviour {
	public bool bDebug = true;
	public Aspect.aspect aspectName = Aspect.aspect.Enemy;
	public float detectionRate = 1.0f;

	protected float elapsedTime = 0.0f;

	protected virtual void Initialise() { }
	protected virtual void UpdateSense() { }

	// Use this for initialization
	void Start () {
		elapsedTime = 0.0f;
		Initialise();
	}

	// Update is called once per frame
	void Update () {
		UpdateSense();
	}
}


text:
<?php
/**
 *
 * @todo modify plugin to create the composer.json and vendor file and folder automatically if they dont exist.
 *
 * @todo when done first todo remove that file and folder as its not part of the framework
 *
 */
namespace SimpleMvC\plugins;

function setup_composer($data)
{
	$composer_autoloader = core_directory.'/vendor/autoload.php';
	require_once($composer_autoloader);
}

?>


text:
<?php
$classMap = array('Recsys' => 'src/');

spl_autoload_register(function($class) {
    $namespace = ltrim($class, '\\');
    global $classMap;

    while (false !== $pos = strrpos($namespace, '\\')) {
        $namespace = substr($class, 0, $pos);
        $className = substr($class, $pos + 1);

        if (isset($classMap[$namespace])) {
            $baseDir = $classMap[$namespace];
        } else {
            $baseDir = __DIR__ . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, strtolower($namespace)) . DIRECTORY_SEPARATOR;
        }
        $filename = $baseDir . $className . '.php';
        if (file_exists($filename)) {
            require $filename;
            break;
        }
    }
});

$vendor = __DIR__ . '/../vendor/autoload.php';
if (file_exists($vendor)) {
    require_once $vendor;
}


text:
using Client.Commands.Contracts;
using Client.Core.Contracts;
using Data.Context;
using Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

namespace Client.Commands
{
    public class ConfirmOrderCommand : ICommand
    {
        private readonly IAutoRentContext context;
        private readonly IOrderComposer orderComposer;

        public ConfirmOrderCommand(IAutoRentContext context, IOrderComposer orderComposer)
        {
            this.context = context ?? throw new ArgumentNullException("context");
            this.orderComposer = orderComposer ?? throw new ArgumentNullException("orderComposer");
        }

        public string Execute(IList<string> parameters)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            var departureDate = DateTime.Parse(parameters[0]);
            var destination = parameters[1];
            var duration = int.Parse(parameters[2]);
            var carAvailableAgainAfter = departureDate.AddDays(duration + 1);

            var carId = orderComposer.SelectedCar.Id;
            var user = orderComposer.SelectedUser;

            var order = new Order()
            {
                CarId = carId,
                User = (User)user,
                DepartureDate = departureDate,
                ArrivalDate = departureDate.AddDays(duration)
            };

            context.Orders.Add(order);
            context.SaveChanges();

            string result = string.Format("You have succesfully booked your AutoRent car! It would be waiting for you on" + $"{order.DepartureDate.ToString()}" +
                $"{order.Car.Office.Address.ToString()}, {order.Car.Office.City.ToString()}.");

            return result;
        }
    }
}


text:
<!DOCTYPE html>

    <title>Casa - Beta</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Casa">
    <meta name="keywords" content="Casa">
    <meta name="author" content="Logan McAnsh">
    <meta name="theme-color" content="#6BC281">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="shortcut icon" href="assets/img/favicon/favicon.ico">
    <link rel="shortcut icon" href="assets/img/favicon/favicon-32.png" sizes="32x32">
    <link rel="apple-touch-icon-precomposed" sizes="228x228" href="assets/img/favicon/favicon-228.png">
    <link rel="apple-touch-icon-precomposed" sizes="195x195" href="assets/img/favicon/favicon-195.png">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="assets/img/favicon/favicon-152.png">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/img/favicon/favicon-144.png">
    <link rel="apple-touch-icon-precomposed" sizes="128x128" href="assets/img/favicon/favicon-128.png">
    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="assets/img/favicon/favicon-120.png">
    <link rel="apple-touch-icon-precomposed" sizes="96x96" href="assets/img/favicon/favicon-96.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/img/favicon/favicon-72.png">
    <link rel="apple-touch-icon-precomposed" href="assets/img/favicon/favicon-57.png">
    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@logansmcansh">
    <meta name="twitter:title" content="Casa Beta">
    <meta name="twitter:description" content="Casa Beta">
    <meta name="twitter:image" content="https://mcansh.github.io/casa/assets/img/favicon/favicon.png">

CasaBETA

          <button type="button" class="hamburger hamburger--squeeze"></button>

HomesRentalsMortgagesSign inView on GitHub

Find that place you can call home.

Start searching for your dream home or apartment with our state of the art search tools.
Let's Go

Real time analytics

Our house value estimates are updated every day to provide the most up-to-date value on your current home.
Details

Our mission is simple.

We strive every single day to provide the best experience for our customers. We know how stressful home buying can be, and we want to eliminate that stress by providing a tool that reassures our customers that they're making the right purchase.

Let's buy a house together.

Whether it's your first home or your 5th, we'll always be here to help.
Let's Go

Over 1.5 million homes have been sold through Casa to date. Learn more.

Casa

Homes

Rentals

Mortgages

Sign in

Support

Help

FAQ

Contact Us

Contact Us

Casa LLC
078 Fulton Ave.
Grand Rapids, MI 49501

616-777-7777

Casa

Copyright 2015


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>The Dashboard</title>
    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="dist/application.min.css">


text:
using UnityEngine;
using System.Collections;

public class PanelSwith1 : MonoBehaviour
{
    public bool sb1;
    public bool bl = true;
    public Renderer sl;
    private GameObject l1;
    private Light light1;

    void Start()
    {
        l1 = GameObject.Find("Point light1").gameObject;
        light1 = l1.GetComponent<Light>();
        sl = sl.transform.GetComponent<Renderer>();
        sl.material.color = Color.red;
        light1.color = Color.red;
    }

    void OnCollisionStay(Collision col)
    {
        if (col.gameObject.tag == "Player" || col.gameObject.tag == "Cat")
        {
            sb1 = true;
            sl.material.color = Color.blue;
            light1.color = Color.cyan;
        }
    }

    void OnCollisionExit(Collision col)
    {
        if (col.gameObject.tag == "Player" || col.gameObject.tag == "Cat")
        {
            sb1 = false;
            if (bl)
            {
                sl.material.color = Color.red;
                light1.color = Color.red;
            }
        }
    }
}


text:
pg.compoundPath = function() {

	var isCompoundPath = function(item) {
		return item && item.className === 'CompoundPath';
	};

	var isCompoundPathChild = function(item) {
		if(item.parent) {
			return item.parent.className === 'CompoundPath';
		} else {
			return false;
		}
	};

	var getItemsCompoundPath = function(item) {
		var itemParent = item.parent;

		if(isCompoundPath(itemParent)) {
			return itemParent;
		} else {
			return null;
		}

	};

	var createFromSelection = function() {
		var items = pg.selection.getSelectedPaths();
		if(items.length < 2) return;

		var path = new paper.CompoundPath({fillRule: 'evenodd'});

		for(var i=0; i<items.length; i++) {
			path.addChild(items[i]);
			items[i].selected = false;
		}

		path = pg.stylebar.applyActiveToolbarStyle(path);

		pg.selection.setItemSelection(path, true);
		pg.undo.snapshot('createCompoundPathFromSelection');
	};

	var releaseSelection = function() {
		var items = pg.selection.getSelectedItems();

		var cPathsToDelete = [];
		for(var i=0; i<items.length; i++) {
			var item = items[i];

			if(isCompoundPath(item)) {

				for(var j=0; j<item.children.length; j++) {
					var path = item.children[j];
					path.parent = item.layer;
					pg.selection.setItemSelection(path, true);
					j--;
				}
				cPathsToDelete.push(item);
				pg.selection.setItemSelection(item, false);

			} else {
				items[i].parent = item.layer;
			}
		}

		for(var j=0; j<cPathsToDelete.length; j++) {
			cPathsToDelete[j].remove();
		}
		pg.undo.snapshot('releaseCompoundPath');
	};

	return {
		isCompoundPath: isCompoundPath,
		isCompoundPathChild: isCompoundPathChild,
		getItemsCompoundPath: getItemsCompoundPath,
		createFromSelection: createFromSelection,
		releaseSelection: releaseSelection
	};
}();


text:
/*
 * Author: doe300
 *
 * See the file "LICENSE" for the full license governing this code.
 */

#include "CacheEntry.h"

#include "../intermediate/IntermediateInstruction.h"

using namespace vc4c;
using namespace vc4c::periphery;
using namespace vc4c::intermediate;

CacheEntry::~CacheEntry() noexcept = default;

tools::SmallSortedPointerSet<RAMAccessInstruction*> CacheEntry::getMemoryAccesses()
{
    tools::SmallSortedPointerSet<RAMAccessInstruction*> result;
    for(auto access : accesses)
    {
        if(auto acc = dynamic_cast<RAMAccessInstruction*>(access))
            result.emplace(acc);
    }
    return result;
}

tools::SmallSortedPointerSet<const RAMAccessInstruction*> CacheEntry::getMemoryAccesses() const
{
    tools::SmallSortedPointerSet<const RAMAccessInstruction*> result;
    for(auto access : accesses)
    {
        if(auto acc = dynamic_cast<const RAMAccessInstruction*>(access))
            result.emplace(acc);
    }
    return result;
}

tools::SmallSortedPointerSet<CacheAccessInstruction*> CacheEntry::getQPUAccesses()
{
    tools::SmallSortedPointerSet<CacheAccessInstruction*> result;
    for(auto access : accesses)
    {
        if(auto acc = dynamic_cast<CacheAccessInstruction*>(access))
            result.emplace(acc);
    }
    return result;
}

tools::SmallSortedPointerSet<const CacheAccessInstruction*> CacheEntry::getQPUAccesses() const
{
    tools::SmallSortedPointerSet<const CacheAccessInstruction*> result;
    for(auto access : accesses)
    {
        if(auto acc = dynamic_cast<const CacheAccessInstruction*>(access))
            result.emplace(acc);
    }
    return result;
}


text:
module.exports =
  { applySubKeys: applySubKeys
  , sameSorted:   sameSorted
  , same:         same
  }

// Create a list of histogram metrics keys "key@subkey", using a base key.
//
// mkey    - String
// subkeys - [String]
//
// Returns [String]
function applySubKeys(mkey, subkeys) {
  var mkeys  = new Array(subkeys.length)
  for (var i = 0, l = subkeys.length; i < l; i++) {
    mkeys[i] = mkey + "@" + subkeys[i]
  }
  return mkeys
}

// Compare two lists of strings.
//
// Returns Boolean
function same(list1, list2) {
  if (list1.length !== list2.length) return false
  for (var i = 0; i < list1.length; i++) {
    if (list1[i] !== list2[i]) return false
  }
  return true
}

// Returns true if the lists are the `same` when sorted.
function sameSorted(list1, list2) {
  return same(list1.slice().sort(), list2.slice().sort())
}


text:
package org.async.rmi.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.async.rmi.Connection;
import org.async.rmi.Factory;
import org.async.rmi.Modules;
import org.async.rmi.TimeSpan;
import org.async.rmi.client.RemoteObjectAddress;
import org.async.rmi.messages.Message;
import org.async.rmi.pool.Pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeoutException;

/**
 * Created by Barak Bar Orion
 * 27/10/14.
 */
public class NettyClientConnectionFactory implements Factory<CompletableFuture<Connection<Message>>> {
    @SuppressWarnings("UnusedDeclaration")
    private static final Logger logger = LoggerFactory.getLogger(NettyClientConnectionFactory.class);

    private final Bootstrap bootstrap;
    private final RemoteObjectAddress address;
    private Pool<Connection<Message>> pool;

    public NettyClientConnectionFactory(final EventLoopGroup group, final RemoteObjectAddress address, final UUID clientId) {
        this.address = address;
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(
                                new HandshakeMessageDecoder(),
                                new ClientHandshakeHandler(clientId),
                                new MessageEncoder(),
                                new MessageDecoder(),
                                new RMIClientHandler());
                    }
                });
    }

    public void setPool(Pool<Connection<Message>> pool) {
        this.pool = pool;
    }

    @Override
    public CompletableFuture<Connection<Message>> create() {
        TimeSpan clientConnectTimeout = Modules.getInstance().getConfiguration().getClientConnectTimeout();
        final NettyClientConnection connection = new NettyClientConnection(bootstrap, address, pool);
        final CompletableFuture<Connection<Message>> res = connection.connect();
        ForkJoinPool.commonPool().execute(() -> {
            try {
                res.get(clientConnectTimeout.getTime(), clientConnectTimeout.getTimeUnit());
            } catch (ExecutionException e) {
                res.completeExceptionally(e.getCause());
            } catch (InterruptedException | TimeoutException e) {
                res.completeExceptionally(e);
            }
        });
        return res;
    }

}


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

<title>ManageReferralControl (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.naming.ldap.ManageReferralControl class">
<meta name="keywords" content="OID">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

compact3

javax.naming.ldap

Class ManageReferralControl

java.lang.Object

javax.naming.ldap.BasicControl

javax.naming.ldap.ManageReferralControl

All Implemented Interfaces:

Serializable, Control

public final class ManageReferralControl
extends BasicControl

Requests that referral and other special LDAP objects be manipulated
 as normal LDAP objects. It enables the requestor to interrogate or
 update such objects.

 This class implements the LDAPv3 Request Control for ManageDsaIT
 as defined in
 RFC 3296.

 The control has no control value.

Since:

1.5

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

static String
OID

The ManageReferral control's assigned object identifier
 is 2.16.840.1.113730.3.4.2.

Fields inherited from class javax.naming.ldap.BasicControl

criticality, id, value

Fields inherited from interface javax.naming.ldap.Control

CRITICAL, NONCRITICAL

Constructor Summary

Constructors

Constructor and Description

ManageReferralControl()

Constructs a critical ManageReferral control.

ManageReferralControl(boolean criticality)

Constructs a ManageReferral control.

Method Summary

Methods inherited from class javax.naming.ldap.BasicControl

getEncodedValue, getID, isCritical

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

OID

public static final String OID

The ManageReferral control's assigned object identifier
 is 2.16.840.1.113730.3.4.2.

See Also:

Constant Field Values

Constructor Detail

ManageReferralControl

public ManageReferralControl()

Constructs a critical ManageReferral control.

ManageReferralControl

public ManageReferralControl(boolean criticality)

Constructs a ManageReferral control.

Parameters:

criticality - The control's criticality setting.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
package com.microsoft.azure.storage.queue;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.microsoft.azure.storage.Constants;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.core.Base64;
import com.microsoft.azure.storage.core.SR;
import com.microsoft.azure.storage.core.Utility;

/**
 * Represents a message in the Microsoft Azure Queue service.
 */
public class CloudQueueMessage {

    /**
     * Holds the dequeue count.
     */
    private int dequeueCount;

    /**
     * Holds the time that the message expires.
     */
    private Date expirationTime;

    /**
     * Holds the message ID.
     */
    private String id;

    /**
     * Holds the time that the message was added to the queue.
     */
    private Date insertionTime;

    /**
     * Holds the message content.
     */
    protected String messageContent;

    /**
     * Holds the message type.
     */
    private QueueMessageType messageType;

    /**
     * Holds the time that the message will next be visible.
     */
    private Date nextVisibleTime;

    /**
     * Holds the message's pop receipt.
     */
    private String popReceipt;

    /**
     * Initializes a new instance of the CloudQueueMessage class (used internally).
     */
    protected CloudQueueMessage() {
        // no op
    }

    /**
     * Initializes a new instance of the CloudQueueMessage class with a byte
     * array containing the message.
     *
     * @param content
     *        A byte array which contains the message.
     */
    public CloudQueueMessage(final byte[] content) {
        this.setMessageContent(content);
    }

    /**
     * Initializes a new instance of the CloudQueueMessage class with a String
     * containing the message.
     *
     * @param content
     *        A String which contains the message.
     */
    public CloudQueueMessage(final String content) {
        this.setMessageContent(content);
    }

    /**
     * Gets the dequeue count.
     *
     * @return An int which contains the dequeue count.
     */
    public final int getDequeueCount() {
        return this.dequeueCount;
    }

    /**
     * Gets the time that the message expires.
     *
     * @return A java.util.Date object which represents the time that the message expires.
     */
    public final Date getExpirationTime() {
        return this.expirationTime;
    }

    /**
     * Gets the message ID.
     *
     * @return A String which contains the message ID.
     */
    public final String getId() {
        return this.id;
    }

    /**
     * Gets the time the message was added to the queue.
     *
     * @return A java.util.Date which represents the time the message was added to the queue.
     */
    public final Date getInsertionTime() {
        return this.insertionTime;
    }

    /**
     * Gets the content of the message as a byte array.
     *
     * @return A byte array which contains the content of the message.
     *
     * @throws StorageException
     *         If a storage service error occurred.
     */
    public final byte[] getMessageContentAsByte() throws StorageException {
        if (Utility.isNullOrEmpty(this.messageContent)) {
            return new byte[0];
        }

        if (this.messageType == QueueMessageType.RAW_STRING) {
            try {
                return this.messageContent.getBytes(Constants.UTF8_CHARSET);
            }
            catch (final UnsupportedEncodingException e) {
                throw Utility.generateNewUnexpectedStorageException(e);
            }
        }
        else {
            return Base64.decode(this.messageContent);
        }
    }

    /**
     * Gets the content of the message as a string.
     *
     * @return A String which contains the content of the message.
     *
     * @throws StorageException
     *         If a storage service error occurred.
     */
    public final String getMessageContentAsString() throws StorageException {
        if (this.messageType == QueueMessageType.RAW_STRING) {
            return this.messageContent;
        }
        else {
            if (Utility.isNullOrEmpty(this.messageContent)) {
                return null;
            }

            try {
                return new String(Base64.decode(this.messageContent), Constants.UTF8_CHARSET);
            }
            catch (final UnsupportedEncodingException e) {
                throw Utility.generateNewUnexpectedStorageException(e);
            }
        }
    }

    /**
     * Gets the content of the message for transfer (internal use only).
     *
     * @param shouldEncodeMessage
     *          Indicates if the message should be encoded.
     * @param options
     *          A {@link QueueRequestOptions} object that specifies additional options for the request.
     *
     * @return A String which contains the content of the message.
     *
     * @throws StorageException
     *         If a storage service error occurred.
     */
    protected final String getMessageContentForTransfer(final boolean shouldEncodeMessage, QueueRequestOptions options)
            throws StorageException {
        String result = null;

        if (options.getEncryptionPolicy() != null)
        {
            // Create an encrypted message that will hold the message contents along with encryption related metadata and return it.
            // The encrypted message is already Base 64 encoded. So no need to process further in this method.
            String encryptedMessageString = options.getEncryptionPolicy().encryptMessage(this.getMessageContentAsByte());

            // the size of Base64 encoded string is the number of bytes this message will take up on server.
            if (encryptedMessageString.length() > QueueConstants.MAX_MESSAGE_SIZE)
            {
                throw new IllegalArgumentException(
                        String.format(SR.ENCRYPTED_MESSAGE_TOO_LARGE, QueueConstants.MAX_MESSAGE_SIZE));
            }

            return encryptedMessageString;
        }

        if (this.messageType == QueueMessageType.RAW_STRING && shouldEncodeMessage) {
            result = Base64.encode(this.getMessageContentAsByte());
        }
        else {
            result = this.messageContent;
        }

        if (result != null && result.length() > QueueConstants.MAX_MESSAGE_SIZE) {
            throw new IllegalArgumentException(
                    String.format(SR.INVALID_MESSAGE_LENGTH, QueueConstants.MAX_MESSAGE_SIZE));
        }

        return result;
    }

    /**
     * Gets the message ID.
     *
     * @return A String which contains the message ID.
     */
    public final String getMessageId() {
        return this.id;
    }

    /**
     * Gets the message type.
     *
     * @return A QueueMessageType value which represents the message type.
     */
    protected final QueueMessageType getMessageType() {
        return this.messageType;
    }

    /**
     * Gets the time that the message will next be visible.
     *
     * @return A java.util.Date with the time that the message will
     *         next be visible.
     */
    public final Date getNextVisibleTime() {
        return this.nextVisibleTime;
    }

    /**
     * Gets the message's pop receipt.
     *
     * @return A String which contains the message's pop receipt.
     */
    public final String getPopReceipt() {
        return this.popReceipt;
    }

    /**
     * Sets the dequeue count.
     *
     * @param dequeueCount
     *        An int which contains the dequeue count.
     */
    protected final void setDequeueCount(int dequeueCount) {
        this.dequeueCount = dequeueCount;
    }

    /**
     * Sets the expiration time for the message.
     *
     * @param expirationTime
     *        The java.util.Date which represents the expiration time to set on the message.
     */
    protected final void setExpirationTime(final Date expirationTime) {
        this.expirationTime = expirationTime;
    }

    /**
     * Sets the java.util.Date representing the time the message was added to the queue.
     *
     * @param insertiontTime
     *        The java.util.Date representing the time the message was added to the queue.
     */
    protected final void setInsertionTime(Date insertionTime) {
        this.insertionTime = insertionTime;
    }

    /**
     * Sets the content of the message as a byte array.
     *
     * @param content
     *        A byte array which contains the content of the message.
     */
    public final void setMessageContent(final byte[] content) {
        Utility.assertNotNull("content", content);

        this.messageContent = Base64.encode(content);
        this.messageType = QueueMessageType.BASE_64_ENCODED;
    }

    /**
     * Sets the content of the message as a String.
     *
     * @param content
     *        A String which contains the content of the message.
     */
    public final void setMessageContent(final String content) {
        this.messageContent = content;
        this.messageType = QueueMessageType.RAW_STRING;
    }

    /**
     * Sets the message ID.
     *
     * @param id
     *        A String which represents the message ID.
     */
    protected final void setMessageId(String id) {
        this.id = id;
    }

    /**
     * Sets the message's type
     *
     * @param messageType
     *        A QueueMessageType value which represents the message type.
     */
    protected final void setMessageType(final QueueMessageType messageType) {
        this.messageType = messageType;
    }

    /**
     * Sets the time for the message to become visible in the queue.
     *
     * @param nextVisibleTime
     *        A java.util.Date with the time that the message will
     *        next be visible.
     */
    protected final void setNextVisibleTime(final Date nextVisibleTime) {
        this.nextVisibleTime = nextVisibleTime;
    }

    /**
     * Sets the message's pop receipt.
     *
     * @param popReceipt
     *        A String which contains the message's pop receipt.
     */
    protected final void setPopReceipt(final String popReceipt) {
        this.popReceipt = popReceipt;
    }
}


text:
/*global angular */
angular.module('vicarApp').factory('exportService', function() {
  'use strict';

  //var koalaPic,
  //    converter = new KoalaPicture();

  // convert to koalapic
  // TODO: do this on demand, when user actually wants to save a koala pic
  //koalaPic = converter.convert(convertedImage);
  //$scope.mainImage = converter.toPixelImage(koalaPic, peptoPalette);
  //$scope.koalaDownloadLink = koalaPic.toUrl();

  return {

  };

});


text:
package com.sun.jini.norm;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.jini.config.ConfigurationException;

import com.sun.jini.norm.lookup.SubStore;
import com.sun.jini.reliableLog.LogHandler;
import com.sun.jini.reliableLog.ReliableLog;
import com.sun.jini.system.FileSystem;
import com.sun.jini.thread.ReadersWriter;

/**
 * Class that actually stores a Norm server's state to disk.  Basically
 * a wrapper around ReliableLog with the addition of lock management.
 *
 * @author Sun Microsystems, Inc.
 */
class PersistentStore {
    /** Logger for logging messages for this class */
    private static final Logger logger = Logger.getLogger("com.sun.jini.norm");

    /**
     * Object we use to reliably and persistently log updates to our
     * state, or null if not persistent.
     */
    private ReliableLog log;

    /**
     * No mutation of persistent state can occur during a snapshot,
     * however, we can have multiple mutators, use
     * ReadersWriter object to manage this invariant.  Note
     * as far as the lock is concerned the mutators are the readers and
     * snapshot thread the writer since for us mutation is the
     * non-exclusive operation.
     */
    final private ReadersWriter mutatorLock = new ReadersWriter();

    /**
     * Thread local that tracks if (and how many times) the current thread
     * has acquired a non-exclusive mutator lock.
     */
    final static private ThreadLocal lockState = new ThreadLocal();

    /** Cache a Long object with a zero value */
    final static private Long zero = new Long(0);

    /** Location of the persistent store, or null if not persistent */
    final private File storeLocation;

    /** Object that handles the recovery of logs, or null if not persistent  */
    final private LogHandler logHandler;

    /** The NormServer we are part of */
    final private NormServerBaseImpl server;

    /** Number of updates since last snapshot */
    private int updateCount;

    /** A list of all of the sub-stores */
    private List subStores = new LinkedList();

    /**
     * Construct a store that will persist its data to the specified
     * directory.
     *
     * @param logDir directory where the store should persist its data,
     *        which must exist, unless it is null, in which case
     *	      there is no persistence
     * @param logHandler object that will process the log and last
     *        snapshot to recover the server's state
     * @param server the server is called back after an update so it can
     *        decide whether or not to do a snapshot
     * @throws StoreException if there is a problem setting up the store
     */
    PersistentStore(String logDir, LogHandler logHandler,
		    NormServerBaseImpl server)
	throws StoreException
    {
	this.logHandler = logHandler;
	this.server = server;
	if (logDir == null) {
	    storeLocation = null;
	} else {
	    storeLocation = new File(logDir);
	    try {
		log = new ReliableLog(
		    storeLocation.getCanonicalPath(), logHandler);
	    } catch (IOException e) {
		throw new CorruptedStoreException(
		    "Failure creating reliable log", e);
	    }

	    try {
		log.recover();
	    } catch (IOException e) {
		throw new CorruptedStoreException(
		    "Failure recovering reliable log", e);
	    }
	}
    }

    /**
     * Destroy the store.
     *
     * @throws IOException if it has difficulty removing the log files
     */
    void destroy() throws IOException {
	// Prep all the sub-stores to be destroyed
	for (Iterator i = subStores.iterator(); i.hasNext(); ) {
	    SubStore subStore = (SubStore) i.next();
	    subStore.prepareDestroy();
	}
	if (log != null) {
	    log.deletePersistentStore();
	    FileSystem.destroy(storeLocation, true);
	}
    }

    /**
     * Inform the store of a sub-store
     */
    void addSubStore(SubStore subStore) throws StoreException {
	try {
	    if (log == null) {
		subStore.setDirectory(null);
	    } else {
		final String subDir = subStore.subDirectory();

		if (subDir == null) {
		    subStore.setDirectory(storeLocation);
		} else {
		    subStore.setDirectory(new File(storeLocation, subDir));
		}
	    }

	    subStores.add(subStore);
	} catch (IOException e) {
	    throw new StoreException("Failure adding substore " + subStore,
				     e);
	} catch (ConfigurationException e) {
	    throw new StoreException("Failure adding substore " + subStore,
				     e);
	}
    }

    /////////////////////////////////////////////////////////////////
    // Methods for obtaining and releasing the locks on the store

    /**
     * Block until we can acquire a non-exclusive mutator lock on the
     * server's persistent state.  This lock should be acquired in a
     * try block and a releaseMutatorLock call
     * should be placed in a finally block.
     */
    void acquireMutatorLock() {
	// Do we already hold a lock?

	Long lockStateVal = (Long) lockState.get();
	if (lockStateVal == null)
	    lockStateVal = zero;

	final long longVal = lockStateVal.longValue();

	if (longVal == 0) {
	    // No, this thread currently does not hold a lock,
	    // grab non-exclusive lock (which for mutatorLock is a
	    // read lock)
	    mutatorLock.readLock();
	}

	// Either way, bump the lock count and update our thread state
	lockState.set(new Long(longVal + 1));
    }

    /**
     * Release one level of mutator locks if this thread holds at least one.
     */
    void releaseMutatorLock() {
	Long lockStateVal = (Long) lockState.get();
	if (lockStateVal == null)
	    lockStateVal = zero;

	final long longVal = lockStateVal.longValue();

	if (longVal == 0) {
	    // No lock to release, return
	    return;
	}

	if (longVal == 1) {
	    // Last one on stack release lock
	    // Using read lock because we want a non-exclusive lock
	    mutatorLock.readUnlock();
	    lockStateVal = zero;
	} else {
	    lockStateVal = new Long(longVal - 1);
	}

	lockState.set(lockStateVal);
    }

    //////////////////////////////////////////////////////////////////
    // Methods for writing records to the log and taking and
    // coordinating snapshots

    /**
     * Log an update. Will flush to disk before returning.
     *
     * @throws IllegalStateException if the current thread does not hold
     *	       a non-exclusive mutator lock
     * @throws IOException
     * @see ReliableLog#update
     */
    void update(Object o) {
	if (log == null) {
	    return;
	}
	final Long lockStateVal = (Long) lockState.get();
	if (lockStateVal == null || lockStateVal.longValue() == 0) {
	    throw new IllegalStateException("PersistentStore.update:" +
	        "Must acquire mutator lock before calling update()");
	}

	synchronized (this) {
	    try {
		log.update(o, true);
		updateCount++;
		server.updatePerformed(updateCount);
	    } catch (IOException e) {
		// $$$ should probably be propagating this exception
		logger.log(Level.WARNING, "IOException while updating log", e);
	    }
	}
    }

    /**
     * Generate a snapshot, will perform the necessary locking to ensure no
     * threads are mutating the state of the server before creating the
     * snapshot.
     *
     * @throws IOException
     * @see ReliableLog#snapshot
     */
    void snapshot() throws IOException {
	if (log == null) {
	    return;
	}
	try {
	    // Using write lock because we want an exclusive lock
	    mutatorLock.writeLock();
	    updateCount = 0;

	    // Don't need to sync on this because
	    // mutatorLock.writeLock() gives us an exclusive lock
	    log.snapshot();
	} finally {
	    // Using write lock because we want an exclusive lock
	    mutatorLock.writeUnlock();
	}
    }
}


text:
bool getObjectShadingGroups(const MDagPath& shapeObjectDP, MIntArray& perFaceAssignments, MObjectArray& shadingGroups, bool needsPerFaceInfo);
bool getObjectShadingGroups(const MDagPath& shapeObjectDP, MObject& shadingGroup);
bool getObjectShadingGroups(const MObject& geoObject, MObject& sGroup, int instId);

#endif  // !SHADINGTOOLS_SHADINGUTILS_H


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <name>API for REST transactions</name>
    <artifactId>etx-api</artifactId>

    <parent>
        <groupId>com.alx</groupId>
        <artifactId>etx</artifactId>
        <version>1.0.0</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--test-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java8</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-spring</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
This is (will be) a small CLI tool that administrators will be able to run
during planned outages to see which playbooks are currently being run, by whom,
and which hosts are affected by them.

It makes use of Datagrepper (if datagrepper happens to be down during the
outage at the moment you run this, you should try again
when it's back online).

# License

BSD-2. (c) 2015 Red Hat, Inc.


text:
/**
 *
 */
package stack.patterns.adapter;

/**
 * @author Damjan Vantur
 *
 */
public class CeilingLight implements Light {

	boolean lightOn;

	public CeilingLight() {
		this.lightOn = false;
	}

	@Override
	public void turnOn() {
		this.lightOn = true;
	}

	@Override
	public void turnOff() {
		this.lightOn = false;
	}

	@Override
	public boolean isLightOn() {
		return this.lightOn;
	}

}


text:
use crate::sys;
use libc::c_void;
use std::marker::PhantomData;
use std::mem;

use crate::TimerSubsystem;

impl TimerSubsystem {
    /// Constructs a new timer using the boxed closure `callback`.
    ///
    /// The timer is started immediately, it will be cancelled either:
    ///
    /// * when the timer is dropped
    /// * or when the callback returns a non-positive continuation interval
    #[must_use = "if unused the Timer will be dropped immediately"]
    #[doc(alias = "SDL_AddTimer")]
    pub fn add_timer<'b, 'c>(&'b self, delay: u32, callback: TimerCallback<'c>) -> Timer<'b, 'c> {
        unsafe {
            let callback = Box::new(callback);
            let timer_id = sys::SDL_AddTimer(
                delay,
                Some(c_timer_callback),
                mem::transmute_copy(&callback),
            );

            Timer {
                callback: Some(callback),
                raw: timer_id,
                _marker: PhantomData,
            }
        }
    }

    /// Gets the number of milliseconds elapsed since the timer subsystem was initialized.
    ///
    /// It's recommended that you use another library for timekeeping, such as `time`.
    #[doc(alias = "SDL_GetTicks")]
    pub fn ticks(&self) -> u32 {
        // Google says this is probably not thread-safe (TODO: prove/disprove this).
        unsafe { sys::SDL_GetTicks() }
    }

    /// Sleeps the current thread for the specified amount of milliseconds.
    ///
    /// It's recommended that you use `std::thread::sleep()` instead.
    #[doc(alias = "SDL_Delay")]
    pub fn delay(&mut self, ms: u32) {
        // Google says this is probably not thread-safe (TODO: prove/disprove this).
        unsafe { sys::SDL_Delay(ms) }
    }

    #[doc(alias = "SDL_GetPerformanceCounter")]
    pub fn performance_counter(&self) -> u64 {
        unsafe { sys::SDL_GetPerformanceCounter() }
    }

    #[doc(alias = "SDL_GetPerformanceFrequency")]
    pub fn performance_frequency(&self) -> u64 {
        unsafe { sys::SDL_GetPerformanceFrequency() }
    }
}

pub type TimerCallback<'a> = Box<dyn FnMut() -> u32 + 'a + Send>;

pub struct Timer<'b, 'a> {
    callback: Option<Box<TimerCallback<'a>>>,
    raw: sys::SDL_TimerID,
    _marker: PhantomData<&'b ()>,
}

impl<'b, 'a> Timer<'b, 'a> {
    /// Returns the closure as a trait-object and cancels the timer
    /// by consuming it...
    pub fn into_inner(mut self) -> TimerCallback<'a> {
        *self.callback.take().unwrap()
    }
}

impl<'b, 'a> Drop for Timer<'b, 'a> {
    #[inline]
    #[doc(alias = "SDL_RemoveTimer")]
    fn drop(&mut self) {
        // SDL_RemoveTimer returns SDL_FALSE if the timer wasn't found (impossible),
        // or the timer has been cancelled via the callback (possible).
        // The timer being cancelled isn't an issue, so we ignore the result.
        unsafe { sys::SDL_RemoveTimer(self.raw) };
    }
}

extern "C" fn c_timer_callback(_interval: u32, param: *mut c_void) -> u32 {
    let f = param as *mut TimerCallback<'_>;
    unsafe { (*f)() }
}

#[cfg(not(target_os = "macos"))]
#[cfg(test)]
mod test {
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    #[test]
    fn test_timer() {
        test_timer_runs_multiple_times();
        test_timer_runs_at_least_once();
        test_timer_can_be_recreated();
    }

    fn test_timer_runs_multiple_times() {
        let sdl_context = crate::sdl::init().unwrap();
        let timer_subsystem = sdl_context.timer().unwrap();

        let local_num = Arc::new(Mutex::new(0));
        let timer_num = local_num.clone();

        let _timer = timer_subsystem.add_timer(
            20,
            Box::new(|| {
                // increment up to 10 times (0 -> 9)
                // tick again in 100ms after each increment
                //
                let mut num = timer_num.lock().unwrap();
                if *num < 9 {
                    *num += 1;
                    20
                } else {
                    0
                }
            }),
        );

        // tick the timer at least 10 times w/ 200ms of "buffer"
        ::std::thread::sleep(Duration::from_millis(250));
        let num = local_num.lock().unwrap(); // read the number back
        assert_eq!(*num, 9); // it should have incremented at least 10 times...
    }

    fn test_timer_runs_at_least_once() {
        let sdl_context = crate::sdl::init().unwrap();
        let timer_subsystem = sdl_context.timer().unwrap();

        let local_flag = Arc::new(Mutex::new(false));
        let timer_flag = local_flag.clone();

        let _timer = timer_subsystem.add_timer(
            20,
            Box::new(|| {
                let mut flag = timer_flag.lock().unwrap();
                *flag = true;
                0
            }),
        );

        ::std::thread::sleep(Duration::from_millis(50));
        let flag = local_flag.lock().unwrap();
        assert_eq!(*flag, true);
    }

    fn test_timer_can_be_recreated() {
        let sdl_context = crate::sdl::init().unwrap();
        let timer_subsystem = sdl_context.timer().unwrap();

        let local_num = Arc::new(Mutex::new(0));
        let timer_num = local_num.clone();

        // run the timer once and reclaim its closure
        let timer_1 = timer_subsystem.add_timer(
            20,
            Box::new(move || {
                let mut num = timer_num.lock().unwrap();
                *num += 1; // increment the number
                0 // do not run timer again
            }),
        );

        // reclaim closure after timer runs
        ::std::thread::sleep(Duration::from_millis(50));
        let closure = timer_1.into_inner();

        // create a second timer and increment again
        let _timer_2 = timer_subsystem.add_timer(20, closure);
        ::std::thread::sleep(Duration::from_millis(50));

        // check that timer was incremented twice
        let num = local_num.lock().unwrap();
        assert_eq!(*num, 2);
    }
}


text:
/* Cursor */

var Cursor =
{
    x: 0, y: 0,
    init: function () {
        this.setEvent('mouse');
        this.setEvent('touch');
    },
    setEvent: function (type) {
        var moveHandler = document['on' + type + 'move'] || function () { };
        document['on' + type + 'move'] = function (e) {
            moveHandler(e);
            Cursor.refresh(e);
        }
    },
    refresh: function (e) {
        if (!e) {
            e = window.event;
        }
        if (e.type == 'mousemove') {
            this.set(e);
        }
        else if (e.touches) {
            this.set(e.touches[0]);
        }
    },
    set: function (e) {
        if (e.pageX || e.pageY) {
            this.x = e.pageX;
            this.y = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            this.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            this.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
    }
};
Cursor.init();

/* Position */

var Position =
{
    get: function (obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            }
            while ((obj = obj.offsetParent));
        }
        return [curleft, curtop];
    }
};

/* Dragdealer */

var Slider = function (element, options) {
    if (typeof(element) === 'string') {
        this.wrapper = document.getElementById(element);
    } else {
        this.wrapper = element;
    }
    var handle = element.getElementsByTagName('div')[0];
    if (!handle) {
        return;
    }
    this.init(element, handle, options || {});
    this.setup();
};
Slider.prototype =
{
    init: function (wrapper, handle, options) {
        this.wrapper = wrapper;
        this.handle = handle;
        this.options = options;

        this.disabled = this.getOption('disabled', false);
        this.horizontal = this.getOption('horizontal', true);
        this.vertical = this.getOption('vertical', false);
        this.slide = this.getOption('slide', true);
        this.steps = this.getOption('steps', 0);
        this.snap = this.getOption('snap', false);
        this.loose = this.getOption('loose', false);
        this.speed = this.getOption('speed', 10) / 100;
        this.xPrecision = this.getOption('xPrecision', 0);
        this.yPrecision = this.getOption('yPrecision', 0);

        this.callback = options.callback || null;
        this.animationCallback = options.animationCallback || null;

        this.bounds = {
            left: options.left || 0, right: -(options.right || 0),
            top: options.top || 0, bottom: -(options.bottom || 0),
            x0: 0, x1: 0, xRange: 0,
            y0: 0, y1: 0, yRange: 0
        };
        this.value = {
            prev: [-1, -1],
            current: [options.x || 0, options.y || 0],
            target: [options.x || 0, options.y || 0]
        };
        this.offset = {
            wrapper: [0, 0],
            mouse: [0, 0],
            prev: [-999999, -999999],
            current: [0, 0],
            target: [0, 0]
        };
        this.change = [0, 0];

        this.activity = false;
        this.dragging = false;
        this.tapping = false;
    },
    getOption: function (name, defaultValue) {
        return this.options[name] !== undefined ? this.options[name] : defaultValue;
    },
    setup: function () {
        this.setWrapperOffset();
        this.setBoundsPadding();
        this.setBounds();
        this.setSteps();

        this.addListeners();
    },
    setWrapperOffset: function () {
        this.offset.wrapper = Position.get(this.wrapper);
    },
    setBoundsPadding: function () {
        if (!this.bounds.left && !this.bounds.right) {
            this.bounds.left = Position.get(this.handle)[0] - this.offset.wrapper[0];
            this.bounds.right = -this.bounds.left;
        }
        if (!this.bounds.top && !this.bounds.bottom) {
            this.bounds.top = Position.get(this.handle)[1] - this.offset.wrapper[1];
            this.bounds.bottom = -this.bounds.top;
        }
    },
    setBounds: function () {
        this.bounds.x0 = this.bounds.left;
        this.bounds.x1 = this.wrapper.offsetWidth + this.bounds.right;
        this.bounds.xRange = (this.bounds.x1 - this.bounds.x0) - this.handle.offsetWidth;

        this.bounds.y0 = this.bounds.top;
        this.bounds.y1 = this.wrapper.offsetHeight + this.bounds.bottom;
        this.bounds.yRange = (this.bounds.y1 - this.bounds.y0) - this.handle.offsetHeight;

        this.bounds.xStep = 1 / (this.xPrecision || Math.max(this.wrapper.offsetWidth, this.handle.offsetWidth));
        this.bounds.yStep = 1 / (this.yPrecision || Math.max(this.wrapper.offsetHeight, this.handle.offsetHeight));
    },
    setSteps: function () {
        if (this.steps > 1) {
            this.stepRatios = [];
            for (var i = 0; i <= this.steps - 1; i++) {
                this.stepRatios[i] = i / (this.steps - 1);
            }
        }
    },
    addListeners: function () {
        var self = this;

        this.wrapper.onselectstart = function () {
            return false;
        }
        this.handle.onmousedown = this.handle.ontouchstart = function (e) {
            self.handleDownHandler(e);
        };
        this.wrapper.onmousedown = this.wrapper.ontouchstart = function (e) {
            self.wrapperDownHandler(e);
        };
        var mouseUpHandler = document.onmouseup || function () { };
        document.onmouseup = function (e) {
            mouseUpHandler(e);
            self.documentUpHandler(e);
        };
        var touchEndHandler = document.ontouchend || function () { };
        document.ontouchend = function (e) {
            touchEndHandler(e);
            self.documentUpHandler(e);
        };
        var resizeHandler = window.onresize || function () { };
        window.onresize = function (e) {
            resizeHandler(e);
            self.documentResizeHandler(e);
        };
        this.wrapper.onmousemove = function (e) {
            self.activity = true;
        }
        this.wrapper.onclick = function (e) {
            return !self.activity;
        }

        this.interval = setInterval(function () { self.animate() }, 25);
        self.animate(false, true);
    },
    handleDownHandler: function (e) {
        this.activity = false;
        Cursor.refresh(e);

        this.preventDefaults(e, true);
        this.startDrag();
        this.cancelEvent(e);
    },
    wrapperDownHandler: function (e) {
        Cursor.refresh(e);

        this.preventDefaults(e, true);
        this.startTap();
    },
    documentUpHandler: function (e) {
        this.stopDrag();
        this.stopTap();
        //this.cancelEvent(e);
    },
    documentResizeHandler: function (e) {
        this.setWrapperOffset();
        this.setBounds();

        this.update();
    },
    enable: function () {
        this.disabled = false;
        this.handle.className = this.handle.className.replace(/\s?disabled/g, '');
    },
    disable: function () {
        this.disabled = true;
        this.handle.className += ' disabled';
    },
    setStep: function (x, y, snap) {
        this.setValue(
			this.steps && x > 1 ? (x - 1) / (this.steps - 1) : 0,
			this.steps && y > 1 ? (y - 1) / (this.steps - 1) : 0,
			snap
		);
    },
    setValue: function (x, y, snap) {
        this.setTargetValue([x, y || 0]);
        if (snap) {
            this.groupCopy(this.value.current, this.value.target);
        }
    },
    startTap: function (target) {
        if (this.disabled) {
            return;
        }
        this.tapping = true;

        if (target === undefined) {
            target = [
				Cursor.x - this.offset.wrapper[0] - (this.handle.offsetWidth / 2),
				Cursor.y - this.offset.wrapper[1] - (this.handle.offsetHeight / 2)
            ];
        }
        this.setTargetOffset(target);
    },
    stopTap: function () {
        if (this.disabled || !this.tapping) {
            return;
        }
        this.tapping = false;

        this.setTargetValue(this.value.current);
        this.result();
    },
    startDrag: function () {
        if (this.disabled) {
            return;
        }
        this.offset.mouse = [
			Cursor.x - Position.get(this.handle)[0],
			Cursor.y - Position.get(this.handle)[1]
        ];

        this.dragging = true;
    },
    stopDrag: function () {
        if (this.disabled || !this.dragging) {
            return;
        }
        this.dragging = false;

        var target = this.groupClone(this.value.current);
        if (this.slide) {
            var ratioChange = this.change;
            target[0] += ratioChange[0] * 4;
            target[1] += ratioChange[1] * 4;
        }
        this.setTargetValue(target);
        this.result();
    },
    feedback: function () {
        var value = this.value.current;
        if (this.snap && this.steps > 1) {
            value = this.getClosestSteps(value);
        }
        if (!this.groupCompare(value, this.value.prev)) {
            if (typeof (this.animationCallback) == 'function') {
                this.animationCallback(value[0], value[1]);
            }
            this.groupCopy(this.value.prev, value);
        }
    },
    result: function () {
        if (typeof (this.callback) == 'function') {
            this.callback(this.value.target[0], this.value.target[1]);
        }
    },
    animate: function (direct, first) {
        if (direct && !this.dragging) {
            return;
        }
        if (this.dragging) {
            var prevTarget = this.groupClone(this.value.target);

            var offset = [
				Cursor.x - this.offset.wrapper[0] - this.offset.mouse[0],
				Cursor.y - this.offset.wrapper[1] - this.offset.mouse[1]
            ];
            this.setTargetOffset(offset, this.loose);

            this.change = [
				this.value.target[0] - prevTarget[0],
				this.value.target[1] - prevTarget[1]
            ];
        }
        if (this.dragging || first) {
            this.groupCopy(this.value.current, this.value.target);
        }
        if (this.dragging || this.glide() || first) {
            this.update();
            this.feedback();
        }
    },
    glide: function () {
        var diff = [
			this.value.target[0] - this.value.current[0],
			this.value.target[1] - this.value.current[1]
        ];
        if (!diff[0] && !diff[1]) {
            return false;
        }
        if (Math.abs(diff[0]) > this.bounds.xStep || Math.abs(diff[1]) > this.bounds.yStep) {
            this.value.current[0] += diff[0] * this.speed;
            this.value.current[1] += diff[1] * this.speed;
        }
        else {
            this.groupCopy(this.value.current, this.value.target);
        }
        return true;
    },
    update: function () {
        if (!this.snap) {
            this.offset.current = this.getOffsetsByRatios(this.value.current);
        }
        else {
            this.offset.current = this.getOffsetsByRatios(
				this.getClosestSteps(this.value.current)
			);
        }
        this.show();
    },
    show: function () {
        if (!this.groupCompare(this.offset.current, this.offset.prev)) {
            if (this.horizontal) {
                this.handle.style.left = String(this.offset.current[0]) + 'px';
            }
            if (this.vertical) {
                this.handle.style.top = String(this.offset.current[1]) + 'px';
            }
            this.groupCopy(this.offset.prev, this.offset.current);
        }
    },
    setTargetValue: function (value, loose) {
        var target = loose ? this.getLooseValue(value) : this.getProperValue(value);

        this.groupCopy(this.value.target, target);
        this.offset.target = this.getOffsetsByRatios(target);
    },
    setTargetOffset: function (offset, loose) {
        var value = this.getRatiosByOffsets(offset);
        var target = loose ? this.getLooseValue(value) : this.getProperValue(value);

        this.groupCopy(this.value.target, target);
        this.offset.target = this.getOffsetsByRatios(target);
    },
    getLooseValue: function (value) {
        var proper = this.getProperValue(value);
        return [
			proper[0] + ((value[0] - proper[0]) / 4),
			proper[1] + ((value[1] - proper[1]) / 4)
        ];
    },
    getProperValue: function (value) {
        var proper = this.groupClone(value);

        proper[0] = Math.max(proper[0], 0);
        proper[1] = Math.max(proper[1], 0);
        proper[0] = Math.min(proper[0], 1);
        proper[1] = Math.min(proper[1], 1);

        if ((!this.dragging && !this.tapping) || this.snap) {
            if (this.steps > 1) {
                proper = this.getClosestSteps(proper);
            }
        }
        return proper;
    },
    getRatiosByOffsets: function (group) {
        return [
			this.getRatioByOffset(group[0], this.bounds.xRange, this.bounds.x0),
			this.getRatioByOffset(group[1], this.bounds.yRange, this.bounds.y0)
        ];
    },
    getRatioByOffset: function (offset, range, padding) {
        return range ? (offset - padding) / range : 0;
    },
    getOffsetsByRatios: function (group) {
        return [
			this.getOffsetByRatio(group[0], this.bounds.xRange, this.bounds.x0),
			this.getOffsetByRatio(group[1], this.bounds.yRange, this.bounds.y0)
        ];
    },
    getOffsetByRatio: function (ratio, range, padding) {
        return Math.round(ratio * range) + padding;
    },
    getClosestSteps: function (group) {
        return [
			this.getClosestStep(group[0]),
			this.getClosestStep(group[1])
        ];
    },
    getClosestStep: function (value) {
        var k = 0;
        var min = 1;
        for (var i = 0; i <= this.steps - 1; i++) {
            if (Math.abs(this.stepRatios[i] - value) < min) {
                min = Math.abs(this.stepRatios[i] - value);
                k = i;
            }
        }
        return this.stepRatios[k];
    },
    groupCompare: function (a, b) {
        return a[0] == b[0] && a[1] == b[1];
    },
    groupCopy: function (a, b) {
        a[0] = b[0];
        a[1] = b[1];
    },
    groupClone: function (a) {
        return [a[0], a[1]];
    },
    preventDefaults: function (e, selection) {
        if (!e) {
            e = window.event;
        }
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;

        if (selection && document.selection) {
            document.selection.empty();
        }
    },
    cancelEvent: function (e) {
        if (!e) {
            e = window.event;
        }
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        e.cancelBubble = true;
    }
};


text: print("Hello \t World!")


text:
package org.kie.wires.core.client.properties;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.jboss.errai.ioc.client.container.IOCBeanDef;
import org.jboss.errai.ioc.client.container.SyncBeanManager;
import org.kie.wires.core.api.properties.PropertyEditorAdaptor;

/**
 * A cache of PropertyEditorAdaptors
 */
@ApplicationScoped
public class PropertyEditorAdaptorsCache {

    @Inject
    private SyncBeanManager iocManager;

    private Set<PropertyEditorAdaptor> adaptors = new HashSet<PropertyEditorAdaptor>();

    @PostConstruct
    private void setup() {
        this.adaptors = getAvailableAdaptors();
    }

    public Set<PropertyEditorAdaptor> getAdaptors() {
        return adaptors;
    }

    private Set<PropertyEditorAdaptor> getAvailableAdaptors() {
        final Set<PropertyEditorAdaptor> factories = new HashSet<PropertyEditorAdaptor>();
        final Collection<IOCBeanDef<PropertyEditorAdaptor>> factoryBeans = iocManager.lookupBeans( PropertyEditorAdaptor.class );
        for ( IOCBeanDef<PropertyEditorAdaptor> factoryBean : factoryBeans ) {
            factories.add( factoryBean.getInstance() );
        }
        return factories;
    }

}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M3.25,18.75V5.25H16L20.75,12L15.95,18.75Z"/>
</vector>


text:
package org.yeastrc.xlink.dto;

/**
 * Table search_linker_per_side_linkable_residues_tbl
 *
 * FK: search_linker_per_side_definition_tbl
 */
public class SearchLinkerPerSideLinkableResiduesDTO {

	private int id;
	private int searchLinkerPerSideDefinitionId;
	private String residue;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getResidue() {
		return residue;
	}
	public void setResidue(String residue) {
		this.residue = residue;
	}
	public int getSearchLinkerPerSideDefinitionId() {
		return searchLinkerPerSideDefinitionId;
	}
	public void setSearchLinkerPerSideDefinitionId(int searchLinkerPerSideDefinitionId) {
		this.searchLinkerPerSideDefinitionId = searchLinkerPerSideDefinitionId;
	}

}


text:
This project is purely a "wrapper" around a normal command-line application. It adds functionality like timeouts, abort requests, time-stamp logging, etc

# Quick Start

## Execute the command

Specify the `-task` and then lastly the actual command-line (like `ping` in the below example).

### Windows:

```
go get -u github.com/golang-devops/exec-logger
cd %Temp% & mkdir test-exec-logger & cd test-exec-logger
exec-logger -task exec ping 127.0.0.1 -n 3
```

### Linux:

```
go get -u github.com/golang-devops/exec-logger
cd $Temp && mkdir test-exec-logger && cd ./test-exec-logger
exec-logger -task exec ping 127.0.0.1 -c 3
```

## Inspect created files

There should now be four files withing a **subfolder** `exec-logger` of this temp dir, namely:

- `local-context.json` - gets written out at the start and includes the `UserName` and `HostName` of the machine on which it runs
- `alive.txt` - gets written out every 2 seconds to inform "external observers" that the process is alive and responding.
- `exited.json` - gets written out when the process finished and contains the `ExitCode`, `Error` (if any), `ExitTime` (of exit) and `Duration` (in golang native [time.Duration](https://golang.org/pkg/time/#Duration) format). These fields are contained in the `ExitStatusDto` struct
- `log.log` - contains the stdout/stderr of the "wrapped command" which is that of the `ping` command in the above example

Note that the `log.log` file added time-stamp prefixes to each line received from `ping`. It also has additional information like the last line that should read **"Command exited with code 0"**.

The `exited.json` file should contain a zero `ExitCode`.

## Failure example

Delete the above three files if they already exist.

Change the above command to a "broken" one (for example by removing the number passed to the `-n` flag for windows or `-c` flag for linux. Broken windows command `exec-logger -task exec ping 127.0.0.1 -n`. Broken linux command `exec-logger -task exec ping 127.0.0.1 -c`.

Now the three files will be created again. This time the `exited.json` file should contain a non-zero `ExitCode` with an `Error`. The `log.log` file will contain a line or two with `EASY_EXEC_ERROR:` prefix after the timestamp. Those lines are the `Stderr` lines received by the `ping` command. The last of those error lines would also contain `Unable to run command` which is generated by the exec-logger itself.

## Abort the process prematurely

Delete the above three files if they already exist.

If an "external observer" of this process wants to abort it, it could just create a file called `must-abort.txt` inside this folder.

Run the same example from above but change the number flag (`-n` for windows or `-c` for linux) to something huge, like 3000. This means it will ping 3000 times. But we will abort this process using this mentioned file.

After running that 3000 command open another console window in the same temp directory and call `echo "" > must-abort.txt` to create the empty file. Now watch the first console windows should shortly after that abort the ping command. After aborting the `log.log` file will contain a line with `Got ABORT message` and another with `Successfully killed process with PID`. The `exited.json` will also contain a non-zero `ExitCode`.

## Auto time-out using a duration

Delete the above three files if they already exist.

Now to only allow the command to run for a certain time we can use the `-timeout-kill` flag. Change the above command to something like:

- windows: `exec-logger -timeout-kill 5s -task exec ping 127.0.0.1 -n 3000`
- linux: `exec-logger -timeout-kill 5s -task exec ping 127.0.0.1 -c 3000`

Note the added flag `-timeout-kill 5s`. This will attempt to run ping for 3000 seconds but we tell it to abort after `5s`. This timeout flag is in the format of native golang [time.Duration](https://golang.org/pkg/time/#Duration).

After 5 seconds it should automatically abort and our usual three files should be there. The `exited.json` file should again have a non-zero `ExitCode` with its error being something like "The command timed out after '5s'". The `log.log` will also contain a line reading `Timeout of 5s reached, now aborting` as well as `Successfully killed process with PID`.

# Acknowledgments

- [shirou/gopsutil](https://github.com/shirou/gopsutil) - Used for Linux to obtain process children to be killed

# Contribution

Pull requests are welcome.


text:
package com.facebook.litho.sections.common;

import com.facebook.litho.annotations.Event;

/**
 * An {@link Event} that is handled by a {@link HideableDataDiffSectionSpec} to remove an edge from
 * the {@link DataDiffSection}
 *
 * @param model the edge model object.
 */
@Event
public class HideItemEvent {
  public Object model;
}


text:
using UnityEngine;
using System.Collections;

public class BattleCommandIdle : BattleCommandBase
{
	public override void Handle ()
	{
		Actor actor = battleplayer.unitActorMap[Caster];
		actor.Idle();
	}
}


text:
package org.apache.zeppelin.rest;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;

import com.google.gson.Gson;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.socket.NotebookServer;
import org.apache.zeppelin.utils.TestUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.user.AuthenticationInfo;

/**
 * Zeppelin notebook rest api tests.
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NotebookRestApiTest extends AbstractTestRestApi {
  Gson gson = new Gson();
  AuthenticationInfo anonymous;

  @BeforeClass
  public static void init() throws Exception {
    startUp(NotebookRestApiTest.class.getSimpleName());
    TestUtils.getInstance(Notebook.class).setParagraphJobListener(NotebookServer.getInstance());
  }

  @AfterClass
  public static void destroy() throws Exception {
    AbstractTestRestApi.shutDown();
  }

  @Before
  public void setUp() {
    anonymous = new AuthenticationInfo("anonymous");
  }

  @Test
  public void testGetNoteParagraphJobStatus() throws IOException {
    Note note1 = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);

      String paragraphId = note1.getLastParagraph().getId();

      GetMethod get = httpGet("/notebook/job/" + note1.getId() + "/" + paragraphId);
      assertThat(get, isAllowed());
      Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      Map<String, Set<String>> paragraphStatus = (Map<String, Set<String>>) resp.get("body");

      // Check id and status have proper value
      assertEquals(paragraphStatus.get("id"), paragraphId);
      assertEquals(paragraphStatus.get("status"), "READY");
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
    }
  }

  @Test
  public void testRunParagraphJob() throws IOException {
    Note note1 = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);

      Paragraph p = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);

      // run blank paragraph
      PostMethod post = httpPost("/notebook/job/" + note1.getId() + "/" + p.getId(), "");
      assertThat(post, isAllowed());
      Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals(resp.get("status"), "OK");
      post.releaseConnection();
      assertEquals(p.getStatus(), Job.Status.FINISHED);

      // run non-blank paragraph
      p.setText("test");
      post = httpPost("/notebook/job/" + note1.getId() + "/" + p.getId(), "");
      assertThat(post, isAllowed());
      resp = gson.fromJson(post.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals(resp.get("status"), "OK");
      post.releaseConnection();
      assertNotEquals(p.getStatus(), Job.Status.READY);
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
    }
  }

  @Test
  public void testRunParagraphSynchronously() throws IOException {
    Note note1 = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);

      Paragraph p = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);

      // run non-blank paragraph
      String title = "title";
      String text = "%sh\n sleep 1";
      p.setTitle(title);
      p.setText(text);

      PostMethod post = httpPost("/notebook/run/" + note1.getId() + "/" + p.getId(), "");
      assertThat(post, isAllowed());
      Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals(resp.get("status"), "OK");
      post.releaseConnection();
      assertNotEquals(p.getStatus(), Job.Status.READY);

      // Check if the paragraph is emptied
      assertEquals(title, p.getTitle());
      assertEquals(text, p.getText());

      // run invalid code
      text = "%sh\n invalid_cmd";
      p.setTitle(title);
      p.setText(text);

      post = httpPost("/notebook/run/" + note1.getId() + "/" + p.getId(), "");
      assertEquals(500, post.getStatusCode());
      resp = gson.fromJson(post.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals("INTERNAL_SERVER_ERROR", resp.get("status"));
      StringMap stringMap = (StringMap) resp.get("body");
      assertEquals("ERROR", stringMap.get("code"));
      List<StringMap> interpreterResults = (List<StringMap>) stringMap.get("msg");
      assertTrue(interpreterResults.get(0).toString(),
              interpreterResults.get(0).get("data").toString().contains("invalid_cmd: command not found"));
      post.releaseConnection();
      assertNotEquals(p.getStatus(), Job.Status.READY);

      // Check if the paragraph is emptied
      assertEquals(title, p.getTitle());
      assertEquals(text, p.getText());
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
    }
  }

  @Test
  public void testRunNoteBlocking() throws IOException {
    Note note1 = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      // 2 paragraphs
      // P1:
      //    %python
      //    import time
      //    time.sleep(1)
      //    user='abc'
      // P2:
      //    %python
      //    from __future__ import print_function
      //    print(user)
      //
      Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      Paragraph p2 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      p1.setText("%python import time\ntime.sleep(1)\nuser='abc'");
      p2.setText("%python from __future__ import print_function\nprint(user)");

      PostMethod post = httpPost("/notebook/job/" + note1.getId(), "");
      assertThat(post, isAllowed());
      Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals(resp.get("status"), "OK");
      post.releaseConnection();

      assertEquals(Job.Status.FINISHED, p1.getStatus());
      assertEquals(Job.Status.FINISHED, p2.getStatus());
      assertEquals("abc\n", p2.getReturn().message().get(0).getData());
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
    }
  }

  @Test
  public void testRunNoteNonBlocking() throws Exception {
    Note note1 = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      // 2 paragraphs
      // P1:
      //    %python
      //    import time
      //    time.sleep(5)
      //    name='hello'
      //    z.put('name', name)
      // P2:
      //    %%sh(interpolate=true)
      //    echo '{name}'
      //
      Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      Paragraph p2 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      p1.setText("%python import time\ntime.sleep(5)\nname='hello'\nz.put('name', name)");
      p2.setText("%sh(interpolate=true) echo '{name}'");

      PostMethod post = httpPost("/notebook/job/" + note1.getId() + "?waitToFinish=false", "");
      assertThat(post, isAllowed());
      Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals(resp.get("status"), "OK");
      post.releaseConnection();

      p1.waitUntilFinished();
      p2.waitUntilFinished();

      assertEquals(Job.Status.FINISHED, p1.getStatus());
      assertEquals(Job.Status.FINISHED, p2.getStatus());
      assertEquals("hello\n", p2.getReturn().message().get(0).getData());
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
    }
  }

  @Test
  public void testRunAllParagraph_FirstFailed() throws IOException {
    Note note1 = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      // 2 paragraphs
      // P1:
      //    %python
      //    import time
      //    time.sleep(1)
      //    from __future__ import print_function
      //    print(user)
      // P2:
      //    %python
      //    user='abc'
      //
      Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      Paragraph p2 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      p1.setText("%python import time\ntime.sleep(1)\nfrom __future__ import print_function\nprint(user2)");
      p2.setText("%python user2='abc'\nprint(user2)");

      PostMethod post = httpPost("/notebook/job/" + note1.getId(), "");
      assertThat(post, isExpectationFailed());
      Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals(resp.get("status"), "EXPECTATION_FAILED");
      assertTrue(resp.get("message").toString().contains("Fail to run note because paragraph"));
      post.releaseConnection();

      assertEquals(Job.Status.ERROR, p1.getStatus());
      // p2 will be skipped because p1 is failed.
      assertEquals(Job.Status.READY, p2.getStatus());
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
    }
  }

  @Test
  public void testCloneNote() throws IOException {
    Note note1 = null;
    String clonedNoteId = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      PostMethod post = httpPost("/notebook/" + note1.getId(), "");
      LOG.info("testCloneNote response\n" + post.getResponseBodyAsString());
      assertThat(post, isAllowed());
      Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      clonedNoteId = (String) resp.get("body");
      post.releaseConnection();

      GetMethod get = httpGet("/notebook/" + clonedNoteId);
      assertThat(get, isAllowed());
      Map<String, Object> resp2 = gson.fromJson(get.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      Map<String, Object> resp2Body = (Map<String, Object>) resp2.get("body");

      //    assertEquals(resp2Body.get("name"), "Note " + clonedNoteId);
      get.releaseConnection();
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
      if (null != clonedNoteId) {
        TestUtils.getInstance(Notebook.class).removeNote(clonedNoteId, anonymous);
      }
    }
  }

  @Test
  public void testRenameNote() throws IOException {
    Note note = null;
    try {
      String oldName = "old_name";
      note = TestUtils.getInstance(Notebook.class).createNote(oldName, anonymous);
      assertEquals(note.getName(), oldName);
      String noteId = note.getId();

      final String newName = "testName";
      String jsonRequest = "{\"name\": " + newName + "}";

      PutMethod put = httpPut("/notebook/" + noteId + "/rename/", jsonRequest);
      assertThat("test testRenameNote:", put, isAllowed());
      put.releaseConnection();

      assertEquals(note.getName(), newName);
    } finally {
      // cleanup
      if (null != note) {
        TestUtils.getInstance(Notebook.class).removeNote(note.getId(), anonymous);
      }
    }
  }

  @Test
  public void testUpdateParagraphConfig() throws IOException {
    Note note = null;
    try {
      note = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      String noteId = note.getId();
      Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      assertNull(p.getConfig().get("colWidth"));
      String paragraphId = p.getId();
      String jsonRequest = "{\"colWidth\": 6.0}";

      PutMethod put = httpPut("/notebook/" + noteId + "/paragraph/" + paragraphId + "/config",
              jsonRequest);
      assertThat("test testUpdateParagraphConfig:", put, isAllowed());

      Map<String, Object> resp = gson.fromJson(put.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      Map<String, Object> respBody = (Map<String, Object>) resp.get("body");
      Map<String, Object> config = (Map<String, Object>) respBody.get("config");
      put.releaseConnection();

      assertEquals(config.get("colWidth"), 6.0);
      note = TestUtils.getInstance(Notebook.class).getNote(noteId);
      assertEquals(note.getParagraph(paragraphId).getConfig().get("colWidth"), 6.0);
    } finally {
      // cleanup
      if (null != note) {
        TestUtils.getInstance(Notebook.class).removeNote(note.getId(), anonymous);
      }
    }
  }

  @Test
  public void testClearAllParagraphOutput() throws IOException {
    Note note = null;
    try {
      // Create note and set result explicitly
      note = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      Paragraph p1 = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      InterpreterResult result = new InterpreterResult(InterpreterResult.Code.SUCCESS,
              InterpreterResult.Type.TEXT, "result");
      p1.setResult(result);

      Paragraph p2 = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      p2.setReturn(result, new Throwable());

      // clear paragraph result
      PutMethod put = httpPut("/notebook/" + note.getId() + "/clear", "");
      LOG.info("test clear paragraph output response\n" + put.getResponseBodyAsString());
      assertThat(put, isAllowed());
      put.releaseConnection();

      // check if paragraph results are cleared
      GetMethod get = httpGet("/notebook/" + note.getId() + "/paragraph/" + p1.getId());
      assertThat(get, isAllowed());
      Map<String, Object> resp1 = gson.fromJson(get.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      Map<String, Object> resp1Body = (Map<String, Object>) resp1.get("body");
      assertNull(resp1Body.get("result"));

      get = httpGet("/notebook/" + note.getId() + "/paragraph/" + p2.getId());
      assertThat(get, isAllowed());
      Map<String, Object> resp2 = gson.fromJson(get.getResponseBodyAsString(),
              new TypeToken<Map<String, Object>>() {}.getType());
      Map<String, Object> resp2Body = (Map<String, Object>) resp2.get("body");
      assertNull(resp2Body.get("result"));
      get.releaseConnection();
    } finally {
      // cleanup
      if (null != note) {
        TestUtils.getInstance(Notebook.class).removeNote(note.getId(), anonymous);
      }
    }
  }

  @Test
  public void testRunWithServerRestart() throws Exception {
    Note note1 = null;
    try {
      note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous);
      // 2 paragraphs
      // P1:
      //    %python
      //    import time
      //    time.sleep(1)
      //    from __future__ import print_function
      //    print(user)
      // P2:
      //    %python
      //    user='abc'
      //
      Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      Paragraph p2 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS);
      p1.setText("%python import time\ntime.sleep(1)\nuser='abc'");
      p2.setText("%python from __future__ import print_function\nprint(user)");

      PostMethod post1 = httpPost("/notebook/job/" + note1.getId(), "");
      assertThat(post1, isAllowed());
      post1.releaseConnection();
      PutMethod put = httpPut("/notebook/" + note1.getId() + "/clear", "");
      LOG.info("test clear paragraph output response\n" + put.getResponseBodyAsString());
      assertThat(put, isAllowed());
      put.releaseConnection();

      // restart server (while keeping interpreter configuration)
      AbstractTestRestApi.shutDown(false);
      startUp(NotebookRestApiTest.class.getSimpleName(), false);

      note1 = TestUtils.getInstance(Notebook.class).getNote(note1.getId());
      p1 = note1.getParagraph(p1.getId());
      p2 = note1.getParagraph(p2.getId());

      PostMethod post2 = httpPost("/notebook/job/" + note1.getId(), "");
      assertThat(post2, isAllowed());
      Map<String, Object> resp = gson.fromJson(post2.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() {}.getType());
      assertEquals(resp.get("status"), "OK");
      post2.releaseConnection();

      assertEquals(Job.Status.FINISHED, p1.getStatus());
      assertEquals(p2.getReturn().toString(), Job.Status.FINISHED, p2.getStatus());
      assertNotNull(p2.getReturn());
      assertEquals("abc\n", p2.getReturn().message().get(0).getData());
    } finally {
      // cleanup
      if (null != note1) {
        TestUtils.getInstance(Notebook.class).removeNote(note1.getId(), anonymous);
      }
    }
  }
}