text:
using System.Web.Mvc;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using AlloyDemoKit.Business.Rendering;
using EPiServer.Web.Mvc;
using EPiServer.Web.Mvc.Html;
using AlloyDemoKit.Business.Data;

namespace AlloyDemoKit.Business.Initialization
{
    [InitializableModule]
    public class DependencyResolverInitialization : IConfigurableModule
    {
        public void ConfigureContainer(ServiceConfigurationContext context)
        {

            //Implementations for custom interfaces can be registered here.

            context.ConfigurationComplete += (o, e) =>
            {
                //Register custom implementations that should be used in favour of the default implementations
                context.Services.AddTransient<IContentRenderer, ErrorHandlingContentRenderer>()
                    .AddTransient<ContentAreaRenderer, AlloyContentAreaRenderer>()
                    .AddTransient<IFileDataImporter, FileDataImporter>();

            };
        }

        public void Initialize(InitializationEngine context)
        {
            DependencyResolver.SetResolver(new ServiceLocatorDependencyResolver(context.Locate.Advanced));
        }

        public void Uninitialize(InitializationEngine context)
        {
        }

        public void Preload(string[] parameters)
        {
        }
    }
}


text:
package org.zstack.test.cascade;

import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.storage.backup.BackupStorageInventory;
import org.zstack.network.service.virtualrouter.VirtualRouterOfferingVO;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;

/**
 * 1. have VR images on a backup storage
 * 2. have a virtual route offering referring to that image
 * 3. delete the backup storage
 * <p>
 * confirm the virtual router offering is deleted as well
 */
public class TestCascadeDeletion34 {
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/virtualRouter/virtualRouterSNAT.xml", con);
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.addSpringConfig("VirtualRouter.xml");
        deployer.addSpringConfig("VirtualRouterSimulator.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
    }

    @Test
    public void test() throws ApiSenderException, InterruptedException {
        api.setTimeout(10000000);
        BackupStorageInventory bs = deployer.backupStorages.get("sftp");
        api.deleteBackupStorage(bs.getUuid());
        CascadeTestHelper helper = new CascadeTestHelper();
        helper.zeroInDatabase(VirtualRouterOfferingVO.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using DrumbleApp.Shared.Entities;
using DrumbleApp.Shared.Infrastructure.Services.Api.Drumble.ResultModel.Results;
using DrumbleApp.Shared.ValueObjects;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace DrumbleApp.Shared.Interfaces
{
    public interface IDrumbleApiService
    {
        Task<Token> RegisterAnonymous(CancellationToken ct);

        Task<ContactResult> Contact(CancellationToken ct, User user, Email from, string subject, string message);

        Task<bool> RegisterEmail(CancellationToken ct, User user, Email email);

        Task<User> RegisterFacebook(CancellationToken ct, User user);

        Task<User> RegisterTwitter(CancellationToken ct, User user);

        Task<User> LoginFacebook(CancellationToken ct, User user);

        Task<User> LoginTwitter(CancellationToken ct, User user);

        Task<bool> LoginEmail(CancellationToken ct, Email email);

        Task<User> Identify(CancellationToken ct, Email email, Pin onetimePin);

        Task<User> Authorise(CancellationToken ct, User user, Email email, Pin onetimePin);
    }
}


text:
namespace media {

class MEDIA_EXPORT MP3StreamParser : public MPEGAudioStreamParserBase {
 public:
  MP3StreamParser();
  virtual ~MP3StreamParser();

 private:
  // MPEGAudioStreamParserBase overrides.
  virtual int ParseFrameHeader(const uint8* data,
                               int size,
                               int* frame_size,
                               int* sample_rate,
                               ChannelLayout* channel_layout,
                               int* sample_count) const OVERRIDE;

  DISALLOW_COPY_AND_ASSIGN(MP3StreamParser);
};

}  // namespace media

#endif  // MEDIA_FORMATS_MPEG_MP3_STREAM_PARSER_H_


text:
'use_strict';

var _GET = {};
location.search.substr(1).split("&").forEach(function(item) {_GET[item.split("=")[0]] = item.split("=")[1]});
console.log(_GET);

var player = document.getElementById('main-player');
player.removeAttribute('controls');
var btn_play_pause = document.getElementById('btn-play-pause');
var btn_settings = document.getElementById('btn-settings');
var btn_fullscreen = document.getElementById('btn-fullscreen');
var btn_volume = document.getElementById('btn-volume');
var input_volume = document.getElementById('input-volume');
var input_playback = document.getElementById('input-playback');
var input_loop = document.getElementById('input-loop');
var progress_bar_container = document.getElementById('progress-bar');
var progress_bar_in_buffer = document.getElementById('in-buffer');
var progress_bar_completed = document.getElementById('completed');
var progress_text = document.getElementById('progress-text');
var title_text = document.getElementById('title-text');
if(_GET.title){
  title_text.innerHTML = decodeURI(_GET.title);
}
var controls = document.getElementById('controls');
var volume = document.getElementById('volume');
input_volume.value = player.volume * 100;

var is_playing = false;
var is_dragging = false;
var is_fullscreen = false;
var is_muted = false;
var is_settings_open = false;
var mouse_still = 0;

//* EVENTS *//

window.onresize = function(){
  resize();
};

window.onload = function(){
  resize();
};

player.onmouseenter = function(){
  controls.style.opacity = 100;
};

player.onmouseleave = function(){
  controls.style.opacity = 100;
};

player.onmousemove = function(){
  mouse_still = 0;
};

player.onended = function(){
  pause(true);
};

controls.onmouseenter = function(){
  controls.style.opacity = 100;
};

controls.onmouseleave = function(){
  controls.style.opacity = 100;
};

controls.onmousemove = function(){
  mouse_still = 0;
};

btn_play_pause.onclick = function(){
  togglePlayPause();
};

btn_volume.onclick = function(){
  toggleMute();
};

btn_volume.onmouseenter = function(){
  volume.style.opacity = 100;
  volume.style.visibility = 'visible';
};

btn_volume.parentElement.onmouseleave = function(){
  volume.style.opacity = 0;
  volume.style.visibility = 'hidden';
};

btn_fullscreen.onclick = function(){
  fullscreenToggle();
};

btn_settings.onclick = function(){
  if(is_settings_open){
    settings.style.opacity = 0;
    settings.style.visibility = 'hidden';
  }else{
    settings.style.opacity = 100;
    settings.style.visibility = 'visible';
  }
  is_settings_open = !is_settings_open;
};

input_volume.oninput = function(){
  player.volume = input_volume.value;
  updateVolumeIcon();
};

input_loop.onchange = function(){
  player.loop = input_loop.value;
};

input_playback.onchange = function(){
  player.playbackRate = input_playback.value;
};

progress_bar_container.onclick = function(e){
  setTime(e.offsetX / progress_bar_container.offsetWidth);
};

progress_bar_container.onmousedown = function(){
  is_dragging = true;
};

progress_bar_container.onmouseup = function(){
  is_dragging = false;
};

progress_bar_container.onmousemove = function(e){
  if(is_dragging){
    setTime(e.offsetX / progress_bar_container.offsetWidth);
  }
};

setInterval(function(){
  updateTimeDisplay(player.currentTime, player.duration);
  mouse_still++;
}, 10);

//* END EVENTS */

//* FUNCTIONS *//

/**
 * Do resizing things that require javascript
 */
function resize(){
  player.width = window.innerWidth;
  player.height = window.innerHeight;

  if(player.width < 460){   //if the screen is small hide progress text element
    progress_text.style.display = 'none';
    //                                   width - button * 4 - margin
    progress_bar_container.style.width = player.width - 50 - 50 - 50 - 50 - 20 +'px';
  }else{
    progress_text.style.display = 'inline';
    progress_bar_container.style.width = player.width - 50 - 50 - 50 - 50 - progress_text.offsetWidth - 20 +'px';
  }
};

/**
 * Set the time to a location
 */
function setTime(percentage){
  player.currentTime = player.duration * percentage;
  updateTimeDisplay(player.currentTime, player.duration);
}

/**
 * Update the progress bar and time display
 */
function updateTimeDisplay(currentTime, duration){
  if(duration <= 0 || !duration){ //prevent running when not loaded
    return;
  }
  var ct_s = Math.floor(currentTime % 60);
  var ct_m = Math.floor(currentTime / 60);
  var d_s = Math.floor(duration % 60);
  var d_m = Math.floor(duration / 60);
  ct_s = ct_s < 10 ? '0' + ct_s : ct_s;
  ct_m = ct_m < 10 ? '0' + ct_m : ct_m;
  d_s = d_s < 10 ? '0' + d_s : d_s;
  d_m = d_m < 10 ? '0' + d_m : d_m;

  progress_text.innerHTML = ct_m + ":" + ct_s + " / " + d_m + ":" + d_s;
  progress_bar_completed.style.width = (currentTime / duration) * 100 + '%';
  progress_bar_in_buffer.style.width = (player.buffered.end(0) / duration) * 100 + '%';
};

/**
 * Toggle video playback
 */
function togglePlayPause(){
  if(is_playing){
    pause();
  }else{
    play();
  }
};

/**
 * Stop video playback
 */
function pause(ended){
  is_playing = false;
  btn_play_pause.innerHTML = '';
  player.pause();
};

/**
 * Start video playback
 */
function play(){
  is_playing = true;
  player.play();
  btn_play_pause.innerHTML = '';
};

/**
 * Toggle fullscreen for video
 */
function fullscreenToggle(){
  if(is_fullscreen){
    leaveFullscreen();
  }else{
    enterFullscreen();
  }
};

/**
 * Leave fullscreen
 */
function leaveFullscreen(){
  is_fullscreen = false;
  if (document.cancelFullScreen) {
    document.cancelFullScreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitCancelFullScreen) {
    document.webkitCancelFullScreen();
  }
};

/**
 * Enter fullscreen
 */
function enterFullscreen(){
  is_fullscreen = true;
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  } else {
    alertMessage('Fullscreen is not supported by your browser', 'error');
    is_fullscreen = false;
  }
}

/**
 * Toggle mute of video
 */
function toggleMute(){
  if(is_muted){
    unmute();
  }else{
    mute();
  }
};

/**
 * Mute sound
 */
function mute(){
  is_muted = true;
  player.muted = true;
  input_volume.value = 0;
  updateVolumeIcon();
};

/**
 * Unmute sound
 */
function unmute(){
  is_muted = false;
  player.muted = false;
  input_volume.value = player.volume;
  updateVolumeIcon();
};

/**
 * Update the volume icon based on volume of playback
 */
function updateVolumeIcon(){
  if(is_muted){
    btn_volume.innerHTML = '';
  }else if(player.volume > .6){
    btn_volume.innerHTML = '';
  }else if(player.volume <= .6 && player.volume != 0){
    btn_volume.innerHTML = '';
  }else{
    btn_volume.innerHTML = '';
  }
};

/**
 * Put a message on the screen
 * (For now just an ordinary alert)
 */
function alertMessage(msg, type){
  alert(msg);
};

//* END FUNCTIONS *//


text:
$(function() {
	//加载bootstrap
	Metronic.init(); // init metronic core componets
	Layout.init(); // init layout
	Tasks.initDashboardWidget(); // init tash dashboard widget
	ComponentsDropdowns.init();

	//$("#d11").click(WdatePicker());
     //$.fn.datepicker({language:'zh-CN'});

	 $(".date-picker").datepicker({
                autoclose: true,
                language:'zh-CN'
            });
});


text:
namespace PlatformRig { namespace Overlays
{
    static void DrawButton(IOverlayContext* context, const char name[], const Rect&buttonRect, Interactables&interactables, InterfaceState& interfaceState)
    {
        InteractableId id = InteractableId_Make(name);
        if (interfaceState.HasMouseOver(id)) {
            DrawElipse(context, buttonRect, ColorB(0xff000000u));
            DrawText(context, buttonRect, (interfaceState.IsMouseButtonHeld())?2.f:1.25f, nullptr, ColorB(0xff000000u), name);
        } else {
            DrawElipse(context, buttonRect, ColorB(0xffffffffu));
            DrawText(context, buttonRect, 1.25f, nullptr, ColorB(0xffffffffu), name);
        }
        interactables.Register(Interactables::Widget(buttonRect, id));
    }

    BufferUploadDisplay::GPUMetrics::GPUMetrics()
    {
        _slidingAverageCostMS = 0.f;
        _slidingAverageBytesPerSecond = 0;
    }

    BufferUploadDisplay::FrameRecord::FrameRecord()
    {
        _frameId = 0x0;
        _gpuCost = 0.f;
        _commandListStart = _commandListEnd = ~unsigned(0x0);
    }

    BufferUploadDisplay::BufferUploadDisplay(BufferUploads::IManager* manager)
    : _manager(manager)
    {
        _graphMinValueHistory = _graphMaxValueHistory = 0.f;
        XlZeroMemory(_accumulatedCreateCount);
        XlZeroMemory(_accumulatedCreateBytes);
        XlZeroMemory(_accumulatedUploadCount);
        XlZeroMemory(_accumulatedUploadBytes);
        _graphsMode = 0;
        _mostRecentGPUFrequency = 0;
        _lastUploadBeginTime = 0;
        _mostRecentGPUCost = 0.f;
        _mostRecentGPUFrameId = 0;
        _lockedFrameId = ~unsigned(0x0);
        _drawHistory = false;

        #if defined(WIN32) || defined(WIN64)
            int64 timerFrequency;
            QueryPerformanceFrequency((LARGE_INTEGER*)&timerFrequency);
            _reciprocalTimerFrequency = 1./double(timerFrequency);
        #endif

        assert(s_gpuListenerDisplay==0);
        s_gpuListenerDisplay = this;
    }

    BufferUploadDisplay::~BufferUploadDisplay()
    {
        assert(s_gpuListenerDisplay==this);
        s_gpuListenerDisplay = NULL;
    }

    static const char* AsString(BufferUploads::UploadDataType::Enum value)
    {
        using namespace BufferUploads::UploadDataType;
        switch (value) {
        case Texture:   return "Texture";
        case Vertex:    return "Vertex";
        case Index:     return "Index";
        default: return "<<unknown>>";
        }
    };

    static std::string BuildDescription(const BufferUploads::BufferDesc& desc)
    {
        using namespace BufferUploads;
        char buffer[2048];
        if (desc._type == BufferDesc::Type::Texture) {
            const TextureDesc& tDesc = desc._textureDesc;
            xl_snprintf(buffer, dimof(buffer), "[%s] Tex(%s) (%4ix%4i) mips:(%i)",
                desc._name, (tDesc._dimensionality==TextureDesc::Dimensionality::T2D)?"  2D":"Cube",
                tDesc._width, tDesc._height, tDesc._mipCount);
        } else if (desc._type == BufferDesc::Type::LinearBuffer) {
            if (desc._bindFlags & BindFlag::VertexBuffer) {
                xl_snprintf(buffer, dimof(buffer), "[%s] VB (%6.2fkb)",
                    desc._name, desc._linearBufferDesc._sizeInBytes/1024.f);
            } else if (desc._bindFlags & BindFlag::IndexBuffer) {
                xl_snprintf(buffer, dimof(buffer), "[%s] IB (%6.2fkb)",
                    desc._name, desc._linearBufferDesc._sizeInBytes/1024.f);
            }
        } else {
            xl_snprintf(buffer, dimof(buffer), "Unknown");
        }
        return std::string(buffer);
    }

    namespace GraphTabs
    {
        enum Enum
        {
            Uploads, CreatesMB, CreatesCount, DeviceCreatesCount, Latency, PendingBuffers, CommandListCount, GPUCost, GPUBytesPerSecond, AveGPUCost, ThreadActivity, BatchedCopy, FramePriorityStall
        };
        static const char* Names[] = {
            "Uploads (MB)", "Creates (MB)", "Creates (count)", "Device creates (count)", "Latency (ms)", "Pending Buffers (MB)", "Command List Count", "GPU Cost", "GPU bytes/second", "Ave GPU cost", "Thread Activity", "Batched copy", "Frame Priority Stalls"
        };
    }

    static const unsigned s_MaxGraphSegments = 256;

    void    BufferUploadDisplay::Render(IOverlayContext* context, Layout& layout, Interactables& interactables, InterfaceState& interfaceState)
    {
        using namespace BufferUploads;
        CommandListMetrics mostRecentResults;
        unsigned commandListCount = 0;

            //      Keep popping metrics from the upload manager until we stop getting valid ones
        BufferUploads::IManager* manager = _manager;
        if (manager) {
            for (;;) {
                CommandListMetrics metrics = manager->PopMetrics();
                if (!metrics._commitTime) {
                    break;
                }
                mostRecentResults = metrics;
                _recentHistory.push_back(metrics);
                AddCommandListToFrame(metrics._frameId, unsigned(_recentHistory.size()-1));
                for (unsigned c=0; c<BufferUploads::UploadDataType::Max; ++c) {
                    _accumulatedCreateCount[c] += metrics._countCreations[c];
                    _accumulatedCreateBytes[c] += metrics._bytesCreated[c];
                    _accumulatedUploadCount[c] += metrics._countUploaded[c];
                    _accumulatedUploadBytes[c] += metrics._bytesUploaded[c] + metrics._bytesUploadedDuringCreation[c];
                }
                ++commandListCount;
            }
        }

        if (!mostRecentResults._commitTime && _recentHistory.size()) {
            mostRecentResults = _recentHistory[_recentHistory.size()-1];
        }

        {
            ScopedLock(_gpuEventsBufferLock);
            ProcessGPUEvents_MT(AsPointer(_gpuEventsBuffer.begin()), AsPointer(_gpuEventsBuffer.end()));
            _gpuEventsBuffer.erase(_gpuEventsBuffer.begin(), _gpuEventsBuffer.end());
        }

            //      Present these frame by frame results visually.
            //      But also show information about the recent history (retired textures, etc)
        Rect topThird    = layout.AllocateFullWidthFraction(.25f+(_drawHistory?0.f:.4f));
        Rect buttons     = layout.AllocateFullWidthFraction(.05f);
        Rect middleThird = layout.AllocateFullWidthFraction(.2f);
        Rect bottomThird = layout.AllocateFullWidthFraction(.1f+(_drawHistory?.4f:.0f));

            //      Top part is a few graphs of the bytes uploaded/frame (or other statistics)
        {
            Layout topArea(topThird);
            unsigned graphCount = (_graphsMode<=GraphTabs::PendingBuffers)?UploadDataType::Max:1;
            for (unsigned c=0; c<graphCount; ++c) {
                Rect graphArea = topArea.AllocateFullHeightFraction(1.f/float(graphCount));
                DrawRoundedRectangle(context, graphArea);

                //  Copy the recent history into an array of floats, so we can graph the results...
                float valuesBuffer[s_MaxGraphSegments];
                size_t valuesCount = 0;
                for (std::deque<FrameRecord>::const_reverse_iterator i =_frames.rbegin(); i!=_frames.rend(); ++i) {
                    if (valuesCount>=dimof(valuesBuffer)) {
                        break;
                    }
                    ++valuesCount;
                    using namespace GraphTabs;
                    float& value = valuesBuffer[dimof(valuesBuffer)-valuesCount];
                    value = 0.f;
                    if (graphCount == UploadDataType::Max) {
                        if (_graphsMode == Latency) { // latency (ms)
                            TimeMarker transactionLatencySum = 0;
                            unsigned transactionLatencyCount = 0;
                            for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) {
                                BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                                for (unsigned i2=0; i2<commandList.RetirementCount(); ++i2) {
                                    const AssemblyLineRetirement& retirement = commandList.Retirement(i2);
                                    transactionLatencySum += retirement._retirementTime - retirement._requestTime;
                                    ++transactionLatencyCount;
                                }
                            }

                            float averageTransactionLatency = transactionLatencyCount?float(double(transactionLatencySum/TimeMarker(transactionLatencyCount)) * _reciprocalTimerFrequency):0.f;
                            value = averageTransactionLatency;
                        } else if (_graphsMode == PendingBuffers) { // pending buffers
                            if (i->_commandListStart!=i->_commandListEnd) {
                                value = _recentHistory[i->_commandListEnd-1]._assemblyLineMetrics._queuedBytes[c] / (1024.f*1024.f);
                            }
                        } else {
                            for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) {
                                BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                                if (_graphsMode == Uploads) { // bytes uploaded
                                    value += (commandList._bytesUploaded[c] + commandList._bytesUploadedDuringCreation[c]) / (1024.f*1024.f);
                                } else if (_graphsMode == CreatesMB) { // creations (bytes)
                                    value += commandList._bytesCreated[c] / (1024.f*1024.f);
                                } else if (_graphsMode == CreatesCount) { // creations (count)
                                    value += commandList._countCreations[c];
                                } else if (_graphsMode == DeviceCreatesCount) {
                                    value += commandList._countDeviceCreations[c];
                                } else if (_graphsMode == FramePriorityStall) {
                                    value += float(commandList._framePriorityStallTime * _reciprocalTimerFrequency * 1000.f);
                                }
                            }
                        }
                    } else {
                        if (_graphsMode == CommandListCount) {
                            value = float(i->_commandListEnd-i->_commandListStart);
                        } else if (_graphsMode == GPUCost) {
                            value = i->_gpuCost;
                        } else if (_graphsMode == GPUBytesPerSecond) {
                            value = i->_gpuMetrics._slidingAverageBytesPerSecond / (1024.f * 1024.f);
                        } else if (_graphsMode == AveGPUCost) {
                            value = i->_gpuMetrics._slidingAverageCostMS;
                        } else if (_graphsMode == ThreadActivity) {
                            TimeMarker processingTimeSum = 0, waitTimeSum = 0;
                            for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) {
                                BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                                processingTimeSum += commandList._processingEnd - commandList._processingStart;
                                waitTimeSum += commandList._waitTime;
                            }
                            value = (float(processingTimeSum))?(100.f * (1.0f-(waitTimeSum/float(processingTimeSum)))):0.f;
                        } else if (_graphsMode == BatchedCopy) {
                            value = 0;
                            for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) {
                                BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                                value += commandList._batchedCopyBytes;
                            }
                        }
                    }
                }

                Rect sectionNameRect(
                    Coord2(graphArea._topLeft[0], graphArea._topLeft[1]),
                    Coord2(graphArea._bottomRight[0], LinearInterpolate(graphArea._topLeft[1], graphArea._bottomRight[1], 0.2f)) );
                if (graphCount == UploadDataType::Max) {
                    DrawFormatText(
                        context, sectionNameRect, 2.5f, nullptr, ColorB(0xffffffffu), "%s (%s)",
                        AsString(UploadDataType::Enum(c)), GraphTabs::Names[_graphsMode]);
                } else {
                    DrawText(context, sectionNameRect, 2.5f, nullptr, ColorB(0xffffffffu), GraphTabs::Names[_graphsMode]);
                }

				if (valuesCount > 0) {
					float mostRecentValue = valuesBuffer[dimof(valuesBuffer) - valuesCount];
					Rect valueRect(
						Coord2(graphArea._topLeft[0], graphArea._topLeft[1]),
						Coord2(sectionNameRect._bottomRight[0], LinearInterpolate(graphArea._topLeft[1], graphArea._bottomRight[1], 0.4f)));
					DrawFormatText(context, valueRect, 2.f, nullptr, ColorB(0xffffffffu), "%6.3f", mostRecentValue);
				}

                Rect realGraphRect(
                    Coord2(graphArea._topLeft[0], LinearInterpolate(graphArea._topLeft[1], graphArea._bottomRight[1], 0.333f)),
                    Coord2(graphArea._bottomRight[0], graphArea._bottomRight[1]) );

                DrawHistoryGraph(   context, realGraphRect, &valuesBuffer[dimof(valuesBuffer)-valuesCount], (unsigned)valuesCount, (unsigned)dimof(valuesBuffer),
                                    _graphMinValueHistory, _graphMaxValueHistory);

                if (_graphsMode == GraphTabs::GPUCost) {
                        // GPU cost graph should also have the total bytes uploaded draw in
                    size_t valuesCount = 0;
                    for (std::deque<FrameRecord>::const_reverse_iterator i =_frames.rbegin(); i!=_frames.rend(); ++i) {
                        if (valuesCount>=dimof(valuesBuffer)) {
                            break;
                        }
                        ++valuesCount;
                        valuesBuffer[dimof(valuesBuffer)-valuesCount] = 0;
                        for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) {
                            BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                            for (unsigned c2=0; c2<UploadDataType::Max; ++c2) {
                                valuesBuffer[dimof(valuesBuffer)-valuesCount] += (commandList._bytesUploaded[c2] + commandList._bytesUploadedDuringCreation[c2]) / (1024.f*1024.f);
                            }
                        }
                    }

                    DrawHistoryGraph_ExtraLine( context, realGraphRect, &valuesBuffer[dimof(valuesBuffer)-valuesCount], (unsigned)valuesCount, (unsigned)dimof(valuesBuffer),
                                                _graphMinValueHistory, _graphMaxValueHistory);
                }

                {
                    const InteractableId framePicker = InteractableId_Make("FramePicker");
                    size_t newValuesCount = 0;
                    for (std::deque<FrameRecord>::const_reverse_iterator i =_frames.rbegin(); i!=_frames.rend(); ++i) {
                        if (newValuesCount>=dimof(valuesBuffer)) {
                            break;
                        }
                        int graphPartIndex = int(dimof(valuesBuffer)-newValuesCount-1);
                        Rect graphPart( Coord2(LinearInterpolate(graphArea._topLeft[0], graphArea._bottomRight[0], (graphPartIndex)/float(dimof(valuesBuffer))), graphArea._topLeft[1]),
                                        Coord2(LinearInterpolate(graphArea._topLeft[0], graphArea._bottomRight[0], (graphPartIndex+1)/float(dimof(valuesBuffer))), graphArea._bottomRight[1]));
                        InteractableId id = framePicker + newValuesCount;
                        if (interfaceState.HasMouseOver(id)) {
                            DrawRectangle(context, graphPart, ColorB(0x3f7f7f7fu));
                        } else if (i->_frameId == _lockedFrameId) {
                            DrawRectangle(context, graphPart, ColorB(0x3f7f3f7fu));
                        }
                        interactables.Register(Interactables::Widget(graphPart, id));
                        ++newValuesCount;
                    }
                }
            }
        }

            //      a few buttons in the middle to control the data in the graphs
        {
            Layout buttonsArea(buttons);
            for (unsigned c=0; c<dimof(GraphTabs::Names); ++c) {
                Rect buttonRect = buttonsArea.AllocateFullHeightFraction( 1.f/float(dimof(GraphTabs::Names)) );
                DrawButton(context, GraphTabs::Names[c], buttonRect, interactables, interfaceState);
            }
        }

        const Coord rowHeight    = 6;
        const Coord rowHeight2   = 12;

            //      Middle part is some written statics
        {
            Layout middleArea(middleThird);
            Layout columnZero(middleArea.AllocateFullHeightFraction(.333f));
            Layout columnOne (middleArea.AllocateFullHeightFraction(.333f));
            Layout columnTwo (middleArea.AllocateFullHeightFraction(.333f));

            GPUMetrics gpuMetrics = CalculateGPUMetrics();

                //////
            TimeMarker transactionLatencySum = 0;
            unsigned transactionLatencyCount = 0;
            TimeMarker commandListLatencySum = 0;
            unsigned commandListLatencyCount = 0;
            for (   std::deque<CommandListMetrics>::const_reverse_iterator i =_recentHistory.rbegin();i!=_recentHistory.rend(); ++i) {
                for (unsigned i2=0; i2<i->RetirementCount(); ++i2) {
                    const AssemblyLineRetirement& retire = i->Retirement(i2);
                    transactionLatencySum += retire._retirementTime - retire._requestTime;
                    ++transactionLatencyCount;
                }
                commandListLatencySum += i->_commitTime - i->_resolveTime;
                ++commandListLatencyCount;
            }

            TimeMarker processingTimeSum = 0, waitTimeSum = 0;
            unsigned wakeCountSum = 0;

            size_t validFrameIndex = _frames.size()-1;
            for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i, --validFrameIndex) {
                if (i->_gpuCost != 0.f && i->_commandListStart != i->_commandListEnd) {
                    break;
                }
            }
            if (validFrameIndex < _frames.size()) {
                for (unsigned cl=_frames[validFrameIndex]._commandListStart; cl<_frames[validFrameIndex]._commandListEnd; ++cl) {
                    BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                    processingTimeSum += commandList._processingEnd - commandList._processingStart;
                    waitTimeSum += commandList._waitTime;
                    wakeCountSum += commandList._wakeCount;
                }
            }

            float averageTransactionLatency = transactionLatencyCount?float(double(transactionLatencySum/TimeMarker(transactionLatencyCount)) * _reciprocalTimerFrequency):0.f;
            float averageCommandListLatency = commandListLatencyCount?float(double(commandListLatencySum/TimeMarker(commandListLatencyCount)) * _reciprocalTimerFrequency):0.f;

            DrawFormatText(context, columnZero.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Ave latency: (%6.2f)ms", averageTransactionLatency * 1000.f);
            DrawFormatText(context, columnZero.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Creates: T(%i)V(%i)I(%i)",
                mostRecentResults._countCreations[UploadDataType::Texture], mostRecentResults._countCreations[UploadDataType::Vertex], mostRecentResults._countCreations[UploadDataType::Index]);
            DrawFormatText(context, columnZero.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Command list latency: (%6.2f)ms", averageCommandListLatency * 1000.f);
            DrawFormatText(context, columnZero.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "GPU theoretical MB/second: (%6.2f)MB", gpuMetrics._slidingAverageBytesPerSecond/float(1024.f*1024.f));
            DrawFormatText(context, columnZero.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "GPU ave cost: (%6.2f)ms", gpuMetrics._slidingAverageCostMS);

                //////
            DrawFormatText(context, columnOne.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "AccumulatedValues");
            DrawFormatText(context, columnOne.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Creates: (T%i) (V%i) (I%i)",
                _accumulatedCreateCount[UploadDataType::Texture], _accumulatedCreateCount[UploadDataType::Vertex], _accumulatedCreateCount[UploadDataType::Index]);
            DrawFormatText(context, columnOne.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Creates (MB): (T%8.3f) (V%8.3f) (I%8.3f)",
                _accumulatedCreateBytes[UploadDataType::Texture] / (1024.f*1024.f), _accumulatedCreateBytes[UploadDataType::Vertex] / (1024.f*1024.f), _accumulatedCreateBytes[UploadDataType::Index] / (1024.f*1024.f));
            DrawFormatText(context, columnOne.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Uploads: (T%i) (V%i) (I%i)",
                _accumulatedUploadCount[UploadDataType::Texture], _accumulatedUploadCount[UploadDataType::Vertex], _accumulatedUploadCount[UploadDataType::Index]);
            DrawFormatText(context, columnOne.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Uploads (MB): (T%8.3f) (V%8.3f) (I%8.3f)",
                _accumulatedUploadBytes[UploadDataType::Texture] / (1024.f*1024.f), _accumulatedUploadBytes[UploadDataType::Vertex] / (1024.f*1024.f), _accumulatedUploadBytes[UploadDataType::Index] / (1024.f*1024.f));
            DrawFormatText(context, columnOne.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Thread activity (%6.3f)%% (%i)",
                (float(processingTimeSum))?(100.f * (1.0f-(waitTimeSum/float(processingTimeSum)))):0.f, wakeCountSum);

                //////
            DrawFormatText(context, columnTwo.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Pending creates: (%i/%i)", mostRecentResults._assemblyLineMetrics._queuedCreates, mostRecentResults._assemblyLineMetrics._queuedPeakCreates);
            DrawFormatText(context, columnTwo.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Pending uploads: (%i/%i)", mostRecentResults._assemblyLineMetrics._queuedUploads, mostRecentResults._assemblyLineMetrics._queuedPeakUploads);
            DrawFormatText(context, columnTwo.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Pending staging creates: (%i/%i)", mostRecentResults._assemblyLineMetrics._queuedStagingCreates, mostRecentResults._assemblyLineMetrics._queuedPeakStagingCreates);
            DrawFormatText(context, columnTwo.AllocateFullWidth(rowHeight2), 2.f, nullptr, ColorB(0xffffffffu), "Transaction count: (%i/%i/%i)", mostRecentResults._assemblyLineMetrics._transactionCount, mostRecentResults._assemblyLineMetrics._temporaryTransactionsAllocated, mostRecentResults._assemblyLineMetrics._longTermTransactionsAllocated);
        }

            //      Bottom part is a list of recent retirements
        {
            Layout bottomArea(bottomThird);
            Layout columns[4] = {
                Layout(bottomArea.AllocateFullHeightFraction(1.0f/float(dimof(columns)))),
                Layout(bottomArea.AllocateFullHeightFraction(1.0f/float(dimof(columns)))),
                Layout(bottomArea.AllocateFullHeightFraction(1.0f/float(dimof(columns)))),
                Layout(bottomArea.AllocateFullHeightFraction(1.0f/float(dimof(columns))))
            };
            for (unsigned c=0; c<dimof(columns); ++c) {
                DrawRoundedRectangle(context, columns[c].GetMaximumSize());
            }
            {
                Rect buttonRect = columns[0].AllocateFullWidth(rowHeight);
                InteractableId id = InteractableId_Make("ShowUploadHistory");
                DrawText(context, buttonRect, 1.25f, nullptr, interfaceState.HasMouseOver(id)?ColorB(0xff000000u):ColorB(0xffffffffu), _drawHistory?"Hide":"Show");
                interactables.Register(Interactables::Widget(buttonRect, id));
            }
            if (_drawHistory) {
                unsigned columnIndex = 0;
                unsigned frameCounter = 0;
                for (std::deque<FrameRecord>::const_reverse_iterator i=_frames.rbegin(); (i!=_frames.rend())&&(columnIndex<dimof(columns)); ++i, ++frameCounter) {
                    if (_lockedFrameId != ~unsigned(0x0) && i->_frameId != _lockedFrameId) {
                        continue;
                    }
                    for (unsigned cl=i->_commandListEnd-1; (cl>=i->_commandListStart)&&(columnIndex<dimof(columns)); --cl) {
                        const BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                        for (unsigned i2=0; i2<commandList.RetirementCount(); ++i2) {
                            Rect rect = columns[columnIndex].AllocateFullWidth(rowHeight);
                            if (!(IsGood(rect) && rect._bottomRight[1] < bottomThird._bottomRight[1] && rect._topLeft[1] >= bottomThird._topLeft[1])) {
                                ++columnIndex;
                                if (columnIndex >= dimof(columns)) {
                                    break;
                                }
                                rect = columns[columnIndex].AllocateFullWidth(rowHeight);
                            }

                            const AssemblyLineRetirement& retire = commandList.Retirement(i2);
                            DrawFormatText(context, rect, 1.f, nullptr, (frameCounter&0x1)?ColorB(0xff7f7fffu):ColorB(0xffffffffu), "%s Latency:%6.2f",
                                BuildDescription(retire._desc).c_str(), float(double(retire._retirementTime-retire._requestTime)*_reciprocalTimerFrequency*1000.));
                        }
                    }
                }
            }
        }
    }

    bool    BufferUploadDisplay::ProcessInput(InterfaceState& interfaceState, const InputSnapshot& input)
    {
        if (interfaceState.TopMostId()) {
            if (input.IsRelease_LButton()) {
                InteractableId topMostWidget = interfaceState.TopMostId();
                for (unsigned c=0; c<dimof(GraphTabs::Names); ++c) {
                    if (topMostWidget == InteractableId_Make(GraphTabs::Names[c])) {
                        _graphsMode = c;
                        return true;
                    }
                }

                if (topMostWidget == InteractableId_Make("ShowUploadHistory")) {
                    _drawHistory = !_drawHistory;
                    return true;
                }

                const InteractableId framePicker = InteractableId_Make("FramePicker");
                if (topMostWidget >= framePicker && topMostWidget < (framePicker+s_MaxGraphSegments)) {
                    unsigned graphIndex = unsigned(topMostWidget - framePicker);
                    _lockedFrameId = _frames[std::max(0,signed(_frames.size())-signed(graphIndex)-1)]._frameId;
                    return true;
                }

                return false;
            }
        }
        return false;
    }

    void    BufferUploadDisplay::AddCommandListToFrame(unsigned frameId, unsigned commandListIndex)
    {
        for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i) {
            if (i->_frameId == frameId) {
                if (i->_commandListStart == ~unsigned(0x0)) {
                    i->_commandListStart = commandListIndex;
                    i->_commandListEnd = commandListIndex+1;
                } else {
                    assert(commandListIndex == i->_commandListEnd || commandListIndex == (i->_commandListEnd-1));
                    i->_commandListEnd = std::max(i->_commandListEnd, commandListIndex+1);
                }
                i->_gpuMetrics = CalculateGPUMetrics();
                return;
            } else if (i->_frameId < frameId) {
                    //      We went too far and didn't find this frame... We'll have to insert it in as a new frame.
                FrameRecord newFrame;
                newFrame._frameId = frameId;
                newFrame._commandListStart = commandListIndex;
                newFrame._commandListEnd = commandListIndex+1;
                std::deque<FrameRecord>::iterator newItem = _frames.insert(i.base(),newFrame);
                newItem->_gpuMetrics = CalculateGPUMetrics();
                return;
            }
        }

        FrameRecord newFrame;
        newFrame._frameId = frameId;
        newFrame._commandListStart = commandListIndex;
        newFrame._commandListEnd = commandListIndex+1;
        _frames.push_back(newFrame);
        _frames[_frames.size()-1]._gpuMetrics = CalculateGPUMetrics();
    }

    void    BufferUploadDisplay::AddGPUToCostToFrame(unsigned frameId, float gpuCost)
    {
        for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i) {
            if (i->_frameId == frameId) {
                i->_gpuCost += gpuCost;
                i->_gpuMetrics = CalculateGPUMetrics();
                return;
            } else if (i->_frameId < frameId) {
                // we went too far and didn't find this frame... We'll have to insert it in as a new frame.
                FrameRecord newFrame;
                newFrame._frameId = frameId;
                newFrame._gpuCost = gpuCost;
                std::deque<FrameRecord>::iterator newItem = _frames.insert(i.base(),newFrame);
                newItem->_gpuMetrics = CalculateGPUMetrics();
                return;
            }
        }

        FrameRecord newFrame;
        newFrame._frameId = frameId;
        newFrame._gpuCost = gpuCost;
        _frames.push_back(newFrame);
        _frames[_frames.size()-1]._gpuMetrics = CalculateGPUMetrics();
    }

    BufferUploadDisplay::GPUMetrics   BufferUploadDisplay::CalculateGPUMetrics()
    {
                //////
                //      calculate the GPU upload speed... How much GPU time should we expect to consume per mb uploaded,
                //      based on a sliding average
        BufferUploadDisplay::GPUMetrics result;
        result._slidingAverageBytesPerSecond = 0;
        result._slidingAverageCostMS = 0.f;

        unsigned framesCountWithValidGPUCost = (unsigned)_frames.size();
        for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i, --framesCountWithValidGPUCost) {
            if (i->_gpuCost != 0.f && i->_commandListStart != i->_commandListEnd) {
                break;
            }
        }

        const unsigned samples = std::min(unsigned(framesCountWithValidGPUCost), 256u);
        std::deque<FrameRecord>::const_iterator gI = _frames.begin() + (_frames.size()-samples);
        float totalGPUCost = 0.f; unsigned totalBytesUploaded = 0;
        for (unsigned c=0; c<samples; ++c, ++gI) {
            float gpuCost = gI->_gpuCost; unsigned bytesUploaded = 0;
            for (unsigned cl=gI->_commandListStart; cl<gI->_commandListEnd; ++cl) {
                BufferUploads::CommandListMetrics& commandList = _recentHistory[cl];
                for (unsigned c2=0; c2<BufferUploads::UploadDataType::Max; ++c2) {
                    bytesUploaded += commandList._bytesUploaded[c2] + commandList._bytesUploadedDuringCreation[c2];
                }
            }
            totalGPUCost += gpuCost;
            totalBytesUploaded += bytesUploaded;
        }
        if (totalGPUCost) {
            result._slidingAverageBytesPerSecond = unsigned(totalBytesUploaded / (totalGPUCost/1000.f));
        }
        if (samples) {
            result._slidingAverageCostMS = totalGPUCost / float(samples);
        }
        return result;
    }

    void    BufferUploadDisplay::ProcessGPUEvents(const void* eventsBufferStart, const void* eventsBufferEnd)
    {
        ScopedLock(_gpuEventsBufferLock);
        size_t oldSize = _gpuEventsBuffer.size();
        size_t eventsBufferSize = ptrdiff_t(eventsBufferEnd) - ptrdiff_t(eventsBufferStart);
        _gpuEventsBuffer.resize(_gpuEventsBuffer.size() + eventsBufferSize);
        memcpy(&_gpuEventsBuffer[oldSize], eventsBufferStart, eventsBufferSize);
    }

    void    BufferUploadDisplay::ProcessGPUEvents_MT(const void* eventsBufferStart, const void* eventsBufferEnd)
    {
        const void * evnt = eventsBufferStart;
        while (evnt < eventsBufferEnd) {
            uint32 eventType = (uint32)*((const size_t*)evnt); evnt = PtrAdd(evnt, sizeof(size_t));
            if (eventType == ~uint32(0x0)) {
                size_t frameId = *((const size_t*)evnt); evnt = PtrAdd(evnt, sizeof(size_t));
                GPUTime frequency = *((const uint64*)evnt); evnt = PtrAdd(evnt, sizeof(uint64));
                _mostRecentGPUFrequency = frequency;
                _mostRecentGPUFrameId = (unsigned)frameId;
            } else {
                const char* eventName = *((const char**)evnt); evnt = PtrAdd(evnt, sizeof(const char*));
                assert((size_t(evnt)%sizeof(uint64))==0);
                uint64 timeValue = *((const uint64*)evnt); evnt = PtrAdd(evnt, sizeof(uint64));

                if (eventName && !XlCompareStringI(eventName, "GPU_UPLOAD")) {
                    if (eventType == 0) {
                        _lastUploadBeginTime = timeValue;
                    } else {
                        if (_lastUploadBeginTime) {
                            _mostRecentGPUCost = float(double(timeValue - _lastUploadBeginTime) / double(_mostRecentGPUFrequency) * 1000.);

                                //      write this result into the GPU time for any frames that need it...
                            AddGPUToCostToFrame(_mostRecentGPUFrameId, _mostRecentGPUCost);
                        }
                    }
                }
            }
        }
    }

    BufferUploadDisplay* BufferUploadDisplay::s_gpuListenerDisplay = 0;
    void BufferUploadDisplay::GPUEventListener(const void* eventsBufferStart, const void* eventsBufferEnd)
    {
        if (s_gpuListenerDisplay) {
            s_gpuListenerDisplay->ProcessGPUEvents(eventsBufferStart, eventsBufferEnd);
        }
    }

        ////////////////////////////////////////////////////////////////////

    ResourcePoolDisplay::ResourcePoolDisplay(BufferUploads::IManager* manager)
    {
        _manager = manager;
        _filter = 0;
        _detailsIndex = 0;
        _graphMin = _graphMax = 0.f;
    }

    ResourcePoolDisplay::~ResourcePoolDisplay()
    {
    }

    namespace ResourcePoolDisplayTabs
    {
        static const char* Names[] = { "Index Buffers", "Vertex Buffers", "Staging Textures" };
    }

    bool    ResourcePoolDisplay::Filter(const BufferUploads::BufferDesc& desc)
    {
        if (_filter == 0 && (desc._bindFlags&BufferUploads::BindFlag::IndexBuffer)) return true;
        if (_filter == 1 && (desc._bindFlags&BufferUploads::BindFlag::VertexBuffer)) return true;
        if (_filter == 2 && (desc._type == BufferUploads::BufferDesc::Type::Texture)) return true;
        return false;
    }

    static const InteractableId ResourcePoolDisplayGraph = InteractableId_Make("ResourcePoolDisplayGraph");

    void    ResourcePoolDisplay::Render(IOverlayContext* context, Layout& layout, Interactables&interactables, InterfaceState& interfaceState)
    {
        using namespace BufferUploads;
        IManager* manager = _manager;
        if (manager) {
            PoolSystemMetrics metrics = manager->CalculatePoolMetrics();

                /////////////////////////////////////////////////////////////////////////////
            const std::vector<PoolMetrics>& metricsVector = (_filter==2)?metrics._stagingPools:metrics._resourcePools;
            unsigned maxSize = 0, count = 0;
            for (std::vector<PoolMetrics>::const_iterator i=metricsVector.begin();i!=metricsVector.end(); ++i) {
                if (Filter(i->_desc)) {
                    maxSize = std::max(maxSize, i->_peakSize);
                    ++count;
                }
            }

                /////////////////////////////////////////////////////////////////////////////
            layout.AllocateFullWidth(128);  // leave some space at the top
            Layout buttonsLayout(layout.AllocateFullWidth(32));
            for (unsigned c=0; c<dimof(ResourcePoolDisplayTabs::Names); ++c) {
                DrawButton(context, ResourcePoolDisplayTabs::Names[c], buttonsLayout.AllocateFullHeightFraction(1.f/float(dimof(ResourcePoolDisplayTabs::Names))), interactables, interfaceState);
            }

            if (count) {
                    /////////////////////////////////////////////////////////////////////////////
                Rect barChartRect = layout.AllocateFullWidth(400);
                Layout barsLayout(barChartRect);
                barsLayout._paddingBetweenAllocations = 4;
                const unsigned barWidth = (barChartRect.Width() - (count-1) * barsLayout._paddingBetweenAllocations - 2*barsLayout._paddingInternalBorder) / count;

                static ColorB rectColor(96, 192, 170, 128);
                static ColorB peakMarkerColor(192, 64, 64, 128);
                static ColorB textColour(192, 192, 192, 128);

                    /////////////////////////////////////////////////////////////////////////////
                unsigned c=0;
                const PoolMetrics* detailsMetrics = NULL;
                for (std::vector<PoolMetrics>::const_iterator i=metricsVector.begin(); i!=metricsVector.end(); ++i) {
                    if (Filter(i->_desc)) {
                        float A = i->_currentSize / float(maxSize);
                        float B = i->_peakSize / float(maxSize);
                        Rect fullRect = barsLayout.AllocateFullHeight(barWidth);
                        Rect colouredRect(Coord2(fullRect._topLeft[0], LinearInterpolate(fullRect._topLeft[1], fullRect._bottomRight[1], 1.f-A)), fullRect._bottomRight);
                        DrawRectangle(context, colouredRect, rectColor);
                        DrawRectangle(context, Rect(    Coord2(fullRect._topLeft[0], LinearInterpolate(fullRect._topLeft[1], fullRect._bottomRight[1], 1.f-B)),
                                                        Coord2(fullRect._bottomRight[0], LinearInterpolate(fullRect._topLeft[1], fullRect._bottomRight[1], 1.f-B)+2)), peakMarkerColor);

                        Rect textRect(colouredRect._topLeft, Coord2(colouredRect._bottomRight[0], colouredRect._topLeft[1]+10));
                        if (i->_peakSize) {
                            const BufferDesc& desc = i->_desc;
                            if (desc._type == BufferDesc::Type::LinearBuffer) {
                                if (desc._bindFlags & BindFlag::IndexBuffer) {
                                    DrawFormatText(context, textRect, 1.f, nullptr, textColour, "IB %6.2fk", desc._linearBufferDesc._sizeInBytes / 1024.f);
                                } else if (desc._bindFlags & BindFlag::VertexBuffer) {
                                    DrawFormatText(context, textRect, 1.f, nullptr, textColour, "VB %6.2fk", desc._linearBufferDesc._sizeInBytes / 1024.f);
                                } else {
                                    DrawFormatText(context, textRect, 1.f, nullptr, textColour, "B %6.2fk", desc._linearBufferDesc._sizeInBytes / 1024.f);
                                }
                            } else if (desc._type == BufferDesc::Type::Texture) {
                                DrawFormatText(context, textRect, 1.f, nullptr, textColour, "Tex %ix%i", desc._textureDesc._width, desc._textureDesc._height);
                            }
                            textRect._topLeft[1] += 16; textRect._bottomRight[1] += 16;
                            if (i->_currentSize) {
                                DrawFormatText(context, textRect, 1.f, nullptr, textColour, "%i (%6.3fMB)",
                                    i->_currentSize, (i->_currentSize * manager->ByteCount(i->_desc)) / (1024.f*1024.f));
                            }
                        }

                        InteractableId id = ResourcePoolDisplayGraph+c;
                        if (_detailsIndex==c) {
                            detailsMetrics = &(*i);
                        }
                        interactables.Register(Interactables::Widget(fullRect, id));
                        ++c;
                    }
                }

                if (detailsMetrics) {
                    _detailsHistory.push_back(*detailsMetrics);
                    Rect textRect = layout.AllocateFullWidth(32);
                    DrawFormatText(context, textRect, 2.f, nullptr, textColour, "Real size: %6.2fMB, Created size: %6.2fMB, Padding overhead: %6.2fMB, Count: %i",
                        detailsMetrics->_totalRealSize/(1024.f*1024.f), detailsMetrics->_totalCreateSize/(1024.f*1024.f), (detailsMetrics->_totalCreateSize-detailsMetrics->_totalRealSize)/(1024.f*1024.f),
                        detailsMetrics->_totalCreateCount);

                    Rect historyRect = layout.AllocateFullWidth(200);
                    float historyValues[256];
                    unsigned historyCount = 0;
                    for (std::vector<PoolMetrics>::const_reverse_iterator i=_detailsHistory.rbegin(); i!=_detailsHistory.rend() && historyCount < dimof(historyValues); ++i, ++historyCount) {
                        historyValues[historyCount] = float(i->_recentReleaseCount);
                    }
                    DrawHistoryGraph(context, historyRect, historyValues, historyCount, dimof(historyValues), _graphMin, _graphMax);
                }
            }
        }
    }

    bool    ResourcePoolDisplay::ProcessInput(InterfaceState& interfaceState, const InputSnapshot& input)
    {
        if (interfaceState.TopMostId()) {
            if (input.IsRelease_LButton()) {
                InteractableId topMostWidget = interfaceState.TopMostId();
                if (topMostWidget == InteractableId_Make(ResourcePoolDisplayTabs::Names[0])) {
                    _filter = 0;
                    return true;
                } else if (topMostWidget == InteractableId_Make(ResourcePoolDisplayTabs::Names[1])) {
                    _filter = 1;
                    return true;
                } else if (topMostWidget == InteractableId_Make(ResourcePoolDisplayTabs::Names[2])) {
                    _filter = 2;
                    return true;
                } else if (topMostWidget >= ResourcePoolDisplayGraph && topMostWidget < ResourcePoolDisplayGraph+100) {
                    _detailsIndex = unsigned(topMostWidget-ResourcePoolDisplayGraph);
                    _detailsHistory.clear();
                    return true;
                }
            }
        }
        return false;
    }

        ////////////////////////////////////////////////////////////////////

    static const unsigned FramesOfWarmth = 60;

    void    BatchingDisplay::Render(IOverlayContext* context, Layout& layout, Interactables&interactables, InterfaceState& interfaceState)
    {
        using namespace BufferUploads;
        IManager* manager = _manager;
        if (manager) {
            PoolSystemMetrics poolMetrics = manager->CalculatePoolMetrics();
            const BatchingSystemMetrics& metrics = poolMetrics._batchingSystemMetrics;

            layout.AllocateFullWidth(32);  // leave some space at the top
            static ColorB textColour(192, 192, 192, 128);
            static ColorB unallocatedLineColour(192, 192, 192, 128);

            unsigned allocatedSpace = 0, unallocatedSpace = 0;
            unsigned largestFreeBlock = 0;
            unsigned largestHeapSize = 0;
            unsigned totalBlockCount = 0;
            for (std::vector<BatchedHeapMetrics>::const_iterator i=metrics._heaps.begin(); i!=metrics._heaps.end(); ++i) {
                allocatedSpace += i->_allocatedSpace;
                unallocatedSpace += i->_unallocatedSpace;
                largestFreeBlock = std::max(largestFreeBlock, i->_largestFreeBlock);
                largestHeapSize = std::max(largestHeapSize, i->_heapSize);
                totalBlockCount += i->_referencedCountedBlockCount;
            }

            {
                DrawFormatText(context, layout.AllocateFullWidth(16), 1.5f, nullptr, textColour, "Heap count: %i / Total allocated: %7.3fMb / Total unallocated: %7.3fMb",
                    metrics._heaps.size(), allocatedSpace/(1024.f*1024.f), unallocatedSpace/(1024.f*1024.f));
                DrawFormatText(context, layout.AllocateFullWidth(16), 1.5f, nullptr, textColour, "Largest free block: %7.3fKb / Average unallocated: %7.3fKb",
                    largestFreeBlock/1024.f, unallocatedSpace/(float(metrics._heaps.size())*1024.f));
                DrawFormatText(context, layout.AllocateFullWidth(16), 1.5f, nullptr, textColour, "Block count: %i / Ave block size: %7.3fKb",
                    totalBlockCount, allocatedSpace/float(totalBlockCount*1024.f));
            }

            unsigned currentFrameId = GetFrameID();

            {
                const unsigned lineHeight = 4;
                Rect outsideRect = layout.AllocateFullWidth(DebuggingDisplay::Coord(metrics._heaps.size()*lineHeight + layout._paddingInternalBorder*2));
                Rect heapAllocationDisplay = Layout(outsideRect).AllocateFullWidthFraction(100.f);

                DrawRoundedRectangle(context, outsideRect);

                std::vector<Float3> lines;
                std::vector<ColorB> lineColors;
                lines.reserve(metrics._heaps.size()*lineHeight*2*10);
                lineColors.reserve(metrics._heaps.size()*lineHeight*10);

                float X = heapAllocationDisplay.Width() / float(largestHeapSize);
                unsigned y = heapAllocationDisplay._topLeft[1];

                for (std::vector<BatchedHeapMetrics>::const_iterator i=metrics._heaps.begin(); i!=metrics._heaps.end(); ++i) {
                    unsigned heapIndex = (unsigned)std::distance(metrics._heaps.begin(), i);

                    unsigned lastStart = 0;
                    const bool drawAllocated = true;
                    for (std::vector<unsigned>::const_iterator i2=i->_markers.begin(); (i2+1)<i->_markers.end(); i2+=2) {
                        unsigned start, end;
                        if (drawAllocated) {
                            start = lastStart;
                            end = *i2;
                        } else {
                            start = *i2;
                            end = *(i2+1);
                        }
                        if (start != end) {
                            float warmth = CalculateWarmth(heapIndex, start, end, drawAllocated);
                            ColorB col = ColorB::FromNormalized(warmth, 0.f, 1.0f-warmth);
                            for (unsigned c=0; c<lineHeight; ++c) {
                                const Coord x = Coord(start*X + heapAllocationDisplay._topLeft[0]);
                                lines.push_back(AsPixelCoords(Coord2(x, y+c)));
                                lines.push_back(AsPixelCoords(Coord2(std::max(x+1, Coord(end*X + heapAllocationDisplay._topLeft[0])), y+c)));
                                lineColors.push_back(col);
                                lineColors.push_back(col);
                            }
                        }
                        lastStart = *(i2+1);
                    }

                    y += lineHeight;
                }

                if (!lines.empty()) {
                    context->DrawLines(ProjectionMode::P2D, AsPointer(lines.begin()), (uint32)lines.size(), AsPointer(lineColors.begin()));
                }
            }

            _lastFrameMetrics = metrics;

                //      extinquish cooling spans
            for (std::vector<WarmSpan>::iterator i=_warmSpans.begin(); i!=_warmSpans.end();) {
                if (i->_frameStart <= (currentFrameId-FramesOfWarmth)) {
                    i = _warmSpans.erase(i);
                } else {
                    ++i;
                }
            }
        }
    }

    float BatchingDisplay::CalculateWarmth(unsigned heapIndex, unsigned begin, unsigned end, bool allocatedMode)
    {
        const unsigned currentFrameId = GetFrameID();
        for (std::vector<WarmSpan>::const_iterator i=_warmSpans.begin(); i!=_warmSpans.end(); ++i) {
            if (i->_heapIndex == heapIndex && i->_begin == begin && i->_end == end) {
                return 1.f-std::min((currentFrameId-i->_frameStart)/float(FramesOfWarmth), 1.f);
            }
        }

        const bool thereLastFrame = FindSpan(heapIndex, begin, end, allocatedMode);
        if (!thereLastFrame) {
            WarmSpan warmSpan;
            warmSpan._heapIndex = heapIndex;
            warmSpan._begin = begin;
            warmSpan._end = end;
            warmSpan._frameStart = currentFrameId;
            _warmSpans.push_back(warmSpan);
            return 1.f;
        }

        return 0.f;
    }

    bool BatchingDisplay::FindSpan(unsigned heapIndex, unsigned begin, unsigned end, bool allocatedMode)
    {
        if (heapIndex >= _lastFrameMetrics._heaps.size()) {
            return false;
        }

        unsigned lastStart = 0;
        for (std::vector<unsigned>::const_iterator i2=_lastFrameMetrics._heaps[heapIndex]._markers.begin(); (i2+1)<_lastFrameMetrics._heaps[heapIndex]._markers.end(); i2+=2) {
            unsigned spanBegin, spanEnd;
            if (allocatedMode) {
                spanBegin = lastStart;
                spanEnd = *i2;
            } else {
                spanBegin = *i2;
                spanEnd = *(i2+1);
            }
            if (begin == spanBegin && end == spanEnd) {
                return true;
            }
            lastStart = *(i2+1);
        }
        return false;
    }

    bool    BatchingDisplay::ProcessInput(InterfaceState& interfaceState, const InputSnapshot& input)
    {
        return false;
    }

    BatchingDisplay::BatchingDisplay(BufferUploads::IManager* manager)
    : _manager(manager)
    {
    }

    BatchingDisplay::~BatchingDisplay()
    {

    }
}}


text:
package com.aldebaran.helloandroid;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.aldebaran.qi.CallError;
import com.aldebaran.qi.EmbeddedTools;
import com.aldebaran.qi.Session;
import com.aldebaran.qi.helper.proxies.ALAudioDevice;
import com.aldebaran.qi.helper.proxies.ALMotion;
import com.aldebaran.qi.helper.proxies.ALRobotPosture;
import com.aldebaran.qi.helper.proxies.ALTextToSpeech;

import java.io.File;

public class MyActivity extends Activity {
	private static final String TAG = "MyActivity";
	private ALMotion alMotion;
	private ALTextToSpeech alSpeech;
	private Session session;
	private EditText ip;
	private Context context;
	private ALRobotPosture alPosture;
	private Thread routine;
	private ALAudioDevice alAudioDevice;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.main);
		ip = (EditText) findViewById(R.id.robot_ip_edit);

		EmbeddedTools ebt = new EmbeddedTools();
		File cacheDir = getApplicationContext().getCacheDir();
		Log.d(TAG, "Extracting libraries in " + cacheDir.getAbsolutePath());
		ebt.overrideTempDirectory(cacheDir);
		ebt.loadEmbeddedLibraries();
	}

	private void startServiceRoutine(final String ipAddress) {

		routine = new Thread(new Runnable() {
			@Override
			public void run() {
				Looper.prepare();
				session = new Session();
				session.onDisconnected("onDisconnected", this);
				try {
					Log.i(TAG, "Ip address : " + ipAddress);
					session.connect("tcp://" + ipAddress + ":9559").get();
					alMotion = new ALMotion(session);
					alSpeech = new ALTextToSpeech(session);
					alPosture = new ALRobotPosture(session);
					alAudioDevice = new ALAudioDevice(session);

					setButtonVisible(true);

				} catch (Exception e) {
					setButtonVisible(false);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(context, "The robot is unreachable", Toast.LENGTH_SHORT).show();
						}
					});
				}
			}

			public void onDisconnected(String message) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(context, "Connection lost", Toast.LENGTH_SHORT).show();
						setButtonVisible(false);
					}
				});
			}
		});
		routine.start();
	}

	private void setButtonVisible(final boolean isVisible) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				findViewById(R.id.command1).setVisibility(isVisible ? View.VISIBLE : View.GONE);
				findViewById(R.id.command2).setVisibility(isVisible ? View.VISIBLE : View.GONE);
				findViewById(R.id.command3).setVisibility(isVisible ? View.VISIBLE : View.GONE);
				if (isVisible) {
					((Button) findViewById(R.id.connectButton)).setText("Disconnect");
				} else {
					((Button) findViewById(R.id.connectButton)).setText("Connect");
				}
			}
		});
	}

	public void connect(View view) {
		Button button = (Button) view;
		if (button.getText().equals("Connect")) {
			if (ip.getText() != null
					&& !ip.getText().toString().equals("")) {

				String address = ip.getText().toString();
				startServiceRoutine(address);
			} else {
				Toast.makeText(context, "Please enter a robot ip or a robot name", Toast.LENGTH_SHORT).show();
			}
		} else {
			session.close();
		}
	}

	public void onHandController(View view) throws InterruptedException, CallError {
		Button button = (Button) view;
		if (button.getText().equals("Open Hand")) {
			alMotion.openHand("RHand");
			alMotion.openHand("LHand");
			button.setText("Close Hand");
		} else {
			alMotion.closeHand("RHand");
			alMotion.closeHand("LHand");
			button.setText("Open Hand");

		}
	}

	public void onRestController(View view) throws InterruptedException, CallError {
		Button button = (Button) view;
		if (button.getText().equals("Rest")) {
			alSpeech.say("Rest");
			alMotion.rest();
			button.setText("WakeUp");
		} else {
			alSpeech.say("Wake");
			alMotion.wakeUp();
			button.setText("Rest");
		}
	}

	public void onSitController(View view) throws InterruptedException, CallError {
		Button button = (Button) view;
		if (button.getText().equals("Sit")) {
			alPosture.goToPosture("Sit", 0.5f);
			button.setText("Stand");
		} else {
			alPosture.goToPosture("Stand", 0.5f);
			button.setText("Sit");
		}
	}

	private float velocityX = 0f;
	private float velocityY = 0f;

	public void onGoToFront(View view) throws InterruptedException, CallError {
		velocityX += 0.2f;
		alMotion.moveToward(velocityX, velocityY, 0f);
	}

	public void onStop(View view) throws InterruptedException, CallError {
		velocityX = 0f;
		velocityY = 0f;
		alMotion.moveToward(velocityX, velocityY, 0f);
	}

	public void onGoToLeft(View view) throws InterruptedException, CallError {
		velocityY += 0.2f;
		alMotion.moveToward(velocityX, velocityY, 0f);
	}

	public void onGoToRight(View view) throws InterruptedException, CallError {
		velocityY -= 0.2f;
		alMotion.moveToward(velocityX, velocityY, 0f);
	}

	public void onGoToBack(View view) throws InterruptedException, CallError {
		velocityX -= 0.2f;
		alMotion.moveToward(velocityX, velocityY, 0f);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		try {
			if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {

				Integer currentVolume = alAudioDevice.getOutputVolume();
				currentVolume -= 1;

				alAudioDevice.setOutputVolume(currentVolume >= 0 ? currentVolume : 0);

				return true;
			} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {

				Integer currentVolume = alAudioDevice.getOutputVolume();
				currentVolume += 1;

				alAudioDevice.setOutputVolume(currentVolume <= 100 ? currentVolume : 100);

				return true;
			}
		} catch (CallError callError) {
			callError.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}

	public void say(View view) throws InterruptedException, CallError {
		String text = ((EditText) findViewById(R.id.say_edit)).getText().toString();
		alSpeech.say(text);
	}

}


text:
import fileinput
import glob
import optparse
import os
import textwrap

def AggregateVectorIcons(working_directory, output_cc, output_h):
  """Compiles all .icon files in a directory into two C++ files.

  Args:
      working_directory: The path to the directory that holds the .icon files
          and C++ templates.
      output_cc: The path that should be used to write the .cc file.
      output_h: The path that should be used to write the .h file.
  """

  icon_list = glob.glob(working_directory + "*.icon")

  input_header_template = open(os.path.join(working_directory,
                                            "vector_icons.h.template"))
  header_template_contents = input_header_template.readlines()
  input_header_template.close()
  output_header = open(output_h, "w")
  for line in header_template_contents:
    if not "TEMPLATE_PLACEHOLDER" in line:
      output_header.write(line)
      continue

    for icon_path in icon_list:
      # The icon name should be of the format "foo.icon" or "foo.1x.icon".
      (icon_name, extension) = os.path.splitext(os.path.basename(icon_path))
      (icon_name, scale_factor) = os.path.splitext(icon_name)
      if not scale_factor:
        output_header.write("  {},\n".format(icon_name.upper()))
  output_header.close()

  input_cc_template = open(
      os.path.join(working_directory, "vector_icons.cc.template"))
  cc_template_contents = input_cc_template.readlines()
  input_cc_template.close()
  output_cc = open(output_cc, "w")
  for line in cc_template_contents:
    if not "TEMPLATE_PLACEHOLDER" in line:
      output_cc.write(line)
      continue;

    for icon_path in icon_list:
      (icon_name, extension) = os.path.splitext(os.path.basename(icon_path))
      (icon_name, scale_factor) = os.path.splitext(icon_name)
      assert not scale_factor or scale_factor == ".1x"
      if (("1X" in line and scale_factor != ".1x") or
          (not "1X" in line and scale_factor == ".1x")):
        continue

      icon_file = open(icon_path)
      vector_commands = "".join(icon_file.readlines())
      icon_file.close()
      output_cc.write("ICON_TEMPLATE({}, {})\n".format(icon_name.upper(),
                                                       vector_commands))
  output_cc.close()

def main():
  parser = optparse.OptionParser()
  parser.add_option("--working_directory",
                    help="The directory to look for template C++ as well as "
                         "icon files.")
  parser.add_option("--output_cc",
                    help="The path to output the CC file to.")
  parser.add_option("--output_h",
                    help="The path to output the header file to.")

  (options, args) = parser.parse_args()

  AggregateVectorIcons(options.working_directory,
                       options.output_cc,
                       options.output_h)

if __name__ == "__main__":
  main()


text:
import numpy as np

def check_arguments(fun, y0, support_complex):
    """Helper function for checking arguments common to all solvers."""
    y0 = np.asarray(y0)
    if np.issubdtype(y0.dtype, np.complexfloating):
        if not support_complex:
            raise ValueError("`y0` is complex, but the chosen solver does "
                             "not support integration in a complex domain.")
        dtype = complex
    else:
        dtype = float
    y0 = y0.astype(dtype, copy=False)

    if y0.ndim != 1:
        raise ValueError("`y0` must be 1-dimensional.")

    def fun_wrapped(t, y):
        return np.asarray(fun(t, y), dtype=dtype)

    return fun_wrapped, y0

class OdeSolver:
    """Base class for ODE solvers.

    In order to implement a new solver you need to follow the guidelines:

        1. A constructor must accept parameters presented in the base class
           (listed below) along with any other parameters specific to a solver.
        2. A constructor must accept arbitrary extraneous arguments
           ``**extraneous``, but warn that these arguments are irrelevant
           using `common.warn_extraneous` function. Do not pass these
           arguments to the base class.
        3. A solver must implement a private method `_step_impl(self)` which
           propagates a solver one step further. It must return tuple
           ``(success, message)``, where ``success`` is a boolean indicating
           whether a step was successful, and ``message`` is a string
           containing description of a failure if a step failed or None
           otherwise.
        4. A solver must implement a private method `_dense_output_impl(self)`,
           which returns a `DenseOutput` object covering the last successful
           step.
        5. A solver must have attributes listed below in Attributes section.
           Note that ``t_old`` and ``step_size`` are updated automatically.
        6. Use `fun(self, t, y)` method for the system rhs evaluation, this
           way the number of function evaluations (`nfev`) will be tracked
           automatically.
        7. For convenience, a base class provides `fun_single(self, t, y)` and
           `fun_vectorized(self, t, y)` for evaluating the rhs in
           non-vectorized and vectorized fashions respectively (regardless of
           how `fun` from the constructor is implemented). These calls don't
           increment `nfev`.
        8. If a solver uses a Jacobian matrix and LU decompositions, it should
           track the number of Jacobian evaluations (`njev`) and the number of
           LU decompositions (`nlu`).
        9. By convention, the function evaluations used to compute a finite
           difference approximation of the Jacobian should not be counted in
           `nfev`, thus use `fun_single(self, t, y)` or
           `fun_vectorized(self, t, y)` when computing a finite difference
           approximation of the Jacobian.

    Parameters
    ----------
    fun : callable
        Right-hand side of the system. The calling signature is ``fun(t, y)``.
        Here ``t`` is a scalar and there are two options for ndarray ``y``.
        It can either have shape (n,), then ``fun`` must return array_like with
        shape (n,). Or, alternatively, it can have shape (n, n_points), then
        ``fun`` must return array_like with shape (n, n_points) (each column
        corresponds to a single column in ``y``). The choice between the two
        options is determined by `vectorized` argument (see below).
    t0 : float
        Initial time.
    y0 : array_like, shape (n,)
        Initial state.
    t_bound : float
        Boundary time --- the integration won't continue beyond it. It also
        determines the direction of the integration.
    vectorized : bool
        Whether `fun` is implemented in a vectorized fashion.
    support_complex : bool, optional
        Whether integration in a complex domain should be supported.
        Generally determined by a derived solver class capabilities.
        Default is False.

    Attributes
    ----------
    n : int
        Number of equations.
    status : string
        Current status of the solver: 'running', 'finished' or 'failed'.
    t_bound : float
        Boundary time.
    direction : float
        Integration direction: +1 or -1.
    t : float
        Current time.
    y : ndarray
        Current state.
    t_old : float
        Previous time. None if no steps were made yet.
    step_size : float
        Size of the last successful step. None if no steps were made yet.
    nfev : int
        Number of the system's rhs evaluations.
    njev : int
        Number of the Jacobian evaluations.
    nlu : int
        Number of LU decompositions.
    """
    TOO_SMALL_STEP = "Required step size is less than spacing between numbers."

    def __init__(self, fun, t0, y0, t_bound, vectorized,
                 support_complex=False):
        self.t_old = None
        self.t = t0
        self._fun, self.y = check_arguments(fun, y0, support_complex)
        self.t_bound = t_bound
        self.vectorized = vectorized

        if vectorized:
            def fun_single(t, y):
                return self._fun(t, y[:, None]).ravel()
            fun_vectorized = self._fun
        else:
            fun_single = self._fun

            def fun_vectorized(t, y):
                f = np.empty_like(y)
                for i, yi in enumerate(y.T):
                    f[:, i] = self._fun(t, yi)
                return f

        def fun(t, y):
            self.nfev += 1
            return self.fun_single(t, y)

        self.fun = fun
        self.fun_single = fun_single
        self.fun_vectorized = fun_vectorized

        self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1
        self.n = self.y.size
        self.status = 'running'

        self.nfev = 0
        self.njev = 0
        self.nlu = 0

    @property
    def step_size(self):
        if self.t_old is None:
            return None
        else:
            return np.abs(self.t - self.t_old)

    def step(self):
        """Perform one integration step.

        Returns
        -------
        message : string or None
            Report from the solver. Typically a reason for a failure if
            `self.status` is 'failed' after the step was taken or None
            otherwise.
        """
        if self.status != 'running':
            raise RuntimeError("Attempt to step on a failed or finished "
                               "solver.")

        if self.n == 0 or self.t == self.t_bound:
            # Handle corner cases of empty solver or no integration.
            self.t_old = self.t
            self.t = self.t_bound
            message = None
            self.status = 'finished'
        else:
            t = self.t
            success, message = self._step_impl()

            if not success:
                self.status = 'failed'
            else:
                self.t_old = t
                if self.direction * (self.t - self.t_bound) >= 0:
                    self.status = 'finished'

        return message

    def dense_output(self):
        """Compute a local interpolant over the last successful step.

        Returns
        -------
        sol : `DenseOutput`
            Local interpolant over the last successful step.
        """
        if self.t_old is None:
            raise RuntimeError("Dense output is available after a successful "
                               "step was made.")

        if self.n == 0 or self.t == self.t_old:
            # Handle corner cases of empty solver and no integration.
            return ConstantDenseOutput(self.t_old, self.t, self.y)
        else:
            return self._dense_output_impl()

    def _step_impl(self):
        raise NotImplementedError

    def _dense_output_impl(self):
        raise NotImplementedError

class DenseOutput:
    """Base class for local interpolant over step made by an ODE solver.

    It interpolates between `t_min` and `t_max` (see Attributes below).
    Evaluation outside this interval is not forbidden, but the accuracy is not
    guaranteed.

    Attributes
    ----------
    t_min, t_max : float
        Time range of the interpolation.
    """
    def __init__(self, t_old, t):
        self.t_old = t_old
        self.t = t
        self.t_min = min(t, t_old)
        self.t_max = max(t, t_old)

    def __call__(self, t):
        """Evaluate the interpolant.

        Parameters
        ----------
        t : float or array_like with shape (n_points,)
            Points to evaluate the solution at.

        Returns
        -------
        y : ndarray, shape (n,) or (n, n_points)
            Computed values. Shape depends on whether `t` was a scalar or a
            1-D array.
        """
        t = np.asarray(t)
        if t.ndim > 1:
            raise ValueError("`t` must be a float or a 1-D array.")
        return self._call_impl(t)

    def _call_impl(self, t):
        raise NotImplementedError

class ConstantDenseOutput(DenseOutput):
    """Constant value interpolator.

    This class used for degenerate integration cases: equal integration limits
    or a system with 0 equations.
    """
    def __init__(self, t_old, t, value):
        super().__init__(t_old, t)
        self.value = value

    def _call_impl(self, t):
        if t.ndim == 0:
            return self.value
        else:
            ret = np.empty((self.value.shape[0], t.shape[0]))
            ret[:] = self.value[:, None]
            return ret


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.userhook">

    <uses-permission android:name="android.permission.INTERNET" />

    <!-- used to allow users to upload images (ex. screenshots) from their device -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application>

        <!-- User Hook -->
        <activity android:name="com.userhook.view.UHHostedPageActivity"
            android:theme="@style/UserHook"
            />

        <!-- User Hook Push Setup -->
        <service
            android:name="com.userhook.push.UHFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name="com.userhook.push.UHFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>


text:
<?php
namespace Kr\OAuthClient;

class OAuthClientEvents
{
    // TODO: MOVE
    const SERVER_REQUEST = "client.server_request";

    /**
     * Dispatched right before a resource request is sent
     *
     * Used to add authentication to the request
     */
    const RESOURCE_REQUEST = "oauth.client.resource_request";

    /**
     * Dispatched after the server has responded to a resource request
     *
     * Just there for convenience
     */
    const RESOURCE_RESPONSE = "oauth.client.resource_response";

    /**
     * Dispatched right before the client requests a new access token
     * At this point the grant_type will have already been resolved
     *
     * Used to add correct credentials to the token request
     */
    const TOKEN_REQUEST = "oauth.client.token_request";

    /**
     * Dispatched right after the server has responded to a token request
     *
     * Used to store access tokens
     */
    const TOKEN_RESPONSE = "oauth.client.token_response";

    /**
     * Dispatched right before the user is redirected to the authorization url
     *
     * Used to build the authorization url
     */
    const AUTHORIZATION_REQUEST = "oauth.client.authorization_request";

    /**
     * Dispatched whenever a user has just completed the authorization process
     * And has been redirected back to the redirect_uri
     *
     * Used for either the authorization code grant or the implicit grant
     */
    const AUTHORIZATION_RESPONSE = "oauth.client.authorization_response";
}


text:
namespace cf {
	// interface

	export interface IOptionsListOptions{
		context: HTMLElement;
		eventTarget: EventDispatcher;
		referenceTag: ITag;
	}

	// class
	// builds x OptionsButton from the registered SelectTag
	export class OptionsList {

		public elements: Array<OptionButton>;
		private eventTarget: EventDispatcher;
		private context: HTMLElement;
		private multiChoice: boolean;
		private referenceTag: ITag;
		private onOptionButtonClickCallback: () => void;

		public get type():string{
			return "OptionsList";
		}

		constructor(options: IOptionsListOptions){
			this.context = options.context;
			this.eventTarget = options.eventTarget;
			this.referenceTag = options.referenceTag;

			// check for multi choice select tag
			this.multiChoice = this.referenceTag.domElement.hasAttribute("multiple");

			this.onOptionButtonClickCallback = this.onOptionButtonClick.bind(this);
			this.eventTarget.addEventListener(OptionButtonEvents.CLICK, this.onOptionButtonClickCallback, false);

			this.createElements();
		}

		public getValue(): Array<OptionButton> {
			let arr: Array<OptionButton> = [];
			for (let i = 0; i < this.elements.length; i++) {
				let element: OptionButton = <OptionButton>this.elements[i];
				if(!this.multiChoice && element.selected){
					arr.push(element);
					return arr;
				}else if(this.multiChoice && element.selected){
					arr.push(element);
				}
			}
			return arr;
		}

		private onOptionButtonClick(event: CustomEvent){
			// if mutiple... then dont remove selection on other buttons
			if(!this.multiChoice){
				// only one is selectable at the time.

				for (let i = 0; i < this.elements.length; i++) {
					let element: OptionButton = <OptionButton>this.elements[i];
					if(element != event.detail){
						element.selected = false;
					}else{
						element.selected = true;
					}
				}

				ConversationalForm.illustrateFlow(this, "dispatch", ControlElementEvents.SUBMIT_VALUE, this.referenceTag);
				this.eventTarget.dispatchEvent(new CustomEvent(ControlElementEvents.SUBMIT_VALUE, {
					detail: <OptionButton> event.detail
				}));
			}else{
				(<OptionButton> event.detail).selected = !(<OptionButton> event.detail).selected;
			}
		}

		private createElements(){
			this.elements = [];
			var optionTags: Array<OptionTag> = (<SelectTag>this.referenceTag).optionTags;
			for (let i = 0; i < optionTags.length; i++) {
				let tag: OptionTag = optionTags[i];

				const btn: OptionButton = new OptionButton(<IOptionButtonOptions> {
					referenceTag: tag,
					isMultiChoice: (<SelectTag>this.referenceTag).multipleChoice,
					eventTarget: this.eventTarget
				});

				this.elements.push(btn);

				this.context.appendChild(btn.el);
			}
		}

		public dealloc(){
			this.eventTarget.removeEventListener(OptionButtonEvents.CLICK, this.onOptionButtonClickCallback, false);
			this.onOptionButtonClickCallback = null;

			while(this.elements.length > 0)
				this.elements.pop().dealloc();
			this.elements = null;
		}
	}
}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Quilt4.Service.Startup))]

namespace Quilt4.Service
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
package connector

import "github.com/cosminrentea/gobbler/protocol"

type Request interface {
	Subscriber() Subscriber
	Message() *protocol.Message
}

type request struct {
	subscriber Subscriber
	message    *protocol.Message
}

func NewRequest(s Subscriber, m *protocol.Message) Request {
	return &request{s, m}
}

func (r *request) Subscriber() Subscriber {
	return r.subscriber
}

func (r *request) Message() *protocol.Message {
	return r.message
}


text:
<?php

namespace AppBundle\API\Bitstamp\PrivateAPI;

/**
 * Bitstamp buy private API endpoint wrapper.
 */
class Buy extends AbstractPrivateAPI
{
    // {@inheritdoc}
    const ENDPOINT = 'buy';

    /**
     * {@inheritdoc}
     */
    public function requiredParams()
    {
        return ['amount', 'price'];
    }
}


text:
package br.gov.siscomex.portalunico.rcnt.model;

import java.util.List;

import javax.validation.Valid;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "DadosDoManisfestoDaCarga", propOrder =
    { "idElemento", "numero", "tipo", "listaConhecimentos"
})

@XmlRootElement(name="DadosDoManisfestoDaCarga")
public class DadosDoManisfestoDaCarga  {

  @XmlElement(name="idElemento")
  @ApiModelProperty(value = "Identificação de cada elemento da lista.
Tamanho: 40")
 /**
   * Identificação de cada elemento da lista.
Tamanho: 40
  **/
  private String idElemento = null;

  @XmlElement(name="numero")
  @ApiModelProperty(example = "1318500002175", value = "Número do Manifesto.
Tamanho: 100")
 /**
   * Número do Manifesto.
Tamanho: 100
  **/
  private String numero = null;

@XmlType(name="TipoEnum")
@XmlEnum(String.class)
public enum TipoEnum {

	@XmlEnumValue("'MICDTA'")
	@JsonProperty("'MICDTA'")
	MICDTA_(String.valueOf("'MICDTA'")),

	@XmlEnumValue("'TIFDTA'")
	@JsonProperty("'TIFDTA'")
	TIFDTA_(String.valueOf("'TIFDTA'")),

	@XmlEnumValue("'MDFE'")
	@JsonProperty("'MDFE'")
	MDFE_(String.valueOf("'MDFE'")),

	@XmlEnumValue("'MELET'")
	@JsonProperty("'MELET'")
	MELET_(String.valueOf("'MELET'"));

    private String value;

    TipoEnum (String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    @Override
    public String toString() {
        return String.valueOf(value);
    }

    public static TipoEnum fromValue(String v) {
        for (TipoEnum b : TipoEnum.values()) {
            if (String.valueOf(b.value).equals(v)) {
                return b;
            }
        }
        throw new IllegalArgumentException("Unexpected value '" + v + "' to TipoEnum");
    }
}

  @XmlElement(name="tipo")
  @ApiModelProperty(example = "MICDTA", value = "Tipo do manifesto conforme tabela de domínio.
Domínio:
MICDTA - MicDTA
TIFDTA - TifDTA
MDFE - MDF-e
MELET - Manifesto Eletrônico")
 /**
   * Tipo do manifesto conforme tabela de domínio.
Domínio:
MICDTA - MicDTA
TIFDTA - TifDTA
MDFE - MDF-e
MELET - Manifesto Eletrônico
  **/
  private TipoEnum tipo = null;

  @XmlElement(name="listaConhecimentos")
  @ApiModelProperty(value = "Lista de conhecimentos de carga.")
  @Valid
 /**
   * Lista de conhecimentos de carga.
  **/
  private List<DadosDoConhecimentoDaCarga> listaConhecimentos = null;
 /**
   * Identificação de cada elemento da lista.<br/>Tamanho: 40
   * @return idElemento
  **/
  @JsonProperty("idElemento")
  public String getIdElemento() {
    return idElemento;
  }

  public void setIdElemento(String idElemento) {
    this.idElemento = idElemento;
  }

  public DadosDoManisfestoDaCarga idElemento(String idElemento) {
    this.idElemento = idElemento;
    return this;
  }

 /**
   * Número do Manifesto.<br/>Tamanho: 100
   * @return numero
  **/
  @JsonProperty("numero")
  public String getNumero() {
    return numero;
  }

  public void setNumero(String numero) {
    this.numero = numero;
  }

  public DadosDoManisfestoDaCarga numero(String numero) {
    this.numero = numero;
    return this;
  }

 /**
   * Tipo do manifesto conforme tabela de domínio.<br/>Domínio:<br/>MICDTA - MicDTA<br/>TIFDTA - TifDTA<br/>MDFE - MDF-e<br/>MELET - Manifesto Eletrônico
   * @return tipo
  **/
  @JsonProperty("tipo")
  public String getTipo() {
    if (tipo == null) {
      return null;
    }
    return tipo.value();
  }

  public void setTipo(TipoEnum tipo) {
    this.tipo = tipo;
  }

  public DadosDoManisfestoDaCarga tipo(TipoEnum tipo) {
    this.tipo = tipo;
    return this;
  }

 /**
   * Lista de conhecimentos de carga.
   * @return listaConhecimentos
  **/
  @JsonProperty("listaConhecimentos")
  public List<DadosDoConhecimentoDaCarga> getListaConhecimentos() {
    return listaConhecimentos;
  }

  public void setListaConhecimentos(List<DadosDoConhecimentoDaCarga> listaConhecimentos) {
    this.listaConhecimentos = listaConhecimentos;
  }

  public DadosDoManisfestoDaCarga listaConhecimentos(List<DadosDoConhecimentoDaCarga> listaConhecimentos) {
    this.listaConhecimentos = listaConhecimentos;
    return this;
  }

  public DadosDoManisfestoDaCarga addListaConhecimentosItem(DadosDoConhecimentoDaCarga listaConhecimentosItem) {
    this.listaConhecimentos.add(listaConhecimentosItem);
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class DadosDoManisfestoDaCarga {\n");

    sb.append("    idElemento: ").append(toIndentedString(idElemento)).append("\n");
    sb.append("    numero: ").append(toIndentedString(numero)).append("\n");
    sb.append("    tipo: ").append(toIndentedString(tipo)).append("\n");
    sb.append("    listaConhecimentos: ").append(toIndentedString(listaConhecimentos)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}