text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Reflection;

namespace WindStyle.WindowsLiveWriter.Plugin.SlugHelper
{
    [Serializable]
    public class Option
    {
        public static Option Current
        {
            get
            {
                if (field_Option == null)
                {
                    try
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(Option));
                        using (XmlReader reader = XmlReader.Create(field_OptionFilePath))
                        {
                            field_Option = serializer.Deserialize(reader) as Option;
                        }
                    }
                    catch
                    {
                        field_Option = new Option();
                    }
                }
                return field_Option;
            }
        }
        private static Option field_Option;

        private static string field_OptionFilePath
        {
            get
            {
                return Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(Option)).Location),
                    "WindStyle.WindowsLiveWriter.Plugin.SlugHelper.Config.xml");
            }
        }

        public Option()
        {
            this.Reset();
        }

        internal void Save()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Option));
            using (XmlWriter writer = XmlWriter.Create(field_OptionFilePath))
            {
                serializer.Serialize(writer, this);
            }
        }

        internal void Reset()
        {
            this.IgnoreWhenSlugExist = false;
        }

        [XmlElement("IgnoreWhenSlugExist")]
        public bool IgnoreWhenSlugExist { get; set; }
    }
}


text:
local addonName, addon = ...

local L = LibStub("AceLocale-3.0"):GetLocale(addonName)

function addon:GetOptions()
    return {
        type = 'group',
        args = {
            minimap = {
                name = L.opt_minimap_icon,
                -- desc = L.opt_minimap_icon_desc,
                type = 'toggle',
                set = function(info, value)
                    self.db.profile.minimap.hide = not value
                    if value then
                        self.icon:Show(addonName)
                    else
                        self.icon:Hide(addonName)
                    end
                end,
                get = function(info)
                    return not self.db.profile.minimap.hide
                end,
            },
        },
    }
end

redpajama_set_name: RedPajamaGithub


text:
//========================================================================
// GLFW 3.4 macOS - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2019 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//    claim that you wrote the original software. If you use this software
//    in a product, an acknowledgment in the product documentation would
//    be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
//    be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
//    distribution.
//
//========================================================================
// It is fine to use C99 in this file because it will not be built with VS
//========================================================================

#include "internal.h"

#include <stdlib.h>
#include <limits.h>
#include <math.h>

#include <IOKit/graphics/IOGraphicsLib.h>
#include <ApplicationServices/ApplicationServices.h>

// Get the name of the specified display, or NULL
//
static char* getDisplayName(CGDirectDisplayID displayID)
{
    io_iterator_t it;
    io_service_t service;
    CFDictionaryRef info;

    if (IOServiceGetMatchingServices(kIOMasterPortDefault,
                                     IOServiceMatching("IODisplayConnect"),
                                     &it) != 0)
    {
        // This may happen if a desktop Mac is running headless
        return NULL;
    }

    while ((service = IOIteratorNext(it)) != 0)
    {
        info = IODisplayCreateInfoDictionary(service,
                                             kIODisplayOnlyPreferredName);

        CFNumberRef vendorIDRef =
            CFDictionaryGetValue(info, CFSTR(kDisplayVendorID));
        CFNumberRef productIDRef =
            CFDictionaryGetValue(info, CFSTR(kDisplayProductID));
        if (!vendorIDRef || !productIDRef)
        {
            CFRelease(info);
            continue;
        }

        unsigned int vendorID, productID;
        CFNumberGetValue(vendorIDRef, kCFNumberIntType, &vendorID);
        CFNumberGetValue(productIDRef, kCFNumberIntType, &productID);

        if (CGDisplayVendorNumber(displayID) == vendorID &&
            CGDisplayModelNumber(displayID) == productID)
        {
            // Info dictionary is used and freed below
            break;
        }

        CFRelease(info);
    }

    IOObjectRelease(it);

    if (!service)
    {
        _glfwInputError(GLFW_PLATFORM_ERROR,
                        "Cocoa: Failed to find service port for display");
        return NULL;
    }

    CFDictionaryRef names =
        CFDictionaryGetValue(info, CFSTR(kDisplayProductName));

    CFStringRef nameRef;

    if (!names || !CFDictionaryGetValueIfPresent(names, CFSTR("en_US"),
                                                 (const void**) &nameRef))
    {
        // This may happen if a desktop Mac is running headless
        CFRelease(info);
        return NULL;
    }

    const CFIndex size =
        CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef),
                                          kCFStringEncodingUTF8);
    char* name = calloc(size + 1, 1);
    CFStringGetCString(nameRef, name, size, kCFStringEncodingUTF8);

    CFRelease(info);
    return name;
}

// Check whether the display mode should be included in enumeration
//
static GLFWbool modeIsGood(CGDisplayModeRef mode)
{
    uint32_t flags = CGDisplayModeGetIOFlags(mode);

    if (!(flags & kDisplayModeValidFlag) || !(flags & kDisplayModeSafeFlag))
        return GLFW_FALSE;
    if (flags & kDisplayModeInterlacedFlag)
        return GLFW_FALSE;
    if (flags & kDisplayModeStretchedFlag)
        return GLFW_FALSE;

#if MAC_OS_X_VERSION_MAX_ALLOWED <= 101100
    CFStringRef format = CGDisplayModeCopyPixelEncoding(mode);
    if (CFStringCompare(format, CFSTR(IO16BitDirectPixels), 0) &&
        CFStringCompare(format, CFSTR(IO32BitDirectPixels), 0))
    {
        CFRelease(format);
        return GLFW_FALSE;
    }

    CFRelease(format);
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED */
    return GLFW_TRUE;
}

// Convert Core Graphics display mode to GLFW video mode
//
static GLFWvidmode vidmodeFromCGDisplayMode(CGDisplayModeRef mode,
                                            CVDisplayLinkRef link)
{
    GLFWvidmode result;
    result.width = (int) CGDisplayModeGetWidth(mode);
    result.height = (int) CGDisplayModeGetHeight(mode);
    result.refreshRate = (int) round(CGDisplayModeGetRefreshRate(mode));

    if (result.refreshRate == 0)
    {
        const CVTime time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link);
        if (!(time.flags & kCVTimeIsIndefinite))
            result.refreshRate = (int) (time.timeScale / (double) time.timeValue);
    }

#if MAC_OS_X_VERSION_MAX_ALLOWED <= 101100
    CFStringRef format = CGDisplayModeCopyPixelEncoding(mode);
    if (CFStringCompare(format, CFSTR(IO16BitDirectPixels), 0) == 0)
    {
        result.redBits = 5;
        result.greenBits = 5;
        result.blueBits = 5;
    }
    else
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED */
    {
        result.redBits = 8;
        result.greenBits = 8;
        result.blueBits = 8;
    }

#if MAC_OS_X_VERSION_MAX_ALLOWED <= 101100
    CFRelease(format);
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED */
    return result;
}

// Starts reservation for display fading
//
static CGDisplayFadeReservationToken beginFadeReservation(void)
{
    CGDisplayFadeReservationToken token = kCGDisplayFadeReservationInvalidToken;

    if (CGAcquireDisplayFadeReservation(5, &token) == kCGErrorSuccess)
    {
        CGDisplayFade(token, 0.3,
                      kCGDisplayBlendNormal,
                      kCGDisplayBlendSolidColor,
                      0.0, 0.0, 0.0,
                      TRUE);
    }

    return token;
}

// Ends reservation for display fading
//
static void endFadeReservation(CGDisplayFadeReservationToken token)
{
    if (token != kCGDisplayFadeReservationInvalidToken)
    {
        CGDisplayFade(token, 0.5,
                      kCGDisplayBlendSolidColor,
                      kCGDisplayBlendNormal,
                      0.0, 0.0, 0.0,
                      FALSE);
        CGReleaseDisplayFadeReservation(token);
    }
}

// Finds and caches the NSScreen corresponding to the specified monitor
//
static GLFWbool refreshMonitorScreen(_GLFWmonitor* monitor)
{
    if (monitor->ns.screen)
        return GLFW_TRUE;

    for (NSScreen* screen in [NSScreen screens])
    {
        NSNumber* displayID = [screen deviceDescription][@"NSScreenNumber"];

        // HACK: Compare unit numbers instead of display IDs to work around
        //       display replacement on machines with automatic graphics
        //       switching
        if (monitor->ns.unitNumber == CGDisplayUnitNumber([displayID unsignedIntValue]))
        {
            monitor->ns.screen = screen;
            return GLFW_TRUE;
        }
    }

    _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to find a screen for monitor");
    return GLFW_FALSE;
}

//////////////////////////////////////////////////////////////////////////
//////                       GLFW internal API                      //////
//////////////////////////////////////////////////////////////////////////

// Poll for changes in the set of connected monitors
//
void _glfwPollMonitorsNS(void)
{
    uint32_t displayCount;
    CGGetOnlineDisplayList(0, NULL, &displayCount);
    CGDirectDisplayID* displays = calloc(displayCount, sizeof(CGDirectDisplayID));
    CGGetOnlineDisplayList(displayCount, displays, &displayCount);

    for (uint32_t i = 0;  i < _glfw.monitorCount;  i++)
        _glfw.monitors[i]->ns.screen = nil;

    _GLFWmonitor** disconnected = NULL;
    uint32_t disconnectedCount = _glfw.monitorCount;
    if (disconnectedCount)
    {
        disconnected = calloc(_glfw.monitorCount, sizeof(_GLFWmonitor*));
        memcpy(disconnected,
               _glfw.monitors,
               _glfw.monitorCount * sizeof(_GLFWmonitor*));
    }

    for (uint32_t i = 0;  i < displayCount;  i++)
    {
        if (CGDisplayIsAsleep(displays[i]))
            continue;

        // HACK: Compare unit numbers instead of display IDs to work around
        //       display replacement on machines with automatic graphics
        //       switching
        const uint32_t unitNumber = CGDisplayUnitNumber(displays[i]);
        for (uint32_t j = 0;  j < disconnectedCount;  j++)
        {
            if (disconnected[j] && disconnected[j]->ns.unitNumber == unitNumber)
            {
                disconnected[j] = NULL;
                break;
            }
        }

        const CGSize size = CGDisplayScreenSize(displays[i]);
        char* name = getDisplayName(displays[i]);
        if (!name)
            name = _glfw_strdup("Unknown");

        _GLFWmonitor* monitor = _glfwAllocMonitor(name, size.width, size.height);
        monitor->ns.displayID  = displays[i];
        monitor->ns.unitNumber = unitNumber;

        free(name);

        _glfwInputMonitor(monitor, GLFW_CONNECTED, _GLFW_INSERT_LAST);
    }

    for (uint32_t i = 0;  i < disconnectedCount;  i++)
    {
        if (disconnected[i])
            _glfwInputMonitor(disconnected[i], GLFW_DISCONNECTED, 0);
    }

    free(disconnected);
    free(displays);
}

// Change the current video mode
//
void _glfwSetVideoModeNS(_GLFWmonitor* monitor, const GLFWvidmode* desired)
{
    GLFWvidmode current;
    _glfwPlatformGetVideoMode(monitor, &current);

    const GLFWvidmode* best = _glfwChooseVideoMode(monitor, desired);
    if (_glfwCompareVideoModes(&current, best) == 0)
        return;

    CVDisplayLinkRef link;
    CVDisplayLinkCreateWithCGDisplay(monitor->ns.displayID, &link);

    CFArrayRef modes = CGDisplayCopyAllDisplayModes(monitor->ns.displayID, NULL);
    const CFIndex count = CFArrayGetCount(modes);
    CGDisplayModeRef native = NULL;

    for (CFIndex i = 0;  i < count;  i++)
    {
        CGDisplayModeRef dm = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i);
        if (!modeIsGood(dm))
            continue;

        const GLFWvidmode mode = vidmodeFromCGDisplayMode(dm, link);
        if (_glfwCompareVideoModes(best, &mode) == 0)
        {
            native = dm;
            break;
        }
    }

    if (native)
    {
        if (monitor->ns.previousMode == NULL)
            monitor->ns.previousMode = CGDisplayCopyDisplayMode(monitor->ns.displayID);

        CGDisplayFadeReservationToken token = beginFadeReservation();
        CGDisplaySetDisplayMode(monitor->ns.displayID, native, NULL);
        endFadeReservation(token);
    }

    CFRelease(modes);
    CVDisplayLinkRelease(link);
}

// Restore the previously saved (original) video mode
//
void _glfwRestoreVideoModeNS(_GLFWmonitor* monitor)
{
    if (monitor->ns.previousMode)
    {
        CGDisplayFadeReservationToken token = beginFadeReservation();
        CGDisplaySetDisplayMode(monitor->ns.displayID,
                                monitor->ns.previousMode, NULL);
        endFadeReservation(token);

        CGDisplayModeRelease(monitor->ns.previousMode);
        monitor->ns.previousMode = NULL;
    }
}

//////////////////////////////////////////////////////////////////////////
//////                       GLFW platform API                      //////
//////////////////////////////////////////////////////////////////////////

void _glfwPlatformFreeMonitor(_GLFWmonitor* monitor)
{
}

void _glfwPlatformGetMonitorPos(_GLFWmonitor* monitor, int* xpos, int* ypos)
{
    @autoreleasepool {

    const CGRect bounds = CGDisplayBounds(monitor->ns.displayID);

    if (xpos)
        *xpos = (int) bounds.origin.x;
    if (ypos)
        *ypos = (int) bounds.origin.y;

    } // autoreleasepool
}

void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor,
                                         float* xscale, float* yscale)
{
    @autoreleasepool {

    if (!refreshMonitorScreen(monitor))
        return;

    const NSRect points = [monitor->ns.screen frame];
    const NSRect pixels = [monitor->ns.screen convertRectToBacking:points];

    if (xscale)
        *xscale = (float) (pixels.size.width / points.size.width);
    if (yscale)
        *yscale = (float) (pixels.size.height / points.size.height);

    } // autoreleasepool
}

void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor,
                                     int* xpos, int* ypos,
                                     int* width, int* height)
{
    @autoreleasepool {

    if (!refreshMonitorScreen(monitor))
        return;

    const NSRect frameRect = [monitor->ns.screen visibleFrame];

    if (xpos)
        *xpos = frameRect.origin.x;
    if (ypos)
        *ypos = _glfwTransformYNS(frameRect.origin.y + frameRect.size.height - 1);
    if (width)
        *width = frameRect.size.width;
    if (height)
        *height = frameRect.size.height;

    } // autoreleasepool
}

GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* count)
{
    @autoreleasepool {

    *count = 0;

    CVDisplayLinkRef link;
    CVDisplayLinkCreateWithCGDisplay(monitor->ns.displayID, &link);

    CFArrayRef modes = CGDisplayCopyAllDisplayModes(monitor->ns.displayID, NULL);
    const CFIndex found = CFArrayGetCount(modes);
    GLFWvidmode* result = calloc(found, sizeof(GLFWvidmode));

    for (CFIndex i = 0;  i < found;  i++)
    {
        CGDisplayModeRef dm = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i);
        if (!modeIsGood(dm))
            continue;

        const GLFWvidmode mode = vidmodeFromCGDisplayMode(dm, link);
        CFIndex j;

        for (j = 0;  j < *count;  j++)
        {
            if (_glfwCompareVideoModes(result + j, &mode) == 0)
                break;
        }

        // Skip duplicate modes
        if (i < *count)
            continue;

        (*count)++;
        result[*count - 1] = mode;
    }

    CFRelease(modes);
    CVDisplayLinkRelease(link);
    return result;

    } // autoreleasepool
}

void _glfwPlatformGetVideoMode(_GLFWmonitor* monitor, GLFWvidmode *mode)
{
    @autoreleasepool {

    CVDisplayLinkRef link;
    CVDisplayLinkCreateWithCGDisplay(monitor->ns.displayID, &link);

    CGDisplayModeRef native = CGDisplayCopyDisplayMode(monitor->ns.displayID);
    *mode = vidmodeFromCGDisplayMode(native, link);
    CGDisplayModeRelease(native);

    CVDisplayLinkRelease(link);

    } // autoreleasepool
}

GLFWbool _glfwPlatformGetGammaRamp(_GLFWmonitor* monitor, GLFWgammaramp* ramp)
{
    @autoreleasepool {

    uint32_t size = CGDisplayGammaTableCapacity(monitor->ns.displayID);
    CGGammaValue* values = calloc(size * 3, sizeof(CGGammaValue));

    CGGetDisplayTransferByTable(monitor->ns.displayID,
                                size,
                                values,
                                values + size,
                                values + size * 2,
                                &size);

    _glfwAllocGammaArrays(ramp, size);

    for (uint32_t i = 0; i < size; i++)
    {
        ramp->red[i]   = (unsigned short) (values[i] * 65535);
        ramp->green[i] = (unsigned short) (values[i + size] * 65535);
        ramp->blue[i]  = (unsigned short) (values[i + size * 2] * 65535);
    }

    free(values);
    return GLFW_TRUE;

    } // autoreleasepool
}

void _glfwPlatformSetGammaRamp(_GLFWmonitor* monitor, const GLFWgammaramp* ramp)
{
    @autoreleasepool {

    CGGammaValue* values = calloc(ramp->size * 3, sizeof(CGGammaValue));

    for (unsigned int i = 0;  i < ramp->size;  i++)
    {
        values[i]                  = ramp->red[i] / 65535.f;
        values[i + ramp->size]     = ramp->green[i] / 65535.f;
        values[i + ramp->size * 2] = ramp->blue[i] / 65535.f;
    }

    CGSetDisplayTransferByTable(monitor->ns.displayID,
                                ramp->size,
                                values,
                                values + ramp->size,
                                values + ramp->size * 2);

    free(values);

    } // autoreleasepool
}

//////////////////////////////////////////////////////////////////////////
//////                        GLFW native API                       //////
//////////////////////////////////////////////////////////////////////////

GLFWAPI CGDirectDisplayID glfwGetCocoaMonitor(GLFWmonitor* handle)
{
    _GLFWmonitor* monitor = (_GLFWmonitor*) handle;
    _GLFW_REQUIRE_INIT_OR_RETURN(kCGNullDirectDisplay);
    return monitor->ns.displayID;
}


text:
package pep_083

import scala.collection.mutable

object solution {

  val filename = "src/pep_083/matrix.txt"
  val input = io.Source.fromFile(filename).mkString.trim.split("\n").map(_.split(",") map (_.toInt))
  val lastRow = input.size - 1
  val lastCol = input.head.size - 1

  case class Position(row: Int, col: Int) {
    def isFirstRow: Boolean = row == 0

    def isFirstCol: Boolean = col == 0

    def isLastRow: Boolean = row == lastRow

    def isLastCol: Boolean = col == lastCol

    def isStartPosition: Boolean = isFirstRow && isFirstCol

    def isEndPosition: Boolean = isLastRow && isLastCol

    def moveUp: Position = Position(row - 1, col)

    def moveLeft: Position = Position(row, col - 1)

    def moveRight: Position = Position(row, col + 1)

    def moveDown: Position = Position(row + 1, col)

    def nextPositions: Set[Position] = Position(row, col) match {
      case cell if cell.isEndPosition => Set()
      case cell if cell.isStartPosition => Set(cell.moveDown, cell.moveRight)
      case cell =>
        val nextPositions = mutable.Set(cell.moveUp, cell.moveDown, cell.moveLeft, cell.moveRight)
        if (cell.isFirstRow) nextPositions.remove(cell.moveUp)
        if (cell.isFirstCol) nextPositions.remove(cell.moveLeft)
        if (cell.isLastRow) nextPositions.remove(cell.moveDown)
        if (cell.isLastCol) nextPositions.remove(cell.moveRight)
        nextPositions.toSet
    }
  }

  val positions = for {
    r <- 0 to lastRow
    c <- 0 to lastCol
  } yield Position(r, c)

  val (startPositions, otherPositions) = positions.partition(_.isStartPosition)
  val values = mutable.Map[Position, Int]() ++ positions.map(p => p -> input(p.row)(p.col))
  val distance = mutable.Map[Position, Int]() ++ startPositions.map(p => p -> values(p))

  case class PositionsToExplore(priority: Int, position: Position) extends Ordered[PositionsToExplore] {
    def compare(that: PositionsToExplore) = that.priority compare this.priority
  }

  var positionsToExplore = mutable.PriorityQueue[PositionsToExplore]() ++
    startPositions.map(PositionsToExplore(0, _)) ++
    otherPositions.map(PositionsToExplore(Int.MaxValue, _))

  def solve(): Int = {
    var result = Int.MaxValue

    while (positionsToExplore.nonEmpty) {
      val position = positionsToExplore.dequeue().position
      val neighbors = position.nextPositions
      neighbors.foreach {
        case neighbor =>
          // val pathValue = distance.getOrElseUpdate(position, Int.MaxValue) + input(neighbor.row)(neighbor.col)
          val pathValue = if (distance.contains(position)) {
            distance.get(position).get + values(neighbor)
          } else {
            Int.MaxValue
          }

          // refactor tryout
          // val a: Option[Int] = distance.get(position)
          // val pv: Int = distance.get(position).getOrElse(Int.MaxValue)
          // val pvv: Int = if (pv == Int.MaxValue) pv else pv + values(neighbor)

          if (neighbor.isEndPosition && pathValue < result) {
            result = pathValue
          }

          if (pathValue < distance.getOrElse(neighbor, Int.MaxValue)) {
            distance.update(neighbor, pathValue)
            // TODO PriorityQueue has O(n) for random access :-/
            positionsToExplore = positionsToExplore.filterNot(_.position == neighbor)
            positionsToExplore += PositionsToExplore(pathValue, neighbor)
          }
      }
    }
    result
  }
}


text:
#ifndef HTMLTemplateElement_h
#define HTMLTemplateElement_h

#include "core/html/HTMLElement.h"

namespace blink {

class DocumentFragment;
class TemplateContentDocumentFragment;

class HTMLTemplateElement final : public HTMLElement {
    DEFINE_WRAPPERTYPEINFO();
public:
    DECLARE_NODE_FACTORY(HTMLTemplateElement);
    ~HTMLTemplateElement() override;
    DECLARE_VIRTUAL_TRACE();

    DocumentFragment* content() const;

private:
    RawPtr<Node> cloneNode(bool deep) override;
    void didMoveToNewDocument(Document& oldDocument) override;

    explicit HTMLTemplateElement(Document&);

    mutable Member<TemplateContentDocumentFragment> m_content;
};

} // namespace blink

#endif // HTMLTemplateElement_h


text:
Origen.app.runner.launch action: :compile,
                          files: "#{Origen.root}/templates/test/inline.txt.erb",
                          output: "#{Origen.root}/tmp"

Pattern.create do

end


text:
#!/usr/bin/env php
<?php

/*
 * This is not a stand-alone server.  It should be run as a normal
 * php web script (like through Apache's mod_php) or as a cgi script
 * (like with the included runserver.py).  You can connect to it with
 * THttpClient in any language that supports it.  The PHP tutorial client
 * will work if you pass it the argument "--http".
 */

if (php_sapi_name() == 'cli') {
  ini_set("display_errors", "stderr");
}

$GLOBALS['THRIFT_ROOT'] = realpath(dirname(__FILE__).'/../..').'/lib/php/src';

require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TPhpStream.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';

/**
 * Suppress errors in here, which happen because we have not installed into
 * $GLOBALS['THRIFT_ROOT'].'/packages/tutorial' like we are supposed to!
 *
 * Normally we would only have to include Calculator.php which would properly
 * include the other files from their packages/ folder locations, but we
 * include everything here due to the bogus path setup.
 */
error_reporting(E_NONE);
$GEN_DIR = realpath(dirname(__FILE__).'/..').'/gen-php';
require_once $GEN_DIR.'/SharedService.php';
require_once $GEN_DIR.'/shared_types.php';
require_once $GEN_DIR.'/Calculator.php';
require_once $GEN_DIR.'/tutorial_types.php';
error_reporting(E_ALL);

class CalculatorHandler implements CalculatorIf {
  protected $log = array();

  public function ping() {
    error_log("ping()");
  }

  public function add($num1, $num2) {
    error_log("add({$num1}, {$num2})");
    return $num1 + $num2;
  }

  public function calculate($logid, $w) {
    error_log("calculate({$logid}, {{$w->op}, {$w->num1}, {$w->num2}})");
    switch ($w->op) {
      case tutorial_Operation::ADD:
        $val = $w->num1 + $w->num2;
        break;
      case tutorial_Operation::SUBTRACT:
        $val = $w->num1 - $w->num2;
        break;
      case tutorial_Operation::MULTIPLY:
        $val = $w->num1 * $w->num2;
        break;
      case tutorial_Operation::DIVIDE:
        if ($w->num2 == 0) {
          $io = new tutorial_InvalidOperation();
          $io->what = $w->op;
          $io->why = "Cannot divide by 0";
          throw $io;
        }
        $val = $w->num1 / $w->num2;
        break;
      default:
        $io = new tutorial_InvalidOperation();
        $io->what = $w->op;
        $io->why = "Invalid Operation";
        throw $io;
    }

    $log = new SharedStruct();
    $log->key = $logid;
    $log->value = (string)$val;
    $this->log[$logid] = $log;

    return $val;
  }

  public function getStruct($key) {
    error_log("getStruct({$key})");
    // This actually doesn't work because the PHP interpreter is
    // restarted for every request.
    //return $this->log[$key];
    return new SharedStruct(array("key" => $key, "value" => "PHP is stateless!"));
  }

  public function zip() {
    error_log("zip()");
  }

};

header('Content-Type', 'application/x-thrift');
if (php_sapi_name() == 'cli') {
  echo "\r\n";
}

$handler = new CalculatorHandler();
$processor = new CalculatorProcessor($handler);

$transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W));
$protocol = new TBinaryProtocol($transport, true, true);

$transport->open();
$processor->process($protocol, $protocol);
$transport->close();


text:
/* 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 org.flowable.engine.test.el.function;

import static org.assertj.core.api.Assertions.assertThat;

import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.test.HistoryTestHelper;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.test.Deployment;
import org.flowable.task.api.Task;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.junit.jupiter.api.Test;

/**
 * @author Filip Hrisafov
 */
class TaskFunctionDelegatesTest extends PluggableFlowableTestCase {

    @Test
    @Deployment
    void testTaskGet() {
        ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
                .processDefinitionKey("testTaskGetFunction")
                .start();

        Object taskAssignee = managementService.executeCommand(commandContext -> {
            ExecutionEntity instance = CommandContextUtil.getExecutionEntityManager(commandContext).findById(processInstance.getId());
            return CommandContextUtil.getProcessEngineConfiguration(commandContext)
                    .getExpressionManager()
                    .createExpression("${task:get(taskId).assignee}")
                    .getValue(instance);
        });

        assertThat(taskAssignee).isNull();

        Task task = taskService.createTaskQuery().singleResult();
        assertThat(task).isNotNull();
        assertThat(task.getName()).isEqualTo("my task");
        taskService.setAssignee(task.getId(), "kermit");

        taskAssignee = managementService.executeCommand(commandContext -> {
            ExecutionEntity instance = CommandContextUtil.getExecutionEntityManager(commandContext).findById(processInstance.getId());
            return CommandContextUtil.getProcessEngineConfiguration(commandContext)
                    .getExpressionManager()
                    .createExpression("${task:get(taskId).assignee}")
                    .getValue(instance);
        });

        assertThat(taskAssignee).isEqualTo("kermit");

        taskService.complete(task.getId());

        assertThat(runtimeService.getVariable(processInstance.getId(), "taskAssignee")).isEqualTo("kermit");

        task = taskService.createTaskQuery().singleResult();
        assertThat(task).isNotNull();
        assertThat(task.getName()).isEqualTo("my second task");

        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            HistoricVariableInstance historicTaskAssignee = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(processInstance.getId())
                    .variableName("taskAssignee")
                    .singleResult();
            assertThat(historicTaskAssignee).isNotNull();
            assertThat(historicTaskAssignee.getValue()).isEqualTo("kermit");
        }

        taskAssignee = managementService.executeCommand(commandContext -> {
            ExecutionEntity instance = CommandContextUtil.getExecutionEntityManager(commandContext).findById(processInstance.getId());
            return CommandContextUtil.getProcessEngineConfiguration(commandContext)
                    .getExpressionManager()
                    .createExpression("${task:get(taskId).assignee}")
                    .getValue(instance);
        });

        assertThat(taskAssignee).isEqualTo("kermit");

    }

}


text:
using System;
using System.Reflection;

/*
public delegate object ArrDel (int i);

public class Gen<T> {
    public object newArr (int i) {
	return new T [i];
    }

    public ArrDel newDel () {
	return new ArrDel (this.newArr);
    }
}

public delegate object DelObj (object g, int i);
public delegate object DelStr (object g, int i);
*/

public class main {
    public static int work () {
	Gen<string> gs = new Gen<string> ();
	Gen<object> go = new Gen<object> ();

	MethodInfo miObj = typeof (Gen<object>).GetMethod ("newArr", BindingFlags.Public | BindingFlags.Instance);
	MethodInfo miStr = typeof (Gen<string>).GetMethod ("newArr", BindingFlags.Public | BindingFlags.Instance);

	if (miObj == miStr) {
	    Console.WriteLine ("methods equal");
	    return 1;
	}

	ObjArrDel oad = go.newObjDel ();
	StrArrDel sad = gs.newStrDel ();
	StrArrDel sad2 = (StrArrDel)Delegate.CreateDelegate (typeof (StrArrDel), null, miStr);

	if (oad.Method != miObj) {
	    Console.WriteLine ("wrong object method");
	    if (oad.Method == miStr)
		Console.WriteLine ("object method is string");
	    return 1;
	}

	if (sad.Method != miStr) {
	    Console.WriteLine ("wrong string method");
	    if (sad.Method == miObj)
		Console.WriteLine ("string method is object");
	    else
		return 1;
	} else {
	    Console.WriteLine ("right string method");
	}

	if (sad2.Method != miStr) {
	    Console.WriteLine ("wrong string2 method");
	    if (sad2.Method == miObj)
		Console.WriteLine ("string2 method is object");
	    return 1;
	}

	Console.WriteLine ("calling object del");
	if (oad (go, 3).GetType () != typeof (object [])) {
	    Console.WriteLine ("not object array");
	    return 1;
	}

	Console.WriteLine ("calling string del");
	if (sad (gs, 3).GetType () != typeof (string [])) {
	    Console.WriteLine ("not string array");
	    return 1;
	}

	Console.WriteLine ("calling string del2");
	if (sad2 (gs, 3).GetType () != typeof (string [])) {
	    Console.WriteLine ("not string2 array");
	    return 1;
	}

	try {
	    StrArrDel sad3 = (StrArrDel)Delegate.CreateDelegate (typeof (StrArrDel), null, miObj);
	    Console.WriteLine ("object method for string delegate");
	    return 1;
	} catch (ArgumentException) {
	}

	/*
	DelObj delObj = (DelObj)Delegate.CreateDelegate (typeof (DelObj), null, miObj);

	if (delObj (go, 3).GetType () != typeof (object []))
	    return 1;

	DelStr delStr = (DelStr)Delegate.CreateDelegate (typeof (DelStr), null, miStr);

	if (delStr (gs, 3).GetType () != typeof (string []))
	    return 1;
	*/

	/*
	ArrDel ad = go.newDel ();
	if (ad (3).GetType () != typeof (object []))
	    return 1;

	ad = gs.newDel ();
	if (ad (3).GetType () != typeof (string []))
	    return 1;
	*/

	Console.WriteLine ("done");

	return 0;
    }

    public static int Main () {
	Gen<string> gs = new Gen<string> ();
	Gen<object> go = new Gen<object> ();

	gs.newArr (3);
	go.newArr (3);

	return work ();
    }
}


text:
require 'spec_helper'

describe ManagedInteractive do
  it_behaves_like "a base interactive", :managed_interactive

  let(:library_interactive) { FactoryGirl.create(:library_interactive,
                                                 :name => 'Test Library managed_Interactive',
                                                 :base_url => 'http://concord.org/',
                                                 :aspect_ratio_method => "base aspect_ratio_method",
                                                 :native_width => 100,
                                                 :native_height => 200,
                                                 :click_to_play => true,
                                                 :full_window => true,
                                                 :click_to_play_prompt => "base click_to_play_prompt",
                                                 :image_url => "http://base.url/image",
                                                 :enable_learner_state => true,
                                                 :show_delete_data_button => false,
                                                 :has_report_url => true,
                                                 :no_snapshots => true,
                                                 :report_item_url => ""
                                                )}

  let(:mw_interactive) { FactoryGirl.create(:mw_interactive) }
  let(:managed_interactive) { FactoryGirl.create(:managed_interactive,
                                                 :library_interactive => library_interactive,
                                                 :url_fragment => "test",
                                                 :linked_interactive => mw_interactive
                                                )}
  let (:page) { FactoryGirl.create(:page) }

  it 'has valid attributes' do
    managed_interactive.valid?
  end

  it 'can to associate an interactive page' do
    page.add_interactive(managed_interactive)

    managed_interactive.reload
    page.reload

    expect(managed_interactive.interactive_page).to eq(page)
  end

  describe '#to_hash' do
    it 'has useful values' do
      expected = {
        library_interactive_id: managed_interactive.library_interactive_id,
        name: managed_interactive.name,
        url_fragment: managed_interactive.url_fragment,
        authored_state: managed_interactive.authored_state,
        is_hidden: managed_interactive.is_hidden,
        is_full_width: managed_interactive.is_full_width,
        show_in_featured_question_report: managed_interactive.show_in_featured_question_report,
        inherit_aspect_ratio_method: managed_interactive.inherit_aspect_ratio_method,
        custom_aspect_ratio_method: managed_interactive.custom_aspect_ratio_method,
        inherit_native_width: managed_interactive.inherit_native_width,
        custom_native_width: managed_interactive.custom_native_width,
        inherit_native_height: managed_interactive.inherit_native_height,
        custom_native_height: managed_interactive.custom_native_height,
        inherit_click_to_play: managed_interactive.inherit_click_to_play,
        custom_click_to_play: managed_interactive.custom_click_to_play,
        inherit_full_window: managed_interactive.inherit_full_window,
        custom_full_window: managed_interactive.custom_full_window,
        inherit_click_to_play_prompt: managed_interactive.inherit_click_to_play_prompt,
        custom_click_to_play_prompt: managed_interactive.custom_click_to_play_prompt,
        inherit_image_url: managed_interactive.inherit_image_url,
        custom_image_url: managed_interactive.custom_image_url
       }
      expect(managed_interactive.to_hash).to eq(expected)
    end
  end

  describe '#to_authoring_hash' do
    it 'has useful values' do
      page.add_interactive(managed_interactive)

      managed_interactive.reload
      page.reload

      expected = managed_interactive.to_hash
      expected[:id] = managed_interactive.id
      expected[:linked_interactive_id] = managed_interactive.linked_interactive_id
      expected[:linked_interactive_type] = managed_interactive.linked_interactive_type
      expected[:aspect_ratio] = managed_interactive.aspect_ratio
      expected[:interactive_item_id] = managed_interactive.interactive_item_id
      expected[:linked_interactive_item_id] = managed_interactive.linked_interactive_item_id
      expected[:linked_interactives] = managed_interactive.linked_interactives_list
      expect(managed_interactive.to_authoring_hash).to eq(expected)
    end
  end

  describe '#to_authoring_preview_hash' do
    it 'has useful values' do
      expected = managed_interactive.to_interactive
      expected[:linked_interactives] = managed_interactive.linked_interactives_list
      expect(managed_interactive.to_authoring_preview_hash).to eq(expected)
    end
  end

  describe '#duplicate' do
    it 'is a new instance of MwInteractive with values' do
      managed_interactive.is_hidden = true
      expect(managed_interactive.duplicate).to be_a_new(ManagedInteractive).with({
        library_interactive_id: managed_interactive.library_interactive_id,
        name: managed_interactive.name,
        url_fragment: managed_interactive.url_fragment,
        authored_state: managed_interactive.authored_state,
        is_hidden: managed_interactive.is_hidden,
        is_full_width: managed_interactive.is_full_width,
        show_in_featured_question_report: managed_interactive.show_in_featured_question_report,
        inherit_aspect_ratio_method: managed_interactive.inherit_aspect_ratio_method,
        custom_aspect_ratio_method: managed_interactive.custom_aspect_ratio_method,
        inherit_native_width: managed_interactive.inherit_native_width,
        custom_native_width: managed_interactive.custom_native_width,
        inherit_native_height: managed_interactive.inherit_native_height,
        custom_native_height: managed_interactive.custom_native_height,
        inherit_click_to_play: managed_interactive.inherit_click_to_play,
        custom_click_to_play: managed_interactive.custom_click_to_play,
        inherit_full_window: managed_interactive.inherit_full_window,
        custom_full_window: managed_interactive.custom_full_window,
        inherit_click_to_play_prompt: managed_interactive.inherit_click_to_play_prompt,
        custom_click_to_play_prompt: managed_interactive.custom_click_to_play_prompt,
        inherit_image_url: managed_interactive.inherit_image_url,
        custom_image_url: managed_interactive.custom_image_url
      })
    end
  end

  describe "#to_interactive" do
    it 'has useful values' do
      expect(managed_interactive.to_interactive).to eq({
        id: managed_interactive.id,
        name: managed_interactive.name,
        url: managed_interactive.url,
        native_width: managed_interactive.native_width,
        native_height: managed_interactive.native_height,
        enable_learner_state: managed_interactive.enable_learner_state,
        show_delete_data_button: managed_interactive.show_delete_data_button,
        has_report_url: managed_interactive.has_report_url,
        click_to_play: managed_interactive.click_to_play,
        click_to_play_prompt: managed_interactive.click_to_play_prompt,
        full_window: managed_interactive.full_window,
        image_url: managed_interactive.image_url,
        is_hidden: managed_interactive.is_hidden,
        is_full_width: managed_interactive.is_full_width,
        show_in_featured_question_report: managed_interactive.show_in_featured_question_report,
        authored_state: managed_interactive.authored_state,
        aspect_ratio: managed_interactive.aspect_ratio,
        aspect_ratio_method: managed_interactive.aspect_ratio_method,
        no_snapshots: managed_interactive.no_snapshots,
        linked_interactive_id: managed_interactive.linked_interactive_id,
        linked_interactive_type: managed_interactive.linked_interactive_type
      })
    end
  end

  describe '#export' do
    describe 'without a library interactive set' do
      let(:library_interactive) { nil }
      it 'exports' do
        exported = managed_interactive.export()
        expect(exported[:library_interactive]).to be nil
      end
    end

    it 'exports with a library interactive set' do
      exported = managed_interactive.export()
      expect(exported[:library_interactive]).not_to be nil
    end
  end

  describe "#import" do
    it 'imports what is exported' do
      exported = managed_interactive.export()
      imported = ManagedInteractive.import(exported)
      expect(imported.export()).to eq exported

      # tests if the existing library interactive is loaded
      expect(imported.library_interactive_id).not_to be_nil
      expect(imported.library_interactive_id).to be managed_interactive.library_interactive_id
    end

    it 'creates a new library interactive if export_hash not found' do
      managed_interactive.library_interactive.base_url = "https://not.in.database"
      imported = ManagedInteractive.import(managed_interactive.export())
      expect(imported.export()).to eq managed_interactive.export()

      # tests if a new library interactive is created
      expect(imported.library_interactive_id).to be_nil
      imported.save
      expect(imported.library_interactive_id).not_to be managed_interactive.library_interactive_id
      expect(imported.library_interactive_id).to be > managed_interactive.library_interactive_id
    end

    it 'does not create duplicate new library interactives if export_hash not found' do
      managed_interactive.library_interactive.base_url = "https://not.in.database"
      exported = managed_interactive.export()
      imported1 = ManagedInteractive.import(exported)
      imported2 = ManagedInteractive.import(exported)
      expect(imported1.export()).to eq managed_interactive.export()
      expect(imported2.export()).to eq managed_interactive.export()

      # tests if a new library interactive is created
      expect(imported1.library_interactive_id).to be_nil
      expect(imported2.library_interactive_id).not_to be_nil  # the import saves the library interactive
      imported1.save
      expect(imported1.library_interactive_id).to be imported2.library_interactive_id
      expect(imported1.library_interactive_id).not_to be managed_interactive.library_interactive_id
      expect(imported1.library_interactive_id).to be > managed_interactive.library_interactive_id
    end
  end

  describe "portal_type" do
    it "returns iframe interactive like mw_interactive does" do
      expect(ManagedInteractive.portal_type).to eq "iframe interactive"
    end
  end

  describe "validation" do

    it "ensures custom_native_width is valid" do
      managed_interactive.custom_native_width = 100
      expect(managed_interactive).to be_valid
      managed_interactive.custom_native_width = "not an number"
      expect(managed_interactive).not_to be_valid
    end

    it "ensures custom_native_height is valid" do
      managed_interactive.custom_native_height = 100
      expect(managed_interactive).to be_valid
      managed_interactive.custom_native_height = "not an number"
      expect(managed_interactive).not_to be_valid
    end
  end

  describe "inheritance methods" do
    # NOTE: all the inherit_* attributes default to true and are tested for that along with testing if the library_interactive is nil

    it "concats the url" do
      expect(managed_interactive.url).to eq 'http://concord.org/test'
      managed_interactive.library_interactive = nil
      expect(managed_interactive.url).to eq nil
    end

    it "returns aspect_ratio_method" do
      expect(managed_interactive.aspect_ratio_method).to eq library_interactive.aspect_ratio_method
      managed_interactive.custom_aspect_ratio_method = "custom aspect_ratio_method"
      expect(managed_interactive.aspect_ratio_method).to eq library_interactive.aspect_ratio_method
      managed_interactive.inherit_aspect_ratio_method = false
      expect(managed_interactive.aspect_ratio_method).to eq "custom aspect_ratio_method"
      managed_interactive.inherit_aspect_ratio_method = true
      expect(managed_interactive.aspect_ratio_method).to eq library_interactive.aspect_ratio_method
      managed_interactive.library_interactive = nil
      expect(managed_interactive.aspect_ratio_method).to eq "custom aspect_ratio_method"
    end

    it "returns native_width" do
      expect(managed_interactive.native_width).to eq library_interactive.native_width
      managed_interactive.custom_native_width = library_interactive.native_width * 2
      expect(managed_interactive.native_width).to eq library_interactive.native_width
      managed_interactive.inherit_native_width = false
      expect(managed_interactive.native_width).to eq library_interactive.native_width * 2
      managed_interactive.inherit_native_width = true
      expect(managed_interactive.native_width).to eq library_interactive.native_width
      managed_interactive.library_interactive = nil
      expect(managed_interactive.native_width).to eq library_interactive.native_width * 2
    end

    it "returns native_height" do
      expect(managed_interactive.native_height).to eq library_interactive.native_height
      managed_interactive.custom_native_height = library_interactive.native_height * 2
      expect(managed_interactive.native_height).to eq library_interactive.native_height
      managed_interactive.inherit_native_height = false
      expect(managed_interactive.native_height).to eq library_interactive.native_height * 2
      managed_interactive.inherit_native_height = true
      expect(managed_interactive.native_height).to eq library_interactive.native_height
      managed_interactive.library_interactive = nil
      expect(managed_interactive.native_height).to eq library_interactive.native_height * 2
    end

    it "returns click_to_play" do
      expect(managed_interactive.click_to_play).to eq library_interactive.click_to_play
      managed_interactive.custom_click_to_play = !library_interactive.click_to_play
      expect(managed_interactive.click_to_play).to eq library_interactive.click_to_play
      managed_interactive.inherit_click_to_play = false
      expect(managed_interactive.click_to_play).to eq !library_interactive.click_to_play
      managed_interactive.inherit_click_to_play = true
      expect(managed_interactive.click_to_play).to eq library_interactive.click_to_play
      managed_interactive.library_interactive = nil
      expect(managed_interactive.click_to_play).to eq !library_interactive.click_to_play
    end

    it "returns full_window" do
      expect(managed_interactive.full_window).to eq library_interactive.full_window
      managed_interactive.custom_full_window = !library_interactive.full_window
      expect(managed_interactive.full_window).to eq library_interactive.full_window
      managed_interactive.inherit_full_window = false
      expect(managed_interactive.full_window).to eq !library_interactive.full_window
      managed_interactive.inherit_full_window = true
      expect(managed_interactive.full_window).to eq library_interactive.full_window
      managed_interactive.library_interactive = nil
      expect(managed_interactive.full_window).to eq !library_interactive.full_window
    end

    it "returns click_to_play_prompt" do
      expect(managed_interactive.click_to_play_prompt).to eq library_interactive.click_to_play_prompt
      managed_interactive.custom_click_to_play_prompt = "custom click_to_play_prompt"
      expect(managed_interactive.click_to_play_prompt).to eq library_interactive.click_to_play_prompt
      managed_interactive.inherit_click_to_play_prompt = false
      expect(managed_interactive.click_to_play_prompt).to eq "custom click_to_play_prompt"
      managed_interactive.inherit_click_to_play_prompt = true
      expect(managed_interactive.click_to_play_prompt).to eq library_interactive.click_to_play_prompt
      managed_interactive.library_interactive = nil
      expect(managed_interactive.click_to_play_prompt).to eq "custom click_to_play_prompt"
    end

    it "returns image_url" do
      expect(managed_interactive.image_url).to eq library_interactive.image_url
      managed_interactive.custom_image_url = "custom image_url"
      expect(managed_interactive.image_url).to eq library_interactive.image_url
      managed_interactive.inherit_image_url = false
      expect(managed_interactive.image_url).to eq "custom image_url"
      managed_interactive.inherit_image_url = true
      expect(managed_interactive.image_url).to eq library_interactive.image_url
      managed_interactive.library_interactive = nil
      expect(managed_interactive.image_url).to eq "custom image_url"
    end
  end

  describe "proxied methods" do
    it "returns enable_learner_state" do
      expect(library_interactive.enable_learner_state).to be true
      expect(managed_interactive.enable_learner_state).to eq library_interactive.enable_learner_state
      # without a library interactive it defaults to false
      managed_interactive.library_interactive = nil
      expect(managed_interactive.enable_learner_state).to be false
    end

    it "returns show_delete_data_button" do
      expect(library_interactive.show_delete_data_button).to be false
      expect(managed_interactive.show_delete_data_button).to eq library_interactive.show_delete_data_button
      # without a library interactive it defaults to true
      managed_interactive.library_interactive = nil
      expect(managed_interactive.show_delete_data_button).to be true
    end

    it "returns has_report_url" do
      expect(library_interactive.has_report_url).to be true
      expect(managed_interactive.has_report_url).to eq library_interactive.has_report_url
      # without a library interactive it defaults to false
      managed_interactive.library_interactive = nil
      expect(managed_interactive.has_report_url).to be false
    end

    it "returns no_snapshots" do
      expect(library_interactive.no_snapshots).to be true
      expect(managed_interactive.no_snapshots).to eq library_interactive.no_snapshots
      # without a library interactive it defaults to false
      managed_interactive.library_interactive = nil
      expect(managed_interactive.no_snapshots).to be false
    end
  end

  # this is only tested here and not also in mw_interactive as it all uses code in the base_interactive
  describe "interactive_item_id" do

    before :each do
      page.add_interactive(managed_interactive)
      managed_interactive.reload
      page.reload
    end

    it "has a getter" do
      expect(managed_interactive.interactive_item_id).to eq "interactive_#{managed_interactive.page_item.id}"
    end

    it "does not have a setter" do
      expect(managed_interactive.respond_to?('interactive_item_id=')).to be false
    end
  end

  describe "linked_interactive_item_id" do

    let(:mw_interactive2) { FactoryGirl.create(:mw_interactive) }

    before :each do
      page.add_interactive(mw_interactive)
      page.add_interactive(mw_interactive2)
      page.add_interactive(managed_interactive)
      managed_interactive.reload
      mw_interactive.reload
      page.reload
    end

    it "has a getter" do
      expect(managed_interactive.linked_interactive).to eq mw_interactive
      expect(managed_interactive.linked_interactive_item_id).to eq mw_interactive.interactive_item_id
      expect(mw_interactive.interactive_item_id).to_not eq nil
      expect(managed_interactive.linked_interactive_item_id).to_not eq nil
    end

    it "has a setter" do
      expect(managed_interactive.linked_interactive).to eq mw_interactive
      managed_interactive.linked_interactive_item_id = mw_interactive2.interactive_item_id
      managed_interactive.save!
      managed_interactive.reload
      expect(managed_interactive.linked_interactive).to eq mw_interactive2
    end
  end
end


text:
var sever=require("./server/server");
var router=require("./router/router");
var a={};

sever.star(router);


text:
package com.google.common.css.compiler.passes;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.css.compiler.ast.CssClassSelectorNode;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssConstantReferenceNode;
import com.google.common.css.compiler.ast.CssDefinitionNode;
import com.google.common.css.compiler.ast.CssForLoopRuleNode;
import com.google.common.css.compiler.ast.CssLoopVariableNode;
import com.google.common.css.compiler.ast.CssNumericNode;
import com.google.common.css.compiler.ast.CssPseudoClassNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.MutatingVisitController;

import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.Nullable;

/**
 * A pass that updates for loop variables with a given value.
 *
 * <p>The pass is expected to run multiple times on the same loop, where each time the loop variable
 * is replaced with a different value, according to the loop iteration.
 */
class LoopVariableReplacementPass extends DefaultTreeVisitor implements CssCompilerPass {

  private final String variable;
  private final int value;
  private final Set<String> loopDefinitions;
  private final MutatingVisitController visitController;
  private final int loopId;
  private final Pattern variableInNthArgumentPattern;

  public LoopVariableReplacementPass(
      String variable,
      int value,
      Set<String> loopDefinitions,
      MutatingVisitController visitController,
      int loopId) {
    this.variable = variable;
    this.value = value;
    this.loopDefinitions = loopDefinitions;
    this.visitController = visitController;
    this.loopId = loopId;
    variableInNthArgumentPattern =
        Pattern.compile("\\s*(?:-|\\+)?" + Pattern.quote(variable) + "n?\\s*");
  }

  @Override
  public boolean enterValueNode(CssValueNode node) {
    CssNumericNode newNode = updateValueNode(node);
    if (newNode != null) {
      visitController.replaceCurrentBlockChildWith(ImmutableList.of(newNode), true);
    }
    return true;
  }

  @Override
  public boolean enterClassSelector(CssClassSelectorNode classSelector) {
    String[] parts = classSelector.getRefinerName().split("-");
    for (int i = 0; i < parts.length; ++i) {
      parts[i] = replaceVariable(parts[i]);
    }
    String refinerName = Joiner.on("-").join(parts);
    if (!refinerName.equals(classSelector.getRefinerName())) {
      visitController.replaceCurrentBlockChildWith(
          ImmutableList.of(new CssClassSelectorNode(
              refinerName,
              classSelector.getScoping(),
              classSelector.getSourceCodeLocation())),
          true);
    }
    return true;
  }

  @Override
  public boolean enterArgumentNode(CssValueNode node) {
    CssNumericNode newNode = updateValueNode(node);
    if (newNode != null) {
      visitController.replaceCurrentBlockChildWith(ImmutableList.of(newNode), true);
    }
    return true;
  }

  @Override
  public boolean enterDefinition(CssDefinitionNode node) {
    CssValueNode definitionName = node.getName();
    definitionName.setValue(replaceDefinition(definitionName.getValue()));
    return true;
  }

  @Override
  public boolean enterPseudoClass(CssPseudoClassNode refiner) {
    if (refiner.getFunctionType().equals(CssPseudoClassNode.FunctionType.NTH)) {
      String[] parts = refiner.getArgument().split("\\+");
      for (int i = 0; i < parts.length; ++i) {
        if (variableInNthArgumentPattern.matcher(parts[i]).matches()) {
          parts[i] = parts[i].replaceFirst(Pattern.quote(variable), String.valueOf(value));
        }
      }

      refiner.setArgument(Joiner.on("+").join(parts));
    }
    return true;
  }

  @Override
  public boolean enterForLoop(CssForLoopRuleNode node) {
    CssNumericNode from = updateValueNode(node.getFrom());
    if (from != null) {
      node.setFrom(from);
    }
    CssNumericNode to = updateValueNode(node.getTo());
    if (to != null) {
      node.setTo(to);
    }
    CssNumericNode step = updateValueNode(node.getStep());
    if (step != null) {
      node.setStep(step);
    }
    return true;
  }

  /**
   * If possible updates the given node with the right value. In the case the node type has to be
   * replaced, it returns the new node.
   */
  @Nullable
  private CssNumericNode updateValueNode(CssValueNode node) {
    if (node instanceof CssConstantReferenceNode) {
      if (loopDefinitions.contains(node.getValue())) {
        node.setValue(replaceDefinition(node.getValue()));
      }
    } else if (node instanceof CssLoopVariableNode) {
      CssLoopVariableNode variableNode = (CssLoopVariableNode) node;
      if (needsReplacement(variableNode.getValue())) {
        return new CssNumericNode(
            String.valueOf(value), CssNumericNode.NO_UNITS, node.getSourceCodeLocation());
      }
    }
    return null;
  }

  private boolean needsReplacement(String identifier) {
    return identifier.equals(variable);
  }

  private String replaceVariable(String identifier) {
    return needsReplacement(identifier) ? String.valueOf(value) : identifier;
  }

  private String replaceDefinition(String definiton) {
    return definiton + "__" + "LOOP" + loopId + "__" + value;
  }

  @Override
  public void runPass() {
    visitController.startVisit(this);
  }
}


text:
package wiremap;

public class WiremapOutlinedSphere extends WiremapSphere {
    private int mOutlineThickness;
    private int mOutlineColor;

    public WiremapOutlinedSphere(Wiremap map, float x, float y, float z,
            int baseColor, float radius, int outlineThickness, int outlineColor) {
        super(map, x, y, z, baseColor, radius);
        setOutlineThickness(outlineThickness);
        setOutlineColor(outlineColor);
    }

    public void display() {
        mMap.getParent().pushMatrix();
        displayCenter();
        displayOutline();
        mMap.getParent().popMatrix();
    }

    private void displayOutline() {
        for(int i = 0; i < mMap.getWireCount(); i++) {
            // if a wire's x coord is close enough to the globe's center
            if(mMap.getWireDepth(i) >= 0
                    && (mMap.getWireX(i) >= (mX - mRadius))
                    && (mMap.getWireX(i) <= (mX + mRadius))) {
                // find the distance from the wire to the globe's center
                double localHyp;
                double actualDistance =
                        Math.sqrt(Math.pow(mMap.getWireX(i) - mX, 2)
                                + Math.pow(mMap.getWireZ(i) - mZ, 2));
                if(mMap.getWireZ(i) < mZ) {
                    localHyp =
                            Math.sqrt(Math.pow(mMap.getWireX(i) - mX, 2)
                                    + Math.pow(mMap.getWireZ(i)
                                            + mMap.getDepthUnit() / 2 - mZ, 2));
                } else {
                    localHyp =
                            Math.sqrt(Math.pow(mMap.getWireX(i) - mX, 2)
                                    + Math.pow(mMap.getWireZ(i)
                                            - mMap.getDepthUnit() / 2 - mZ, 2));
                }
                // if the wire's xz coord is close enough to the globe's center
                if(localHyp <= mRadius) {
                    // find the height of the globe at that point
                    double centerY =
                            Math.sqrt(Math.pow(mRadius, 2)
                                    - Math.pow(actualDistance, 2));
                    double yMinProjection =
                            (mY + centerY) * mMap.getDepth() / mMap.getWireZ(i);
                    double yMaxProjection =
                            (mY - centerY) * mMap.getDepth() / mMap.getWireZ(i);

                    WiremapSliver sliver =
                            new WiremapSliver(mMap,
                                    i,
                                    (int) (yMaxProjection * mMap.getPixelsPerInch()),
                                    mOutlineColor,
                                    mOutlineThickness,
                                    0,
                                    0);
                    sliver.display();

                    sliver.setStartingHeight((int) (yMinProjection * mMap.getPixelsPerInch()));
                    sliver.display();
                }
            }
        }
    }

    public void setOutlineThickness(int thickness) {
        mOutlineThickness = thickness;
    }

    public void setOutlineColor(int outlineColor) {
        mOutlineColor = outlineColor;
    }
}


text:
package org.springframework.cloud.task.listener;

import org.junit.Test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
import org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

import static org.junit.Assert.assertNotNull;

/**
 * @author Michael Minella
 * @author Ilayaperumal Gopinathan
 * @author Glenn Renfro
 */
public class TaskEventTests {

	private static final String TASK_NAME = "taskEventTest";

	@Test
	public void testDefaultConfiguration() {
		ConfigurableApplicationContext applicationContext =
				SpringApplication.run(new Class[]{PropertyPlaceholderAutoConfiguration.class,EmbeddedDataSourceConfiguration.class,TaskEventsConfiguration.class,
								TaskEventAutoConfiguration.class,
								TestSupportBinderAutoConfiguration.class},
						new String[]{ "--spring.cloud.task.closecontext_enable=false",
								"--spring.main.web-environment=false"});

		assertNotNull(applicationContext.getBean("taskEventListener"));
		assertNotNull(applicationContext.getBean(TaskEventAutoConfiguration.TaskEventChannels.class));
	}

	@Configuration
	@EnableTask
	public static class TaskEventsConfiguration {
	}

}


text:
'use strict';

const stylelint = require('../../lib');
const { caseConfigFile, caseFilesForFix, prepForSnapshot } = require('../systemTestUtils');

const CASE_NUMBER = '003';

it('fs - zen garden CSS with standard config', async () => {
	expect(
		prepForSnapshot(
			await stylelint.lint({
				files: await caseFilesForFix(CASE_NUMBER),
				configFile: caseConfigFile(CASE_NUMBER),
				fix: true,
			}),
		),
	).toMatchSnapshot();
}, 10000);


text:
package com.alibaba.dubbo.common.store.support;

import com.alibaba.dubbo.common.store.DataStore;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class SimpleDataStore implements DataStore {

    // <component name or id, <data-name, data-value>>
    private ConcurrentMap<String, ConcurrentMap<String, Object>> data =
            new ConcurrentHashMap<String, ConcurrentMap<String, Object>>();

    public Map<String, Object> get(String componentName) {
        ConcurrentMap<String, Object> value = data.get(componentName);
        if (value == null) return new HashMap<String, Object>();

        return new HashMap<String, Object>(value);
    }

    public Object get(String componentName, String key) {
        if (!data.containsKey(componentName)) {
            return null;
        }
        return data.get(componentName).get(key);
    }

    public void put(String componentName, String key, Object value) {
        Map<String, Object> componentData = data.get(componentName);
        if (null == componentData) {
            data.putIfAbsent(componentName, new ConcurrentHashMap<String, Object>());
            componentData = data.get(componentName);
        }
        componentData.put(key, value);
    }

    public void remove(String componentName, String key) {
        if (!data.containsKey(componentName)) {
            return;
        }
        data.get(componentName).remove(key);
    }

}


text:
NAME=cl-vectors
VERSION="`cat VERSION`"
FULLNAME="$NAME-$VERSION"
TARGET="./dist/$FULLNAME"
TARGZ="$TARGET.tar.gz"
if [ -e "$TARGZ" ]; then
  echo "$TARGZ already exists."
  exit 1
fi
mkdir -p "$TARGET" && rm -rf "$TARGET" && mkdir "$TARGET"
cat MANIFEST|while read FN; do cp "$FN" "$TARGET/$FN"; done
(cd "$TARGET"; sed -i 's/\$VERSION\$/'"$VERSION"'/' *.asd)
tar cvzfC "$TARGZ" "$TARGET/.." "$FULLNAME"


text:
CREATE ROLE mtd_db_owner1;
CREATE ROLE mtd_db_owner2;

--CREATE DATABASE mtd_db_name1 WITH OWNER = mtd_db_owner1 TEMPLATE =template1 ENCODING='latin8'  CONNECTION LIMIT= 2;
CREATE DATABASE mtd_db_name1 WITH OWNER = mtd_db_owner1 TEMPLATE =template1 CONNECTION LIMIT= 2;
ALTER DATABASE mtd_db_name1 WITH  CONNECTION LIMIT 3;

CREATE DATABASE mtd_db_name2 with OWNER=mtd_db_owner1;
ALTER DATABASE mtd_db_name2  RENAME TO mtd_new_db_name2;

CREATE DATABASE mtd_new_db_name1 with OWNER=mtd_db_owner1;
ALTER DATABASE mtd_new_db_name1  OWNER TO mtd_db_owner2;

CREATE SCHEMA mtd_myschema;
CREATE DATABASE mtd_db_name3;
ALTER DATABASE mtd_db_name3 SET search_path TO mtd_myschema, public, pg_catalog;

CREATE DATABASE mtd_db_name4;
ALTER DATABASE mtd_db_name4 SET search_path TO mtd_myschema, public, pg_catalog;
ALTER DATABASE mtd_db_name4 RESET search_path;

CREATE DATABASE mtd_db_name5;
ALTER DATABASE mtd_db_name5 SET search_path TO mtd_myschema, public, pg_catalog;
ALTER DATABASE mtd_db_name5 RESET ALL;

drop database mtd_db_name1;
drop database mtd_db_name3;
drop database mtd_db_name4;
drop database mtd_db_name5;
drop database mtd_new_db_name1;
drop database mtd_new_db_name2;
drop schema mtd_myschema;
drop role mtd_db_owner1;
drop role mtd_db_owner2;


text:
Panel for the [Django Debug Toolbar](https://github.com/django-debug-toolbar/django-debug-toolbar)
to easily and quickly switch between users.
 * View details on the currently logged in user.
 * Easily switch between recently logged in users.
 * Login as any user from an arbitrary email address, username or user ID.

#####Requirements

* Django 1.10
* Python 3.5
* Django Debug Toolbar 1.6

##Installation

Add ``djdt_user_panel`` to your ``INSTALLED_APPS``

    INSTALLED_APPS = (
    ...
        'djdt_user_panel',
        ...
    )

Add ``djdt_user_panel.panels.UserPanel`` to ``DEBUG_TOOLBAR_PANELS``

    DEBUG_TOOLBAR_PANELS = (
        'djdt_user_panel.panels.UserPanel',
        'debug_toolbar.panels.versions.VersionsPanel',
        'debug_toolbar.panels.timer.TimerPanel',
        'debug_toolbar.panels.settings.SettingsPanel',
        'debug_toolbar.panels.headers.HeadersPanel',
        'debug_toolbar.panels.request.RequestPanel',
        'debug_toolbar.panels.sql.SQLPanel',
        'debug_toolbar.panels.staticfiles.StaticFilesPanel',
        'debug_toolbar.panels.templates.TemplatesPanel',
        'debug_toolbar.panels.cache.CachePanel',
        'debug_toolbar.panels.signals.SignalsPanel',
        'debug_toolbar.panels.logging.LoggingPanel',
        'debug_toolbar.panels.redirects.RedirectsPanel',
    )

You can disable any of the above panels you do not wish to show in the Debug Toolbar by removing them or commenting them out.

##Links
 Based on original code by [playfire](https://github.com/playfire/django-debug-toolbar-user-panel)


text:
/** Automatically generated file. DO NOT MODIFY */
package net.everythingandroid.smspopup;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Grid Demo</title>
  <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono|IBM+Plex+Sans" rel="stylesheet">
  <link rel="stylesheet" href="./styles.scss">


text:
.class Lcom/android/server/LockSettingsStorage$Cache;
.super Ljava/lang/Object;
.source "LockSettingsStorage.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/LockSettingsStorage;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Cache"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/server/LockSettingsStorage$Cache$CacheKey;
    }
.end annotation

# instance fields
.field private final mCache:Landroid/util/ArrayMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/util/ArrayMap",
            "<",
            "Lcom/android/server/LockSettingsStorage$Cache$CacheKey;",
            "Ljava/lang/Object;",
            ">;"
        }
    .end annotation
.end field

.field private final mCacheKey:Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

.field private mVersion:I

# direct methods
.method private constructor <init>()V
    .locals 2

    .prologue
    .line 388
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 389
    new-instance v0, Landroid/util/ArrayMap;

    invoke-direct {v0}, Landroid/util/ArrayMap;-><init>()V

    iput-object v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    .line 390
    new-instance v0, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    const/4 v1, 0x0

    invoke-direct {v0, v1}, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;-><init>(Lcom/android/server/LockSettingsStorage$1;)V

    iput-object v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCacheKey:Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    .line 391
    const/4 v0, 0x0

    iput v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I

    .line 476
    return-void
.end method

.method synthetic constructor <init>(Lcom/android/server/LockSettingsStorage$1;)V
    .locals 0
    .param p1, "x0"    # Lcom/android/server/LockSettingsStorage$1;

    .prologue
    .line 388
    invoke-direct {p0}, Lcom/android/server/LockSettingsStorage$Cache;-><init>()V

    return-void
.end method

.method static synthetic access$100(Lcom/android/server/LockSettingsStorage$Cache;)I
    .locals 1
    .param p0, "x0"    # Lcom/android/server/LockSettingsStorage$Cache;

    .prologue
    .line 388
    invoke-direct {p0}, Lcom/android/server/LockSettingsStorage$Cache;->getVersion()I

    move-result v0

    return v0
.end method

.method private declared-synchronized contains(ILjava/lang/String;I)Z
    .locals 2
    .param p1, "type"    # I
    .param p2, "key"    # Ljava/lang/String;
    .param p3, "userId"    # I

    .prologue
    .line 449
    monitor-enter p0

    :try_start_0
    iget-object v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    iget-object v1, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCacheKey:Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    invoke-virtual {v1, p1, p2, p3}, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;->set(ILjava/lang/String;I)Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/util/ArrayMap;->containsKey(Ljava/lang/Object;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result v0

    monitor-exit p0

    return v0

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method private declared-synchronized getVersion()I
    .locals 1

    .prologue
    .line 457
    monitor-enter p0

    :try_start_0
    iget v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit p0

    return v0

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method private declared-synchronized peek(ILjava/lang/String;I)Ljava/lang/Object;
    .locals 2
    .param p1, "type"    # I
    .param p2, "key"    # Ljava/lang/String;
    .param p3, "userId"    # I

    .prologue
    .line 453
    monitor-enter p0

    :try_start_0
    iget-object v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    iget-object v1, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCacheKey:Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    invoke-virtual {v1, p1, p2, p3}, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;->set(ILjava/lang/String;I)Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/util/ArrayMap;->get(Ljava/lang/Object;)Ljava/lang/Object;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v0

    monitor-exit p0

    return-object v0

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method private declared-synchronized put(ILjava/lang/String;Ljava/lang/Object;I)V
    .locals 3
    .param p1, "type"    # I
    .param p2, "key"    # Ljava/lang/String;
    .param p3, "value"    # Ljava/lang/Object;
    .param p4, "userId"    # I

    .prologue
    .line 437
    monitor-enter p0

    :try_start_0
    iget-object v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    new-instance v1, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    const/4 v2, 0x0

    invoke-direct {v1, v2}, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;-><init>(Lcom/android/server/LockSettingsStorage$1;)V

    invoke-virtual {v1, p1, p2, p4}, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;->set(ILjava/lang/String;I)Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    move-result-object v1

    invoke-virtual {v0, v1, p3}, Landroid/util/ArrayMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 438
    iget v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I

    add-int/lit8 v0, v0, 0x1

    iput v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 439
    monitor-exit p0

    return-void

    .line 437
    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method private declared-synchronized putIfUnchanged(ILjava/lang/String;Ljava/lang/Object;II)V
    .locals 1
    .param p1, "type"    # I
    .param p2, "key"    # Ljava/lang/String;
    .param p3, "value"    # Ljava/lang/Object;
    .param p4, "userId"    # I
    .param p5, "version"    # I

    .prologue
    .line 443
    monitor-enter p0

    :try_start_0
    invoke-direct {p0, p1, p2, p4}, Lcom/android/server/LockSettingsStorage$Cache;->contains(ILjava/lang/String;I)Z

    move-result v0

    if-nez v0, :cond_0

    iget v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I

    if-ne v0, p5, :cond_0

    .line 444
    invoke-direct {p0, p1, p2, p3, p4}, Lcom/android/server/LockSettingsStorage$Cache;->put(ILjava/lang/String;Ljava/lang/Object;I)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 446
    :cond_0
    monitor-exit p0

    return-void

    .line 443
    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

# virtual methods
.method declared-synchronized clear()V
    .locals 1

    .prologue
    .line 472
    monitor-enter p0

    :try_start_0
    iget-object v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    invoke-virtual {v0}, Landroid/util/ArrayMap;->clear()V

    .line 473
    iget v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I

    add-int/lit8 v0, v0, 0x1

    iput v0, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 474
    monitor-exit p0

    return-void

    .line 472
    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method hasFile(Ljava/lang/String;)Z
    .locals 2
    .param p1, "fileName"    # Ljava/lang/String;

    .prologue
    .line 415
    const/4 v0, 0x1

    const/4 v1, -0x1

    invoke-direct {p0, v0, p1, v1}, Lcom/android/server/LockSettingsStorage$Cache;->contains(ILjava/lang/String;I)Z

    move-result v0

    return v0
.end method

.method hasKeyValue(Ljava/lang/String;I)Z
    .locals 1
    .param p1, "key"    # Ljava/lang/String;
    .param p2, "userId"    # I

    .prologue
    .line 399
    const/4 v0, 0x0

    invoke-direct {p0, v0, p1, p2}, Lcom/android/server/LockSettingsStorage$Cache;->contains(ILjava/lang/String;I)Z

    move-result v0

    return v0
.end method

.method isFetched(I)Z
    .locals 2
    .param p1, "userId"    # I

    .prologue
    .line 431
    const/4 v0, 0x2

    const-string v1, ""

    invoke-direct {p0, v0, v1, p1}, Lcom/android/server/LockSettingsStorage$Cache;->contains(ILjava/lang/String;I)Z

    move-result v0

    return v0
.end method

.method peekFile(Ljava/lang/String;)[B
    .locals 2
    .param p1, "fileName"    # Ljava/lang/String;

    .prologue
    .line 411
    const/4 v0, 0x1

    const/4 v1, -0x1

    invoke-direct {p0, v0, p1, v1}, Lcom/android/server/LockSettingsStorage$Cache;->peek(ILjava/lang/String;I)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [B

    check-cast v0, [B

    return-object v0
.end method

.method peekKeyValue(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/String;
    .locals 2
    .param p1, "key"    # Ljava/lang/String;
    .param p2, "defaultValue"    # Ljava/lang/String;
    .param p3, "userId"    # I

    .prologue
    .line 394
    const/4 v1, 0x0

    invoke-direct {p0, v1, p1, p3}, Lcom/android/server/LockSettingsStorage$Cache;->peek(ILjava/lang/String;I)Ljava/lang/Object;

    move-result-object v0

    .line 395
    .local v0, "cached":Ljava/lang/Object;
    # getter for: Lcom/android/server/LockSettingsStorage;->DEFAULT:Ljava/lang/Object;
    invoke-static {}, Lcom/android/server/LockSettingsStorage;->access$300()Ljava/lang/Object;

    move-result-object v1

    if-ne v0, v1, :cond_0

    .end local v0    # "cached":Ljava/lang/Object;
    .end local p2    # "defaultValue":Ljava/lang/String;
    :goto_0
    return-object p2

    .restart local v0    # "cached":Ljava/lang/Object;
    .restart local p2    # "defaultValue":Ljava/lang/String;
    :cond_0
    check-cast v0, Ljava/lang/String;

    move-object p2, v0

    goto :goto_0
.end method

.method putFile(Ljava/lang/String;[B)V
    .locals 2
    .param p1, "key"    # Ljava/lang/String;
    .param p2, "value"    # [B

    .prologue
    .line 419
    const/4 v0, 0x1

    const/4 v1, -0x1

    invoke-direct {p0, v0, p1, p2, v1}, Lcom/android/server/LockSettingsStorage$Cache;->put(ILjava/lang/String;Ljava/lang/Object;I)V

    .line 420
    return-void
.end method

.method putFileIfUnchanged(Ljava/lang/String;[BI)V
    .locals 6
    .param p1, "key"    # Ljava/lang/String;
    .param p2, "value"    # [B
    .param p3, "version"    # I

    .prologue
    .line 423
    const/4 v1, 0x1

    const/4 v4, -0x1

    move-object v0, p0

    move-object v2, p1

    move-object v3, p2

    move v5, p3

    invoke-direct/range {v0 .. v5}, Lcom/android/server/LockSettingsStorage$Cache;->putIfUnchanged(ILjava/lang/String;Ljava/lang/Object;II)V

    .line 424
    return-void
.end method

.method putKeyValue(Ljava/lang/String;Ljava/lang/String;I)V
    .locals 1
    .param p1, "key"    # Ljava/lang/String;
    .param p2, "value"    # Ljava/lang/String;
    .param p3, "userId"    # I

    .prologue
    .line 403
    const/4 v0, 0x0

    invoke-direct {p0, v0, p1, p2, p3}, Lcom/android/server/LockSettingsStorage$Cache;->put(ILjava/lang/String;Ljava/lang/Object;I)V

    .line 404
    return-void
.end method

.method putKeyValueIfUnchanged(Ljava/lang/String;Ljava/lang/Object;II)V
    .locals 6
    .param p1, "key"    # Ljava/lang/String;
    .param p2, "value"    # Ljava/lang/Object;
    .param p3, "userId"    # I
    .param p4, "version"    # I

    .prologue
    .line 407
    const/4 v1, 0x0

    move-object v0, p0

    move-object v2, p1

    move-object v3, p2

    move v4, p3

    move v5, p4

    invoke-direct/range {v0 .. v5}, Lcom/android/server/LockSettingsStorage$Cache;->putIfUnchanged(ILjava/lang/String;Ljava/lang/Object;II)V

    .line 408
    return-void
.end method

.method declared-synchronized removeUser(I)V
    .locals 2
    .param p1, "userId"    # I

    .prologue
    .line 461
    monitor-enter p0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    invoke-virtual {v1}, Landroid/util/ArrayMap;->size()I

    move-result v1

    add-int/lit8 v0, v1, -0x1

    .local v0, "i":I
    :goto_0
    if-ltz v0, :cond_1

    .line 462
    iget-object v1, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    invoke-virtual {v1, v0}, Landroid/util/ArrayMap;->keyAt(I)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;

    iget v1, v1, Lcom/android/server/LockSettingsStorage$Cache$CacheKey;->userId:I

    if-ne v1, p1, :cond_0

    .line 463
    iget-object v1, p0, Lcom/android/server/LockSettingsStorage$Cache;->mCache:Landroid/util/ArrayMap;

    invoke-virtual {v1, v0}, Landroid/util/ArrayMap;->removeAt(I)Ljava/lang/Object;

    .line 461
    :cond_0
    add-int/lit8 v0, v0, -0x1

    goto :goto_0

    .line 468
    :cond_1
    iget v1, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I

    add-int/lit8 v1, v1, 0x1

    iput v1, p0, Lcom/android/server/LockSettingsStorage$Cache;->mVersion:I
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 469
    monitor-exit p0

    return-void

    .line 461
    .end local v0    # "i":I
    :catchall_0
    move-exception v1

    monitor-exit p0

    throw v1
.end method

.method setFetched(I)V
    .locals 3
    .param p1, "userId"    # I

    .prologue
    .line 427
    const/4 v0, 0x2

    const-string v1, "isFetched"

    const-string v2, "true"

    invoke-direct {p0, v0, v1, v2, p1}, Lcom/android/server/LockSettingsStorage$Cache;->put(ILjava/lang/String;Ljava/lang/Object;I)V

    .line 428
    return-void
.end method


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

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.backup.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * BackupSelectionMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class BackupSelectionMarshaller {

    private static final MarshallingInfo<String> SELECTIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SelectionName").build();
    private static final MarshallingInfo<String> IAMROLEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("IamRoleArn").build();
    private static final MarshallingInfo<List> RESOURCES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Resources").build();
    private static final MarshallingInfo<List> LISTOFTAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ListOfTags").build();

    private static final BackupSelectionMarshaller instance = new BackupSelectionMarshaller();

    public static BackupSelectionMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(BackupSelection backupSelection, ProtocolMarshaller protocolMarshaller) {

        if (backupSelection == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(backupSelection.getSelectionName(), SELECTIONNAME_BINDING);
            protocolMarshaller.marshall(backupSelection.getIamRoleArn(), IAMROLEARN_BINDING);
            protocolMarshaller.marshall(backupSelection.getResources(), RESOURCES_BINDING);
            protocolMarshaller.marshall(backupSelection.getListOfTags(), LISTOFTAGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
var FormFileUpload = function () {

    return {
        //main function to initiate the module
        init: function () {

            // Initialize the jQuery File Upload widget:
            $('#fileupload').fileupload({
                // Uncomment the following to send cross-domain cookies:
                //xhrFields: {withCredentials: true},
                url: 'assets/plugins/jquery-file-upload/server/php/'
            });

            // Enable iframe cross-domain access via redirect option:
            $('#fileupload').fileupload(
                'option',
                'redirect',
                window.location.href.replace(
                    /\/[^\/]*$/,
                    '/cors/result.html?%s'
                )
            );

            // Demo settings:
            $('#fileupload').fileupload('option', {
                url: $('#fileupload').fileupload('option', 'url'),
                // Enable image resizing, except for Android and Opera,
                // which actually support image resizing, but fail to
                // send Blob objects via XHR requests:
                disableImageResize: /Android(?!.*Chrome)|Opera/
                    .test(window.navigator.userAgent),
                maxFileSize: 5000000,
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
            });

            // Upload server status check for browsers with CORS support:
            if ($.support.cors) {
                $.ajax({
                    url: 'assets/plugins/jquery-file-upload/server/php/',
                    type: 'HEAD'
                }).fail(function () {
                        $('<div class="alert alert-danger"/>')
                            .text('Upload server currently unavailable - ' +
                                new Date())
                            .appendTo('#fileupload');
                    });
            }

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

            // Initialize the jQuery File Upload widget:
            $('#fileupload').fileupload({
                // Uncomment the following to send cross-domain cookies:
                //xhrFields: {withCredentials: true},
                autoUpload: false,
                url: 'assets/plugins/jquery-file-upload/server/php/'
            });

            // initialize uniform checkboxes
            App.initUniform('.fileupload-toggle-checkbox');
        }

    };

}();


text:
<?php
/**
 * Created by PhpStorm.
 * User: brodriguez
 * Date: 04/12/16
 * Time: 09:58 PM
 */

namespace Usuarios\Controller;

use Application\Entity\User;
use HtProfileImage\Service\ProfileImageServiceInterface;
use Negotiation\FormatNegotiator;
use Usuarios\Form\CrearUsuarioFilter;
use Usuarios\Form\EditarUsuarioForm;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Paginator\Adapter\ArrayAdapter;
use Zend\Paginator\Paginator;
use Zend\View\Model\ViewModel;
use ZfcUser\Options\ModuleOptions;

class UsuariosController extends AbstractActionController
{
    protected $options, $userMapper, $optionsImage;
    protected $zfcUserOptions;
    protected $adminUserService;
    protected $profileImageService;
    protected $roleMapper;
    protected $usuarioMapper;
    protected $rolesMapper;

    public function __construct()
    {

    }

    public function indexAction()
    {
        $usuarioMapper = $this->getUsuarioMapper();
        $users = $usuarioMapper->fetchAll();

        $users->buffer();
        foreach ($users as $user){
            $roles = $this->getMyRoleMapper()->getRolesById($user->getId());
            $user->addRole($roles);
        }

        return array(
            'users' => $users,
        );
    }

    public function getMyRoleMapper()
    {
        if (null === $this->rolesMapper) {
            $this->rolesMapper = $this->getServiceLocator()->get('RoleMapper');
        }
        return $this->rolesMapper;
    }

    public function getUsuarioMapper()
    {
        if (null === $this->usuarioMapper) {
            $this->usuarioMapper = $this->getServiceLocator()->get('UsuarioMapper');
        }
        return $this->usuarioMapper;
    }

    public function editAction()
    {
        $userId = $this->getEvent()->getRouteMatch()->getParam('userId');
        $user = $this->getUsuarioMapper()->findById($userId);

        $formulario = $this->getServiceLocator()->get('EditarUsuarioForm');
        $formulario->bind($user);
        $formulario->get('rolId')->setValue(null);
        $roles = $this->getMyRoleMapper()->getRolesById($user->getId());
        $id = $roles->getId();
        $formulario->get('select_roles')->setValue($id);
        $formulario->get('rolId')->setValue($id);
        $formImage = $this->getServiceLocator()->get('HtProfileImage\ProfileImageForm');

        $request = $this->getRequest();
        $imageUploaded = false;
        if ($request->isPost()) {
            $submit = $request->getPost()->get('submit');
            if ($submit === 'Upload'){
                $negotiator   = new FormatNegotiator();
                $format = $negotiator->getBest(
                    $request->getHeader('Accept')->getFieldValue(),
                    ['application/json', 'text/html']
                );
                $profileImageService = $this->getServiceLocator()->get('HtProfileImage\Service\ProfileImageService');
                $this->profileImageService = $profileImageService;
                if ($this->profileImageService->storeImage($user, $request->getFiles()->toArray())) {
                    if ($format->getValue() === 'application/json') {
                        return new Model\JsonModel([
                            'uploaded' => true
                        ]);
                    } else {
                        $formulario->populateFromUser($user);
                        $imageUploaded = true;
                        return array(
                            'editUserForm' => $formulario,
                            'userId' => $userId,
                            'formImage' => $formImage,
                            'imageUploaded' => $imageUploaded,
                        );
                    }
                    $imageUploaded = true;
                } else {
                    $response = $this->getResponse();
                    /** @var \Zend\Http\Response $response */
                    $response->setStatusCode(400);
                    if ($format->getValue() === 'application/json') {
                        return new Model\JsonModel([
                            'error' => true,
                            'messages' => $form->getMessages()
                        ]);
                    }

                }
            }

            if ($submit === 'Guardar'){
                $formulario->setData($request->getPost());
                if ($formulario->isValid()) {
                    if ($request->getPost()->get('password') === ""){
                        $user->setPassword(null);
                    }
                    $user = $this->getUsuarioMapper()->edit($formulario, (array)$request->getPost(), $user);
                    if ($user) {
                        $rolId = $request->getPost()->get('rolId');
                        $roleId = $this->getMyRoleMapper()->getRoleId($rolId);
                        $userId =$user->getId();

                        $this->getMyRoleMapper()->update($userId, $roleId);

                        $user->addRole($rolId);
                        $this->flashMessenger()->addSuccessMessage('El Usuario fue editado');
                        return $this->redirect()->toRoute('usuarios');
                    }
                }
            }

        } else {
            $formulario->populateFromUser($user);
        }

        return array(
            'editUserForm' => $formulario,
            'userId' => $userId,
            'formImage' => $formImage,
            'imageUploaded' => $imageUploaded,
        );
    }

    public function createAction()
    {
        $user = new User();

        $formulario = $this->getServiceLocator()->get('EditarUsuarioForm');
        $formulario->setInputFilter(new CrearUsuarioFilter());
        $formulario->bind($user);
        $formulario->get('rolId')->setValue(null);
        $formImage = $this->getServiceLocator()->get('HtProfileImage\ProfileImageForm');

        $request = $this->getRequest();
        $imageUploaded = false;

        if ($request->isPost()) {
            $submit = $request->getPost()->get('submit');

            if ($submit === 'Upload'){
                $negotiator   = new FormatNegotiator();
                $format = $negotiator->getBest(
                    $request->getHeader('Accept')->getFieldValue(),
                    ['application/json', 'text/html']
                );
                $profileImageService = $this->getServiceLocator()->get('HtProfileImage\Service\ProfileImageService');
                $this->profileImageService = $profileImageService;
                if ($this->profileImageService->storeImage($user, $request->getFiles()->toArray())) {
                    if ($format->getValue() === 'application/json') {
                        return new Model\JsonModel([
                            'uploaded' => true
                        ]);
                    } else {
                        $formulario->populateFromUser($user);
                        $imageUploaded = true;
                        return array(
                            'editUserForm' => $formulario,
                            'formImage' => $formImage,
                            'imageUploaded' => $imageUploaded,
                        );
                    }
                    $imageUploaded = true;
                } else {
                    $response = $this->getResponse();
                    /** @var \Zend\Http\Response $response */
                    $response->setStatusCode(400);
                    if ($format->getValue() === 'application/json') {
                        return new Model\JsonModel([
                            'error' => true,
                            'messages' => $form->getMessages()
                        ]);
                    }

                }
            }

            if ($submit === 'Guardar'){
                $formulario->setData($request->getPost());
                if ($formulario->isValid()) {
                    if ($request->getPost()->get('password') === ""){
                        $user->setPassword(null);
                    }
                    $user = $this->getUsuarioMapper()->edit($formulario, (array)$request->getPost(), $user);
                    if ($user) {
                        $rolId = $request->getPost()->get('rolId');
                        $roleId = $this->getMyRoleMapper()->getRoleId($rolId);
                        $userId =$user->getId();

                        $this->getMyRoleMapper()->save($userId, $roleId);

                        $user->addRole($rolId);
                        $this->flashMessenger()->addSuccessMessage('El Usuario fue editado');
                        return $this->redirect()->toRoute('usuarios');
                    }
                }
            }

        }

        return array(
            'editUserForm' => $formulario,
            'formImage' => $formImage,
            'imageUploaded' => $imageUploaded,
        );
    }
}