text:
Copyright (c) 2014 Google Inc.

See LICENSE file for full terms of limited license.
]]

require 'image'

local trans = torch.class('dqn.TransitionTable')

function trans:__init(args)
    self.stateDim = args.stateDim
    self.numActions = args.numActions
    self.histLen = args.histLen
    self.maxSize = args.maxSize or 1024^2
    self.bufferSize = args.bufferSize or 1024
    self.histType = args.histType or "linear"
    self.histSpacing = args.histSpacing or 1
    self.zeroFrames = args.zeroFrames or 1
    self.nonTermProb = args.nonTermProb or 1
    self.nonEventProb = args.nonEventProb or 1
    self.gpu = args.gpu
    self.numEntries = 0
    self.insertIndex = 0

    self.histIndices = {}
    local histLen = self.histLen
    if self.histType == "linear" then
        -- History is the last histLen frames.
        self.recentMemSize = self.histSpacing*histLen
        for i=1,histLen do
            self.histIndices[i] = i*self.histSpacing
        end
    elseif self.histType == "exp2" then
        -- The ith history frame is from 2^(i-1) frames ago.
        self.recentMemSize = 2^(histLen-1)
        self.histIndices[1] = 1
        for i=1,histLen-1 do
            self.histIndices[i+1] = self.histIndices[i] + 2^(7-i)
        end
    elseif self.histType == "exp1.25" then
        -- The ith history frame is from 1.25^(i-1) frames ago.
        self.histIndices[histLen] = 1
        for i=histLen-1,1,-1 do
            self.histIndices[i] = math.ceil(1.25*self.histIndices[i+1])+1
        end
        self.recentMemSize = self.histIndices[1]
        for i=1,histLen do
            self.histIndices[i] = self.recentMemSize - self.histIndices[i] + 1
        end
    end

    self.s = torch.ByteTensor(self.maxSize, self.stateDim):fill(0)
    self.a = torch.LongTensor(self.maxSize):fill(0)
    self.r = torch.zeros(self.maxSize)
    self.t = torch.ByteTensor(self.maxSize):fill(0)
    self.action_encodings = torch.eye(self.numActions)

    -- Tables for storing the last histLen states.  They are used for
    -- constructing the most recent agent state more easily.
    self.recent_s = {}
    self.recent_a = {}
    self.recent_t = {}

    local s_size = self.stateDim*histLen
    self.buf_a      = torch.LongTensor(self.bufferSize):fill(0)
    self.buf_r      = torch.zeros(self.bufferSize)
    self.buf_term   = torch.ByteTensor(self.bufferSize):fill(0)
    self.buf_s      = torch.ByteTensor(self.bufferSize, s_size):fill(0)
    self.buf_s2     = torch.ByteTensor(self.bufferSize, s_size):fill(0)

    if self.gpu and self.gpu >= 0 then
        self.gpu_s  = self.buf_s:float():cuda()
        self.gpu_s2 = self.buf_s2:float():cuda()
    end
end

function trans:reset()
    self.numEntries = 0
    self.insertIndex = 0
end

function trans:size()
    return self.numEntries
end

function trans:empty()
    return self.numEntries == 0
end

function trans:fill_buffer()
    assert(self.numEntries >= self.bufferSize)
    -- clear CPU buffers
    self.buf_ind = 1
    local ind
    for buf_ind=1,self.bufferSize do
        local s, a, r, s2, term = self:sample_one(1)
        self.buf_s[buf_ind]:copy(s)
        self.buf_a[buf_ind] = a
        self.buf_r[buf_ind] = r
        self.buf_s2[buf_ind]:copy(s2)
        self.buf_term[buf_ind] = term
    end
    self.buf_s  = self.buf_s:float():div(255)
    self.buf_s2 = self.buf_s2:float():div(255)
    if self.gpu and self.gpu >= 0 then
        self.gpu_s:copy(self.buf_s)
        self.gpu_s2:copy(self.buf_s2)
    end
end

function trans:sample_one()
    assert(self.numEntries > 1)
    local index
    local valid = false
    while not valid do
        -- start at 2 because of previous action
        index = torch.random(2, self.numEntries-self.recentMemSize)
        if self.t[index+self.recentMemSize-1] == 0 then
            valid = true
        end
        if self.nonTermProb < 1 and self.t[index+self.recentMemSize] == 0 and
            torch.uniform() > self.nonTermProb then
            -- Discard non-terminal states with probability (1-nonTermProb).
            -- Note that this is the terminal flag for s_{t+1}.
            valid = false
        end
        if self.nonEventProb < 1 and self.t[index+self.recentMemSize] == 0 and
            self.r[index+self.recentMemSize-1] == 0 and
            torch.uniform() > self.nonTermProb then
            -- Discard non-terminal or non-reward states with
            -- probability (1-nonTermProb).
            valid = false
        end
    end

    return self:get(index)
end

function trans:sample(batch_size)
    local batch_size = batch_size or 1
    assert(batch_size < self.bufferSize)

    if not self.buf_ind or self.buf_ind + batch_size - 1 > self.bufferSize then
        self:fill_buffer()
    end

    local index = self.buf_ind

    self.buf_ind = self.buf_ind+batch_size
    local range = {{index, index+batch_size-1}}

    local buf_s, buf_s2, buf_a, buf_r, buf_term = self.buf_s, self.buf_s2,
        self.buf_a, self.buf_r, self.buf_term
    if self.gpu and self.gpu >=0  then
        buf_s = self.gpu_s
        buf_s2 = self.gpu_s2
    end

    return buf_s[range], buf_a[range], buf_r[range], buf_s2[range], buf_term[range]
end

function trans:concatFrames(index, use_recent)
    if use_recent then
        s, t = self.recent_s, self.recent_t
    else
        s, t = self.s, self.t
    end

    local fullstate = s[1].new()
    fullstate:resize(self.histLen, unpack(s[1]:size():totable()))

    -- Zero out frames from all but the most recent episode.
    local zero_out = false
    local episode_start = self.histLen

    for i=self.histLen-1,1,-1 do
        if not zero_out then
            for j=index+self.histIndices[i]-1,index+self.histIndices[i+1]-2 do
                if t[j] == 1 then
                    zero_out = true
                    break
                end
            end
        end

        if zero_out then
            fullstate[i]:zero()
        else
            episode_start = i
        end
    end

    if self.zeroFrames == 0 then
        episode_start = 1
    end

    -- Copy frames from the current episode.
    for i=episode_start,self.histLen do
        fullstate[i]:copy(s[index+self.histIndices[i]-1])
    end

    return fullstate
end

function trans:concatActions(index, use_recent)
    local act_hist = torch.FloatTensor(self.histLen, self.numActions)
    if use_recent then
        a, t = self.recent_a, self.recent_t
    else
        a, t = self.a, self.t
    end

    -- Zero out frames from all but the most recent episode.
    local zero_out = false
    local episode_start = self.histLen

    for i=self.histLen-1,1,-1 do
        if not zero_out then
            for j=index+self.histIndices[i]-1,index+self.histIndices[i+1]-2 do
                if t[j] == 1 then
                    zero_out = true
                    break
                end
            end
        end

        if zero_out then
            act_hist[i]:zero()
        else
            episode_start = i
        end
    end

    if self.zeroFrames == 0 then
        episode_start = 1
    end

    -- Copy frames from the current episode.
    for i=episode_start,self.histLen do
        act_hist[i]:copy(self.action_encodings[a[index+self.histIndices[i]-1]])
    end

    return act_hist
end

function trans:get_recent()
    -- Assumes that the most recent state has been added, but the action has not
    return self:concatFrames(1, true):float():div(255)
end

function trans:get(index)
    local s = self:concatFrames(index)
    local s2 = self:concatFrames(index+1)
    local ar_index = index+self.recentMemSize-1

    return s, self.a[ar_index], self.r[ar_index], s2, self.t[ar_index+1]
end

function trans:add(s, a, r, term)
    assert(s, 'State cannot be nil')
    assert(a, 'Action cannot be nil')
    assert(r, 'Reward cannot be nil')

    -- Incremenet until at full capacity
    if self.numEntries < self.maxSize then
        self.numEntries = self.numEntries + 1
    end

    -- Always insert at next index, then wrap around
    self.insertIndex = self.insertIndex + 1
    -- Overwrite oldest experience once at capacity
    if self.insertIndex > self.maxSize then
        self.insertIndex = 1
    end

    -- Overwrite (s,a,r,t) at insertIndex
    self.s[self.insertIndex] = s:clone():float():mul(255)
    self.a[self.insertIndex] = a
    self.r[self.insertIndex] = r
    if term then
        self.t[self.insertIndex] = 1
    else
        self.t[self.insertIndex] = 0
    end
end

function trans:add_recent_state(s, term)
    local s = s:clone():float():mul(255):byte()
    if #self.recent_s == 0 then
        for i=1,self.recentMemSize do
            table.insert(self.recent_s, s:clone():zero())
            table.insert(self.recent_t, 1)
        end
    end

    table.insert(self.recent_s, s)
    if term then
        table.insert(self.recent_t, 1)
    else
        table.insert(self.recent_t, 0)
    end

    -- Keep recentMemSize states.
    if #self.recent_s > self.recentMemSize then
        table.remove(self.recent_s, 1)
        table.remove(self.recent_t, 1)
    end
end

function trans:add_recent_action(a)
    if #self.recent_a == 0 then
        for i=1,self.recentMemSize do
            table.insert(self.recent_a, 1)
        end
    end

    table.insert(self.recent_a, a)

    -- Keep recentMemSize steps.
    if #self.recent_a > self.recentMemSize then
        table.remove(self.recent_a, 1)
    end
end

--[[
Override the write function to serialize this class into a file.
We do not want to store anything into the file, just the necessary info
to create an empty transition table.

@param file (FILE object ) @see torch.DiskFile
--]]
function trans:write(file)
    file:writeObject({self.stateDim,
                      self.numActions,
                      self.histLen,
                      self.maxSize,
                      self.bufferSize,
                      self.numEntries,
                      self.insertIndex,
                      self.recentMemSize,
                      self.histIndices})
end

--[[
Override the read function to desearialize this class from file.
Recreates an empty table.

@param file (FILE object ) @see torch.DiskFile
--]]
function trans:read(file)
    local stateDim, numActions, histLen, maxSize, bufferSize, numEntries, insertIndex, recentMemSize, histIndices = unpack(file:readObject())
    self.stateDim = stateDim
    self.numActions = numActions
    self.histLen = histLen
    self.maxSize = maxSize
    self.bufferSize = bufferSize
    self.recentMemSize = recentMemSize
    self.histIndices = histIndices
    self.numEntries = 0
    self.insertIndex = 0

    self.s = torch.ByteTensor(self.maxSize, self.stateDim):fill(0)
    self.a = torch.LongTensor(self.maxSize):fill(0)
    self.r = torch.zeros(self.maxSize)
    self.t = torch.ByteTensor(self.maxSize):fill(0)
    self.action_encodings = torch.eye(self.numActions)

    -- Tables for storing the last histLen states.  They are used for
    -- constructing the most recent agent state more easily.
    self.recent_s = {}
    self.recent_a = {}
    self.recent_t = {}

    self.buf_a      = torch.LongTensor(self.bufferSize):fill(0)
    self.buf_r      = torch.zeros(self.bufferSize)
    self.buf_term   = torch.ByteTensor(self.bufferSize):fill(0)
    self.buf_s      = torch.ByteTensor(self.bufferSize, self.stateDim * self.histLen):fill(0)
    self.buf_s2     = torch.ByteTensor(self.bufferSize, self.stateDim * self.histLen):fill(0)

    if self.gpu and self.gpu >= 0 then
        self.gpu_s  = self.buf_s:float():cuda()
        self.gpu_s2 = self.buf_s2:float():cuda()
    end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE locale SYSTEM "../../../../../lib/pkp/dtd/locale.dtd">

<!--
  * plugins/citationFormats/mla/locale/ro_RO/locale.xml
  *
  * Copyright (c) 2003-2013 John Willinsky
  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  *
  * Localization strings for this citation plugin in ro_RO.
  * KOSSON FECIT
  -->

<locale name="ro_RO" full_name="Română">
	<message key="plugins.citationFormats.mla.displayName">Modul pentru citarea în format MLA</message>
	<message key="plugins.citationFormats.mla.citationFormatName">MLA</message>
	<message key="plugins.citationFormats.mla.description">Acest modul implementează formatul MLA pentru citări.</message>
	<message key="plugins.citationFormats.mla.noPages">nr. pag.</message>
</locale>

redpajama_set_name: RedPajamaGithub


text:
analysisstore.server package
============================

Submodules
----------

analysisstore.server.conf module
--------------------------------

.. automodule:: analysisstore.server.conf
    :members:
    :undoc-members:
    :show-inheritance:

analysisstore.server.engine module
----------------------------------

.. automodule:: analysisstore.server.engine
    :members:
    :undoc-members:
    :show-inheritance:

analysisstore.server.utils module
---------------------------------

.. automodule:: analysisstore.server.utils
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: analysisstore.server
    :members:
    :undoc-members:
    :show-inheritance:


text:
package filter;

import javax.servlet.*;
import java.io.IOException;

public class FirstFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("First filter start.");
        chain.doFilter(req, resp);
        System.out.println("First filter end.");
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("First filter init.");
    }

}


text:
/**
 * Created by JarvisWalker on 13/2/17.
 */

function SpritePosition(options) {
    this.name = options.name;
    var spriteSheetX = options.spriteSheetX;
    this.spriteSheetY = options.spriteSheetY;
    this.updatedSpriteSheetX = spriteSheetX;

    var canvasX = options.canvasX;
    this.canvasY = options.canvasY;
    this.updatedCanvasX = canvasX;

    var maxFrame = options.maxFrame;

    var multiplier;
    if (options.multiplier !== undefined)
        multiplier = options.multiplier;
    else
        multiplier = DEFAULT_SPRITE_SIZE;

    var isFlipped = false;

    var currentFrameCounter = 0;
    this.update = function() {
        currentFrameCounter++;
        if (currentFrameCounter > maxFrame) {
            currentFrameCounter = 0;
        }
        this.updatedSpriteSheetX = spriteSheetX + multiplier * currentFrameCounter;
    };

    this.updateCanvas = function () {
        currentFrameCounter++;
        if (currentFrameCounter > maxFrame) {
            currentFrameCounter = 0;
        }
        this.updatedCanvasX = canvasX + multiplier * currentFrameCounter;
    };

    this.getPosition = function () {
        return {
            spriteSheetX: this.updatedSpriteSheetX,
            spriteSheetY: this.spriteSheetY,
            canvasX: this.updatedCanvasX,
            canvasY: this.canvasY
        };
    };

    this.reset = function() {
        this.updatedSpriteSheetX = spriteSheetX;
        this.updatedCanvasX = canvasX;
        currentFrameCounter = 0;
    }
}

function generateImage(source) {
    var image = new Image();
    image.src = source;
    return image;
}

function DrawingBoard(id, name) {
    this.name = name;
    var drawingBoard = document.getElementById(id).getContext("2d");

    this.flipHorizontally = function () {
        addLine("Flipping the board");
        drawingBoard.save();

        drawingBoard.translate(45, 0);
        drawingBoard.scale(-1, 1);
    };

    this.restore = function() {
        drawingBoard.restore();
    };

    this.clearSection = function(x, y, width, height) {
        drawingBoard.clearRect(x, y, width, height);
    };

    this.clearEntireScreen = function() {
        drawingBoard.clearRect(0, 0, DEFAULT_SCREEN_SIZE.X, DEFAULT_SCREEN_SIZE.Y);
    };

    this.drawImage = function(image,
                              spriteDetailsX,
                              spriteDetailsY,
                              spriteDetailsWidth,
                              spriteDetailsHeight,
                              canvasDetailsX,
                              canvasDetailsY,
                              canvasDetailsWidth,
                              canvasDetailsHeight) {
        drawingBoard.drawImage(
            image,
            spriteDetailsX,
            spriteDetailsY,
            spriteDetailsWidth,
            spriteDetailsHeight,
            canvasDetailsX,
            canvasDetailsY,
            canvasDetailsWidth,
            canvasDetailsHeight
        );
    };

    this.getDrawingBoard = function() {
        return drawingBoard;
    };
}

//var drawingBoard = document.getElementById("ctx").getContext("2d");
var drawingBoard = new DrawingBoard("ctx", "drawingBoard");

var foregroundBoard = new DrawingBoard("foreground", "foregroundBoard");


text:
/* global NexT, CONFIG, mermaid */

document.addEventListener('page:loaded', () => {
  const mermaidElements = document.querySelectorAll('.mermaid');
  if (mermaidElements.length) {
    NexT.utils.getScript(CONFIG.mermaid.js, {
      condition: window.mermaid
    }).then(() => {
      mermaidElements.forEach(element => {
        const newElement = document.createElement('div');
        newElement.innerHTML = element.innerHTML;
        newElement.className = element.className;
        element.parentNode.replaceChild(newElement, element);
      });

      mermaid.init({
        theme    : CONFIG.mermaid.theme,
        logLevel : 3,
        flowchart: { curve: 'linear' },
        gantt    : { axisFormat: '%m/%d/%Y' },
        sequence : { actorMargin: 50 }
      }, '.mermaid');
    });
  }
});


text:
namespace ui {

class UI_ANDROID_EXPORT OverscrollRefreshHandler {
 public:
  explicit OverscrollRefreshHandler(
      const base::android::JavaRef<jobject>& j_overscroll_refresh_handler);

  // Note: the following methods are virtual because this class is overridden
  // for testing in overscroll_refresh_unittest.cc

  virtual ~OverscrollRefreshHandler();

  // Signals the start of an overscrolling pull. Returns whether the handler
  // will consume the overscroll gesture, in which case it will receive the
  // remaining pull updates.
  virtual bool PullStart(OverscrollAction type,
                         float startx,
                         float starty,
                         bool navigate_forward);

  // Signals a pull update, where |x_delta| and |y_delta| are in device pixels.
  virtual void PullUpdate(float x_delta, float y_delta);

  // Signals the release of the pull, and whether the release is allowed to
  // trigger the refresh action.
  virtual void PullRelease(bool allow_refresh);

  // Reset the active pull state.
  virtual void PullReset();

 private:
  base::android::ScopedJavaGlobalRef<jobject> j_overscroll_refresh_handler_;
};

}  // namespace ui

#endif  // UI_ANDROID_OVERSCROLL_REFRESH_HANDLER_H_


text:
package de.synaxon.graphitereceiver.core;

import de.synaxon.graphitereceiver.domain.MapPrefixSuffix;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MapperPrefixSuffix {

    private File hostnameMap;

    public MapperPrefixSuffix(String path) throws FileNotFoundException {
        Log logger = LogFactory.getLog(MapperPrefixSuffix.class);
        this.hostnameMap = new File(path);
        if(this.hostnameMap.exists()) {
            if(this.hostnameMap.length() == 0) {
                logger.warn("hostname map no exist or is empty");
            }
        } else {
            throw new FileNotFoundException();
        }

    }

    public Map<String, MapPrefixSuffix> getAllMapper(){
        String separator = ";";
        Map<String, MapPrefixSuffix> hostMap = new HashMap<String, MapPrefixSuffix>();
        BufferedReader bufferedReader = bufferedReaderFactory();
        String line;
        try {
            while((line = bufferedReader.readLine()) != null) {
                if(!line.startsWith("#")) {
                    String[] lineFound = line.split(separator);
                    MapPrefixSuffix mapPrefixSuffix = new MapPrefixSuffix(lineFound[1], lineFound[2]);
                    hostMap.put(lineFound[0].toLowerCase(), mapPrefixSuffix);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return hostMap;
    }

    private BufferedReader bufferedReaderFactory(){
        FileReader fileReader;
        BufferedReader bufferedReader = null;

        try {
            fileReader = new FileReader(this.hostnameMap);
            bufferedReader = new BufferedReader(fileReader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bufferedReader;
    }

}


text:
#include "CCDisplayFactory.h"
#include "../CCBone.h"
#include "../CCArmature.h"
#include "../display/CCSkin.h"
#include "../display/CCShaderNode.h"
#include "../utils/CCSpriteFrameCacheHelper.h"
#include "../utils/CCArmatureDataManager.h"
#include "../utils/CCTransformHelp.h"

NS_CC_EXT_BEGIN

void CCDisplayFactory::addDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData)
{
    switch(displayData->displayType)
    {
    case CS_DISPLAY_SPRITE:
        addSpriteDisplay(bone, decoDisplay, displayData);
        break;
    case  CS_DISPLAY_PARTICLE:
        addParticleDisplay(bone, decoDisplay, displayData);
        break;
    case  CS_DISPLAY_ARMATURE:
        addArmatureDisplay(bone, decoDisplay, displayData);
        break;
    default:
        break;
    }
}

void CCDisplayFactory::createDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay)
{
    switch(decoDisplay->getDisplayData()->displayType)
    {
    case CS_DISPLAY_SPRITE:
        createSpriteDisplay(bone, decoDisplay);
        break;
    case CS_DISPLAY_PARTICLE:
        createParticleDisplay(bone, decoDisplay);
        break;
    case CS_DISPLAY_ARMATURE:
        createArmatureDisplay(bone, decoDisplay);
        break;
    default:
        break;
    }
}

void CCDisplayFactory::updateDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, float dt, bool dirty)
{
    CS_RETURN_IF(!decoDisplay);

#if ENABLE_PHYSICS_DETECT
    if (dirty)
    {
        CCColliderDetector *detector = decoDisplay->getColliderDetector();
        if (detector)
        {
            CCAffineTransform t = CCAffineTransformConcat(bone->nodeToArmatureTransform(), bone->getArmature()->nodeToWorldTransform());
            detector->updateTransform(t);
        }
    }
#endif

    switch(decoDisplay->getDisplayData()->displayType)
    {
    case CS_DISPLAY_SPRITE:
        updateSpriteDisplay(bone, decoDisplay, dt, dirty);
        break;
    case CS_DISPLAY_PARTICLE:
        updateParticleDisplay(bone, decoDisplay, dt, dirty);
        break;
    case CS_DISPLAY_ARMATURE:
        updateArmatureDisplay(bone, decoDisplay, dt, dirty);
        break;
    default:
        break;
    }
}

void CCDisplayFactory::addSpriteDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData)
{
    CCSpriteDisplayData *sdp = CCSpriteDisplayData::create();
    sdp->copy((CCSpriteDisplayData *)displayData);
    decoDisplay->setDisplayData(sdp);
    createSpriteDisplay(bone, decoDisplay);
}

void CCDisplayFactory::createSpriteDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay)
{
    CCSkin *skin = NULL;

    CCSpriteDisplayData *displayData = (CCSpriteDisplayData *)decoDisplay->getDisplayData();

    //! remove .xxx
    std::string textureName = displayData->displayName;
    size_t startPos = textureName.find_last_of(".");

    if(startPos != std::string::npos)
    {
        textureName = textureName.erase(startPos);
    }

    //! create display
    if(textureName.length() == 0)
    {
        skin = CCSkin::create();
    }
    else
    {
        skin = CCSkin::createWithSpriteFrameName((textureName + ".png").c_str());
    }

    CCTextureAtlas *atlas = CCSpriteFrameCacheHelper::sharedSpriteFrameCacheHelper()->getTextureAtlas((textureName + ".png").c_str());
    skin->setTextureAtlas(atlas);

    CCTextureData *textureData = CCArmatureDataManager::sharedArmatureDataManager()->getTextureData(textureName.c_str());
    if(textureData)
    {
        //! Init display anchorPoint, every Texture have a anchor point
        skin->setAnchorPoint(ccp( textureData->pivotX, textureData->pivotY));
    }

    skin->setBone(bone);
    skin->setSkinData(*bone->getBoneData());

    decoDisplay->setDisplay(skin);

#if ENABLE_PHYSICS_DETECT
    if (textureData && textureData->contourDataList.count() > 0)
    {

        //! create ContourSprite
        CCColliderDetector *colliderDetector = CCColliderDetector::create(bone);
        colliderDetector->addContourDataList(&textureData->contourDataList);

        decoDisplay->setColliderDetector(colliderDetector);
    }
#endif
}

void CCDisplayFactory::updateSpriteDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, float dt, bool dirty)
{
    CCSkin *skin = (CCSkin *)decoDisplay->getDisplay();
    skin->updateTransform();
}

void CCDisplayFactory::addArmatureDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData)
{
    CCArmatureDisplayData *adp = CCArmatureDisplayData::create(); ;
    adp->copy((CCArmatureDisplayData *)displayData);
    decoDisplay->setDisplayData(adp);

    createArmatureDisplay(bone, decoDisplay);
}
void CCDisplayFactory::createArmatureDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay)
{
    CCArmatureDisplayData *displayData = (CCArmatureDisplayData *)decoDisplay->getDisplayData();

    CCArmature *armature = CCArmature::create(displayData->displayName.c_str(), bone);

    /*
     *  because this bone have called this name, so armature should change it's name, or it can't add to
     *  CCArmature's bone children.
     */
    armature->setName((bone->getName() + "_armatureChild").c_str());

    decoDisplay->setDisplay(armature);
}
void CCDisplayFactory::updateArmatureDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, float dt, bool dirty)
{
    CS_RETURN_IF(!dirty);

    CCArmature *armature = bone->getChildArmature();
    if(armature)
    {
        armature->sortAllChildren();
        armature->update(dt);
    }
}

void CCDisplayFactory::addParticleDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData)
{
    CCParticleDisplayData *adp = CCParticleDisplayData::create(); ;
    adp->copy((CCParticleDisplayData *)displayData);
    decoDisplay->setDisplayData(adp);

    createParticleDisplay(bone, decoDisplay);
}
void CCDisplayFactory::createParticleDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay)
{
    CCParticleDisplayData *displayData = (CCParticleDisplayData *)decoDisplay->getDisplayData();
    CCParticleSystem *system = CCParticleSystemQuad::create(displayData->plist.c_str());
    decoDisplay->setDisplay(system);
}
void CCDisplayFactory::updateParticleDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, float dt, bool dirty)
{
    CCParticleSystem *system = (CCParticleSystem *)decoDisplay->getDisplay();
    CCBaseData node;
    CCTransformHelp::matrixToNode(bone->nodeToArmatureTransform(), node);
    system->setPosition(node.x, node.y);
    system->setScaleX(node.scaleX);
    system->setScaleY(node.scaleY);
    system->update(dt);
}

void CCDisplayFactory::addShaderDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData)
{
    CCShaderDisplayData *sdp = CCShaderDisplayData::create();
    sdp->copy((CCShaderDisplayData *)displayData);
    decoDisplay->setDisplayData(sdp);

    createShaderDisplay(bone, decoDisplay);
}
void CCDisplayFactory::createShaderDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay)
{
    CCShaderDisplayData *displayData = (CCShaderDisplayData *)decoDisplay->getDisplayData();
    CCShaderNode *sn = CCShaderNode::shaderNodeWithVertex(displayData->vert.c_str(), displayData->frag.c_str());
    decoDisplay->setDisplay(sn);
}

NS_CC_EXT_END


text:
Skiwy
=====

IIS Express Manager


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.actions.util;

import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata.MiddlemanType;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionResult;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 * A dummy action for testing.  Its execution runs the specified
 * Runnable or Callable, which is defined by the test case,
 * and touches all the output files.
 */
public class TestAction extends AbstractAction {

  @AutoCodec
  public static final Runnable NO_EFFECT =
      new Runnable() {
        @Override
        public void run() {}
      };

  private static boolean isOptional(Artifact artifact) {
    return artifact.getExecPath().getBaseName().endsWith(".optional");
  }

  private static NestedSet<Artifact> mandatoryArtifacts(NestedSet<Artifact> inputs) {
    return NestedSetBuilder.wrap(
        Order.STABLE_ORDER, Iterables.filter(inputs.toList(), a -> !isOptional(a)));
  }

  private static ImmutableList<Artifact> optionalArtifacts(NestedSet<Artifact> inputs) {
    return ImmutableList.copyOf(Iterables.filter(inputs.toList(), a -> isOptional(a)));
  }

  protected final Callable<Void> effect;
  private final NestedSet<Artifact> mandatoryInputs;
  private final ImmutableList<Artifact> optionalInputs;

  /** Use this constructor if the effect can't throw exceptions. */
  public TestAction(Runnable effect, NestedSet<Artifact> inputs, ImmutableSet<Artifact> outputs) {
    this(Executors.callable(effect, null), inputs, outputs);
  }

  /**
   * Use this constructor if the effect can throw exceptions. Any checked exception thrown will be
   * repackaged as an ActionExecutionException.
   */
  public TestAction(
      Callable<Void> effect, NestedSet<Artifact> inputs, ImmutableSet<Artifact> outputs) {
    super(NULL_ACTION_OWNER, mandatoryArtifacts(inputs), outputs);
    this.mandatoryInputs = getInputs();
    this.optionalInputs = optionalArtifacts(inputs);
    this.effect = effect;
  }

  @Override
  public NestedSet<Artifact> getMandatoryInputs() {
    return mandatoryInputs;
  }

  @Override
  public boolean discoversInputs() {
    return !optionalInputs.isEmpty();
  }

  @Override
  public NestedSet<Artifact> discoverInputs(ActionExecutionContext actionExecutionContext) {
    Preconditions.checkState(discoversInputs(), this);
    NestedSet<Artifact> discoveredInputs =
        NestedSetBuilder.wrap(
            Order.STABLE_ORDER, Iterables.filter(optionalInputs, i -> i.getPath().exists()));
    updateInputs(
        NestedSetBuilder.<Artifact>stableOrder()
            .addTransitive(mandatoryInputs)
            .addTransitive(discoveredInputs)
            .build());
    return discoveredInputs;
  }

  @Override
  public ActionResult execute(ActionExecutionContext actionExecutionContext)
      throws ActionExecutionException {
    for (Artifact artifact : getInputs().toList()) {
      // Do not check *.optional artifacts - artifacts with such extension are
      // used by tests to specify artifacts that may or may not be missing.
      // This is used, e.g., to test Blaze behavior when action has missing
      // input artifacts but still is successfully executed.
      if (!artifact.getPath().exists()) {
        throw new IllegalStateException("action's input file does not exist: "
            + artifact.getPath());
      }
    }

    try {
      effect.call();
    } catch (RuntimeException | Error e) {
      throw e;
    } catch (Exception e) {
      throw new ActionExecutionException(
          "TestAction failed due to exception: " + e.getMessage(), e, this, false);
    }

    try {
      for (Artifact artifact : getOutputs()) {
        FileSystemUtils.touchFile(artifact.getPath());
      }
    } catch (IOException e) {
      throw new AssertionError(e);
    }

    return ActionResult.EMPTY;
  }

  @Override
  protected void computeKey(ActionKeyContext actionKeyContext, Fingerprint fp) {
    fp.addPaths(Artifact.asSortedPathFragments(getOutputs()));
    fp.addPaths(Artifact.asSortedPathFragments(getMandatoryInputs().toList()));
  }

  @Override
  public String getMnemonic() {
    return "Test";
  }

  /** No-op action that has exactly one output, and can be a middleman action. */
  @AutoCodec
  public static class DummyAction extends TestAction {
    private final MiddlemanType type;

    @AutoCodec.Instantiator
    public DummyAction(NestedSet<Artifact> inputs, Artifact primaryOutput, MiddlemanType type) {
      super(NO_EFFECT, inputs, ImmutableSet.of(primaryOutput));
      this.type = type;
    }

    public DummyAction(NestedSet<Artifact> inputs, Artifact output) {
      this(inputs, output, MiddlemanType.NORMAL);
    }

    @Override
    public MiddlemanType getActionType() {
      return type;
    }
  }
}


text:
package fr.ritaly.dungeonmaster.map;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import fr.ritaly.dungeonmaster.Clock;
import fr.ritaly.dungeonmaster.ClockListener;
import fr.ritaly.dungeonmaster.Temporizer;
import fr.ritaly.dungeonmaster.Utils;
import fr.ritaly.dungeonmaster.ai.Creature;
import fr.ritaly.dungeonmaster.champion.Champion;
import fr.ritaly.dungeonmaster.event.ChangeEvent;
import fr.ritaly.dungeonmaster.event.ChangeEventSource;
import fr.ritaly.dungeonmaster.event.ChangeEventSupport;
import fr.ritaly.dungeonmaster.event.ChangeListener;

/**
 * @author Francois RITALY
 */
public class PoisonCloud implements ClockListener, ChangeEventSource {

	private final Log log = LogFactory.getLog(PoisonCloud.class);

	/**
	 * The {@link Element} where the poison cloud is located.
	 */
	private final Element element;

	private final Temporizer temporizer;

	private final ChangeEventSupport eventSupport = new ChangeEventSupport();

	// TODO Handle the strengthening of a poison cloud

	/**
	 * The remaining life time for this poison cloud. Defaults to 10 (seconds).
	 * Only the strength of the poison changes with the spell power (not the
	 * life time).
	 */
	private int lifeTime = 10;

	public PoisonCloud(Element element) {
		Validate.notNull(element, "The given element is null");

		this.element = element;
		this.temporizer = new Temporizer("PoisonCloud" + element.getPosition(), Clock.ONE_SECOND);
	}

	@Override
	public void addChangeListener(ChangeListener listener) {
		eventSupport.addChangeListener(listener);
	}

	@Override
	public void removeChangeListener(ChangeListener listener) {
		eventSupport.removeChangeListener(listener);
	}

	private void fireChangeEvent() {
		eventSupport.fireChangeEvent(new ChangeEvent(this));
	}

	@Override
	public boolean clockTicked() {
		if (temporizer.trigger()) {
			// The poison cloud attacks the champions and creatures inside
			if (element.hasParty()) {
				// Get all living champions
				final List<Champion> champions = element.getParty().getChampions(false);

				for (Champion champion : champions) {
					// TODO Pass as a parameter the damage type
					// TODO Take into account the strength of the poison
					champion.hit(Utils.random(5, 20));
				}
			} else if (element.hasCreatures()) {
				final Set<Creature> creatures = element.getCreatures();

				for (Creature creature : creatures) {
					// TODO Attack the creature
					// TODO Pass as a parameter the damage type
					// TODO Take into account the strength of the poison
				}
			}

			final int backup = lifeTime;

			final boolean again = --lifeTime > 0;

			if (log.isDebugEnabled()) {
				log.debug(this + ".LifeTime: " + backup + " -> " + lifeTime + " [-1]");
			}

			if (!again) {
				// Notify the end of the poison cloud
				fireChangeEvent();
			}
		}

		return (lifeTime > 0);
	}

	@Override
	public String toString() {
		return this.getClass().getSimpleName() + element.getPosition();
	}
}


text:
class StoreController < ApplicationController
  layout 'main'
  include OrderHelper
  include Pagination
  include ActiveMerchant::Billing::Integrations

  before_filter :prep_store_vars

  before_filter :redirect_if_order_empty,
    :only => [
      :checkout, :select_shipping_method, :view_shipping_method, :set_shipping_method,
      :confirm_order, :finish_order
    ]

  before_filter :ssl_required,
    :only => [
      :checkout, :select_shipping_method, :view_shipping_method,
      :set_shipping_method, :confirm_order, :finish_order
    ]

  if Preference.find_by_name('store_test_transactions').is_true?
    ActiveMerchant::Billing::Base.integration_mode = :test
  else
    ActiveMerchant::Billing::Base.integration_mode = :production
  end

  # You can change this in an override depending on how many steps you want.
  #
  # For instance, perhaps you want to skip shipping calculation.
  #
  # If so, in your overidden controller (in /app/controllers/store_controller.rb)
  # You could set this to be:
  #   @@action_after_checkout = 'finish_order'
  @@action_after_checkout = 'select_shipping_method'

  # Our simple store index
  def index
    @title = "Store"
		@tags = Tag.find_alpha
		@tag_names = nil
		@viewing_tags = nil

    @products = Product.paginate(
      :order => 'name ASC',
      :conditions => Product::CONDITIONS_AVAILABLE,
      :page => params[:page],
      :per_page => 10
    )
  end

  def search
    @search_term = params[:search_term]
    @title = "Search Results for: #{@search_term}"
    @products = Product.paginate(
      :order => 'name ASC',
      :conditions => ["(name LIKE ? OR code = ?) AND #{Product::CONDITIONS_AVAILABLE}", "%#{@search_term}%", @search_term],
      :page => params[:page],
      :per_page => 10
    )
    # If only one product comes back, take em directly to it.
    if @products.size == 1
      redirect_to :action => 'show', :id => @products[0].code and return
    else
      render :action => 'index'
    end
  end

	# Shows products by tag or tags.
	# Tags are passed in as id #'s separated by commas.
	#
	def show_by_tags
		# Tags are passed in as an array.
		# Passed into this controller like this:
		# /store/show_by_tags/tag_one/tag_two/tag_three/...
		@tag_names = params[:tags]
		# Generate tag ID list from names
		tag_ids_array = Array.new
		for name in @tag_names
		  temp_tag = Tag.find_by_name(name)
			if temp_tag then
				tag_ids_array << temp_tag.id
      else
        render(:file => 'public/404.html', :status => 404) and return
      end
		end

		if tag_ids_array.size == 0
		  render(:file => 'public/404.html', :status => 404) and return
		end

    @viewing_tags = Tag.find(tag_ids_array, :order => "parent_id ASC")
		viewing_tag_names = @viewing_tags.collect { |t| " > #{t.name}"}
		@title = "Store #{viewing_tag_names}"
		@tags = Tag.find_related_tags(tag_ids_array)

		# Paginate products so we don't have a ton of ugly SQL
		# and conditions in the controller
		per_page = 10
    list = Product.find_by_tags(tag_ids_array, true)
    pager = Paginator.new(list, list.size, per_page, params[:page])
    @products = returning WillPaginate::Collection.new(params[:page] || 1, per_page, list.size) do |p|
      p.replace list[pager.current.offset, pager.items_per_page]
    end

		render :action => 'index'
	end

  # This is a component...
  # Displays a fragment of HTML that shows a product, desc, and "buy now" link
  #
  # THIS IS DEPRECATED IN FAVOR OF THE "product" PARTIAL
  #
  def display_product
    logger.warn("StoreController::display_product is deprecated. Please use the 'product' partial instead.")
    @product = Product.find(:first, :conditions => ["id = ?", params[:id]])
    if (@product.images[0]) then
			@image = @product.images[0]
		else
			@image = nil
		end
    render :layout => false
  end

  def show
    @product = Product.find_by_code(params[:id])
    if !@product
      flash[:notice] = "Sorry, we couldn't find the product you were looking for"
      redirect_to :action => 'index' and return false
    end
    @title = @product.name
    @images = @product.images.find(:all)
    @default_image = @images[0]
    @variations = @product.variations.find(
      :all,
      :order => 'name ASC',
      :conditions => 'quantity > 0'
    )
  end

  # Shows shopping cart in pop-up window.
  #
  def show_cart
    sanitize!
    render :layout => 'modal' and return
  end

  # Adds an item to the cart, then redirects to checkout
  #
  # This is the old way of doing things before the AJAX cart.
  #
  # Left in if someone would like to use it instead.
  def add_to_cart
    sanitize!
    product = Product.find(params[:id])
    @order.add_product(product)
		# In substruct.rb
		redirect_to get_link_to_checkout
  rescue
    logger.error("[ERROR] - Can't find product for id: #{params[:id]}")
    redirect_to_index("Sorry, you tried to buy a product that we don't carry any longer.")
  end

	# Adds an item to our cart via AJAX
	#
	# Returns the cart HTML as a partial to update the view in JS
	def add_to_cart_ajax
	  sanitize!
	  # If variations are present we get that as the ID instead...
	  if params[:variation]
	    product = Variation.find(params[:variation])
	  else
		  product = Product.find(params[:id])
		end

		begin
		  quantity = params[:quantity].to_int
		rescue NoMethodError
		  quantity = (params[:quantity].to_i != 0) ? params[:quantity].to_i : 1
	  end

		logger.info "QUANTITY: #{quantity}"
	  logger.info "PRODUCT QUANTITY: #{product.quantity}"
	  logger.info "Quantity too much? #{(quantity.to_i > product.quantity.to_i)}"

		# Checks quantity against available.
		if (Preference.find_by_name('store_use_inventory_control').is_true? && quantity > product.quantity.to_i)
		  logger.info "There's an error adding to the cart..."
		  render :nothing => true, :status => 400 and return
		else
  		@order.add_product(product, quantity)
  		logger.info "Product added...success"
  		render :partial => 'cart' and return
  	end
	end

	# Removes one item via AJAX
	#
	# Returns the cart HTML as a partial to update the view in JS
	def remove_from_cart_ajax
		product = Item.find(params[:id])
		@order.remove_product(product)
		render :partial => 'cart'
	rescue
		render :text => "There was a problem removing that item. Please refresh this page."
	end

	# Empties the entire cart via ajax...
	# Again, returns cart HTML via partial
	def empty_cart_ajax
		clear_cart_and_order
		render :partial => 'cart'
	end

  # Empties the cart out and redirects to index.
  # Removes any order saved to the DB if there is such a thing.
  #
  # The old (non-ajax) way of doing things
  def empty_cart
    clear_cart_and_order
    redirect_to_index("All items have been removed from your order.")
  end

  # Gathers customer information.
  # Displays form fields for grabbing name/addy/credit info
  #
  # Also displays items in the current order
  def checkout
    @title = "Please enter your information to continue this purchase."
    @cc_processor = Order.get_cc_processor
    if request.get?
      unless @order.has_been_placed? then
        # Save standard form info
        logger.info("\n\nNEW ORDER INIT\n\n")
        initialize_new_order
      else
        logger.info("\n\nEXISTING ORDER INIT\n\n")
        initialize_existing_order
      end
      render :layout => 'checkout' and return
    elsif request.post?
      # Turned into a private method now so we don't have checkout/do_checkout...
      do_checkout()
    end
  end

  # Checks shipping price of items
  # Used with live rate calculation
  # Lets customer choose what method to use
  def select_shipping_method
    @title = "Select Your Shipping Method - Step 2 of 3"

    # Ensure order shipping cost is always set to zero when hitting this page.
    # For display purposes only.
    @order.shipping_cost = 0

    session[:order_shipping_types] = @order.get_shipping_prices

    # Set default price to pick what radio button should be entered
    @default_price = session[:order_shipping_types][0].id if session[:order_shipping_types][0]

    render :layout => 'checkout' and return
  end

  # THIS IS DEPRECATED
  def view_shipping_method
    render :text => 'This action is deprecated. Please use the select_shipping_method action instead.' and return
  end

  # Execution action of select_shipping_method (above)
  # OR called when setting shipping method using a flat calculation...
  #
  # Saves shipping method, redirects to order review page.
  #
  def set_shipping_method
    ship_id = params[:ship_type_id]
    # Convert to integers for comparison purposes!
    ship_type = session[:order_shipping_types].find { |type| type.id.to_i == ship_id.to_i }
    # Might not have a shipping type set...
    if ship_type
      ship_price = ship_type.calculated_price
      @order.order_shipping_type_id = ship_id
      @order.shipping_cost = ship_price
      @order.save
    end

    if Preference.find_by_name('store_show_confirmation').is_true?
      action_after_shipping = 'confirm_order'
    else
      action_after_shipping = 'finish_order'
    end
    redirect_to :action => action_after_shipping
  end

  # This page only exists so the user may confirm their order.
  #
  # They are presented with options to cancel and start over,
  # or process their order.
  #
  def confirm_order
    @title = "Please confirm your order. - Step 3 of 3"
    @cc_login = Order.get_cc_login
    @paypal_url = Paypal.service_url
    # Make sure a shipping method is set
    if @order.order_shipping_type_id == nil
      redirect_to_shipping and return
    end
    render :layout => 'checkout' and return
  end

  # Finishes the order
  #
  # Submits order info to Authorize.net
  def finish_order
    @title = "Thanks for your order!"
    cc_processor = Order.get_cc_processor
    order_success = @order.run_transaction
    if order_success == true
      @payment_message = "Card processed successfully"
      clean_order_success()
    elsif cc_processor == Preference::CC_PROCESSORS[1]
      case order_success
        when 4
          @payment_message = %q\
            Your order has been processed at PayPal but we
	          have not heard back from them yet.  Your order
			      will be ready to ship as soon as we receive
			      confirmation of your payment.
			    \
			    clean_order_success()
	      when 5
	        @payment_message = "Transaction processed successfully"
          clean_order_success()
	      else
	        error_message = "Something went wrong and your transaction failed.
"
	        error_message << "Please try again or contact us."
	        redirect_to_checkout(error_message) and return
        end
    else
      # Redirect to checkout and allow them to enter info again.
      error_message = "Sorry, but your transaction didn't go through.
"
      error_message << "#{order_success}
"
      error_message << "Please try again or contact us."
      redirect_to_checkout(error_message) and return
    end
    render :layout => 'receipt' and return
  end

  #############################################################################
  # PRIVATE METHODS
  #############################################################################
  private

    # Prepares store variables necessary for ordering, etc.
    def prep_store_vars
      # Find or initialize order.
      @order ||= Order.find(
        :first,
        :conditions => ["id = ?", session[:order_id]]
      )
      unless @order
        @order = Order.create!
        session[:order_id] = @order.id
      end
    end

    # Sets order, but sends the customer back to the
    # start if there's not one found.
    #
    # Used on all methods in the checkout process
    # except the first one.
    #
    def redirect_if_order_empty
      # If there's no order redirect to index
      if @order == nil || @order.empty?
        redir_string = "There are no items in your order.\n\n"
        redir_string << "Please add some items to your order before trying to access this page."
        redirect_to_index(redir_string) and return false
      end
    end

    # Cleans the cart out of memory and auto-logs a customer in.
    def clean_order_success
      log_customer_in(@order.customer)
      session[:order_id] = nil
    end

    # Clears the cart and possibly destroys the order
    # Called when the user wants to start over, or when the order is completed.
    def clear_cart_and_order(destroy_order = true)
      @order.empty!
      if destroy_order then
        @order.destroy
        session[:order_id] = nil
      end
    end

    # Redirects to index with a message
    def redirect_to_index(msg = nil)
      flash[:notice] = msg
      redirect_to :action => 'index'
    end
    # Redirects to checkout with a message
    def redirect_to_checkout(msg = nil)
      flash[:notice] = msg
      redirect_to :action => 'checkout'
    end

    # Redirects to proper shipping page.
    def redirect_to_shipping()
      redirect_to :action => @@action_after_checkout
    end

    # Execution action of checkout
    #
    # Tries to create an order. If it cant, returns to the page and shows errors.
    def do_checkout
      # We might be re-doing an existing order.
      # Don't want to create a new order for failed transactions, sooo
      unless @order.has_been_placed? then
        logger.info("\n\n\nCREATING NEW ORDER FROM POST\n\n\n")
        logger.info(params[:use_separate_shipping_address])
        logger.info("\n\n\n")
        create_order_from_post
      else
        logger.info("\n\n\nUPDATING EXISTING ORDER FROM POST\n\n\n")
        update_order_from_post
      end

      # Add cart items to order. Check inventory level first...
      # Now controlled by a preference in the Admin UI
      if Preference.find_by_name('store_use_inventory_control').is_true?
        removed_items = @order.check_inventory()
        logger.info "REMOVED ITEMS: #{removed_items.inspect}"
        # If any items were removed, flash and alert.
        if removed_items.size > 0
          flash_msg = "The following item(s) have gone out of stock before you could purchase them:"
          for item_name in removed_items do
            flash_msg << "\n* #{item_name}"
          end
          flash_msg << "\n\n...The item(s) have been removed from your cart."

          if @order.empty?
            redirect_to_index(flash_msg) and return
          else
            flash.now[:notice] = flash_msg
            render :layout => 'checkout' and return
          end
        end
      end

      # @order.order_line_items.clear
      # @items.each do |line_item|
      #   @order.order_line_items << OrderLineItem.new(line_item.attributes)
      # end
      @order.save
      add_tax()
      # Save the order id to the session so we can find it later
      session[:order_id] = @order.id
      # All went well?
      logger.info("\n\nTRYING TO REDIRECT...")
      redirect_to_shipping and return
      #
    rescue
      logger.error "\n\nSomething went bad when trying to checkout..."
      stack_trace = $@.join("\n")
      logger.error "#{$!}\n\n#{stack_trace}\n"
      @shipping_address = OrderAddress.new unless @use_separate_shipping_address
      flash.now[:notice] = 'There were some problems with the information you entered.

Please look at the fields below.'
      render :layout => 'checkout' and return
    end

    # Stubbed to be overridden in your custom controller if tax
    # is necessary.
    #
    # Gets called after order is successfully saved after checkout, before
    # going to shipping.
    #
    def add_tax

    end

    # When is a cart not a cart?
    #
    # When it was cleared without an open browser session.
    # That's why we sanitize dirty carts.
    def sanitize!
      if session[:order_id]
         order = Order.find(session[:order_id])
         if order.order_status_code_id != 1 && order.order_status_code_id != 3
           clear_cart_and_order(false)
         end
      end
    end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Azure_Scrolls_of_Martial_Prowess.Models
{
    public class Battlegroup : Character
    {
        public int Might { get; }
        public int Size { get; }
        public String Drill { get; }
        public int CurrentSize { get; set; }
        public int CurrentMagnitude { get; set; }
        public Battlegroup(String name, CharacterTemplate template, int Might, int Size, String Drill) : base(name, template)
        {
            this.Might = Might;
            this.Size = Size;
            this.Drill = Drill;
            this.CurrentSize = Size;
            this.CurrentMagnitude = GetCurrentMaxMagnitude();

        }

        public int GetCurrentMaxMagnitude()
        {
            return HealthLevels.Count + CurrentSize;
        }

        public new String GetShortDescription()
        {
            String res = "";
            //onslaught
            res += "O:-" + CurrentOnslaught + ", ";

            //Drill
            res += "D: " + Drill + ", ";
            //Size
            res += "S: " + CurrentSize + "/" + Size+", ";
            //Magnitude
            res += "M: " + CurrentMagnitude + "/"+ GetCurrentMaxMagnitude();
            return res;
        }

        public new Boolean IsOut()
        {
            return (CurrentMagnitude <= 0 && Size <= 0);
        }

    }
}


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.ApiManagement.Models
{
    public partial class CertificateInformation : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("expiry");
            writer.WriteStringValue(ExpireOn, "O");
            writer.WritePropertyName("thumbprint");
            writer.WriteStringValue(Thumbprint);
            writer.WritePropertyName("subject");
            writer.WriteStringValue(Subject);
            writer.WriteEndObject();
        }

        internal static CertificateInformation DeserializeCertificateInformation(JsonElement element)
        {
            DateTimeOffset expiry = default;
            string thumbprint = default;
            string subject = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("expiry"))
                {
                    expiry = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("thumbprint"))
                {
                    thumbprint = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("subject"))
                {
                    subject = property.Value.GetString();
                    continue;
                }
            }
            return new CertificateInformation(expiry, thumbprint, subject);
        }
    }
}


text:
{% extends 'board_base.html' %}
{% load i18n %}
{% load forum_conversation_tags %}

{% block sub_title %}{% trans "Unlock topic" %}{% endblock sub_title %}

{% block content %}

{% trans "Unlock topic" %}

{% trans "Are you sure you want to unlock this topic?" %}

        <form action="" method="post">{% csrf_token %}
          <input type="hidden" name="post" value="yes" />
          <button role="submit" class="btn btn-warning">{% trans "Yes, I'm sure" %}</button>
          {% trans "No, take me back" %}
        </form>

{% endblock content %}


text:
package framework;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import framework.Validator;

public abstract class Entity
{
    public static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    public abstract Validator validate();

    public void hydrate(ResultSet rs) throws Exception
    {
        for(Entry<Method, String> setter : getSetters().entrySet()){
            Class<?> paramType = setter.getKey().getParameterTypes()[0];
            try {
                setter.getKey().invoke(
                    this,
                    paramType.cast(stringToObject(rs.getObject(setter.getValue()).toString(), paramType))
                );
            } catch(Exception e){}
        }
    }

    public void hydrate(HttpServletRequest request) throws Exception
    {
        for(Entry<Method, String> setter : getSetters().entrySet()){
            Class<?> paramType = setter.getKey().getParameterTypes()[0];
            if(request.getParameter(setter.getValue()) != null){
                setter.getKey().invoke(
                    this,
                    paramType.cast(stringToObject(request.getParameter(setter.getValue()).trim(), paramType))
                );
            }
        }
    }

    public static Object stringToObject(String string, Class<?> paramType) throws Exception
    {
        if(Boolean.class.equals(paramType))
            return Boolean.valueOf(string);
        else if(Double.class.equals(paramType))
            return Double.valueOf(string);
        else if(Integer.class.equals(paramType))
            return Integer.valueOf(string);
        else if(Date.class.equals(paramType))
            return formatter.parse(string);

        return string;
    }

    private Map<Method, String> getSetters()
    {
        Map<Method, String> setters = new HashMap<Method, String>();
        Method[] methods = this.getClass().getMethods();

        for(Method method : methods) {
            if(method.getName().substring(0, 3).equals("set")){
                setters.put(
                    method,
                    method.getName().substring(3).replaceAll("(.)([A-Z])", "$1_$2").toLowerCase()
                );
            }
        }

        return setters;
    }
}


text:
@charset "UTF-8";
/*QQ等级图标*/
.ui-icon-qqlevel {
  display: inline-block;
  width: 15px;
  height: 1px;
  position: relative;
  vertical-align: middle; }

.ui-icon-qqlevel:after {
  content: "";
  display: block;
  width: 16px;
  background: url(../img/icon_qqlevel_sprite.png?_bid=306) no-repeat;
  background-repeat: no-repeat;
  position: absolute;
  line-height: 100px;
  height: 16px;
  -webkit-background-size: 16px auto;
  top: -10px; }

.ui-icon-qqlevel-king:after {
  background-position: 0 0; }

.ui-icon-qqlevel-sun:after {
  background-position: 0 -48px; }

.ui-icon-qqlevel-moon:after {
  background-position: 0 -16px; }

.ui-icon-qqlevel-star:after {
  background-position: 0 -32px; }

.ui-icon-qqlevel-none:after {
  background-position: 0 -64px; }


text:
package org.apache.http.config;

import org.apache.http.util.Args;

/**
 * HTTP Message constraints: line length and header count.
 *
 * @since 4.3
 */
public class MessageConstraints implements Cloneable {

    public static final MessageConstraints DEFAULT = new Builder().build();

    private final int maxLineLength;
    private final int maxHeaderCount;

    MessageConstraints(final int maxLineLength, final int maxHeaderCount) {
        super();
        this.maxLineLength = maxLineLength;
        this.maxHeaderCount = maxHeaderCount;
    }

    public int getMaxLineLength() {
        return maxLineLength;
    }

    public int getMaxHeaderCount() {
        return maxHeaderCount;
    }

    @Override
    protected MessageConstraints clone() throws CloneNotSupportedException {
        return (MessageConstraints) super.clone();
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("[maxLineLength=").append(maxLineLength)
                .append(", maxHeaderCount=").append(maxHeaderCount)
                .append("]");
        return builder.toString();
    }

    public static MessageConstraints lineLen(final int max) {
        return new MessageConstraints(Args.notNegative(max, "Max line length"), -1);
    }

    public static MessageConstraints.Builder custom() {
        return new Builder();
    }

    public static MessageConstraints.Builder copy(final MessageConstraints config) {
        Args.notNull(config, "Message constraints");
        return new Builder()
            .setMaxHeaderCount(config.getMaxHeaderCount())
            .setMaxLineLength(config.getMaxLineLength());
    }

    public static class Builder {

        private int maxLineLength;
        private int maxHeaderCount;

        Builder() {
            this.maxLineLength = -1;
            this.maxHeaderCount = -1;
        }

        public Builder setMaxLineLength(final int maxLineLength) {
            this.maxLineLength = maxLineLength;
            return this;
        }

        public Builder setMaxHeaderCount(final int maxHeaderCount) {
            this.maxHeaderCount = maxHeaderCount;
            return this;
        }

        public MessageConstraints build() {
            return new MessageConstraints(maxLineLength, maxHeaderCount);
        }

    }

}


text:
<?php

if (file_exists($autoload = realpath(__DIR__ . "/../../../vendor/autoload.php"))) {
	require_once $autoload;
} else {
	print_r("Autoload not found or on path $autoload");
}

use Gerencianet\Exception\GerencianetException;
use Gerencianet\Gerencianet;

if (file_exists($options = realpath(__DIR__ . "/../../credentials/options.php"))) {
	require_once $options;
}

$body = [
	"name" => "My plan",
	"interval" => 1,
	"repeats" => null
];

try {
	$api = new Gerencianet($options);
	$response = $api->createPlan($params = [], $body);

	print_r("
" . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "
");
} catch (GerencianetException $e) {
	print_r($e->code);
	print_r($e->error);
	print_r($e->errorDescription);
} catch (Exception $e) {
	print_r($e->getMessage());
}