text:
#include "engine.hpp"
#include <iostream>
#include "oddlib/masher.hpp"
#include "oddlib/exceptions.hpp"
#include "logger.hpp"
#include "jsonxx/jsonxx.h"
#include <fstream>
#include "proxy_sqrat.hpp"
#include "alive_version.h"
#include "core/audiobuffer.hpp"
#include "sound.hpp"
#include "gridmap.hpp"
#include "gameselectionstate.hpp"
#include "gamefilesystem.hpp"
#include "rendererfactory.hpp"
#include "debug.hpp"
#include "resourcemapper.hpp"
#include "world.hpp"

#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

#undef DeleteFile

#include "rsc\resource.h"
#include "SDL_syswm.h"
#include "stdthread.h"
#include "imgui/imgui.h"

void setWindowsIcon(SDL_Window *sdlWindow)
{
    HINSTANCE handle = ::GetModuleHandle(nullptr);
    HICON icon = ::LoadIcon(handle, MAKEINTRESOURCE(IDI_MAIN_ICON));
    if (icon != nullptr)
    {
        SDL_SysWMinfo wminfo;
        SDL_VERSION(&wminfo.version);
        if (SDL_GetWindowWMInfo(sdlWindow, &wminfo) == 1)
        {
            HWND hwnd = wminfo.info.win.window;
#ifdef _WIN64
            ::SetClassLongPtr(hwnd, GCLP_HICON, reinterpret_cast<LONG_PTR>(icon));
#else
            ::SetClassLong(hwnd, GCL_HICON, reinterpret_cast<LONG>(icon));
#endif
        }

        HMODULE hKernel32 = ::GetModuleHandle("Kernel32.dll");
        if (hKernel32)
        {
            typedef BOOL(WINAPI *pSetConsoleIcon)(HICON icon);
#ifdef _MSC_VER
#pragma warning(push)
            // C4191: 'reinterpret_cast' : unsafe conversion from 'FARPROC' to 'pSetConsoleIcon'
            // This is a "feature" of GetProcAddress, so ignore.
#pragma warning(disable:4191)
#endif
            pSetConsoleIcon setConsoleIcon = reinterpret_cast<pSetConsoleIcon>(::GetProcAddress(hKernel32, "SetConsoleIcon"));
#ifdef _MSC_VER
#pragma warning(pop)
#endif
            if (setConsoleIcon)
            {
                setConsoleIcon(icon);
            }
        }
    }
}
#endif

Engine::Engine(const std::vector<std::string>& commandLineArguments)
    : mAudioHandler(1024, 44100)
{
    for (const std::string& argument : commandLineArguments)
    {
        if (string_util::iequals("-opengl", argument))
        {
            mTryDirectX9 = false;
        }
        else if (string_util::iequals("-directx9", argument))
        {
#ifndef _WIN32
            LOG_WARNING("DirectX9 is not supported on this platform");
#else
            mTryDirectX9 = true;
#endif
        }
    }
}

Engine::~Engine()
{
    TRACE_ENTRYEXIT;

    ImGui::Shutdown();

    mSound.reset();
    mWorld.reset();

    if (mRenderer)
    {
        mRenderer->ShutDown();
    }
    mRenderer.reset();

    SDL_DestroyWindow(mWindow);
    SDL_Quit();
}

bool Engine::Init()
{
    // load the list of data paths (if any) and discover what they are
    mFileSystem = std::make_unique<GameFileSystem>();
    if (!mFileSystem->Init())
    {
        LOG_ERROR("File system init failure");
        return false;
    }

    if (!InitSDL())
    {
        LOG_ERROR("SDL init failure");
        return false;
    }

    InitSubSystems();

    Debugging().mInput = &mInputState;

    mState = EngineStates::ePreEngineInit;

    mLoadingIcon = std::make_unique<LoadingIcon>(*mFileSystem);
    mLoadingIcon->SetEnabled(true);

    return true;
}

void ScriptLogTrace(const char* msg) { if (msg) { LOG_NOFUNC_TRACE(msg); } else  { LOG_NOFUNC_TRACE("nil"); } }
void ScriptLogInfo(const char* msg) { if (msg) { LOG_NOFUNC_INFO(msg); } else { LOG_NOFUNC_INFO("nil"); } }
void ScriptLogWarning(const char* msg) { if (msg) { LOG_NOFUNC_WARNING(msg); } else { LOG_NOFUNC_WARNING("nil"); } }
void ScriptLogError(const char* msg) { if (msg) { LOG_NOFUNC_ERROR(msg); } else { LOG_NOFUNC_ERROR("nil"); } }

void Engine::Include(const std::string& scriptName)
{
    SquirrelVm::CompileAndRun(*mResourceLocator, scriptName);
}

void Engine::BindScriptTypes()
{
    Sqrat::RootTable().Func("log_info", ScriptLogInfo);
    Sqrat::RootTable().Func("log_trace", ScriptLogTrace);
    Sqrat::RootTable().Func("log_warning", ScriptLogWarning);
    Sqrat::RootTable().Func("log_error", ScriptLogError);

    Sqrat::Class<Engine, Sqrat::NoConstructor<Engine>> engine(Sqrat::DefaultVM::Get(), "Engine");
    engine.Func("include", &Engine::Include);

    Sqrat::RootTable().Bind("Engine", engine);
    // TODO: Use InstanceBinder
    Sqrat::RootTable().SetInstance("gEngine", this);

    Oddlib::IStream::RegisterScriptBindings();
    Actions::RegisterScriptBindings();
    MapObject::RegisterScriptBindings();
    ObjRect::RegisterScriptBindings();
    GridMap::RegisterScriptBindings();
}

void Engine::InitSubSystems()
{
    TRACE_ENTRYEXIT;

    BindScriptTypes();

    mRenderer = RendererFactory::Create(mWindow, mTryDirectX9);

    mRenderer->Init
    (
        (mFileSystem->FsPath() + "data/fonts/Roboto-Regular.ttf").c_str(),
        (mFileSystem->FsPath() + "data/fonts/Roboto-Italic.ttf").c_str(),
        (mFileSystem->FsPath() + "data/fonts/Roboto-Bold.ttf").c_str()
    );

    InitImGui();

    mInputState.AddControllers();
}

void Engine::RunInitScript()
{
    SquirrelVm::CompileAndRun(*mResourceLocator, "main.nut");

    LOG_INFO("Calling script init()");
    Sqrat::Function initFunc(Sqrat::RootTable(), "init");
    initFunc.Execute();
    SquirrelVm::CheckError();
}

// TODO: Using averaging value or anything that is more accurate than this
using THighResClock = std::chrono::high_resolution_clock;
class BasicFramesPerSecondCounter
{
public:
    BasicFramesPerSecondCounter()
    {
        mStartedTime = THighResClock::now();
    }

    template<class T>
    void Update(T fnUpdate)
    {
        mFramesPassed++;
        const THighResClock::duration totalRunTime = THighResClock::now() - mStartedTime;
        const Sint64 timeSinceLastFrameInMsecs = std::chrono::duration_cast<std::chrono::milliseconds>(totalRunTime - mFrameStartTime).count();
        if (timeSinceLastFrameInMsecs > 500 && mFramesPassed > 10)
        {
            const f32 fps = static_cast<f32>(static_cast<f32>(mFramesPassed) / (static_cast<f32>(timeSinceLastFrameInMsecs) / 1000.0f));
            mFrameStartTime = totalRunTime;
            mFramesPassed = 0;
            fnUpdate(fps);
        }
    }

private:
    THighResClock::time_point mStartedTime = {};
    u32 mFramesPassed = 0;
    THighResClock::duration mFrameStartTime = {};
};

static char* WindowTitle(const char* rendererName, f32 fps)
{
    static char buffer[128] = {};
    sprintf(buffer, ALIVE_VERSION_NAME_STR, rendererName, fps);
    return buffer;
}

int Engine::Run()
{
    BasicFramesPerSecondCounter fpsCounter;
    auto startTime = THighResClock::now();

    while (mState != EngineStates::eQuit)
    {
        // Limit update to 60fps
        const THighResClock::duration totalRunTime = THighResClock::now() - startTime;
        const Sint64 timePassed = std::chrono::duration_cast<std::chrono::nanoseconds>(totalRunTime).count();

        if (timePassed >= 16666666)
        {
            Update();
            ImGui::Render();
            startTime = THighResClock::now();
        }

        Render();
        fpsCounter.Update([&](f32 fps)
        {
            SDL_SetWindowTitle(mWindow, WindowTitle(mRenderer->Name(), fps));
        });
    }

    mRenderer->DestroyTexture(mGuiFontHandle);

    return 0;
}

static bool mousePressed[4] = { false, false };
static ImVec2 mousePosScale(1.0f, 1.0f);

static void UpdateImGuiMouseInput()
{
    ImGuiIO& io = ImGui::GetIO();

    SDL_PumpEvents();

    // Setup inputs
    int mouse_x, mouse_y;
    SDL_GetMouseState(&mouse_x, &mouse_y);

    io.MousePos = ImVec2((float)mouse_x * mousePosScale.x, (float)mouse_y * mousePosScale.y);      // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)

    io.MouseDown[0] = mousePressed[0] || (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT));
    io.MouseDown[1] = mousePressed[1] || (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT));
}

void Engine::InitImGui()
{
    ImGui::GetStyle().AntiAliasedLines = true;
    ImGui::GetStyle().AntiAliasedShapes = true;

    ImGuiIO& io = ImGui::GetIO();
    ImFontConfig config;
    config.OversampleH = 3;
    config.OversampleV = 3;
    std::string fontPath = mFileSystem->FsPath() + "data/fonts/Roboto-Regular.ttf";
    if (!io.Fonts->AddFontFromFileTTF(fontPath.c_str(), 18.0f, &config))
    {
        throw Oddlib::Exception(("Failed to load font " + fontPath).c_str());
    }

    ImGui_WindowResize();

    // Build texture
    unsigned char* pixels = nullptr;
    int width = 0;
    int height = 0;
    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);

    // Create texture
    mGuiFontHandle = mRenderer->CreateTexture(AbstractRenderer::eTextureFormats::eRGBA, width, height, AbstractRenderer::eTextureFormats::eRGBA, pixels, true);

    // Store our identifier
    io.Fonts->TexID = mGuiFontHandle.mData;

    // Cleanup (don't clear the input data if you want to append new fonts later)
    io.Fonts->ClearInputData();
    io.Fonts->ClearTexData();

    // setup SDL2 keymapping
    io.KeyMap[ImGuiKey_Tab] = SDL_GetScancodeFromKey(SDLK_TAB);
    io.KeyMap[ImGuiKey_LeftArrow] = SDL_GetScancodeFromKey(SDLK_LEFT);
    io.KeyMap[ImGuiKey_RightArrow] = SDL_GetScancodeFromKey(SDLK_RIGHT);
    io.KeyMap[ImGuiKey_UpArrow] = SDL_GetScancodeFromKey(SDLK_UP);
    io.KeyMap[ImGuiKey_DownArrow] = SDL_GetScancodeFromKey(SDLK_DOWN);
    io.KeyMap[ImGuiKey_Home] = SDL_GetScancodeFromKey(SDLK_HOME);
    io.KeyMap[ImGuiKey_End] = SDL_GetScancodeFromKey(SDLK_END);
    io.KeyMap[ImGuiKey_Delete] = SDL_GetScancodeFromKey(SDLK_DELETE);
    io.KeyMap[ImGuiKey_Backspace] = SDL_GetScancodeFromKey(SDLK_BACKSPACE);
    io.KeyMap[ImGuiKey_Enter] = SDL_GetScancodeFromKey(SDLK_RETURN);
    io.KeyMap[ImGuiKey_Escape] = SDL_GetScancodeFromKey(SDLK_ESCAPE);
    io.KeyMap[ImGuiKey_A] = SDLK_a;
    io.KeyMap[ImGuiKey_C] = SDLK_c;
    io.KeyMap[ImGuiKey_V] = SDLK_v;
    io.KeyMap[ImGuiKey_X] = SDLK_x;
    io.KeyMap[ImGuiKey_Y] = SDLK_y;
    io.KeyMap[ImGuiKey_Z] = SDLK_z;

    ImGui::GetStyle().WindowTitleAlign = ImVec2(0.5f, 0.5f);
    ImGui::GetStyle().WindowRounding = 3.0f;

    auto& style = ImGui::GetStyle();

    style.Colors[ImGuiCol_Text] = ImVec4(1, 1, 1, 1);
    style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.86f, 0.93f, 0.89f, 0.28f);
    style.Colors[ImGuiCol_WindowBg] = ImVec4(0.13f, 0.14f, 0.17f, 1.00f);
    style.Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.20f, 0.22f, 0.27f, 0.58f);
    style.Colors[ImGuiCol_Border] = ImVec4(0.31f, 0.31f, 1.00f, 0.00f);
    style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
    style.Colors[ImGuiCol_FrameBg] = ImVec4(0.20f, 0.22f, 0.27f, 1.00f);
    style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);
    style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_TitleBg] = ImVec4(0.20f, 0.22f, 0.27f, 1.00f);
    style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.20f, 0.22f, 0.27f, 0.75f);
    style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.20f, 0.22f, 0.27f, 0.47f);
    style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.22f, 0.27f, 1.00f);
    style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.47f, 0.77f, 0.83f, 0.21f);
    style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);
    style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.22f, 0.27f, 1.00f);
    style.Colors[ImGuiCol_CheckMark] = ImVec4(0.71f, 0.22f, 0.27f, 1.00f);
    style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.47f, 0.77f, 0.83f, 0.14f);
    style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_Button] = ImVec4(0.47f, 0.77f, 0.83f, 0.14f);
    style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.92f, 0.18f, 0.29f, 0.86f);
    style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_Header] = ImVec4(0.92f, 0.18f, 0.29f, 0.76f);
    style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.92f, 0.18f, 0.29f, 0.86f);
    style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_Column] = ImVec4(0.47f, 0.77f, 0.83f, 0.32f);
    style.Colors[ImGuiCol_ColumnHovered] = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);
    style.Colors[ImGuiCol_ColumnActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_ResizeGrip] = ImVec4(0.47f, 0.77f, 0.83f, 0.04f);
    style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);
    style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_CloseButton] = ImVec4(0.86f, 0.93f, 0.89f, 0.16f);
    style.Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.86f, 0.93f, 0.89f, 0.39f);
    style.Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.86f, 0.93f, 0.89f, 1.00f);
    style.Colors[ImGuiCol_PlotLines] = ImVec4(0.86f, 0.93f, 0.89f, 0.63f);
    style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.86f, 0.93f, 0.89f, 0.63f);
    style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);
    style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.92f, 0.18f, 0.29f, 0.43f);
    //style.Colors[ImGuiCol_TooltipBg] = ImVec4(0.47f, 0.77f, 0.83f, 0.72f);
    style.Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.22f, 0.27f, 0.73f);
}

//TODO: ImGui shutdown/clean up
void Engine::ImGui_WindowResize()
{
    int w, h;
    int fb_w, fb_h;
    SDL_GetWindowSize(mWindow, &w, &h);
    SDL_GetWindowSize(mWindow, &fb_w, &fb_h); // Needs to be corrected for SDL Framebuffer
    mousePosScale.x = (float)fb_w / w;
    mousePosScale.y = (float)fb_h / h;

    ImGuiIO& io = ImGui::GetIO();
    io.DisplaySize = ImVec2((float)fb_w, (float)fb_h);  // Display size, in pixels. For clamping windows positions.
    //    io.PixelCenterOffset = 0.0f;                        // Align OpenGL texels
}

void Engine::Update()
{
    ImGuiIO& io = ImGui::GetIO();
    io.MouseWheel = 0;

    SDL_Event event;
    while (SDL_PollEvent(&event))
    {
        switch (event.type)
        {
        case SDL_MOUSEWHEEL:
            if (event.wheel.y < 0)
            {
                ImGui::GetIO().MouseWheel = -1.0f;
            }
            else
            {
                ImGui::GetIO().MouseWheel = 1.0f;
            }
            break;

        case SDL_QUIT:
            mState = EngineStates::eQuit;
            break;

        case SDL_TEXTINPUT:
        {
            size_t len = strlen(event.text.text);
            for (size_t i = 0; i < len; i++)
            {
                uint32_t keycode = event.text.text[i];
                if (keycode >= 10 && keycode <= 255)
                {
                    ImGui::GetIO().AddInputCharacter((char)keycode);
                }
            }
        }
        break;

        case SDL_WINDOWEVENT:
            switch (event.window.event)
            {
            case SDL_WINDOWEVENT_RESIZED:
            case SDL_WINDOWEVENT_MAXIMIZED:
            case SDL_WINDOWEVENT_RESTORED:
                mRenderer->mSmoothCameraPosition = false;
                ImGui_WindowResize();
                break;
            }
            break;
        case SDL_MOUSEBUTTONUP:
        case SDL_MOUSEBUTTONDOWN:
        {
            mInputState.OnMouseButtonEvent(event.button);
        } break;

        case SDL_CONTROLLERDEVICEADDED:
            mInputState.AddController(event.cdevice);
            break;

        case SDL_CONTROLLERDEVICEREMOVED:
            mInputState.RemoveController(event.cdevice);
            break;

        case SDL_CONTROLLERBUTTONDOWN:
        case SDL_CONTROLLERBUTTONUP:
            mInputState.OnControllerButton(event.cbutton);
            break;

        case SDL_CONTROLLERAXISMOTION:
            mInputState.OnControllerAxis(event.caxis);
            break;

        case SDL_KEYDOWN:
        case SDL_KEYUP:
        {
            mInputState.OnKeyEvent(event.key);

            if (event.type == SDL_KEYDOWN && event.key.keysym.sym == 13)
            {
                const u32 windowFlags = SDL_GetWindowFlags(mWindow);
                bool isFullScreen = ((windowFlags & SDL_WINDOW_FULLSCREEN_DESKTOP) || (windowFlags & SDL_WINDOW_FULLSCREEN));
                SDL_SetWindowFullscreen(mWindow, isFullScreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
                //OnWindowResize();
            }

            const SDL_Scancode key = SDL_GetScancodeFromKey(event.key.keysym.sym);
            if (key >= 0 && key < 512)
            {
                SDL_Keymod modstate = SDL_GetModState();

                io.KeysDown[key] = event.type == SDL_KEYDOWN;
                io.KeyCtrl = (modstate & KMOD_CTRL) != 0;
                io.KeyShift = (modstate & KMOD_SHIFT) != 0;
            }

            break;
        }
        }
    }

    // Set rest of gui input state which wasn't set in event polling loop
    SDL_PumpEvents();

    int mouse_x, mouse_y;
    SDL_GetMouseState(&mouse_x, &mouse_y);

    mInputState.mMousePosition.mX = mouse_x;
    mInputState.mMousePosition.mY = mouse_y;

    mInputState.Update();

    ImGui::NewFrame();

    UpdateImGuiMouseInput();

    mJobSystem.Update();
    mLoadingIcon->Update(*mRenderer);

    switch (mState)
    {
    case EngineStates::eRunSelectedGame:
        if (!mWorld)
        {
            // TODO: Pass in infos from mGameSelectionScreen
            mWorld = std::make_unique<World>(mAudioHandler, *mResourceLocator,
                *mRenderer,
                *mRenderer,
                mGameSelectionScreen->SelectedGame(),
                *mSound,
                *mLoadingIcon);
        }
        mState = mWorld->Update(mInputState, *mRenderer);
        // TODO: Allow returning to eSelectGame
        break;

    case EngineStates::eSelectGame:
        // eQuit or eRunSelectedGame
        mState = mGameSelectionScreen->Update(mInputState, *mRenderer);
        break;

    case EngineStates::ePreEngineInit:
        mJobSystem.StartJob(std::make_shared<EngineJob>(*this, EngineJob::eJobTypes::eInitResources));
        mState = EngineStates::eEngineInit;
        break;

    case EngineStates::eEngineInit:
        // Waiting for OnJobFinished
        break;

    case EngineStates::eQuit:
        break;
    }
}

void Engine::Render()
{
    int w = 0;
    int h = 0;
    SDL_GetWindowSize(mWindow, &w, &h);

    mRenderer->UpdateCamera();
    mRenderer->BeginFrame(w, h);

    switch (mState)
    {
    case EngineStates::eRunSelectedGame:
        if (mWorld)
        {
            mWorld->Render(*mRenderer);
        }
        else
        {
            mRenderer->Clear(0.0f, 0.0f, 0.0f);
        }
        break;

    case EngineStates::eSelectGame:
        mGameSelectionScreen->Render(*mRenderer);
        break;

    case EngineStates::ePreEngineInit:
    case EngineStates::eEngineInit:
    case EngineStates::eQuit:
        mRenderer->Clear(0.0f, 0.0f, 0.0f);
        break;
    }

    mLoadingIcon->Render(*mRenderer);

    mRenderer->EndFrame();
}

bool Engine::InitSDL()
{
    if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS | SDL_INIT_HAPTIC) != 0)
    {
        LOG_ERROR("SDL_Init failed " << SDL_GetError());
        return false;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

    std::string title = WindowTitle("", 0.0f);
    title = title.substr(0, title.find(")")+1);

    mWindow = SDL_CreateWindow(title.c_str(),
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480,
        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (!mWindow)
    {
        LOG_ERROR("Failed to create window: " << SDL_GetError());
        return false;
    }

    SDL_SetWindowMinimumSize(mWindow, 640, 480);

#if defined(_WIN32)
    // I'd like my icon back thanks
    setWindowsIcon(mWindow);
#endif

    return true;
}

void Engine::AddGameDefinitionsFrom(const char* path)
{
    const auto jsonFiles = mFileSystem->EnumerateFiles(path, "*.json");
    for (const auto& gameDef : jsonFiles)
    {
        mGameDefinitions.emplace_back(*mFileSystem, (std::string(path) + "/" + gameDef).c_str(), false);
    }
}

void Engine::AddModDefinitionsFrom(const char* path)
{
    std::string strPath(path);
    AddDirectoryBasedModDefinitionsFrom(strPath);
    AddZipedModDefinitionsFrom(strPath);
}

void Engine::AddDirectoryBasedModDefinitionsFrom(std::string path)
{
    const auto possibleModDirs = mFileSystem->EnumerateFolders(path);
    for (const auto& possibleModDir : possibleModDirs)
    {
        auto modDefinitionFiles = mFileSystem->EnumerateFiles(path + "/" + possibleModDir, "game.json");
        if (!modDefinitionFiles.empty())
        {
            auto fs = IFileSystem::Factory(*mFileSystem, path + "/" + possibleModDir + "/");
            if (fs)
            {
                mGameDefinitions.emplace_back(*fs, modDefinitionFiles[0].c_str(), true);
            }
        }
    }
}

void Engine::AddZipedModDefinitionsFrom(std::string path)
{
    const auto possibleModZips = mFileSystem->EnumerateFiles(path, "*.zip");
    for (const auto& possibleModZip : possibleModZips)
    {
        auto fs = IFileSystem::Factory(*mFileSystem, path + "/" + possibleModZip);
        if (fs)
        {
            auto modDefinitionFiles = fs->EnumerateFiles("", "game.json");
            if (!modDefinitionFiles.empty())
            {
                mGameDefinitions.emplace_back(*fs, modDefinitionFiles[0].c_str(), true);
            }
        }
    }
}

void Engine::InitResources()
{
    TRACE_ENTRYEXIT;

    // load the enumerated "built in" game defs
    AddGameDefinitionsFrom("{GameDir}/data/GameDefinitions");

    // load the enumerated "mod" game defs
    AddModDefinitionsFrom("{UserDir}/Mods");

    // The engine probably won't ship with any mods, but while under development look here too
    AddModDefinitionsFrom("{GameDir}/data/Mods");

    // create the resource mapper loading the resource maps from the json db
    DataPaths dataPaths(*mFileSystem,
        "{GameDir}/data/DataSetIds.json",
        "{UserDir}/DataSets.json");

    ResourceMapper mapper(*mFileSystem,
        "{GameDir}/data/dataset_contents.json",
        "{GameDir}/data/animations.json",
        "{GameDir}/data/sounds.json",
        "{GameDir}/data/paths.json",
        "{GameDir}/data/fmvs.json");

    mResourceLocator = std::make_unique<ResourceLocator>(std::move(mapper), std::move(dataPaths));

    // TODO: After user selects game def then add/validate the required paths/data sets in the res mapper
    // also add in any extra maps for resources defined by the mod @ game selection screen
}

void Engine::OnJobStart(EngineJob::eJobTypes jobType, const CancelFlag& /*quitFlag*/)
{
    if (jobType == EngineJob::eJobTypes::eInitResources)
    {
        InitResources();
    }
}

void Engine::OnJobFinished(EngineJob::eJobTypes jobType)
{
    if (jobType == EngineJob::eJobTypes::eInitResources)
    {
        mLoadingIcon->SetEnabled(false);
        mState = EngineStates::eSelectGame;
        mSound = std::make_unique<Sound>(mAudioHandler, *mResourceLocator, *mFileSystem, mJobSystem);
        mGameSelectionScreen = std::make_unique<GameSelectionState>(mGameDefinitions, *mResourceLocator, *mFileSystem);
        RunInitScript();
    }
}

void SquirrelVm::CompileAndRun(ResourceLocator& resourceLocator, const std::string& scriptName)
{
    TRACE_ENTRYEXIT;

    Sqrat::Script script;
    script.CompileString(resourceLocator.LocateScript(scriptName).get(), scriptName);
    CheckError();

    script.Run();
    CheckError();
}

void SquirrelVm::CompileAndRun(const std::string& scriptName, const std::string& scriptSource)
{
    TRACE_ENTRYEXIT;

    Sqrat::Script script;
    script.CompileString(scriptSource, scriptName);
    CheckError();

    script.Run();
    CheckError();
}

EngineJob::EngineJob(Engine& e, eJobTypes jobType)
    : mJobType(jobType), mEngine(e)
{

}

void EngineJob::OnExecute(const CancelFlag& quitFlag)
{
    mEngine.OnJobStart(mJobType, quitFlag);
}

void EngineJob::OnFinished()
{
    mEngine.OnJobFinished(mJobType);
}

LoadingIcon::LoadingIcon(IFileSystem& fileSystem)
{
    std::unique_ptr<Oddlib::IStream> pngStream = fileSystem.Open("{GameDir}/data/images/loading.png");
    if (pngStream)
    {
        mLoadingIcon = SDLHelpers::LoadPng(*pngStream, true);
    }

    if (!mLoadingIcon)
    {
        throw Oddlib::Exception("Failed to load {GameDir}/data/images/loading.png");
    }
}

void LoadingIcon::Update(CoordinateSpace& /*coords*/)
{

}

void LoadingIcon::Render(AbstractRenderer& renderer)
{
    if (mEnabled)
    {
        TextureHandle hTexture = renderer.CreateTexture(AbstractRenderer::eTextureFormats::eRGBA, mLoadingIcon->w, mLoadingIcon->h, AbstractRenderer::eTextureFormats::eRGBA, mLoadingIcon->pixels, true);

        const f32 imagew = static_cast<f32>(mLoadingIcon->w);
        const f32 imageh = static_cast<f32>(mLoadingIcon->h);

        const f32 padding = 30.0f;

        const f32 xpos = static_cast<f32>(renderer.Width()) - imagew - padding;
        const f32 ypos = static_cast<f32>(renderer.Height()) - imageh - padding;

        renderer.TexturedQuad(hTexture,
            xpos,
            ypos,
            imagew,
            imageh,
            AbstractRenderer::eLayers::eFmv + 5, { 255, 255, 255, 255 }, AbstractRenderer::eNormal, AbstractRenderer::eScreen);

        renderer.DestroyTexture(hTexture);
    }
}

void LoadingIcon::SetEnabled(bool enabled)
{
    mEnabled = enabled;
}


text:
namespace content {

class BluetoothDispatcher;
class ThreadSafeSender;

// Implementation of blink::WebBluetooth. Passes calls through to the thread
// specific BluetoothDispatcher.
class CONTENT_EXPORT WebBluetoothImpl
    : NON_EXPORTED_BASE(public blink::WebBluetooth) {
 public:
  explicit WebBluetoothImpl(ThreadSafeSender* thread_safe_sender);
  WebBluetoothImpl(ThreadSafeSender* thread_safe_sender, int frame_routing_id);
  ~WebBluetoothImpl();

  // blink::WebBluetooth interface:
  void requestDevice(
      const blink::WebRequestDeviceOptions& options,
      blink::WebBluetoothRequestDeviceCallbacks* callbacks) override;
  void connectGATT(const blink::WebString& device_instance_id,
      blink::WebBluetoothConnectGATTCallbacks* callbacks) override;
  void getPrimaryService(
      const blink::WebString& device_instance_id,
      const blink::WebString& service_uuid,
      blink::WebBluetoothGetPrimaryServiceCallbacks* callbacks) override;
  void getCharacteristic(
      const blink::WebString& service_instance_id,
      const blink::WebString& characteristic_uuid,
      blink::WebBluetoothGetCharacteristicCallbacks* callbacks) override;
  void readValue(const blink::WebString& characteristic_instance_id,
                 blink::WebBluetoothReadValueCallbacks* callbacks) override;
  void writeValue(const blink::WebString& characteristic_instance_id,
                  const std::vector<uint8_t>& value,
                  blink::WebBluetoothWriteValueCallbacks*) override;

 private:
  BluetoothDispatcher* GetDispatcher();

  const scoped_refptr<ThreadSafeSender> thread_safe_sender_;
  const int frame_routing_id_;

  DISALLOW_COPY_AND_ASSIGN(WebBluetoothImpl);
};

}  // namespace content

#endif  // CONTENT_CHILD_BLUETOOTH_WEB_BLUETOOTH_IMPL_H_

redpajama_set_name: RedPajamaGithub


text:
package errors

import (
	"encoding/json"
	"fmt"
	"net/http"
	"reflect"
	"strings"
)

// DefaultHTTPCode is used when the error Code cannot be used as an HTTP code.
var DefaultHTTPCode = http.StatusUnprocessableEntity

// Error represents a error interface all swagger framework errors implement
type Error interface {
	error
	Code() int32
}

type apiError struct {
	code    int32
	message string
}

func (a *apiError) Error() string {
	return a.message
}

func (a *apiError) Code() int32 {
	return a.code
}

// MarshalJSON implements the JSON encoding interface
func (a apiError) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"code":    a.code,
		"message": a.message,
	})
}

// New creates a new API error with a code and a message
func New(code int32, message string, args ...interface{}) Error {
	if len(args) > 0 {
		return &apiError{code, fmt.Sprintf(message, args...)}
	}
	return &apiError{code, message}
}

// NotFound creates a new not found error
func NotFound(message string, args ...interface{}) Error {
	if message == "" {
		message = "Not found"
	}
	return New(http.StatusNotFound, fmt.Sprintf(message, args...))
}

// NotImplemented creates a new not implemented error
func NotImplemented(message string) Error {
	return New(http.StatusNotImplemented, message)
}

// MethodNotAllowedError represents an error for when the path matches but the method doesn't
type MethodNotAllowedError struct {
	code    int32
	Allowed []string
	message string
}

func (m *MethodNotAllowedError) Error() string {
	return m.message
}

// Code the error code
func (m *MethodNotAllowedError) Code() int32 {
	return m.code
}

// MarshalJSON implements the JSON encoding interface
func (m MethodNotAllowedError) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"code":    m.code,
		"message": m.message,
		"allowed": m.Allowed,
	})
}

func errorAsJSON(err Error) []byte {
	b, _ := json.Marshal(struct {
		Code    int32  `json:"code"`
		Message string `json:"message"`
	}{err.Code(), err.Error()})
	return b
}

func flattenComposite(errs *CompositeError) *CompositeError {
	var res []error
	for _, er := range errs.Errors {
		switch e := er.(type) {
		case *CompositeError:
			if len(e.Errors) > 0 {
				flat := flattenComposite(e)
				if len(flat.Errors) > 0 {
					res = append(res, flat.Errors...)
				}
			}
		default:
			if e != nil {
				res = append(res, e)
			}
		}
	}
	return CompositeValidationError(res...)
}

// MethodNotAllowed creates a new method not allowed error
func MethodNotAllowed(requested string, allow []string) Error {
	msg := fmt.Sprintf("method %s is not allowed, but [%s] are", requested, strings.Join(allow, ","))
	return &MethodNotAllowedError{code: http.StatusMethodNotAllowed, Allowed: allow, message: msg}
}

// ServeError the error handler interface implementation
func ServeError(rw http.ResponseWriter, r *http.Request, err error) {
	rw.Header().Set("Content-Type", "application/json")
	switch e := err.(type) {
	case *CompositeError:
		er := flattenComposite(e)
		// strips composite errors to first element only
		if len(er.Errors) > 0 {
			ServeError(rw, r, er.Errors[0])
		} else {
			// guard against empty CompositeError (invalid construct)
			ServeError(rw, r, nil)
		}
	case *MethodNotAllowedError:
		rw.Header().Add("Allow", strings.Join(err.(*MethodNotAllowedError).Allowed, ","))
		rw.WriteHeader(asHTTPCode(int(e.Code())))
		if r == nil || r.Method != http.MethodHead {
			_, _ = rw.Write(errorAsJSON(e))
		}
	case Error:
		value := reflect.ValueOf(e)
		if value.Kind() == reflect.Ptr && value.IsNil() {
			rw.WriteHeader(http.StatusInternalServerError)
			_, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
			return
		}
		rw.WriteHeader(asHTTPCode(int(e.Code())))
		if r == nil || r.Method != http.MethodHead {
			_, _ = rw.Write(errorAsJSON(e))
		}
	case nil:
		rw.WriteHeader(http.StatusInternalServerError)
		_, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
	default:
		rw.WriteHeader(http.StatusInternalServerError)
		if r == nil || r.Method != http.MethodHead {
			_, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, err.Error())))
		}
	}
}

func asHTTPCode(input int) int {
	if input >= 600 {
		return DefaultHTTPCode
	}
	return input
}


text:
<?php

namespace Helloworld\Controller;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class IndexControllerFactory implements FactoryInterface {

    public function createService(ServiceLocatorInterface $serviceLocator) {
        $ctr = new IndexController();

        $ctr->setGreetingService(
                $serviceLocator->getServiceLocator()
                        ->get('greetingService')
        );

        return $ctr;
    }

}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::Bindings::HTMLMeterElementBinding::{self, HTMLMeterElementMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::root::DomRoot;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom::nodelist::NodeList;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};

#[dom_struct]
pub struct HTMLMeterElement {
    htmlelement: HTMLElement
}

impl HTMLMeterElement {
    fn new_inherited(local_name: LocalName,
                     prefix: Option<Prefix>,
                     document: &Document) -> HTMLMeterElement {
        HTMLMeterElement {
            htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(local_name: LocalName,
               prefix: Option<Prefix>,
               document: &Document) -> DomRoot<HTMLMeterElement> {
        Node::reflect_node(box HTMLMeterElement::new_inherited(local_name, prefix, document),
                           document,
                           HTMLMeterElementBinding::Wrap)
    }
}

impl HTMLMeterElementMethods for HTMLMeterElement {
    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
    fn Labels(&self) -> DomRoot<NodeList> {
        self.upcast::<HTMLElement>().labels()
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>App Engine Python SDK: google.appengine._internal.django.core.serializers.base.DeserializedObject Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="common.css" rel="stylesheet" type="text/css"/>

App Engine Python SDK
    v1.6.9 rev.445

The Python runtime is available as an experimental Preview feature.

google

appengine

_internal

django

core

serializers

base

DeserializedObject

Public Member Functions |
Public Attributes |
List of all members

google.appengine._internal.django.core.serializers.base.DeserializedObject Class Reference

Inheritance diagram for google.appengine._internal.django.core.serializers.base.DeserializedObject:

  <map id="google.appengine._internal.django.core.serializers.base.DeserializedObject_map" name="google.appengine._internal.django.core.serializers.base.DeserializedObject_map">
</map>

Public Member Functions

def 	__init__

def 	__repr__

def 	save

Public Attributes

 	object

 	m2m_data

Detailed Description

A deserialized model.

Basically a container for holding the pre-saved deserialized data along
with the many-to-many data saved with the object.

Call ``save()`` to save the object (with the many-to-many data) to the
database; call ``save(save_m2m=False)`` to save just the object fields
(and not touch the many-to-many stuff.)

The documentation for this class was generated from the following file:

code/googleappengine-read-only/python/google/appengine/_internal/django/core/serializers/base.py

<address class="footer">
    Maintained by tzmartin
</address>


text:
class ErrorsController < ApplicationController
  skip_before_action :authenticate_user!

  def error_500
    raise '500'
  end

  #def error_404
  #  raise ActiveRecord::RecordNotFound
  #end
end


text:
import omr from 'ovh-mail-redirection'

class Data {

  constructor() {
    this.domains = []
    this.redirections = []

    this.readDomainsFromStorage()
    this.readRedirectionsFromStorage()

    return this
  }

  //
  // DOMAINS
  //

  getDomains() {
    return this.domains
  }

  setDomains(domains) {
    this.domains = domains
    this.writeDomainsToStorage()
  }

  readDomainsFromStorage() {
    let domains = JSON.parse(window.localStorage.getItem('domains'))

    // Ensure a sensible default
    this.domains = domains || []
  }

  writeDomainsToStorage() {
    window.localStorage.setItem('domains', JSON.stringify(this.domains))
  }

  updateDomainsFromServer(callback) {
    let _this = this

    omr.listDomains(function (err, domains) {
      if (err) {
        console.log(err)
      } else {
        _this.setDomains(domains)
      }

      callback(null, _this.domains)
    })
  }

  //
  // REDIRECTIONS
  //

  getRedirections(domain) {
    if (this.redirections[domain]) {
      return this.redirections[domain]
    }

    return []
  }

  setRedirections(domain, redirections) {
    this.redirections[domain] = redirections
    this.writeRedirectionToStorage(domain)
  }

  readRedirectionsFromStorage() {
    let _this = this

    this.domains.map((domain) => {
      let redirections = JSON.parse(window.localStorage.getItem(domain))

      // Ensure a sensible default
      _this.redirections[domain] = redirections || []
    })
  }

  writeRedirectionToStorage(domain) {
    if (this.redirections[domain]) {
      window.localStorage.setItem(domain, JSON.stringify(this.redirections[domain]))
    }
  }

  writeRedirectionsToStorage() {
    let _this = this

    this.domains.map((domain) => {
      _this.writeRedirectionToStorage(domain)
    })
  }

  updateAllRedirectionsFromServer(callback) {
    let _this = this;
    const domainLength = row.length;

    this.domains.map((domain, i) => {
      _this.updateRedirectionsFromServer(domain, (err, redirections) => {
        if (domainLength === i + 1) {
          callback();
        }
      })
    })
  }

  updateRedirectionsFromServer(domain, callback) {
    let _this = this

    omr.listRedirections(domain, function (err, redirections) {
      if (err) {
        console.log(err)
      } else {
        _this.setRedirections(domain, redirections)
      }

      callback(null, _this.redirections[domain])
    })
  }
}

export default Data


text:
@interface HappinessViewController() <FaceViewDataSource>
@property (nonatomic, weak) IBOutlet FaceView *faceView;

@end

@implementation HappinessViewController

@synthesize happiness = _happiness;
@synthesize faceView = _faceView;

- (void) setHappiness:(int)happiness
{
    if (happiness > 100) {
        happiness = 100;
    }
    if (happiness < 0) {
        happiness = 0;
    }
    _happiness = happiness;

    //every time set happiness, redraw
    [self.faceView setNeedsDisplay];
}

- (void) setFaceView:(FaceView *)faceView
{
    _faceView = faceView;
    [self.faceView addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self.faceView action:@selector(handlePinch:)]];
    [self.faceView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleHappinessGesture:)]];
    //delegate
    self.faceView.datasource = self;
}

//protocol method
- (float) smailForFace:(FaceView *)sender
{
    return (self.happiness - 50) / 50.0;
}

- (void) handleHappinessGesture:(UIPanGestureRecognizer *) gestrue
{
    if (gestrue.state == UIGestureRecognizerStateChanged ||
        gestrue.state == UIGestureRecognizerStateEnded) {
        CGPoint translation = [gestrue translationInView:self.faceView];
        self.happiness -= translation.y / 2;
        [gestrue setTranslation:CGPointZero inView:self.faceView];
    }
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

- (BOOL) shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

@end


text:
// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package systemd provides modules for watching the status of a systemd unit.
package systemd // import "barista.run/modules/systemd"

import (
	"strings"
	"time"

	"barista.run/bar"
	"barista.run/base/value"
	"barista.run/base/watchers/dbus"
	"barista.run/base/watchers/localtz"
	"barista.run/outputs"
	"barista.run/timing"

	systemdbus "github.com/coreos/go-systemd/v22/dbus"
)

// State represents possible states of a systemd unit.
type State string

const (
	// StateUnknown indicates an unknown unit state.
	StateUnknown = State("")
	// StateActive indicates that unit is active.
	StateActive = State("active")
	// StateReloading indicates that the unit is active and currently reloading
	// its configuration.
	StateReloading = State("reloading")
	// StateInactive indicates that it is inactive and the previous run was
	// successful or no previous run has taken place yet.
	StateInactive = State("inactive")
	// StateFailed indicates that it is inactive and the previous run was not
	// successful.
	StateFailed = State("failed")
	// StateActivating indicates that the unit has previously been inactive but
	// is currently in the process of entering an active state.
	StateActivating = State("activating")
	// StateDeactivating indicates that the unit is currently in the process of
	// deactivation.
	StateDeactivating = State("deactivating")
)

// UnitInfo includes common information present in both services and timers.
type UnitInfo struct {
	ID          string
	Description string
	State       State
	SubState    string
	Since       time.Time
	// DBus 'call' method to control the unit.
	call func(string, ...interface{}) ([]interface{}, error)
}

// Start enqeues a start job, and possibly depending jobs.
func (u UnitInfo) Start() {
	u.call("Start", "fail")
}

// Stop stops the specified unit rather than starting it.
func (u UnitInfo) Stop() {
	u.call("Stop", "fail")
}

// Restart restarts a unit. If a service is restarted that isn't running it will
// be started.
func (u UnitInfo) Restart() {
	u.call("Restart", "fail")
}

// Reload reloads a unit. Reloading is done only if the unit is already running
// and fails otherwise.
func (u UnitInfo) Reload() {
	u.call("Reload", "fail")
}

// replaced in tests.
var busType = dbus.System

func watchUnit(unitName string) *dbus.PropertiesWatcher {
	escapedName := systemdbus.PathBusEscape(unitName)
	unitPath := "/org/freedesktop/systemd1/unit/" + escapedName
	return dbus.WatchProperties(busType,
		"org.freedesktop.systemd1", unitPath, "org.freedesktop.systemd1.Unit").
		Add("ActiveState", "SubState", "Id", "Description").
		FetchOnSignal("StateChangeTimestamp")
}

// ServiceInfo represents the state of a systemd service.
type ServiceInfo struct {
	UnitInfo
	Type    string
	ExecPID uint32
	MainPID uint32
}

// ServiceModule watches a systemd service and updates on status change
type ServiceModule struct {
	name       string
	outputFunc value.Value
}

// Service creates a module that watches the status of a systemd service.
func Service(name string) *ServiceModule {
	s := &ServiceModule{name: name}
	s.Output(func(i ServiceInfo) bar.Output {
		if i.Since.IsZero() {
			return outputs.Textf("%s (%s)", i.State, i.SubState)
		}
		since := i.Since.Format("15:04")
		if timing.Now().Add(-24 * time.Hour).After(i.Since) {
			since = i.Since.Format("Jan 2")
		}
		return outputs.Textf("%s (%s) since %s", i.State, i.SubState, since)
	})
	return s
}

// Output configures a module to display the output of a user-defined function.
func (s *ServiceModule) Output(outputFunc func(ServiceInfo) bar.Output) *ServiceModule {
	s.outputFunc.Set(outputFunc)
	return s
}

const serviceIface = "org.freedesktop.systemd1.Service"

// Stream starts the module.
func (s *ServiceModule) Stream(sink bar.Sink) {
	w := watchUnit(s.name + ".service")
	defer w.Unsubscribe()

	w.FetchOnSignal(
		serviceIface+".Type",
		serviceIface+".MainPID",
		serviceIface+".ExecMainPID",
	)

	outputFunc := s.outputFunc.Get().(func(ServiceInfo) bar.Output)
	nextOutputFunc, done := s.outputFunc.Subscribe()
	defer done()

	info := getServiceInfo(w)
	for {
		sink.Output(outputFunc(info))
		select {
		case <-w.Updates:
			info = getServiceInfo(w)
		case <-nextOutputFunc:
			outputFunc = s.outputFunc.Get().(func(ServiceInfo) bar.Output)
		}
	}
}

const usecInSec = 1000 * 1000

func timeFromUsec(usecValue interface{}) time.Time {
	usec, _ := usecValue.(uint64)
	if usec == 0 {
		return time.Time{}
	}
	sec := int64(usec / usecInSec)
	usecOnly := int64(usec % usecInSec)
	return time.Unix(sec, usecOnly*1000 /* nsec */).In(localtz.Get())
}

func getUnitInfo(w *dbus.PropertiesWatcher) (UnitInfo, map[string]interface{}) {
	u := UnitInfo{call: w.Call}
	props := w.Get()
	if s, ok := props["ActiveState"].(string); ok {
		u.State = State(s)
	}
	u.ID, _ = props["Id"].(string)
	u.Description, _ = props["Description"].(string)
	u.SubState, _ = props["SubState"].(string)
	u.Since = timeFromUsec(props["StateChangeTimestamp"])
	return u, props
}

func getServiceInfo(w *dbus.PropertiesWatcher) ServiceInfo {
	i := ServiceInfo{}
	var props map[string]interface{}
	i.UnitInfo, props = getUnitInfo(w)
	i.ID = strings.TrimSuffix(i.ID, ".service")
	if mPid, ok := props[serviceIface+".MainPID"].(uint32); ok {
		i.MainPID = mPid
	}
	if ePid, ok := props[serviceIface+".ExecMainPID"].(uint32); ok {
		i.ExecPID = ePid
	}
	i.Type, _ = props[serviceIface+".Type"].(string)
	return i
}

// TimerInfo represents the state of a systemd timer.
type TimerInfo struct {
	UnitInfo
	Unit        string
	LastTrigger time.Time
	NextTrigger time.Time
}

// TimerModule watches a systemd timer and updates on status change
type TimerModule struct {
	name       string
	outputFunc value.Value
}

// Timer creates a module that watches the status of a systemd timer.
func Timer(name string) *TimerModule {
	t := &TimerModule{name: name}
	t.Output(func(i TimerInfo) bar.Output {
		last := "never"
		if !i.LastTrigger.IsZero() {
			last = i.LastTrigger.Format("Jan 2, 15:04")
		}
		next := "never"
		if !i.NextTrigger.IsZero() {
			next = i.NextTrigger.Format("Jan 2, 15:04")
		}
		return outputs.Textf("%s@%s (last:%s)", i.Unit, next, last)
	})
	return t
}

// Output configures a module to display the output of a user-defined function.
func (t *TimerModule) Output(outputFunc func(TimerInfo) bar.Output) *TimerModule {
	t.outputFunc.Set(outputFunc)
	return t
}

const timerIface = "org.freedesktop.systemd1.Timer"

// Stream starts the module.
func (t *TimerModule) Stream(sink bar.Sink) {
	w := watchUnit(t.name + ".timer")
	defer w.Unsubscribe()

	w.FetchOnSignal(
		timerIface+".Unit",
		timerIface+".LastTriggerUSec",
		timerIface+".NextElapseUSecRealtime",
	)

	outputFunc := t.outputFunc.Get().(func(TimerInfo) bar.Output)
	nextOutputFunc, done := t.outputFunc.Subscribe()
	defer done()

	info := getTimerInfo(w)
	for {
		sink.Output(outputFunc(info))
		select {
		case <-w.Updates:
			info = getTimerInfo(w)
		case <-nextOutputFunc:
			outputFunc = t.outputFunc.Get().(func(TimerInfo) bar.Output)
		}
	}
}

func getTimerInfo(w *dbus.PropertiesWatcher) TimerInfo {
	i := TimerInfo{}
	var props map[string]interface{}
	i.UnitInfo, props = getUnitInfo(w)
	i.ID = strings.TrimSuffix(i.ID, ".timer")
	i.LastTrigger = timeFromUsec(props[timerIface+".LastTriggerUSec"])
	i.NextTrigger = timeFromUsec(props[timerIface+".NextElapseUSecRealtime"])
	i.Unit, _ = props[timerIface+".Unit"].(string)
	return i
}


text:
from __future__ import division

import numpy as np
import six

def generate_anchor_base(base_size=16, ratios=[0.5, 1, 2],
                         anchor_scales=[8, 16, 32]):
    """Generate anchor base windows by enumerating aspect ratio and scales.

    Generate anchors that are scaled and modified to the given aspect ratios.
    Area of a scaled anchor is preserved when modifying to the given aspect
    ratio.

    :obj:`R = len(ratios) * len(anchor_scales)` anchors are generated by this
    function.
    The :obj:`i * len(anchor_scales) + j` th anchor corresponds to an anchor
    generated by :obj:`ratios[i]` and :obj:`anchor_scales[j]`.

    For example, if the scale is :math:`8` and the ratio is :math:`0.25`,
    the width and the height of the base window will be stretched by :math:`8`.
    For modifying the anchor to the given aspect ratio,
    the height is halved and the width is doubled.

    Args:
        base_size (number): The width and the height of the reference window.
        ratios (list of floats): This is ratios of width to height of
            the anchors.
        anchor_scales (list of numbers): This is areas of anchors.
            Those areas will be the product of the square of an element in
            :obj:`anchor_scales` and the original area of the reference
            window.

    Returns:
        ~numpy.ndarray:
        An array of shape :math:`(R, 4)`.
        Each element is a set of coordinates of a bounding box.
        The second axis corresponds to
        :math:`(y_{min}, x_{min}, y_{max}, x_{max})` of a bounding box.

    """
    py = base_size / 2.
    px = base_size / 2.

    anchor_base = np.zeros((len(ratios) * len(anchor_scales), 4),
                           dtype=np.float32)
    for i in six.moves.range(len(ratios)):
        for j in six.moves.range(len(anchor_scales)):
            h = base_size * anchor_scales[j] * np.sqrt(ratios[i])
            w = base_size * anchor_scales[j] * np.sqrt(1. / ratios[i])

            index = i * len(anchor_scales) + j
            anchor_base[index, 0] = py - h / 2.
            anchor_base[index, 1] = px - w / 2.
            anchor_base[index, 2] = py + h / 2.
            anchor_base[index, 3] = px + w / 2.
    return anchor_base


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.javacourse</groupId>
    <artifactId>dwr</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>DWR</name>

    <modules>
        <module>DWRExample-N01</module>
    </modules>

</project>


text:
<?php

defined('_JEXEC') or die('RESTRICTED');

wfimport('editor.libraries.classes.extensions');

class WFPopupsExtension extends WFExtension {

    protected static $instance;

    private $_popups = array();
    private $_templates = array();

    /**
     * Constructor activating the default information of the class
     *
     * @access  protected
     */
    public function __construct($config = array()) {
        parent::__construct($config);

        $this->setProperties($config);
    }

    /**
     * Returns a reference to a plugin object
     *
     * This method must be invoked as:
     *
  $advlink =AdvLink::getInstance();

     *
     * @access  public
     * @return  JCE  The editor object.
     * @since 1.5
     */
    public static function getInstance($config = array()) {
        if (!isset(self::$instance)) {
            self::$instance = new WFPopupsExtension($config);
        }

        return self::$instance;
    }

    public function display() {
        parent::display();

        $document = WFDocument::getInstance();

        // Load javascript
        $document->addScript(array(
            'popups'
        ), 'libraries.extensions');

        // get all popups extensions
        $popups = parent::loadExtensions('popups');

        $config = $this->getProperties();

        if ($config) {
            // Create global config
            $document->addScriptDeclaration('WFExtensions.Popups.setConfig(' . json_encode($config) . ');');
        }

        // Create an instance of each popup and check if enabled
        foreach ($popups as $name) {
            $popup = $this->getPopupExtension($name);

            if ($popup->isEnabled()) {
                $this->addPopup($name);

                $params = $popup->getParams();

                if (!empty($params)) {
                    $document->addScriptDeclaration('WFExtensions.Popups.setParams("' . $name . '",' . json_encode($params) . ');');
                }
            }
        }

        $tabs = WFTabs::getInstance();

        // Add popup tab and assign popups reference to document
        if (count($this->getPopups())) {
            $tabs->addTab('popups', 1);
            $tabs->getPanel('popups')->assign('popups', $this);
        }
    }

    private function getPopups() {
        return $this->_popups;
    }

    public function addPopup($popup) {
        $this->_popups[] = $popup;
    }

    private function getTemplates() {
        return $this->_templates;
    }

    public function addTemplate($template) {
        $this->_templates[] = $template;
    }

    private function getPopupExtension($name) {
        static $popups;

        if (!isset($popups)) {
            $popups = array();
        }

        if (empty($popups[$name])) {
            $classname = 'WFPopupsExtension_' . ucfirst($name);

            $popups[$name] = new $classname();
        }

        return $popups[$name];
    }

    public function getPopupList() {
        $options = array();

        $options[] = JHTML::_('select.option', '', '-- ' . WFText::_('WF_POPUP_TYPE_SELECT') . ' --');

        foreach ($this->getPopups() as $popup) {
            $options[] = JHTML::_('select.option', $popup, WFText::_('WF_POPUPS_' . strtoupper($popup) . '_TITLE'));
        }

        return JHTML::_('select.genericlist', $options, 'popup_list', 'class="inputbox levels" size="1"', 'value', 'text', $this->get('default'));
    }

    public function getPopupTemplates() {
        $output = '';

        $path = WF_EDITOR_EXTENSIONS . '/popups';

        $file = 'default.php';

        foreach ($this->getTemplates() as $template) {
            $wf = WFEditorPlugin::getInstance();
            $view = $wf->getView();

            $output .= $view->loadTemplate($template);
        }

        foreach ($this->getPopups() as $popup) {
            $view = new WFView(array(
                        'name' => $popup,
                        'base_path' => WF_EDITOR_EXTENSIONS . '/popups/' . $popup,
                        'template_path' => WF_EDITOR_EXTENSIONS . '/popups/' . $popup . '/tmpl'
                    ));

            $instance = $this->getPopupExtension($popup);
            $view->assign('popup', $instance);

            if (file_exists($path . '/' . $popup . '/tmpl/' . $file)) {
                ob_start();

                $output .= '
';

                $view->display();

                $output .= ob_get_contents();
                $output .= '
';
                ob_end_clean();
            }
        }

        return $output;
    }

}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows.Documents
{
  public partial class Span : Inline
  {
    #region Methods and constructors
    public bool ShouldSerializeInlines(System.Windows.Markup.XamlDesignerSerializationManager manager)
    {
      return default(bool);
    }

    public Span()
    {
    }

    public Span(TextPointer start, TextPointer end)
    {
    }

    public Span(Inline childInline)
    {
    }

    public Span(Inline childInline, TextPointer insertionPosition)
    {
    }
    #endregion

    #region Properties and indexers
    public InlineCollection Inlines
    {
      get
      {
        Contract.Ensures(Contract.Result<System.Windows.Documents.InlineCollection>() != null);

        return default(InlineCollection);
      }
    }
    #endregion
  }
}


text:
class PaginatedArray < Array
  attr_reader :total_count, :current_page,  :per_page

  def initialize(total_count, current_page, per_page)
    @total_count = total_count
    @current_page = current_page
    @per_page = per_page
    super()
  end

  def total_page
    (total_count.fdiv(per_page)).ceil
  end

  def next_page
    next_page = current_page + 1
    next_page <= total_page ? next_page : false
  end

  def previous_page
    previous_page = current_page - 1
    previous_page > 0  ? previous_page : false
  end
end


text:
package org.openengsb.trac;

import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcException;
import org.openengsb.drools.IssuesDomain;
import org.openengsb.drools.model.Issue;
import org.openengsb.trac.constants.TracFieldConstants;
import org.openengsb.trac.constants.TracPriorityConstants;
import org.openengsb.trac.constants.TracStatusConstants;
import org.openengsb.trac.xmlrpc.Ticket;

public class TracConnector implements IssuesDomain {
    private Log log = LogFactory.getLog(getClass());

    private Ticket ticket;

    @Override
    public String createIssue(Issue issue) {
        Hashtable<String, String> attributes = generateAttributes(issue);
        String issueId = "-1";

        try {
            issueId = ticket.create(issue.getSummary(), issue.getDescription(), attributes).toString();
            log.info("Successfully created issue " + issue.getSummary() + ", ID is: " + issueId + ".");
        } catch (XmlRpcException e) {
            log.error("Error creating issue " + issue.getSummary() + ". XMLRPC call failed.");
        }

        return issueId;
    }

    @Override
    public void updateIssue(String id, String comment, Map<String, Object> changes) {
        Hashtable<String, String> attributes = translateChanges(changes);
        if (comment == null || comment.equals("")) {
            comment = "[No comment added by author]";
        }

        try {
            ticket.update(Integer.valueOf(id), comment, attributes);
            log.info("Successfully updated issue " + id + " with " + changes.size() + " changes.");
        } catch (XmlRpcException e) {
            log.error("Error updating issue " + id + ". XMLRPC call failed.");
        } catch (NumberFormatException e) {
            log.error("Error updating issue " + id + ". invalid id.", e);
        }
    }

    @Override
    public void deleteIssue(String id) {
        try {
            ticket.delete(Integer.valueOf(id));
            log.info("Successfully deleted issue " + id + ".");
        } catch (XmlRpcException e) {
            log.error("Error deleting issue " + id + ". XMLRPC call failed.");
        } catch (NumberFormatException e) {
            log.error("Error updating issue " + id + ". invalid id.", e);
        }
    }

    @Override
    public void addComment(String id, String comment) {
        try {
            ticket.update(Integer.valueOf(id), comment);
            log.info("Successfully added comment to issue " + id + ".");
        } catch (XmlRpcException e) {
            log.error("Error adding comment to issue " + id + ". XMLRPC call failed.");
        } catch (NumberFormatException e) {
            log.error("Error updating issue " + id + ". invalid id.", e);
        }
    }

    private Hashtable<String, String> generateAttributes(Issue issue) {
        Hashtable<String, String> attributes = new Hashtable<String, String>();

        if (issue.getOwner() != null) {
            attributes.put(TracFieldConstants.FIELD_OWNER, issue.getOwner());
        }
        if (issue.getReporter() != null) {
            attributes.put(TracFieldConstants.FIELD_REPORTER, issue.getReporter());
        }

        addPriority(attributes, issue.getPriority());
        addStatus(attributes, issue.getStatus());

        return attributes;
    }

    private Hashtable<String, String> translateChanges(Map<String, Object> changes) {
        Hashtable<String, String> attributes = new Hashtable<String, String>();

        for (String field : changes.keySet()) {
            try {
                if (field.equals(Issue.fieldDESCRIPTION)) {
                    attributes.put(TracFieldConstants.FIELD_DESCRIPTION, (String) changes.get(field));
                } else if (field.equals(Issue.fieldOWNER)) {
                    attributes.put(TracFieldConstants.FIELD_OWNER, (String) changes.get(field));
                } else if (field.equals(Issue.fieldREPORTER)) {
                    attributes.put(TracFieldConstants.FIELD_REPORTER, (String) changes.get(field));
                } else if (field.equals(Issue.fieldSUMMARY)) {
                    attributes.put(TracFieldConstants.FIELD_SUMMARY, (String) changes.get(field));
                } else if (field.equals(Issue.fieldPRIORITY)) {
                    addPriority(attributes, (String) changes.get(field));
                } else if (field.equals(Issue.fieldSTATUS)) {
                    addStatus(attributes, (String) changes.get(field));
                }
            } catch (ClassCastException e) {
                log.error("Wrong value provided for field " + field + ": " + changes.get(field).getClass().getName());
            }
        }

        return attributes;
    }

    private void addPriority(Hashtable<String, String> attributes, String priority) {
        if (priority != null) {
            if (priority.equals(Issue.priorityHIGH)) {
                attributes.put(TracFieldConstants.FIELD_PRIORITY, TracPriorityConstants.PRIORITY_HIGH);
            } else if (priority.equals(Issue.priorityIMMEDIATE)) {
                attributes.put(TracFieldConstants.FIELD_PRIORITY, TracPriorityConstants.PRIORITY_IMMEDIATE);
            } else if (priority.equals(Issue.priorityLOW)) {
                attributes.put(TracFieldConstants.FIELD_PRIORITY, TracPriorityConstants.PRIORITY_LOW);
            } else if (priority.equals(Issue.priorityNORMAL)) {
                attributes.put(TracFieldConstants.FIELD_PRIORITY, TracPriorityConstants.PRIORITY_NORMAL);
            } else if (priority.equals(Issue.priorityURGENT)) {
                attributes.put(TracFieldConstants.FIELD_PRIORITY, TracPriorityConstants.PRIORITY_URGENT);
            }
        }
    }

    private void addStatus(Hashtable<String, String> attributes, String status) {
        if (status != null) {
            if (status.equals(Issue.statusNEW)) {
                attributes.put(TracFieldConstants.FIELD_STATUS, TracStatusConstants.STATUS_NEW);
            } else if (status.equals(Issue.statusASSIGNED)) {
                attributes.put(TracFieldConstants.FIELD_STATUS, TracStatusConstants.STATUS_ASSIGNED);
            } else if (status.equals(Issue.statusCLOSED)) {
                attributes.put(TracFieldConstants.FIELD_STATUS, TracStatusConstants.STATUS_CLOSED);
            }
        }
    }

    public void setTicket(Ticket ticket) {
        this.ticket = ticket;
    }

}


text:
require "spec_helper"

describe Tmuxinator::Window do
  let(:project) { double }
  let(:panes) { ["vim", nil, "top"] }
  let(:window_name) { "editor" }
  let(:yaml) do
    {
      window_name => {
        "pre" => ["echo 'I get run in each pane.  Before each pane command!'", nil],
        "layout" => "main-vertical",
        "panes" => panes
      }
    }
  end
  let(:yaml_root) do
    {
      "editor" => {
        "root" => "/project/override",
        "root?" => true,
        "pre" => ["echo 'I get run in each pane.  Before each pane command!'", nil],
        "layout" => "main-vertical",
        "panes" => panes
      }
    }
  end

  let(:window) { Tmuxinator::Window.new(yaml, 0, project) }
  let(:window_root) { Tmuxinator::Window.new(yaml_root, 0, project) }

  before do
    allow(project).to receive_messages(
       :tmux => "tmux",
       :name => "test",
       :base_index => 1,
       :root => "/project/tmuxinator",
       :root? => true
     )
  end

  describe "#initialize" do
    it "creates an instance" do
      expect(window).to be_a(Tmuxinator::Window)
    end
  end

  describe "#root" do
    context "without window root" do
      it "gets the project root" do
        expect(window.root).to include("/project/tmuxinator")
      end
    end

    context "with window root" do
      it "gets the window root" do
        expect(window_root.root).to include("/project/override")
      end
    end
  end

  describe "#panes" do
    let(:pane) { double(:pane) }

    before do
      allow(Tmuxinator::Pane).to receive_messages :new => pane
    end

    context "with a three element Array" do
      let(:panes) { ["vim", nil, "top"] }

      it "creates three panes" do
        expect(Tmuxinator::Pane).to receive(:new).exactly(3).times
        window.panes
      end

      it "returns three panes" do
        expect(window.panes).to eql [pane, pane, pane]
      end
    end

    context "with a String" do
      let(:panes) { "vim" }

      it "creates one pane" do
        expect(Tmuxinator::Pane).to receive(:new).once
        window.panes
      end

      it "returns one pane in an Array" do
        expect(window.panes).to eql [pane]
      end
    end

    context "with nil" do
      let(:panes) { nil }

      it "doesn't create any panes" do
        expect(Tmuxinator::Pane).to_not receive(:new)
        window.panes
      end

      it "returns an empty Array" do
        expect(window.panes).to be_empty
      end
    end
  end

  describe "#pre" do
    context "pre is a string" do
      before do
        yaml["editor"]["pre"] = "vim"
      end

      it "returns the pre command" do
        expect(window.pre).to eq "vim"
      end
    end

    context "pre is not present" do
      before do
        yaml["editor"].delete("pre")
      end

      it "returns nil" do
        expect(window.pre).to be_nil
      end
    end
  end

  describe "#build_commands" do
    context "command is an array" do
      before do
        yaml["editor"] = ["git fetch", "git status"]
      end

      it "returns the flattened command" do
        expect(window.commands).to eq ["tmux send-keys -t test:1 git\\ fetch C-m", "tmux send-keys -t test:1 git\\ status C-m"]
      end
    end

    context "command is a string" do
      before do
        yaml["editor"] = "vim"
      end

      it "returns the command" do
        expect(window.commands).to eq ["tmux send-keys -t test:1 vim C-m"]
      end
    end

    context "command is empty" do
      before do
        yaml["editor"] = ""
      end

      it "returns an empty array" do
        expect(window.commands).to be_empty
      end
    end
  end

  describe "#name_options" do
    context "with a name" do
      let(:window_name) { "editor" }

      it "specifies name with tmux name option" do
        expect(window.tmux_window_name_option).to eq "-n #{window_name}"
      end
    end

    context "without a name" do
      let(:window_name) { nil }

      it "specifies no tmux name option" do
        expect(window.tmux_window_name_option).to be_empty
      end
    end
  end

  describe "#tmux_new_window_command" do
    let(:project) { double(:project) }
    let(:window) { Tmuxinator::Window.new(yaml, 0, project) }
    let(:root?) { true }
    let(:root) { "/project/tmuxinator" }

    before do
      allow(project).to receive_messages(
        :name => "test",
        :tmux => "tmux",
        :root => root,
        :root? => root?,
        :base_index => 1
      )
    end

    let(:tmux_part) { project.tmux }
    let(:window_part) { "new-window" }
    let(:name_part) { window.tmux_window_name_option }
    let(:target_part) { "-t #{window.tmux_window_target}" }
    let(:path_part) { "#{path_option} #{project.root}" }

    let(:path_option) { "-c" }
    let(:full_command) { "#{tmux_part} #{window_part} #{path_part} #{target_part} #{name_part}" }

    before do
      allow(Tmuxinator::Config).to receive(:default_path_option) { path_option }
    end

    it "contstructs window command with path, target, and name options" do
      expect(window.tmux_new_window_command).to eq full_command
    end

    context "root not set" do
      let(:root?) { false }
      let(:root) { nil }

      let(:path_part) { nil }

      it "has an extra space instead of path_part" do
        expect(window.tmux_new_window_command).to eq full_command
      end
    end

    context "name not set" do
      let(:window_name) { nil }
      let(:full_command) { "#{tmux_part} #{window_part} #{path_part} #{target_part} " }

      it "does not set name option" do
        expect(window.tmux_new_window_command).to eq full_command
      end
    end
  end
end


text:
import { beforeEach, describe, it } from '@ephox/bedrock-client';
import { Fun } from '@ephox/katamari';
import { TinyHooks, TinyUiActions } from '@ephox/wrap-mcagar';

import Editor from 'tinymce/core/api/Editor';
import { DataToHtmlCallback } from 'tinymce/plugins/media/core/DataToHtml';
import Plugin from 'tinymce/plugins/media/Plugin';

import * as Utils from '../module/test/Utils';

describe('browser.tinymce.plugins.media.core.SubmitTest', () => {
  const hook = TinyHooks.bddSetupLight<Editor>({
    plugins: [ 'media' ],
    toolbar: 'media',
    base_url: '/project/tinymce/js/tinymce'
  }, [ Plugin ]);

  const mediaUrlResolver = (data: { url: string }, resolve: (data: { html: string }) => void) => {
    setTimeout(() => {
      resolve({
        html: '' + data.url + ''
      });
    }, 500);
  };

  const customEmbed =
  '
' +
  '' +
  '
';

  const pTestResolvedEmbedContentSubmit = async (editor: Editor, url: string, expected: string) => {
    await Utils.pOpenDialog(editor);
    await Utils.pSetFormItemNoEvent(editor, url);
    TinyUiActions.submitDialog(editor);
    await Utils.pAssertEditorContent(editor, expected);
  };

  const pTestManualEmbedContentSubmit = async (editor: Editor, embed: string, expected: string) => {
    await Utils.pOpenDialog(editor);
    await Utils.pPasteTextareaValue(editor, embed);
    TinyUiActions.submitDialog(editor);
    await Utils.pAssertEditorContent(editor, expected);
  };

  const pTestEmbedUnchangedAfterOpenCloseDialog = async (editor: Editor, expected: string) => {
    await Utils.pOpenDialog(editor);
    TinyUiActions.submitDialog(editor);
    await Utils.pAssertEditorContent(editor, expected);
  };

  const pTestTemplateCallbackContentSubmit = async (editor: Editor, templateOption: string, templateCallback: DataToHtmlCallback, url: string, expected: string) => {
    editor.options.set(templateOption, templateCallback);
    await Utils.pOpenDialog(editor);
    await Utils.pPasteSourceValue(editor, url);
    TinyUiActions.submitDialog(editor);
    await Utils.pAssertEditorContent(editor, expected);
    editor.options.unset(templateOption);
  };

  beforeEach(() => {
    hook.editor().setContent('');
  });

  it('TBA: Open dialog, set url, submit dialog and assert content', async () => {
    const editor = hook.editor();
    editor.options.set('media_url_resolver', mediaUrlResolver);
    await pTestResolvedEmbedContentSubmit(editor,
      'https://www.youtube.com/watch?v=IcgmSRJHu_8',
      '
https://www.youtube.com/watch?v=IcgmSRJHu_8
'
    );
  });

  it('TBA: Remove media_url_resolver setting and assert changed content', async () => {
    const editor = hook.editor();
    editor.options.unset('media_url_resolver');
    await pTestResolvedEmbedContentSubmit(editor,
      'https://www.youtube.com/watch?v=IcgmSRJHu_8',
      '

'
    );
  });

  it('TBA: Open dialog, set embed content, submit dialog and assert content', async () => {
    const editor = hook.editor();
    editor.options.set('media_url_resolver', mediaUrlResolver);
    await pTestManualEmbedContentSubmit(editor, customEmbed, customEmbed);
    editor.options.unset('media_url_resolver');
    await pTestEmbedUnchangedAfterOpenCloseDialog(editor, customEmbed);
  });

  it('TBA: Set audio_template_callback and embed content, submit dialog and assert content', async () => {
    // Audio should be any mp3 link to trigger callback
    const editor = hook.editor();
    const audioTemplateCallback = Fun.constant('<audio id="template" controls="controls"><source src="https://assets.mixkit.co/music/preview/mixkit-tech-house-vibes-130.mp3"></audio>');
    const expected = '
<audio id="template" controls="controls"><source src="https://assets.mixkit.co/music/preview/mixkit-tech-house-vibes-130.mp3"></audio>
';
    await pTestTemplateCallbackContentSubmit(editor, 'audio_template_callback', audioTemplateCallback, 'https://assets.mixkit.co/music/preview/mixkit-tech-house-vibes-130.mp3', expected);
    await pTestEmbedUnchangedAfterOpenCloseDialog(editor, expected);
  });

  it('TBA: Set video_template_callback and embed content, submit dialog and assert content', async () => {
    // Video should be any mp4 link to trigger callback
    const editor = hook.editor();
    const videoTemplateCallback = Fun.constant('<video id="template" controls="controls" width="500" height="300" ><source src="https://i.imgur.com/Tu4e5WX.mp4"></video>');
    const expected = '
<video id="template" controls="controls" width="500" height="300"><source src="https://i.imgur.com/Tu4e5WX.mp4"></video>
';
    await pTestTemplateCallbackContentSubmit(editor, 'video_template_callback', videoTemplateCallback, 'https://i.imgur.com/Tu4e5WX.mp4', expected);
    await pTestEmbedUnchangedAfterOpenCloseDialog(editor, expected);
  });

  it('TINY-8684: Set iframe_template_callback and embed content, submit dialog and assert content', async () => {
    // Any youtube link triggers iframe callback
    const editor = hook.editor();
    const iframeTemplateCallback = Fun.constant('');
    const expected = '

';
    await pTestTemplateCallbackContentSubmit(editor, 'iframe_template_callback', iframeTemplateCallback, 'https://www.youtube.com/embed/IcgmSRJHu_8', expected);
    await pTestEmbedUnchangedAfterOpenCloseDialog(editor, expected);
  });
});


text:
<?php declare(strict_types = 1);

namespace Dms\Web\Laravel\Renderer\Widget;

use Dms\Core\Module\IParameterizedAction;
use Dms\Core\Widget\ActionWidget;
use Dms\Core\Widget\IWidget;
use Dms\Web\Laravel\Http\ModuleContext;
use Dms\Web\Laravel\Renderer\Form\ActionFormRenderer;
use Dms\Web\Laravel\Util\KeywordTypeIdentifier;

/**
 * The widget renderer for parameterized actions.
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class ParameterizedActionWidgetRenderer extends WidgetRenderer
{
    /**
     * @var KeywordTypeIdentifier
     */
    protected $keywordTypeIdentifier;

    /**
     * @var ActionFormRenderer
     */
    protected $actionFormRenderer;

    /**
     * ParameterizedActionWidgetRenderer constructor.
     *
     * @param KeywordTypeIdentifier $keywordTypeIdentifier
     * @param ActionFormRenderer    $actionFormRenderer
     */
    public function __construct(KeywordTypeIdentifier $keywordTypeIdentifier, ActionFormRenderer $actionFormRenderer)
    {
        $this->keywordTypeIdentifier = $keywordTypeIdentifier;
        $this->actionFormRenderer    = $actionFormRenderer;
    }

    /**
     * Returns whether this renderer can render the supplied widget.
     *
     * @param ModuleContext $moduleContext
     * @param IWidget       $widget
     *
     * @return bool
     */
    public function accepts(ModuleContext $moduleContext, IWidget $widget) : bool
    {
        return $widget instanceof ActionWidget
        && $widget->getAction() instanceof IParameterizedAction;
    }

    /**
     * Gets an array of links for the supplied widget.
     *
     * @param ModuleContext $moduleContext
     * @param IWidget       $widget
     *
     * @return array
     */
    protected function getWidgetLinks(ModuleContext $moduleContext, IWidget $widget) : array
    {
        return [];
    }

    /**
     * Renders the supplied widget input as a html string.
     *
     * @param ModuleContext $moduleContext
     * @param IWidget       $widget
     *
     * @return string
     */
    protected function renderWidget(ModuleContext $moduleContext, IWidget $widget) : string
    {
        /** @var ActionWidget $widget */
        $action = $widget->getAction();

        return view('dms::components.widget.parameterized-action')
            ->with([
                'action'            => $action,
                'actionFormContent' => $this->actionFormRenderer->renderActionForm($moduleContext, $action),
            ])
            ->render();
    }
}


text:
import FSelection from './FSelection';
import FScene from './FScene';
import FGroupMember from './FGroupMember';
import FGroup from './FGroup';
import FObject from './FObject';

window.FL = {};

window.FL.FObject = FObject;
window.FL.FGroup = FGroup;
window.FL.FScene = FScene;
window.FL.FSelection = FSelection;
window.FL.FGroupMember = FGroupMember;


text:
[![Build Status](https://travis-ci.org/grdme/grd.me-server.svg)](https://travis-ci.org/grdme/grd.me-server)

Grd Me Server
=============

This is the server that handles message routing and key management for [Grd Me](https://github.com/grdme/grd.me).

Grd Me (/ɡärd mē/) is an open source browser plugin that provides encrypted communication across any web platform.  We support aes and ecc. Available at https://grd.me.

Documentation
==============
Documentation regarding API protocols, push protocols, and testing is located [in the wiki](https://github.com/grdme/grd.me-server/wiki).

Dev Setup
==============
### 1. Install
This project uses a Vagrant virtual machine to ensure a homogeneous dev environment and simplify the installation of packages & dependancies.
To use vagrant, you must have vagrant and virtual box installed:

Install Vagrant <https://www.vagrantup.com/downloads.html>

Install Virtual Box <https://www.virtualbox.org/wiki/Downloads>

Clone this repository to your machine.
### 2. Start Vagrant
From the root directory of this repository, run:
```bash
$ vagrant up
```
This will create the virtual machine and install all the required packages / dependancies.

Next, run:
```bash
$ vagrant ssh
```
This will start an ssh session into the virtual machine.

Enter the project directory:
```bash
$ cd /vagrant
```
This is a synced directory with the project folder on your host machine. Any changes here will appear on your host machine and vice-versa.
### 3. Serving & Testing
To start the server, run the following commands in /vagrant on the virtual machine:
```bash
$ npm install
$ npm start
```
To run tests, run:
```bash
$ npm install
$ npm test
```
### 4. Stopping Vagrant
To stop gracefully, run the following from the project directory on your actual machine (not the virtual machine):
```bash
$ vagrant halt
```
To remove all traces of the Vagrant vm, run:
```bash
$ vagrant destroy
```

Cryptography Notice
======================

This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software.
BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted.
See <http://www.wassenaar.org/> for more information.

The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1, which includes information security software using or performing cryptographic functions with asymmetric algorithms.
The form and manner of this distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code.


text:
/* jQuery to fetch the files from firebase */

/**
 * these codes change the object id to server the correct file.
 */
$(document).ready(function() {
  let urlpart = document.URL.split('?')
  $('#object').attr('src', urlpart[1]+'?'+urlpart[2]);
  $('#material').attr('src', urlpart[3]+'?'+urlpart[4]);
})


text:
<?php

/**
 * The generic interface to create a plural form of a name.
 *
 * @author     Hans Lellelid <hans@xmpl.org>
 * @version    $Revision: 1262 $
 * @package    propel.engine.generator
 */
interface Pluralizer {

	/**
	 * Generate a plural name based on the passed in root.
	 * @param      string $root The root that needs to be pluralized (e.g. Author)
	 * @return     string The plural form of $root.
	 */
	public function getPluralForm($root);

}


text:
from bs4 import BeautifulSoup
import urllib2
import re

tao = urllib2.urlopen("http://leocharre.com/wp-content/uploads/tao_te_ching_translated_by_wing_tsit_chan.html")
tao_html = tao.read()
tao.close()

soup = BeautifulSoup(tao_html)

lines = re.split('(\d+.\d)', soup.get_text())[1:]
print lines

f = open('taoteching.txt', 'w')

cur = 0
for i, line in enumerate(lines):
    if len(line) == 0: continue # skip empty strings
    if i % 2 == 0:              # even lines are chapter numbers
        chapter = int(float(line))
        if cur != chapter:
            f.write('\n' + str(chapter) + '\n')
            cur = chapter
    else:
        f.write(line.strip().replace('\n', ' ') + '\n')

f.close()


text:
const router = require("express").Router();
const controller = require("../controllers/searchCtrl");

router.get("/allshops", controller.getAllShops);
router.get("/getshop", controller.getShop);
module.exports = router;


text:
package com.jfsoft.mapper;

import com.jfsoft.model.SysRolemenu;

public interface SysRolemenuMapper {

    int insert(SysRolemenu record);

    int insertSelective(SysRolemenu record);

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.lodz.p.edu.ftims.poi.poi.entities;

import java.util.Date;
import java.util.Objects;

import javax.persistence.GeneratedValue;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 *
 * @author lwieczor
 */
@Document
public class History {

    @Id
    @GeneratedValue
    private String ID;

    @DBRef
    private Department oddzial;

    @DBRef
    private Package pack;

    private Date date;

    public History() {
    }

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public Department getOddzial() {
        return oddzial;
    }

    public void setOddzial(Department oddzial) {
        this.oddzial = oddzial;
    }

    public Package getPack() {
        return pack;
    }

    public void setPack(Package pack) {
        this.pack = pack;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 67 * hash + Objects.hashCode(this.ID);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final History other = (History) obj;
        return Objects.equals(this.ID, other.ID);
    }

}


text:
package org.pentaho.di.core;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

import org.pentaho.di.core.row.RowMetaInterface;

/**
 * A simplified rowset for steps for single threaded execution. This row set has no limited size.
 *
 * @author matt
 */
public class QueueRowSet extends BaseRowSet implements Comparable<RowSet>, RowSet {

  private LinkedList<Object[]> buffer;

  public QueueRowSet() {
    buffer = new LinkedList<Object[]>();
  }

  @Override
  public Object[] getRow() {
    Object[] retRow = buffer.pollFirst();
    return retRow;
  }

  @Override
  public Object[] getRowImmediate() {
    return getRow();
  }

  @Override
  public Object[] getRowWait( long timeout, TimeUnit tu ) {
    return getRow();
  }

  @Override
  public boolean putRow( RowMetaInterface rowMeta, Object[] rowData ) {
    this.rowMeta = rowMeta;
    buffer.add( rowData );
    return true;
  }

  @Override
  public boolean putRowWait( RowMetaInterface rowMeta, Object[] rowData, long time, TimeUnit tu ) {
    return putRow( rowMeta, rowData );
  }

  @Override
  public int size() {
    return buffer.size();
  }

  @Override
  public void clear() {
    buffer.clear();
    done.set( false );
  }

}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.airbnb.android.react.navigation.example">

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
  <application
    android:name=".MainApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
      android:name=".MainActivity"
      android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
      android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
  </application>

</manifest>


text:
. ./config.sh

C1=10.2.1.41
C3=10.2.1.71

launch_all() {
    weave_on $HOST1 launch-router $1
    weave_on $HOST2 launch-router $1 --ipalloc-range="" $HOST1
    weave_on $HOST3 launch-router $1                    $HOST2
}

start_suite "Peer discovery, multi-hop routing and gossip forwarding"

launch_all

start_container $HOST1 $C1/24 --name=c1
start_container $HOST3 $C3/24 --name=c3

assert_raises "exec_on $HOST1 c1 $PING $C3"
stop_router_on $HOST2
assert_raises "exec_on $HOST1 c1 $PING $C3"

stop_router_on $HOST1
stop_router_on $HOST3

launch_all --no-discovery

sleep 5 # give topology gossip some time to propagate

assert_raises "exec_on $HOST1 c1 $PING $C3"

# this stalls if gossip forwarding doesn't work. We wait for slightly
# longer than the gossip interval (30s) before giving up.
assert_raises "timeout 40 cat <( start_container $HOST3 )"

stop_router_on $HOST2
assert_raises "exec_on $HOST1 c1 sh -c '! $PING $C3'"

end_suite


text:
<?php

namespace duncan3dc\SonosTests\Devices;

use duncan3dc\Sonos\Devices\Factory;
use duncan3dc\Sonos\Interfaces\Devices\DeviceInterface;
use Mockery;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\SimpleCache\CacheInterface;

class FactoryTest extends TestCase
{
    public function tearDown(): void
    {
        Mockery::close();
    }

    public function testCreateFromDefaults(): void
    {
        $factory = new Factory();
        $device = $factory->create("192.168.4.1");

        $this->assertInstanceOf(DeviceInterface::class, $device);
    }

    public function testCreateWithDependencies(): void
    {
        $cache = Mockery::mock(CacheInterface::class);
        $logger = Mockery::mock(LoggerInterface::class);

        $factory = new Factory($cache, $logger);
        $device = $factory->create("192.168.4.1");

        $cache
            ->shouldReceive("has")
            ->with("192.168.4.1_test.xml")
            ->once()
            ->andReturn(true);

        $logger
            ->shouldReceive("info")
            ->with("getting xml from cache: http://192.168.4.1:1400/test.xml")
            ->once()
            ->andReturn(true);

        $cache
            ->shouldReceive("get")
            ->with("192.168.4.1_test.xml")
            ->once()
            ->andReturn("<test>ok</test>");

        $result = $device->getXml("/test.xml");
        $this->assertSame("ok", $result->getTag("test")->nodeValue);
    }
}


text:
//
//  WeatherModel.h
//  天气
//
//  海内存知己,我叫叶良辰
//
//  Created by 韩小醋 on 15-10-21.
//  Copyright (c) 2015年 hanxiaocu. All rights reserved.//

#import <Foundation/Foundation.h>

@class Pm25Model,WeatherDetailsInfoModel,RealTimeModel;

@interface AllWeatherModel : NSObject

/**
 *  城市名
 */
@property (nonatomic, strong) NSString *city;
/**
 *  城市天气id
 */
@property (nonatomic, strong) NSString *cityid;
/**
 *  各种建议指数
 */
@property (nonatomic, strong) NSMutableArray *indexes;
/**
 *  pm数值
 */
@property (nonatomic, strong) Pm25Model    *pm25;
/**
 *  城市所在省份
 */
@property (nonatomic, strong) NSString *provinceName;
/**
 *  实时天气
 */
@property (nonatomic, strong) RealTimeModel *realtime;
/**
 *  天气详细信息
 */
@property (nonatomic, strong) WeatherDetailsInfoModel *weatherDetailsInfoModel;
/**
 *  7天天气(昨天,今天,之后5天)
 */
@property (nonatomic, strong) NSMutableArray *weathers;

@end


text:
package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import minerva.Minerva;
import tagging.PosTagger;
import tagging.ScoreWord;
import util.Constants;

public class TestRerank {

	static Map<String, String> questions;
	static PrintWriter writer;
	static int queries = 100;

	private static void setUp() throws Exception {
		questions = new HashMap<String, String>();
		File dir = new File(Constants.qDir);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String outFile = queries + "P:" + sdf.format(date) + ".txt";
		System.out.println("OutFile: " + outFile);
		writer = new PrintWriter(outFile, "UTF-8");
		for (File f : dir.listFiles()) {
			if(f.getName().startsWith(".")) continue;
			System.out.println("Reading file: " + f.getName());
			BufferedReader br = new BufferedReader(new FileReader(f));
			String line;
			while ((line = br.readLine()) != null) {
				String[] cols = line.split("\t");
				if (!cols[6].trim().contains(" "))
					questions.put(cols[5].trim().toLowerCase(), cols[6].trim()
							.toLowerCase());
			}
			br.close();
		}
	}

	public static void testReranker() throws Exception {
		setUp();
		PosTagger tagger = PosTagger.getInstance();
		List<Integer> ts = new ArrayList<Integer>();
		List<Integer> rs = new ArrayList<Integer>();
		List<Integer> ps = new ArrayList<Integer>();
		//writer.println(Integer.toString(questions.entrySet().size()));
		for (Entry<String, String> question : questions.entrySet()) {
			Minerva min = new Minerva(question.getKey(), queries);
			String ans = question.getValue();
			ScoreWord swAns = new ScoreWord(tagger.tagString(ans).get(0)[0]);
			List<ScoreWord> topNouns = min.getTopNouns();
			int t = 1 + topNouns.indexOf(swAns);
			List<ScoreWord> results = min.getRankedTopNouns();
			int r = 1 + results.indexOf(swAns);
			List<ScoreWord> punched = min.getPunchedRankedTopNouns();
			int p = 1 + punched.indexOf(swAns);
			if(t > 0){
				ts.add(t);
				rs.add(r);
				ps.add(p);
				writer.println(t + "\t" + r + "\t" + p + "\t" + question);
				writer.flush();
			}

		}
		Collections.sort(ts);
		Collections.sort(rs);
		Collections.sort(ps);
		int tMedian = ts.get((int)(ts.size()/2));
		int rMedian = rs.get((int)(rs.size()/2));
		int pMedian = ps.get((int)(ps.size()/2));
		writer.println();
		writer.println(tMedian + "\t" + rMedian + "\t" + pMedian);
		double tMean = 0;
		double rMean = 0;
		double pMean = 0;
		for(int i = 0; i < ts.size(); i++){
			tMean += ts.get(i);
			rMean += rs.get(i);
			pMean += ps.get(i);
		}
		tMean = tMean / ts.size();
		rMean = rMean / rs.size();
		pMean = pMean / ps.size();
		writer.println(tMean + "\t" + rMean + "\t" + pMean);

		writer.close();
	}

}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public XmlAttribute[] AnyAttr { get; set; }
```

### Property Value
Type: System.Xml.XmlAttribute[]

## See also
- [ContentType](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ContentType.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)