text:
"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var frontend_1 = require("frontend");
var React = __importStar(require("react"));
var Page_1 = require("./Page");
var Router_1 = require("../components/Router");
var typestyle_1 = require("typestyle");
var Css_1 = require("../Css");
var core_1 = require("@material-ui/core");
var Utils_1 = require("../lib/Utils");
var ResourceInfo_1 = require("../components/ResourceInfo");
var MD2Tabs_1 = __importDefault(require("../atoms/MD2Tabs"));
var ArtifactDetailsTab;
(function (ArtifactDetailsTab) {
    ArtifactDetailsTab[ArtifactDetailsTab["OVERVIEW"] = 0] = "OVERVIEW";
    ArtifactDetailsTab[ArtifactDetailsTab["LINEAGE_EXPLORER"] = 1] = "LINEAGE_EXPLORER";
})(ArtifactDetailsTab = exports.ArtifactDetailsTab || (exports.ArtifactDetailsTab = {}));
var tabs = (_a = {},
    _a[ArtifactDetailsTab.OVERVIEW] = { name: 'Overview' },
    _a[ArtifactDetailsTab.LINEAGE_EXPLORER] = { name: 'Lineage Explorer' },
    _a);
var tabNames = Object.values(tabs).map(function (tabConfig) { return tabConfig.name; });
var ArtifactDetails = /** @class */ (function (_super) {
    __extends(ArtifactDetails, _super);
    function ArtifactDetails(props) {
        var _this = _super.call(this, props) || this;
        _this.api = frontend_1.Api.getInstance();
        _this.state = {
            selectedTab: ArtifactDetailsTab.OVERVIEW
        };
        _this.load = _this.load.bind(_this);
        return _this;
    }
    Object.defineProperty(ArtifactDetails.prototype, "fullTypeName", {
        get: function () {
            return this.props.match.params[Router_1.RouteParams.ARTIFACT_TYPE] || '';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ArtifactDetails.prototype, "properTypeName", {
        get: function () {
            var parts = this.fullTypeName.split('/');
            if (!parts.length)
                return '';
            return Utils_1.titleCase(parts[parts.length - 1]);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ArtifactDetails.prototype, "id", {
        get: function () {
            return this.props.match.params[Router_1.RouteParams.ID];
        },
        enumerable: true,
        configurable: true
    });
    ArtifactDetails.prototype.componentDidMount = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.load()];
            });
        });
    };
    ArtifactDetails.prototype.render = function () {
        if (!this.state.artifact)
            return React.createElement(core_1.CircularProgress, null);
        return (React.createElement("div", { className: typestyle_1.classes(Css_1.commonCss.page) },
            React.createElement("div", { className: typestyle_1.classes(Css_1.padding(20, 't')) },
                React.createElement(MD2Tabs_1.default, { tabs: tabNames, selectedTab: this.state.selectedTab, onSwitch: this.switchTab.bind(this) })),
            this.state.selectedTab === ArtifactDetailsTab.OVERVIEW && (React.createElement("div", { className: typestyle_1.classes(Css_1.padding(20, 'lr')) },
                React.createElement(ResourceInfo_1.ResourceInfo, { typeName: this.properTypeName, resource: this.state.artifact }))),
            this.state.selectedTab === ArtifactDetailsTab.LINEAGE_EXPLORER && (React.createElement(frontend_1.LineageView, { target: this.state.artifact }))));
    };
    ArtifactDetails.prototype.getInitialToolbarState = function () {
        return {
            actions: [],
            breadcrumbs: [{ displayName: 'Artifacts', href: Router_1.RoutePage.ARTIFACTS }],
            pageTitle: this.properTypeName + " " + this.id + " details"
        };
    };
    ArtifactDetails.prototype.refresh = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.load()];
            });
        });
    };
    ArtifactDetails.prototype.load = function () {
        return __awaiter(this, void 0, void 0, function () {
            var request, response, artifact, artifactName, title, version;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        request = new frontend_1.GetArtifactsByIDRequest();
                        request.setArtifactIdsList([Number(this.id)]);
                        return [4 /*yield*/, this.api.metadataStoreService.getArtifactsByID(request)];
                    case 1:
                        response = _a.sent();
                        if (!response) {
                            this.showPageError("Unable to retrieve " + this.fullTypeName + " " + this.id + ".");
                            return [2 /*return*/];
                        }
                        if (!response.getArtifactsList().length) {
                            this.showPageError("No " + this.fullTypeName + " identified by id: " + this.id);
                            return [2 /*return*/];
                        }
                        if (response.getArtifactsList().length > 1) {
                            this.showPageError("Found multiple artifacts with ID: " + this.id);
                            return [2 /*return*/];
                        }
                        artifact = response.getArtifactsList()[0];
                        artifactName = Utils_1.getResourceProperty(artifact, frontend_1.ArtifactProperties.NAME);
                        title = artifactName ? artifactName.toString() : '';
                        version = Utils_1.getResourceProperty(artifact, frontend_1.ArtifactProperties.VERSION);
                        if (version) {
                            title += " (version: " + version + ")";
                        }
                        this.props.updateToolbar({
                            pageTitle: title
                        });
                        this.setState({ artifact: artifact });
                        return [2 /*return*/];
                }
            });
        });
    };
    ArtifactDetails.prototype.switchTab = function (selectedTab) {
        this.setState({ selectedTab: selectedTab });
    };
    return ArtifactDetails;
}(Page_1.Page));
exports.default = ArtifactDetails;
//# sourceMappingURL=ArtifactDetails.js.map


text:
const { app, BrowserWindow } = require('electron');

const path = require('path');
const url = require('url');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 1650, height: 900, show: false});

    // and load the index.html of the app.
    const startUrl = process.env.ELECTRON_START_URL || url.format({
            pathname: path.join(__dirname, '/../build/index.html'),
            protocol: 'file:',
            slashes: true
        });
    mainWindow.loadURL(startUrl);

    mainWindow.on('ready-to-show', () => {
      mainWindow.show();
      // Open the DevTools.
      mainWindow.webContents.openDevTools();
    })

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null
    })

}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', function () {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE CPP #-}
-- ----------------------------------------------------------------------------
-- | Handle conversion of CmmData to LLVM code.
--

module LlvmCodeGen.Data (
        genLlvmData, genData
    ) where

#include "HsVersions.h"

import Llvm
import LlvmCodeGen.Base

import BlockId
import CLabel
import Cmm

import FastString
import qualified Outputable

-- ----------------------------------------------------------------------------
-- * Constants
--

-- | The string appended to a variable name to create its structure type alias
structStr :: LMString
structStr = fsLit "_struct"

-- ----------------------------------------------------------------------------
-- * Top level
--

-- | Pass a CmmStatic section to an equivalent Llvm code.
genLlvmData :: (Section, CmmStatics) -> LlvmM LlvmData
genLlvmData (sec, Statics lbl xs) = do
    label <- strCLabel_llvm lbl
    static <- mapM genData xs
    let types   = map getStatType static

        strucTy = LMStruct types
        tyAlias = LMAlias ((label `appendFS` structStr), strucTy)

        struct         = Just $ LMStaticStruc static tyAlias
        link           = if (externallyVisibleCLabel lbl)
                            then ExternallyVisible else Internal
        const          = if isSecConstant sec then Constant else Global
        varDef         = LMGlobalVar label tyAlias link Nothing Nothing const
        globDef        = LMGlobal varDef struct

    return ([globDef], [tyAlias])

-- | Should a data in this section be considered constant
isSecConstant :: Section -> Bool
isSecConstant Text                    = True
isSecConstant ReadOnlyData            = True
isSecConstant RelocatableReadOnlyData = True
isSecConstant ReadOnlyData16          = True
isSecConstant Data                    = False
isSecConstant UninitialisedData       = False
isSecConstant (OtherSection _)        = False

-- ----------------------------------------------------------------------------
-- * Generate static data
--

-- | Handle static data
genData :: CmmStatic -> LlvmM LlvmStatic

genData (CmmString str) = do
    let v  = map (\x -> LMStaticLit $ LMIntLit (fromIntegral x) i8) str
        ve = v ++ [LMStaticLit $ LMIntLit 0 i8]
    return $ LMStaticArray ve (LMArray (length ve) i8)

genData (CmmUninitialised bytes)
    = return $ LMUninitType (LMArray bytes i8)

genData (CmmStaticLit lit)
    = genStaticLit lit

-- | Generate Llvm code for a static literal.
--
-- Will either generate the code or leave it unresolved if it is a 'CLabel'
-- which isn't yet known.
genStaticLit :: CmmLit -> LlvmM LlvmStatic
genStaticLit (CmmInt i w)
    = return $ LMStaticLit (LMIntLit i (LMInt $ widthInBits w))

genStaticLit (CmmFloat r w)
    = return $ LMStaticLit (LMFloatLit (fromRational r) (widthToLlvmFloat w))

genStaticLit (CmmVec ls)
    = do sls <- mapM toLlvmLit ls
         return $ LMStaticLit (LMVectorLit sls)
  where
    toLlvmLit :: CmmLit -> LlvmM LlvmLit
    toLlvmLit lit = do
      slit <- genStaticLit lit
      case slit of
        LMStaticLit llvmLit -> return llvmLit
        _ -> panic "genStaticLit"

-- Leave unresolved, will fix later
genStaticLit cmm@(CmmLabel l) = do
    var <- getGlobalPtr =<< strCLabel_llvm l
    dflags <- getDynFlags
    let ptr = LMStaticPointer var
        lmty = cmmToLlvmType $ cmmLitType dflags cmm
    return $ LMPtoI ptr lmty

genStaticLit (CmmLabelOff label off) = do
    dflags <- getDynFlags
    var <- genStaticLit (CmmLabel label)
    let offset = LMStaticLit $ LMIntLit (toInteger off) (llvmWord dflags)
    return $ LMAdd var offset

genStaticLit (CmmLabelDiffOff l1 l2 off) = do
    dflags <- getDynFlags
    var1 <- genStaticLit (CmmLabel l1)
    var2 <- genStaticLit (CmmLabel l2)
    let var = LMSub var1 var2
        offset = LMStaticLit $ LMIntLit (toInteger off) (llvmWord dflags)
    return $ LMAdd var offset

genStaticLit (CmmBlock b) = genStaticLit $ CmmLabel $ infoTblLbl b

genStaticLit (CmmHighStackMark)
    = panic "genStaticLit: CmmHighStackMark unsupported!"

-- -----------------------------------------------------------------------------
-- * Misc
--

-- | Error Function
panic :: String -> a
panic s = Outputable.panic $ "LlvmCodeGen.Data." ++ s


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="default.console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUG</level>
        </filter>
    </appender>

    <root level="INFO">
        <appender-ref ref="default.console"/>
    </root>
</configuration>


text:
import compile from './compile'
import store from './store'

export function getCache(filename) {
  return store.cache[filename];
}

export function getPartial(partial) {
  var partial_filename = 'partial:' + partial;
  var cache = getCache(partial_filename);
  if (!cache) {
    var source = store.partials[partial];
    if (source) {
      // 编译模版片段
      cache = compile(source, {
        filename: partial_filename
      });
    }
  }
  return cache;
}


text:
import json
import os
from urllib import unquote_plus, quote
import requests

BASE_URL = "https://memegen.link"

class Memer():

    def get_templates(self):
        temp_url = BASE_URL + "/api/templates/"
        response = requests.get(temp_url).json()

        data = [(v.encode('ascii', 'ignore').replace(temp_url, ""), k.encode('ascii', 'ignore')) for k, v in response.items()]
        data.sort(key = lambda tup: tup[0])
        return data

    def list_templates(self):
        return "\n".join(["`{0}` {1}".format(t[0], t[1])  for t in self.get_templates()])

    def build_url(self, template, top, bottom, alt = None):
        top_url = top.replace("?", "~q") if top else "_"
        bottom_url = bottom.replace("?", "~q") if bottom else "_"
        path = "/{0}/{1}/{2}.jpg".format(template,  top_url, bottom_url).replace(" ", "_")

        if alt:
            path = path + "?alt={}".format(alt)

        return BASE_URL + "/" + path

    def image_exists(self, path):
        if path.split("://")[0] not in ["http", "https"]:
            return False

        r = requests.head(path)
        return r.status_code == requests.codes.ok

    def get_meme(self,  template, top, bottom):
        template = template.lstrip("<").rstrip(">")
        valid_templates = [x[0] for x in self.get_templates()]
        if template in valid_templates:
            return self.build_url(template, top, bottom)
        elif self.image_exists(template):
            return self.build_url("custom", top, bottom, template)
        else:
            return "%s isn't a valid template. provide your own url type `?meme` to see valid choices" % template


text:
A simple cryptographic tool to encrypt your files. The files are encrypted with AES cipher.

**NOTE:** This tool is currently built only for windows. You could try making your own version of this for other OS's but it's not a priority for me now.

### Building
1. Install all dependencies. `npm install`
2. Package the app. `npm run package`
3. Build the installable. `npm run build`

And that's it! Any wanted changes could be made after installing the dependencies. After that just package it and build!

### FAQ
* **Why do I have to *write* the file path?**
 Because the chromium that this runs on prevents the full path from being revealed when you *Browse* for files.

* **Will you make any versions of this for [insertNameOfOSthatIsNotWindows]?**
Well, I only have a Windows, So I cannot debug or fix errors on how this would work on non-Windows machines.

* **I forgot the password I used to encrypt my file. Can I get it back?**
Nope. The password is the *key* you used to encrypt your file, and that *key* is the only thing that can decrypt it.

* **Where can I directly download the executable for this?**
You can download the setup from the [releases](https://github.com/TheVexatious/Cryzmo/releases).

#### TODO
* Better HTML Layout
* Add pictures to README
* covfefe

Feel free to contribute by sending PR's and creating issues!


text:
package com.smartdevicelink.test.rpc.datatypes;

import com.smartdevicelink.proxy.rpc.GPSData;
import com.smartdevicelink.proxy.rpc.enums.CompassDirection;
import com.smartdevicelink.proxy.rpc.enums.Dimension;
import com.smartdevicelink.test.JsonUtils;
import com.smartdevicelink.test.TestValues;

import junit.framework.TestCase;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

/**
 * This is a unit test class for the SmartDeviceLink library project class :
 * {@link com.smartdevicelink.proxy.rpc.GPSData}
 */
public class GPSDataTests extends TestCase {

    private GPSData msg;

    @Override
    public void setUp() {
        msg = new GPSData();

        msg.setActual(TestValues.GENERAL_BOOLEAN);
        msg.setAltitude(TestValues.GENERAL_DOUBLE);
        msg.setCompassDirection(TestValues.GENERAL_COMPASSDIRECTION);
        msg.setDimension(TestValues.GENERAL_DIMENSION);
        msg.setHdop(TestValues.GENERAL_DOUBLE);
        msg.setHeading(TestValues.GENERAL_DOUBLE);
        msg.setLatitudeDegrees(TestValues.GENERAL_DOUBLE);
        msg.setLongitudeDegrees(TestValues.GENERAL_DOUBLE);
        msg.setPdop(TestValues.GENERAL_DOUBLE);
        msg.setSatellites(TestValues.GENERAL_INT);
        msg.setSpeed(TestValues.GENERAL_DOUBLE);
        msg.setUtcDay(TestValues.GENERAL_INT);
        msg.setUtcHours(TestValues.GENERAL_INT);
        msg.setUtcMinutes(TestValues.GENERAL_INT);
        msg.setUtcMonth(TestValues.GENERAL_INT);
        msg.setUtcSeconds(TestValues.GENERAL_INT);
        msg.setUtcYear(TestValues.GENERAL_INT);
        msg.setVdop(TestValues.GENERAL_DOUBLE);
        msg.setShifted(TestValues.GENERAL_BOOLEAN);
    }

    /**
     * Tests the expected values of the RPC message.
     */
    public void testRpcValues() {
        // Test Values
        boolean actual = msg.getActual();
        double latitude = msg.getLatitudeDegrees();
        double longitude = msg.getLongitudeDegrees();
        double altitude = msg.getAltitude();
        double heading = msg.getHeading();
        double speed = msg.getSpeed();
        double pdop = msg.getPdop();
        double hdop = msg.getHdop();
        double vdop = msg.getVdop();
        int utcYear = msg.getUtcYear();
        int utcMin = msg.getUtcMinutes();
        int utcMonths = msg.getUtcMonth();
        int utcDay = msg.getUtcDay();
        int utcHours = msg.getUtcHours();
        int utcSec = msg.getUtcSeconds();
        int satellites = msg.getSatellites();
        Dimension dimension = msg.getDimension();
        CompassDirection direction = msg.getCompassDirection();
        boolean shifted = msg.getShifted();

        // Valid Tests
        assertEquals(TestValues.MATCH, TestValues.GENERAL_BOOLEAN, actual);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, latitude);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, longitude);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, altitude);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, heading);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, speed);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, pdop);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, hdop);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DOUBLE, vdop);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_INT, utcYear);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_INT, utcMin);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_INT, utcMonths);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_INT, utcDay);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_INT, utcHours);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_INT, utcSec);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_INT, satellites);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_DIMENSION, dimension);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_COMPASSDIRECTION, direction);
        assertEquals(TestValues.MATCH, TestValues.GENERAL_BOOLEAN, shifted);

        // Invalid/Null Tests
        GPSData msg = new GPSData();
        assertNotNull(TestValues.NOT_NULL, msg);

        assertNull(TestValues.NULL, msg.getActual());
        assertNull(TestValues.NULL, msg.getAltitude());
        assertNull(TestValues.NULL, msg.getCompassDirection());
        assertNull(TestValues.NULL, msg.getDimension());
        assertNull(TestValues.NULL, msg.getHdop());
        assertNull(TestValues.NULL, msg.getHeading());
        assertNull(TestValues.NULL, msg.getLatitudeDegrees());
        assertNull(TestValues.NULL, msg.getLongitudeDegrees());
        assertNull(TestValues.NULL, msg.getPdop());
        assertNull(TestValues.NULL, msg.getSatellites());
        assertNull(TestValues.NULL, msg.getSpeed());
        assertNull(TestValues.NULL, msg.getUtcDay());
        assertNull(TestValues.NULL, msg.getUtcHours());
        assertNull(TestValues.NULL, msg.getUtcMinutes());
        assertNull(TestValues.NULL, msg.getUtcMonth());
        assertNull(TestValues.NULL, msg.getUtcSeconds());
        assertNull(TestValues.NULL, msg.getUtcYear());
        assertNull(TestValues.NULL, msg.getVdop());
        assertNull(TestValues.NULL, msg.getShifted());
    }

    public void testJson() {
        JSONObject reference = new JSONObject();

        try {
            reference.put(GPSData.KEY_ACTUAL, TestValues.GENERAL_BOOLEAN);
            reference.put(GPSData.KEY_LATITUDE_DEGREES, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_LONGITUDE_DEGREES, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_ALTITUDE, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_HEADING, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_SPEED, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_PDOP, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_HDOP, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_VDOP, TestValues.GENERAL_DOUBLE);
            reference.put(GPSData.KEY_UTC_YEAR, TestValues.GENERAL_INT);
            reference.put(GPSData.KEY_UTC_MONTH, TestValues.GENERAL_INT);
            reference.put(GPSData.KEY_UTC_HOURS, TestValues.GENERAL_INT);
            reference.put(GPSData.KEY_UTC_DAY, TestValues.GENERAL_INT);
            reference.put(GPSData.KEY_UTC_MINUTES, TestValues.GENERAL_INT);
            reference.put(GPSData.KEY_UTC_SECONDS, TestValues.GENERAL_INT);
            reference.put(GPSData.KEY_SATELLITES, TestValues.GENERAL_INT);
            reference.put(GPSData.KEY_DIMENSION, TestValues.GENERAL_DIMENSION);
            reference.put(GPSData.KEY_COMPASS_DIRECTION, TestValues.GENERAL_COMPASSDIRECTION);
            reference.put(GPSData.KEY_SHIFTED, TestValues.GENERAL_BOOLEAN);

            JSONObject underTest = msg.serializeJSON();
            assertEquals(TestValues.MATCH, reference.length(), underTest.length());

            Iterator<?> iterator = reference.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                assertEquals(TestValues.MATCH, JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key));
            }
        } catch (JSONException e) {
            fail(TestValues.JSON_FAIL);
        }
    }
}


text:
<?php

/*
 * This file is part of the Silex framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Silex\Tests\Application;

use Silex\Provider\SecurityServiceProvider;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\HttpFoundation\Request;

/**
 * SecurityTrait test cases.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class SecurityTraitTest extends \PHPUnit_Framework_TestCase
{
    public function testEncodePassword()
    {
        $app = $this->createApplication(array(
            'fabien' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
        ));

        $user = new User('foo', 'bar');
        $password = 'foo';
        $encoded = $app->encodePassword($user, $password);

        $this->assertTrue(
            $app['security.encoder_factory']->getEncoder($user)->isPasswordValid($encoded, $password, $user->getSalt())
        );
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
     */
    public function testIsGrantedWithoutTokenThrowsException()
    {
        $app = $this->createApplication();
        $app->get('/', function () { return 'foo'; });
        $app->handle(Request::create('/'));
        $app->isGranted('ROLE_ADMIN');
    }

    public function testIsGranted()
    {
        $request = Request::create('/');

        $app = $this->createApplication(array(
            'fabien' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
            'monique' => array('ROLE_USER',  '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
        ));
        $app->get('/', function () { return 'foo'; });

        // User is Monique (ROLE_USER)
        $request->headers->set('PHP_AUTH_USER', 'monique');
        $request->headers->set('PHP_AUTH_PW', 'foo');
        $app->handle($request);
        $this->assertTrue($app->isGranted('ROLE_USER'));
        $this->assertFalse($app->isGranted('ROLE_ADMIN'));

        // User is Fabien (ROLE_ADMIN)
        $request->headers->set('PHP_AUTH_USER', 'fabien');
        $request->headers->set('PHP_AUTH_PW', 'foo');
        $app->handle($request);
        $this->assertFalse($app->isGranted('ROLE_USER'));
        $this->assertTrue($app->isGranted('ROLE_ADMIN'));
    }

    public function createApplication($users = array())
    {
        $app = new SecurityApplication();
        $app->register(new SecurityServiceProvider(), array(
            'security.firewalls' => array(
                'default' => array(
                    'http' => true,
                    'users' => $users,
                ),
            ),
        ));

        return $app;
    }
}


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.impl.jobexecutor;

import java.util.List;

import org.flowable.common.engine.api.scope.ScopeTypes;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.bpmn.helper.ErrorPropagation;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.CountingEntityUtil;
import org.flowable.job.service.JobHandler;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.flowable.variable.api.delegate.VariableScope;
import org.flowable.variable.service.VariableService;
import org.flowable.variable.service.impl.persistence.entity.VariableInstanceEntity;

/**
 * @author Filip Hrisafov
 */
public class ExternalWorkerTaskCompleteJobHandler implements JobHandler {

    public static final String TYPE = "external-worker-complete";

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
        ExecutionEntity executionEntity = (ExecutionEntity) variableScope;

        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        VariableService variableService = processEngineConfiguration.getVariableServiceConfiguration().getVariableService();
        List<VariableInstanceEntity> jobVariables = variableService.findVariableInstanceBySubScopeIdAndScopeType(executionEntity.getId(), ScopeTypes.BPMN_EXTERNAL_WORKER);
        for (VariableInstanceEntity jobVariable : jobVariables) {
            executionEntity.setVariable(jobVariable.getName(), jobVariable.getValue());
            CountingEntityUtil.handleDeleteVariableInstanceEntityCount(jobVariable, false);
            variableService.deleteVariableInstance(jobVariable);
        }

        if (configuration != null && configuration.startsWith("error:")) {
            String errorCode;
            if (configuration.length() > 6) {
                errorCode = configuration.substring(6);
            } else {
                errorCode = null;
            }
            ErrorPropagation.propagateError(errorCode, executionEntity);
        } else {
            CommandContextUtil.getAgenda(commandContext).planTriggerExecutionOperation(executionEntity);
        }
    }

}


text:
package net.minecraft.block;

import java.util.Random;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IStringSerializable;
import net.minecraft.world.World;

public class BlockHugeMushroom extends Block
{
    public static final PropertyEnum<EnumType> VARIANT = PropertyEnum.<EnumType>create("variant", EnumType.class);
    private final Block smallBlock;

    public BlockHugeMushroom(Material p_i46392_1_, MapColor p_i46392_2_, Block p_i46392_3_)
    {
        super(p_i46392_1_, p_i46392_2_);
        this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, EnumType.ALL_OUTSIDE));
        this.smallBlock = p_i46392_3_;
    }

    /**
     * Returns the quantity of items to drop on block destruction.
     */
    public int quantityDropped(Random random)
    {
        return Math.max(0, random.nextInt(10) - 7);
    }

    /**
     * Get the MapColor for this Block and the given BlockState
     */
    public MapColor getMapColor(IBlockState state)
    {
        switch ((EnumType)state.getValue(VARIANT))
        {
            case ALL_STEM:
                return MapColor.clothColor;

            case ALL_INSIDE:
                return MapColor.sandColor;

            case STEM:
                return MapColor.sandColor;

            default:
                return super.getMapColor(state);
        }
    }

    /**
     * Get the Item that this Block should drop when harvested.
     */
    public Item getItemDropped(IBlockState state, Random rand, int fortune)
    {
        return Item.getItemFromBlock(this.smallBlock);
    }

    /**
     * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the
     * IBlockstate
     */
    public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
    {
        return this.getDefaultState();
    }

    /**
     * Convert the given metadata into a BlockState for this Block
     */
    public IBlockState getStateFromMeta(int meta)
    {
        return this.getDefaultState().withProperty(VARIANT, EnumType.byMetadata(meta));
    }

    /**
     * Convert the BlockState into the correct metadata value
     */
    public int getMetaFromState(IBlockState state)
    {
        return ((EnumType)state.getValue(VARIANT)).getMetadata();
    }

    protected BlockState createBlockState()
    {
        return new BlockState(this, new IProperty[] {VARIANT});
    }

    public static enum EnumType implements IStringSerializable
    {
        NORTH_WEST(1, "north_west"),
        NORTH(2, "north"),
        NORTH_EAST(3, "north_east"),
        WEST(4, "west"),
        CENTER(5, "center"),
        EAST(6, "east"),
        SOUTH_WEST(7, "south_west"),
        SOUTH(8, "south"),
        SOUTH_EAST(9, "south_east"),
        STEM(10, "stem"),
        ALL_INSIDE(0, "all_inside"),
        ALL_OUTSIDE(14, "all_outside"),
        ALL_STEM(15, "all_stem");

        private static final EnumType[] META_LOOKUP = new EnumType[16];
        private final int meta;
        private final String name;

        private EnumType(int meta, String name)
        {
            this.meta = meta;
            this.name = name;
        }

        public int getMetadata()
        {
            return this.meta;
        }

        public String toString()
        {
            return this.name;
        }

        public static EnumType byMetadata(int meta)
        {
            if (meta < 0 || meta >= META_LOOKUP.length)
            {
                meta = 0;
            }

            EnumType blockhugemushroom$enumtype = META_LOOKUP[meta];
            return blockhugemushroom$enumtype == null ? META_LOOKUP[0] : blockhugemushroom$enumtype;
        }

        public String getName()
        {
            return this.name;
        }

        static {
            for (EnumType blockhugemushroom$enumtype : values())
            {
                META_LOOKUP[blockhugemushroom$enumtype.getMetadata()] = blockhugemushroom$enumtype;
            }
        }
    }
}


text:
package io.bootique.jersey;

import io.bootique.ModuleExtender;
import io.bootique.di.Binder;
import io.bootique.di.Key;
import io.bootique.di.MapBuilder;
import io.bootique.di.SetBuilder;
import io.bootique.di.TypeLiteral;

import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Feature;
import java.util.Map;

public class JerseyModuleExtender extends ModuleExtender<JerseyModuleExtender> {

    private SetBuilder<Feature> features;
    private SetBuilder<DynamicFeature> dynamicFeatures;
    private SetBuilder<Object> resources;
    private SetBuilder<Package> packages;
    private SetBuilder<MappedResource> mappedResources;
    private MapBuilder<String, Object> resourcesByPath;
    private MapBuilder<String, Object> properties;

    JerseyModuleExtender(Binder binder) {
        super(binder);
    }

    public JerseyModuleExtender initAllExtensions() {
        contributeDynamicFeatures();
        contributeFeatures();
        contributePackages();
        contributeResources();
        contributeResourcesByPath();
        contributeMappedResources();
        contributeProperties();

        return this;
    }

    public JerseyModuleExtender addPackage(Package aPackage) {
        contributePackages().addInstance(aPackage);
        return this;
    }

    public JerseyModuleExtender addPackage(Class<?> anyClassInPackage) {
        contributePackages().addInstance(anyClassInPackage.getPackage());
        return this;
    }

    public JerseyModuleExtender addFeature(Feature feature) {
        contributeFeatures().addInstance(feature);
        return this;
    }

    public <T extends Feature> JerseyModuleExtender addFeature(Class<T> featureType) {
        contributeFeatures().add(featureType);
        return this;
    }

    public JerseyModuleExtender addDynamicFeature(DynamicFeature feature) {
        contributeDynamicFeatures().addInstance(feature);
        return this;
    }

    public <T extends DynamicFeature> JerseyModuleExtender addDynamicFeature(Class<T> featureType) {
        contributeDynamicFeatures().add(featureType);
        return this;
    }

    public JerseyModuleExtender addResource(Object resource) {
        contributeResources().addInstance(resource);
        return this;
    }

    public JerseyModuleExtender addResource(Class<?> resource) {
        contributeResources().add(resource);
        return this;
    }

    /**
     * Registers an API resource type with a custom path. The path argument overrides class-level
     * {@link javax.ws.rs.Path} annotation value, allowing to remap resource to a different URL. This even allows to
     * map the same resource multiple times under different paths.
     *
     * @param resource type of the resource
     * @param path     resource URL path that overrides {@link javax.ws.rs.Path} annotation on the resource class.
     * @return this extender
     * @since 2.0
     */
    public JerseyModuleExtender addResource(Class<?> resource, String path) {
        contributeResourcesByPath().put(path, resource);
        return this;
    }

    /**
     * Registers a "mapped" API resource. MappedResource paths override class-level {@link javax.ws.rs.Path} annotation
     * value, allowing to remap resource to a different URL. This even allows to map the same resource multiple times
     * under different paths.
     *
     * @param mappedResource an object that encapsulates resource object and one or more alternative path mappings.
     * @return this extender
     * @since 2.0
     */
    public <T> JerseyModuleExtender addMappedResource(MappedResource<T> mappedResource) {
        contributeMappedResources().addInstance(mappedResource);
        return this;
    }

    /**
     * Registers a "mapped" API resource. MappedResource paths override class-level {@link javax.ws.rs.Path} annotation
     * value, allowing to remap resource to a different URL. This even allows to map the same resource multiple times
     * under different paths.
     *
     * @param mappedResourceKey a DI key of a {@link MappedResource}
     * @return this extender
     * @since 2.0
     */
    public <T> JerseyModuleExtender addMappedResource(Key<MappedResource<T>> mappedResourceKey) {
        contributeMappedResources().add(mappedResourceKey);
        return this;
    }

    /**
     * Registers a "mapped" API resource. MappedResource paths override class-level {@link javax.ws.rs.Path} annotation
     * value, allowing to remap resource to a different URL. This even allows to map the same resource multiple times
     * under different paths.
     *
     * @param mappedResourceType a signature of the {@link MappedResource}. The resource itself is located in DI.
     * @return this extender
     * @since 2.0
     */
    public <T> JerseyModuleExtender addMappedResource(TypeLiteral<MappedResource<T>> mappedResourceType) {
        contributeMappedResources().add(Key.get(mappedResourceType));
        return this;
    }

    /**
     * @since 2.0.B1
     */
    public JerseyModuleExtender setApplication(Application app) {
        binder.bind(Application.class).toInstance(app);
        return this;
    }

    /**
     * @since 2.0.B1
     */
    public JerseyModuleExtender setApplication(Class<? extends Application> appType) {
        binder.bind(Application.class).to(appType);
        return this;
    }

    /**
     * Sets Jersey container property. This allows setting ResourceConfig properties that can not be set via JAX RS features.
     *
     * @param name  property name
     * @param value property value
     * @return this extender
     * @see org.glassfish.jersey.server.ServerProperties
     */
    public JerseyModuleExtender setProperty(String name, Object value) {
        contributeProperties().putInstance(name, value);
        return this;
    }

    /**
     * Sets Jersey container properties.  This allows setting ResourceConfig properties that can not be set via JAX RS features.
     *
     * @return this extender instance
     * @see org.glassfish.jersey.server.ServerProperties
     */
    public JerseyModuleExtender setProperties(Map<String, String> properties) {
        properties.forEach(this::setProperty);
        return this;
    }

    protected MapBuilder<String, Object> contributeResourcesByPath() {
        if (resourcesByPath == null) {
            resourcesByPath = newMap(String.class, Object.class, JerseyModule.RESOURCES_BY_PATH_BINDING);
        }
        return resourcesByPath;
    }

    protected SetBuilder<MappedResource> contributeMappedResources() {
        if (mappedResources == null) {
            mappedResources = newSet(MappedResource.class);
        }
        return mappedResources;
    }

    protected MapBuilder<String, Object> contributeProperties() {
        if (properties == null) {
            // TODO: switch to named bindings defined in JerseyModule?
            properties = newMap(String.class, Object.class, JerseyResource.class);
        }
        return properties;
    }

    protected SetBuilder<Feature> contributeFeatures() {
        if (features == null) {
            features = newSet(Feature.class);
        }
        return features;
    }

    protected SetBuilder<DynamicFeature> contributeDynamicFeatures() {
        if (dynamicFeatures == null) {
            dynamicFeatures = newSet(DynamicFeature.class);
        }
        return dynamicFeatures;
    }

    protected SetBuilder<Object> contributeResources() {
        if (resources == null) {
            // TODO: switch to named bindings defined in JerseyModule?
            resources = newSet(Key.get(Object.class, JerseyResource.class));
        }
        return resources;
    }

    protected SetBuilder<Package> contributePackages() {
        if (packages == null) {
            // TODO: switch to named bindings defined in JerseyModule?
            packages = newSet(Package.class, JerseyResource.class);
        }
        return packages;
    }
}


text:
package com.roshan.gearman.function.mapper;

import java.util.Map;

import org.gearman.GearmanFunction;

/**
 * @author Roshan Alexander
 *
 */
public class GearmanFunctionMapperImpl implements GearmanFunctionMapper {

	private Map<String, GearmanFunction> functionMapper;

	@Override
	public GearmanFunction getGearmanFunction(String functionName) {
		return functionMapper.get(functionName);
	}

	/**
	 * @return the functionMapper
	 */
	public Map<String, GearmanFunction> getFunctionMapper() {
		return functionMapper;
	}

	/**
	 * @param functionMapper
	 *            the functionMapper to set
	 */
	public void setFunctionMapper(Map<String, GearmanFunction> functionMapper) {
		this.functionMapper = functionMapper;
	}

}


text:
from setuptools import find_packages, setup

pkgname = "vdt.versionplugin.puppetmodule"

setup(name=pkgname,
      version="0.1",
      description="Version Increment Plugin that builds a package from a puppet module",
      author="Lars van de Kerkhof",
      author_email="lars@permanentmarkers.nl",
      maintainer="Lars van de Kerkhof",
      maintainer_email="lars@permanentmarkers.nl",
      packages=find_packages(),
      include_package_data=True,
      namespace_packages=['vdt', 'vdt.versionplugin'],
      zip_safe=True,
      install_requires=[
          "setuptools",
          "vdt.version",
          "vdt.versionplugin.default",
      ],
      entry_points={},
)


text:
/*global require*/

var pine = require('./pine'),
    _ = require('lodash-node'),
    exec = require('child_process').exec;

var successCode = 1,
    errorCode = 0;

var processRequest = function(params) {
  var res = params.res,
      shellCommand = params.route.shellCommand;

  _.each(params.args, function(value, key) {
    shellCommand = shellCommand.replace('{{' + key + '}}', value);
  });

  exec(shellCommand, function(error, stdout, stderr) {
    var result = {};

    if (error) {
      result.status = errorCode;
      console.log(error);
      if (stderr) {
        console.log(stderr);
        result.result = stderr;
      }
    } else {
      result.status = successCode;
      result.result = stdout;
    }

    res.send(result);
  });
};

var routes = [
  // GET http://localhost:3000/files/list
  {
    url: '/files/list',
    shellCommand: 'ls'
  },
  // GET http://localhost:3000/files/listDetails
  {
    url: '/files/listDetails',
    shellCommand: 'ls -la',
    argMap: {
      customerid: 'params.customerid'
    }
  },
  // GET http://localhost:3000/echo/HelloUser
  {
    url: '/echo/:message',
    shellCommand: 'echo {{message}}',
    argMap: {
      message: 'params.message'
    }
  }
];

pine({
  processRequest: processRequest,
  routes: routes,
  port: 3000,
  verbose: true
});


text:
package org.eknet.publet.engine

import org.eknet.publet.vfs.{Path, ContentResource, ContentType}

/**
 *
 * @author Eike Kettner
 * @since 28.03.12 23:38
 */
object PassThrough extends PubletEngine {

  def name = 'source
  def process(path: Path, data: ContentResource, target: ContentType) = Some(data)

}


text:
// Sep 14, 2000:
//  Fixed serializer to report IO exception directly, instead at
//  the end of document processing.
//  Reported by Patrick Higgins <phiggins@transzap.com>
// Aug 21, 2000:
//  Fixed bug in startDocument not calling prepare.
//  Reported by Mikael Staldal <d96-mst-ingen-reklam@d.kth.se>
// Aug 21, 2000:
//  Added ability to omit DOCTYPE declaration.
// Sep 1, 2000:
//   If no output format is provided the serializer now defaults
//   to ISO-8859-1 encoding. Reported by Mikael Staldal
//   <d96-mst@d.kth.se>

package org.apache.xml.serialize;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import org.apache.xerces.dom.DOMMessageFormatter;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.AttributeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
 * Implements an HTML/XHTML serializer supporting both DOM and SAX
 * pretty serializing. HTML/XHTML mode is determined in the
 * constructor.  For usage instructions see {@link Serializer}.
 *

 * If an output stream is used, the encoding is taken from the
 * output format (defaults to <tt>UTF-8</tt>). If a writer is
 * used, make sure the writer uses the same encoding (if applies)
 * as specified in the output format.
 *

 * The serializer supports both DOM and SAX. DOM serializing is done
 * by calling {@link #serialize} and SAX serializing is done by firing
 * SAX events and using the serializer as a document handler.
 *

 * If an I/O exception occurs while serializing, the serializer
 * will not throw an exception directly, but only throw it
 * at the end of serializing (either DOM or SAX's {@link
 * org.xml.sax.DocumentHandler#endDocument}.
 *

 * For elements that are not specified as whitespace preserving,
 * the serializer will potentially break long text lines at space
 * boundaries, indent lines, and serialize elements on separate
 * lines. Line terminators will be regarded as spaces, and
 * spaces at beginning of line will be stripped.
 *

 * XHTML is slightly different than HTML:
 *

 *
Element/attribute names are lower case and case matters
 *
Attributes must specify value, even if empty string
 *
Empty elements must have '/' in empty tag
 *
Contents of SCRIPT and STYLE elements serialized as CDATA
 *

 *
 * @deprecated This class was deprecated in Xerces 2.6.2. It is
 * recommended that new applications use JAXP's Transformation API
 * for XML (TrAX) for serializing HTML. See the Xerces documentation
 * for more information.
 * @version $Revision$ $Date$
 * @author Assaf Arkin
 * @see Serializer
 */
public class HTMLSerializer
    extends BaseMarkupSerializer
{

    /**
     * True if serializing in XHTML format.
     */
    private boolean _xhtml;

    public static final String XHTMLNamespace = "http://www.w3.org/1999/xhtml";

    // for users to override XHTMLNamespace if need be.
    private String fUserXHTMLNamespace = null;

    /**
     * Constructs a new HTML/XHTML serializer depending on the value of
     * <tt>xhtml</tt>. The serializer cannot be used without calling
     * {@link #setOutputCharStream} or {@link #setOutputByteStream} first.
     *
     * @param xhtml True if XHTML serializing
     */
    protected HTMLSerializer( boolean xhtml, OutputFormat format )
    {
        super( format );
        _xhtml = xhtml;
    }

    /**
     * Constructs a new serializer. The serializer cannot be used without
     * calling {@link #setOutputCharStream} or {@link #setOutputByteStream}
     * first.
     */
    public HTMLSerializer()
    {
        this( false, new OutputFormat( Method.HTML, "ISO-8859-1", false ) );
    }

    /**
     * Constructs a new serializer. The serializer cannot be used without
     * calling {@link #setOutputCharStream} or {@link #setOutputByteStream}
     * first.
     */
    public HTMLSerializer( OutputFormat format )
    {
        this( false, format != null ? format : new OutputFormat( Method.HTML, "ISO-8859-1", false ) );
    }

    /**
     * Constructs a new serializer that writes to the specified writer
     * using the specified output format. If <tt>format</tt> is null,
     * will use a default output format.
     *
     * @param writer The writer to use
     * @param format The output format to use, null for the default
     */
    public HTMLSerializer( Writer writer, OutputFormat format )
    {
        this( false, format != null ? format : new OutputFormat( Method.HTML, "ISO-8859-1", false ) );
        setOutputCharStream( writer );
    }

    /**
     * Constructs a new serializer that writes to the specified output
     * stream using the specified output format. If <tt>format</tt>
     * is null, will use a default output format.
     *
     * @param output The output stream to use
     * @param format The output format to use, null for the default
     */
    public HTMLSerializer( OutputStream output, OutputFormat format )
    {
        this( false, format != null ? format : new OutputFormat( Method.HTML, "ISO-8859-1", false ) );
        setOutputByteStream( output );
    }

    public void setOutputFormat( OutputFormat format )
    {
        super.setOutputFormat( format != null ? format : new OutputFormat( Method.HTML, "ISO-8859-1", false ) );
    }

    // Set  value for alternate XHTML namespace.
    public void setXHTMLNamespace(String newNamespace) {
        fUserXHTMLNamespace = newNamespace;
    } // setXHTMLNamespace(String)

    //-----------------------------------------//
    // SAX content handler serializing methods //
    //-----------------------------------------//

    public void startElement( String namespaceURI, String localName,
                              String rawName, Attributes attrs )
        throws SAXException
    {
        int          i;
        boolean      preserveSpace;
        ElementState state;
        String       name;
        String       value;
        String       htmlName;
        boolean      addNSAttr = false;

        try {
            if ( _printer == null )
            	throw new IllegalStateException(
				    DOMMessageFormatter.formatMessage(
				    DOMMessageFormatter.SERIALIZER_DOMAIN,
                    "NoWriterSupplied", null));

            state = getElementState();
            if ( isDocumentState() ) {
                // If this is the root element handle it differently.
                // If the first root element in the document, serialize
                // the document's DOCTYPE. Space preserving defaults
                // to that of the output format.
                if ( ! _started )
                    startDocument( (localName == null || localName.length() == 0)
                        ? rawName : localName );
            } else {
                // For any other element, if first in parent, then
                // close parent's opening tag and use the parnet's
                // space preserving.
                if ( state.empty )
                    _printer.printText( '>' );
                // Indent this element on a new line if the first
                // content of the parent element or immediately
                // following an element.
                if ( _indenting && ! state.preserveSpace &&
                     ( state.empty || state.afterElement ) )
                    _printer.breakLine();
            }
            preserveSpace = state.preserveSpace;

            // Do not change the current element state yet.
            // This only happens in endElement().

            // As per SAX2, the namespace URI is an empty string if the element has no
            // namespace URI, or namespaces is turned off. The check against null protects
            // against broken SAX implementations, so I've left it there. - mrglavas
            boolean hasNamespaceURI = (namespaceURI != null && namespaceURI.length() != 0);

            // SAX2: rawName (QName) could be empty string if
            // namespace-prefixes property is false.
            if ( rawName == null || rawName.length() == 0) {
                rawName = localName;
                if ( hasNamespaceURI ) {
                    String prefix;
                    prefix = getPrefix( namespaceURI );
                    if ( prefix != null && prefix.length() != 0 )
                        rawName = prefix + ":" + localName;
                }
                addNSAttr = true;
            }
            if ( !hasNamespaceURI )
                htmlName = rawName;
            else {
                if ( namespaceURI.equals( XHTMLNamespace ) ||
                        (fUserXHTMLNamespace != null && fUserXHTMLNamespace.equals(namespaceURI)) )
                    htmlName = localName;
                else
                    htmlName = null;
            }

            // XHTML: element names are lower case, DOM will be different
            _printer.printText( '<' );
            if ( _xhtml )
                _printer.printText( rawName.toLowerCase(Locale.ENGLISH) );
            else
                _printer.printText( rawName );
            _printer.indent();

            // For each attribute serialize it's name and value as one part,
            // separated with a space so the element can be broken on
            // multiple lines.
            if ( attrs != null ) {
                for ( i = 0 ; i < attrs.getLength() ; ++i ) {
                    _printer.printSpace();
                    name = attrs.getQName( i ).toLowerCase(Locale.ENGLISH);
                    value = attrs.getValue( i );
                    if ( _xhtml || hasNamespaceURI ) {
                        // XHTML: print empty string for null values.
                        if ( value == null ) {
                            _printer.printText( name );
                            _printer.printText( "=\"\"" );
                        } else {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            printEscaped( value );
                            _printer.printText( '"' );
                        }
                    } else {
                        // HTML: Empty values print as attribute name, no value.
                        // HTML: URI attributes will print unescaped
                        if ( value == null ) {
                            value = "";
                        }
                        if ( !_format.getPreserveEmptyAttributes() && value.length() == 0 )
                            _printer.printText( name );
                        else if ( HTMLdtd.isURI( rawName, name ) ) {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            _printer.printText( escapeURI( value ) );
                            _printer.printText( '"' );
                        } else if ( HTMLdtd.isBoolean( rawName, name ) )
                            _printer.printText( name );
                        else {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            printEscaped( value );
                            _printer.printText( '"' );
                        }
                    }
                }
            }
            if ( htmlName != null && HTMLdtd.isPreserveSpace( htmlName ) )
                preserveSpace = true;

            if ( addNSAttr ) {
                Iterator entries = _prefixes.entrySet().iterator();
                while (entries.hasNext()) {
                    _printer.printSpace();
                    Map.Entry entry = (Map.Entry) entries.next();
                    value = (String) entry.getKey();
                    name = (String) entry.getValue();
                    if ( name.length() == 0 ) {
                        _printer.printText( "xmlns=\"" );
                        printEscaped( value );
                        _printer.printText( '"' );
                    }
                    else {
                        _printer.printText( "xmlns:" );
                        _printer.printText( name );
                        _printer.printText( "=\"" );
                        printEscaped( value );
                        _printer.printText( '"' );
                    }
                }
            }

            // Now it's time to enter a new element state
            // with the tag name and space preserving.
            // We still do not change the curent element state.
            state = enterElementState( namespaceURI, localName, rawName, preserveSpace );

            // Prevents line breaks inside A/TD

            if ( htmlName != null && ( htmlName.equalsIgnoreCase( "A" ) ||
                                       htmlName.equalsIgnoreCase( "TD" ) ) ) {
                state.empty = false;
                _printer.printText( '>' );
            }

            // Handle SCRIPT and STYLE specifically by changing the
            // state of the current element to CDATA (XHTML) or
            // unescaped (HTML).
            if ( htmlName != null && ( rawName.equalsIgnoreCase( "SCRIPT" ) ||
                                       rawName.equalsIgnoreCase( "STYLE" ) ) ) {
                if ( _xhtml ) {
                    // XHTML: Print contents as CDATA section
                    state.doCData = true;
                } else {
                    // HTML: Print contents unescaped
                    state.unescaped = true;
                }
            }
        } catch ( IOException except ) {
            throw new SAXException( except );
        }
    }

    public void endElement( String namespaceURI, String localName,
                            String rawName )
        throws SAXException
    {
        try {
            endElementIO( namespaceURI, localName, rawName );
        } catch ( IOException except ) {
            throw new SAXException( except );
        }
    }

    public void endElementIO( String namespaceURI, String localName,
                              String rawName )
        throws IOException
    {
        ElementState state;
        String       htmlName;

        // Works much like content() with additions for closing
        // an element. Note the different checks for the closed
        // element's state and the parent element's state.
        _printer.unindent();
        state = getElementState();

        if ( state.namespaceURI == null || state.namespaceURI.length() == 0 )
            htmlName = state.rawName;
        else {
            if ( state.namespaceURI.equals( XHTMLNamespace ) ||
                        (fUserXHTMLNamespace != null && fUserXHTMLNamespace.equals(state.namespaceURI)) )
                htmlName = state.localName;
            else
                htmlName = null;
        }

        if ( _xhtml) {
            if ( state.empty ) {
                _printer.printText( " />" );
            } else {
                // Must leave CData section first
                if ( state.inCData )
                    _printer.printText( "]]>" );
                // XHTML: element names are lower case, DOM will be different
                _printer.printText( "</" );
                _printer.printText( state.rawName.toLowerCase(Locale.ENGLISH) );
                _printer.printText( '>' );
            }
        } else {
            if ( state.empty )
                _printer.printText( '>' );
            // This element is not empty and that last content was
            // another element, so print a line break before that
            // last element and this element's closing tag.
            // [keith] Provided this is not an anchor.
            // HTML: some elements do not print closing tag (e.g. LI)
            if ( htmlName == null || ! HTMLdtd.isOnlyOpening( htmlName ) ) {
                if ( _indenting && ! state.preserveSpace && state.afterElement )
                    _printer.breakLine();
                // Must leave CData section first (Illegal in HTML, but still)
                if ( state.inCData )
                    _printer.printText( "]]>" );
                _printer.printText( "</" );
                _printer.printText( state.rawName );
                _printer.printText( '>' );
            }
        }
        // Leave the element state and update that of the parent
        // (if we're not root) to not empty and after element.
        state = leaveElementState();
        // Temporary hack to prevent line breaks inside A/TD
        if ( htmlName == null || ( ! htmlName.equalsIgnoreCase( "A" ) &&
                                   ! htmlName.equalsIgnoreCase( "TD" ) ) )

            state.afterElement = true;
        state.empty = false;
        if ( isDocumentState() )
            _printer.flush();
    }

    //------------------------------------------//
    // SAX document handler serializing methods //
    //------------------------------------------//

    public void characters( char[] chars, int start, int length )
        throws SAXException
    {
        ElementState state;

        try {
            // HTML: no CDATA section
            state = content();
            state.doCData = false;
            super.characters( chars, start, length );
        } catch ( IOException except ) {
            throw new SAXException( except );
        }
    }

    public void startElement( String tagName, AttributeList attrs )
        throws SAXException
    {
        int          i;
        boolean      preserveSpace;
        ElementState state;
        String       name;
        String       value;

        try {
            if ( _printer == null )
                throw new IllegalStateException(
				    DOMMessageFormatter.formatMessage(
				    DOMMessageFormatter.SERIALIZER_DOMAIN,
                    "NoWriterSupplied", null));

            state = getElementState();
            if ( isDocumentState() ) {
                // If this is the root element handle it differently.
                // If the first root element in the document, serialize
                // the document's DOCTYPE. Space preserving defaults
                // to that of the output format.
                if ( ! _started )
                    startDocument( tagName );
            } else {
                // For any other element, if first in parent, then
                // close parent's opening tag and use the parnet's
                // space preserving.
                if ( state.empty )
                    _printer.printText( '>' );
                // Indent this element on a new line if the first
                // content of the parent element or immediately
                // following an element.
                if ( _indenting && ! state.preserveSpace &&
                     ( state.empty || state.afterElement ) )
                    _printer.breakLine();
            }
            preserveSpace = state.preserveSpace;

            // Do not change the current element state yet.
            // This only happens in endElement().

            // XHTML: element names are lower case, DOM will be different
            _printer.printText( '<' );
            if ( _xhtml )
                _printer.printText( tagName.toLowerCase(Locale.ENGLISH) );
            else
                _printer.printText( tagName );
            _printer.indent();

            // For each attribute serialize it's name and value as one part,
            // separated with a space so the element can be broken on
            // multiple lines.
            if ( attrs != null ) {
                for ( i = 0 ; i < attrs.getLength() ; ++i ) {
                    _printer.printSpace();
                    name = attrs.getName( i ).toLowerCase(Locale.ENGLISH);
                    value = attrs.getValue( i );
                    if ( _xhtml ) {
                        // XHTML: print empty string for null values.
                        if ( value == null ) {
                            _printer.printText( name );
                            _printer.printText( "=\"\"" );
                        } else {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            printEscaped( value );
                            _printer.printText( '"' );
                        }
                    } else {
                        // HTML: Empty values print as attribute name, no value.
                        // HTML: URI attributes will print unescaped
                        if ( value == null ) {
                            value = "";
                        }
                        if ( !_format.getPreserveEmptyAttributes() && value.length() == 0 )
                            _printer.printText( name );
                        else if ( HTMLdtd.isURI( tagName, name ) ) {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            _printer.printText( escapeURI( value ) );
                            _printer.printText( '"' );
                        } else if ( HTMLdtd.isBoolean( tagName, name ) )
                            _printer.printText( name );
                        else {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            printEscaped( value );
                            _printer.printText( '"' );
                        }
                    }
                }
            }
            if ( HTMLdtd.isPreserveSpace( tagName ) )
                preserveSpace = true;

            // Now it's time to enter a new element state
            // with the tag name and space preserving.
            // We still do not change the curent element state.
            state = enterElementState( null, null, tagName, preserveSpace );

            // Prevents line breaks inside A/TD
            if ( tagName.equalsIgnoreCase( "A" ) || tagName.equalsIgnoreCase( "TD" ) ) {
                state.empty = false;
                _printer.printText( '>' );
            }

            // Handle SCRIPT and STYLE specifically by changing the
            // state of the current element to CDATA (XHTML) or
            // unescaped (HTML).
            if ( tagName.equalsIgnoreCase( "SCRIPT" ) ||
                 tagName.equalsIgnoreCase( "STYLE" ) ) {
                if ( _xhtml ) {
                    // XHTML: Print contents as CDATA section
                    state.doCData = true;
                } else {
                    // HTML: Print contents unescaped
                    state.unescaped = true;
                }
            }
        } catch ( IOException except ) {
            throw new SAXException( except );
        }
    }

    public void endElement( String tagName )
        throws SAXException
    {
        endElement( null, null, tagName );
    }

    //------------------------------------------//
    // Generic node serializing methods methods //
    //------------------------------------------//

    /**
     * Called to serialize the document's DOCTYPE by the root element.
     * The document type declaration must name the root element,
     * but the root element is only known when that element is serialized,
     * and not at the start of the document.
     *

     * This method will check if it has not been called before ({@link #_started}),
     * will serialize the document type declaration, and will serialize all
     * pre-root comments and PIs that were accumulated in the document
     * (see {@link #serializePreRoot}). Pre-root will be serialized even if
     * this is not the first root element of the document.
     */
    protected void startDocument( String rootTagName )
        throws IOException
    {
        // Not supported in HTML/XHTML, but we still have to switch
        // out of DTD mode.
        _printer.leaveDTD();
        if ( ! _started ) {
            // If the public and system identifiers were not specified
            // in the output format, use the appropriate ones for HTML
            // or XHTML.
            if ( _docTypePublicId == null && _docTypeSystemId == null ) {
                if ( _xhtml ) {
                    _docTypePublicId = HTMLdtd.XHTMLPublicId;
                    _docTypeSystemId = HTMLdtd.XHTMLSystemId;
                } else {
                    _docTypePublicId = HTMLdtd.HTMLPublicId;
                    _docTypeSystemId = HTMLdtd.HTMLSystemId;
                }
            }

            if ( ! _format.getOmitDocumentType() ) {
                // XHTML: If public identifier and system identifier
                //  specified, print them, else print just system identifier
                // HTML: If public identifier specified, print it with
                //  system identifier, if specified.
                // XHTML requires that all element names are lower case, so the
                // root on the DOCTYPE must be 'html'. - mrglavas
                if ( _docTypePublicId != null && ( ! _xhtml || _docTypeSystemId != null )  ) {
                    if (_xhtml) {
                        _printer.printText( "<!DOCTYPE html PUBLIC " );
                    }
                    else {
                        _printer.printText( "<!DOCTYPE HTML PUBLIC " );
                    }
                    printDoctypeURL( _docTypePublicId );
                    if ( _docTypeSystemId != null ) {
                        if ( _indenting ) {
                            _printer.breakLine();
                            _printer.printText( "                      " );
                        } else
                        _printer.printText( ' ' );
                        printDoctypeURL( _docTypeSystemId );
                    }
                    _printer.printText( '>' );
                    _printer.breakLine();
                } else if ( _docTypeSystemId != null ) {
                    if (_xhtml) {
                        _printer.printText( "<!DOCTYPE html SYSTEM " );
                    }
                    else {
                        _printer.printText( "<!DOCTYPE HTML SYSTEM " );
                    }
                    printDoctypeURL( _docTypeSystemId );
                    _printer.printText( '>' );
                    _printer.breakLine();
                }
            }
        }

        _started = true;
        // Always serialize these, even if not te first root element.
        serializePreRoot();
    }

    /**
     * Called to serialize a DOM element. Equivalent to calling {@link
     * #startElement}, {@link #endElement} and serializing everything
     * inbetween, but better optimized.
     */
    protected void serializeElement( Element elem )
        throws IOException
    {
        Attr         attr;
        NamedNodeMap attrMap;
        int          i;
        Node         child;
        ElementState state;
        boolean      preserveSpace;
        String       name;
        String       value;
        String       tagName;

        tagName = elem.getTagName();
        state = getElementState();
        if ( isDocumentState() ) {
            // If this is the root element handle it differently.
            // If the first root element in the document, serialize
            // the document's DOCTYPE. Space preserving defaults
            // to that of the output format.
            if ( ! _started )
                startDocument( tagName );
        } else {
            // For any other element, if first in parent, then
            // close parent's opening tag and use the parnet's
            // space preserving.
            if ( state.empty )
                _printer.printText( '>' );
            // Indent this element on a new line if the first
            // content of the parent element or immediately
            // following an element.
            if ( _indenting && ! state.preserveSpace &&
                 ( state.empty || state.afterElement ) )
                _printer.breakLine();
        }
        preserveSpace = state.preserveSpace;

        // Do not change the current element state yet.
        // This only happens in endElement().

        // XHTML: element names are lower case, DOM will be different
        _printer.printText( '<' );
        if ( _xhtml )
            _printer.printText( tagName.toLowerCase(Locale.ENGLISH) );
        else
            _printer.printText( tagName );
        _printer.indent();

        // Lookup the element's attribute, but only print specified
        // attributes. (Unspecified attributes are derived from the DTD.
        // For each attribute print it's name and value as one part,
        // separated with a space so the element can be broken on
        // multiple lines.
        attrMap = elem.getAttributes();
        if ( attrMap != null ) {
            for ( i = 0 ; i < attrMap.getLength() ; ++i ) {
                attr = (Attr) attrMap.item( i );
                name = attr.getName().toLowerCase(Locale.ENGLISH);
                value = attr.getValue();
                if ( attr.getSpecified() ) {
                    _printer.printSpace();
                    if ( _xhtml ) {
                        // XHTML: print empty string for null values.
                        if ( value == null ) {
                            _printer.printText( name );
                            _printer.printText( "=\"\"" );
                        } else {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            printEscaped( value );
                            _printer.printText( '"' );
                        }
                    } else {
                        // HTML: Empty values print as attribute name, no value.
                        // HTML: URI attributes will print unescaped
                        if ( value == null ) {
                            value = "";
                        }
                        if ( !_format.getPreserveEmptyAttributes() && value.length() == 0 )
                            _printer.printText( name );
                        else if ( HTMLdtd.isURI( tagName, name ) ) {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            _printer.printText( escapeURI( value ) );
                            _printer.printText( '"' );
                        } else if ( HTMLdtd.isBoolean( tagName, name ) )
                            _printer.printText( name );
                        else {
                            _printer.printText( name );
                            _printer.printText( "=\"" );
                            printEscaped( value );
                            _printer.printText( '"' );
                        }
                    }
                }
            }
        }
        if ( HTMLdtd.isPreserveSpace( tagName ) )
            preserveSpace = true;

        // If element has children, or if element is not an empty tag,
        // serialize an opening tag.
        if ( elem.hasChildNodes() || ! HTMLdtd.isEmptyTag( tagName ) ) {
            // Enter an element state, and serialize the children
            // one by one. Finally, end the element.
            state = enterElementState( null, null, tagName, preserveSpace );

            // Prevents line breaks inside A/TD
            if ( tagName.equalsIgnoreCase( "A" ) || tagName.equalsIgnoreCase( "TD" ) ) {
                state.empty = false;
                _printer.printText( '>' );
            }

            // Handle SCRIPT and STYLE specifically by changing the
            // state of the current element to CDATA (XHTML) or
            // unescaped (HTML).
            if ( tagName.equalsIgnoreCase( "SCRIPT" ) ||
                 tagName.equalsIgnoreCase( "STYLE" ) ) {
                if ( _xhtml ) {
                    // XHTML: Print contents as CDATA section
                    state.doCData = true;
                } else {
                    // HTML: Print contents unescaped
                    state.unescaped = true;
                }
            }
            child = elem.getFirstChild();
            while ( child != null ) {
                serializeNode( child );
                child = child.getNextSibling();
            }
            endElementIO( null, null, tagName );
        } else {
            _printer.unindent();
            // XHTML: Close empty tag with ' />' so it's XML and HTML compatible.
            // HTML: Empty tags are defined as such in DTD no in document.
            if ( _xhtml )
                _printer.printText( " />" );
            else
                _printer.printText( '>' );
            // After element but parent element is no longer empty.
            state.afterElement = true;
            state.empty = false;
            if ( isDocumentState() )
                _printer.flush();
        }
    }

    protected void characters( String text )
        throws IOException
    {
        // HTML: no CDATA section
        content();
        super.characters( text );
    }

    protected String getEntityRef( int ch )
    {
        return HTMLdtd.fromChar( ch );
    }

    protected String escapeURI( String uri )
    {
        int index;

        // XXX  Apparently Netscape doesn't like if we escape the URI
        //      using %nn, so we leave it as is, just remove any quotes.
        index = uri.indexOf( "\"" );
        if ( index >= 0 ) {
            return uri.substring( 0, index );
        }
        return uri;
    }

}


text:
<plugin name='rendering' version='1.0.0' grailsVersion='1.3.0 > *'>
  <author>Grails Plugin Collective</author>
  <authorEmail>grails.plugin.collective@gmail.com</authorEmail>
  <title>Grails Rendering</title>
  <description>Render GSPs as PDFs, JPEGs, GIFs and PNGs</description>
  <documentation>http://gpc.github.com/grails-rendering</documentation>
  <type>RenderingGrailsPlugin</type>
  <resources>
    <resource>grails.plugin.rendering.RenderingService</resource>
    <resource>grails.plugin.rendering.document.XhtmlDocumentService</resource>
    <resource>grails.plugin.rendering.image.GifRenderingService</resource>
    <resource>grails.plugin.rendering.image.ImageRenderingService</resource>
    <resource>grails.plugin.rendering.image.JpegRenderingService</resource>
    <resource>grails.plugin.rendering.image.PngRenderingService</resource>
    <resource>grails.plugin.rendering.pdf.PdfRenderingService</resource>
    <resource>grails.plugin.rendering.RenderingTagLib</resource>
  </resources>
</plugin>


text:
package nz.co.senanque.functions;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {
		"nz.co.senanque.functions" })
public class FunctionConfiguration {

}


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

<link   rel="stylesheet"
        href="../../css/style.min.0a7442460ca45a8d1ffa9d4f0a0163976899fc7820ce2bb76f693ba0527afb57.css"
        integrity="sha256-CnRCRgykWo0f+p1PCgFjl2iZ/Hggziu3b2k7oFJ6+1c="
        type="text/css"
        media="screen">

<link   rel="stylesheet"
        href="../../css/mobile.min.9d1271f82d33327493aaf7c1818ceac101a822559d694bd14a222d686e28c391.css"
        integrity="sha256-nRJx+C0zMnSTqvfBgYzqwQGoIlWdaUvRSiItaG4ow5E="
        type="text/css"
        media="handheld, only screen and (max-device-width: 960px)">

    <link href="https://unwiredcouch.com/atom.xml" type="application/atom+xml" rel="alternate" title="unwiredcouch.com: All Posts" />

    <title>Slack: Getting Past Burnout, Busywork, and the Myth of Total Efficiency on unwiredcouch.com</title>

Writing

Reading

Setup

About

Drawing

Mastodon

 Slack: Getting Past Burnout, Busywork, and the Myth of Total Efficiency

 by
           Tom DeMarco

 Read: Aug 27, 2019

I really enjoyed this book. As someone who has not been actively part of the dotcom era, and has mostly been told about the bad sides of that time, it's refreshing to read something coming out of that time full of what are still essentially progressive ideas today. Slack as the part of the work where innovation happens vs the always on, always busy culture is something organizations can still learn heaps from today. Definitely recommend reading it.

Imprint


text:
package org.drooms.impl.util.shortestpath.astar;

import org.drooms.api.Node;

class ManhattanDistanceHeuristic<V extends Node> implements
        DistanceHeuristic<V> {

    @Override
    public double estimateDistance(final V source, final V target) {
        final int xDistance = Math.abs(source.getX() - target.getX());
        final int yDistance = Math.abs(source.getY() - target.getY());
        return xDistance + yDistance;
    }

}


text:
author: Ben
comments: true
date: 2010-11-09 18:52:13
layout: post
slug: how-to-automatically-buzz-guests-in
title: How to automatically buzz guests in your neighborhood or apartment
wordpress_id: 633
categories:
- Technology
---

![](http://onlyamodel.com/wp-content/uploads/callbox-twilio.jpg)

I live in a gated community and we share our home with lots of folks.  We can only list one phone number in our callbox, which means I'm constantly buzzing people in.  To make matters worse, when I'm working I sometimes forget to check my phone when I get calls, so I find out a friend has been outside our neighborhood trying to get in and I have 20 missed gate calls.

I mentioned this to my brother-in-law [Jason](http://twitter.com/ardell) and we tried to think of a way to use Google Voice to automatically buzz folks in.  This approach didn't really work out, but some time later he told me about a great service called [Twilio](http://www.twilio.com/) that he used to solve this problem.  Twilio is basically a series of pay-as-you-go VOIP API's that allow you to build simple cloud communications apps using either voice or SMS.

I finally decided to give this a go.  You can use the following approach to buzz folks into your apartment or neighborhood gate.  I tested this implementation last weekend when we had about 20 people over, and it works flawlessly.  Here's the basic premise:

<!-- more -->

  1. Get a Twilio account and buy a local Twilio phone number.

  2. Call your community management and have them change your number in the callbox to your Twilio number.

  3. Point your Twilio phone number at a simple web-app which will control access to your community.

Point 3 can be as complicated as you like, ranging from either (i) automatically buzzing in anyone to (ii) a complete phone menu where someone at your gate can select which roommate they wish to visit, input secret codes to automatically gain entrance, etc.  For an in-depth example of this, you can read a [great tutorial by Danielle Morrill](http://www.daniellemorrill.com/2010/06/how-i-built-a-multi-user-door-buzzer-for-our-apartment/) which provides all the code and explanation of how she set up a multi-user door buzzer for her apartment.  In the end, I decided that Danielle's implementation was way overkill for what I need.  Here are the steps I wanted:

  1. Greet my guest.

  2. Play the #9 DTMF tone to buzz them in.

  3. Send me an SMS message saying "Intruder Alert!"

The [Twilio API](http://www.twilio.com/docs/index) is incredibly well-documented so this is super simple to pull off.  All you need to do is create a file called `callbox.xml` containing the following text, and put it in your public folder in [Dropbox](http://www.dropbox.com).  Point your Twilio number at the public url of this file, and you are all set.

`callbox.xml:`

    <Response>
    	<Say>Greetings, I am a cyborg that Ben has employed to buzz friends into the neighborhood.  Please wait for the gate to open.</Say>
        <Play>9.wav</Play>
        <Sms to="123-456-7890" from="098-765-4321" method="POST">Intruder alert!</Sms>
    </Response>

All you have to do is replace 123-456-7890 with your cell phone number and 098-765-4321 with your Twilio number.  The file `9.wav` is a simple audio file containing the number 9 DTMF tone which should live in the same location in your public Dropbox folder.  You can generate the DTMF tone this using [this web utility](http://www.dialabc.com/sound/generate/).

I really like the simplicity of this solution for now.  Since I receive a text message every time someone uses this, I can easily track if this is ever abused.  If that starts happening, I will implement an algorithm like Danielle's above which will require a secret passcode for entry.  But for now, this is awesome.  Thanks to Twilio for making this possible!

Thanks:  [Jason Ardell](http://ardell.posterous.com/), [Danielle Morrill](http://www.daniellemorrill.com/2010/06/how-i-built-a-multi-user-door-buzzer-for-our-apartment/), [Sean McCann](https://github.com/seanmccann/PHP-Twilio-Apartment-Entry), [Twilio](http://www.twilio.com)


text:
[![Latest Version](https://img.shields.io/github/release/thephpleague/:package_name.svg?style=flat-square)](https://github.com/thephpleague/:package_name/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Build Status](https://img.shields.io/travis/thephpleague/:package_name/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/:package_name)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/:package_name.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/:package_name/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/iGusev/torrent.svg?style=flat-square)](https://scrutinizer-ci.com/g/iGusev/torrent)
[![Total Downloads](https://img.shields.io/packagist/dt/league/:package_name.svg?style=flat-square)](https://packagist.org/packages/league/:package_name)

**Note:** Replace ```:author_name``` ```:author_username``` ```:author_website``` ```:author_email``` ```:package_name``` ```:package_description``` with their correct values in [README.md](README.md), [CHANGELOG.md](CHANGELOG.md), [CONTRIBUTING.md](CONTRIBUTING.md), [LICENSE.md](LICENSE.md) and [composer.json](composer.json) files, then delete this line.

This is where your description should go. Try and limit it to a paragraph or two, and maybe throw in a mention of what
PSRs you support to avoid any confusion with users and contributors.

## Install

Via Composer

``` bash
$ composer require league/torrent
```

## Usage

``` php
$skeleton = new League\Skeleton();
echo $skeleton->echoPhrase('Hello, League!');
```

## Testing

``` bash
$ phpunit
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

## Security

If you discover any security related issues, please email mail@igusev.ru instead of using the issue tracker.

## Credits

- [Ilya Gusev](https://github.com/iGusev)
- [All Contributors](../../contributors)

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.


text:
package org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer;

import org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException;

/**
 * This is a Artifact Saver type. these interface let users to save API artifacts to a storage.
 */
public interface ArtifactSaver {

    /**
     * The init of the Artifact saver, this will be called only once.
     *
     * @throws ArtifactSynchronizerException if there are any configuration errors
     */
    void init() throws ArtifactSynchronizerException;

    /**
     * This method is used to save deployable artifact of an API to the storage
     *
     * @param gatewayRuntimeArtifacts - A String contains all the information about the API and gateway artifacts
     * @throws ArtifactSynchronizerException if there are any errors in the process
     */
    void saveArtifact(String gatewayRuntimeArtifacts, String gatewayLabel, String gatewayInstruction)
            throws ArtifactSynchronizerException;

    /**
     * This method will return true if the API is published in any of the Gateways
     *
     * @param apiId - UUID of the API
     * @return True if API is published in any of the Gateways. False if published in none
     */
    boolean isAPIPublished(String apiId);

    /**
     * Will be called after all saving is done, or when init fails
     */
    void disconnect();

    /**
     * This method will return the name of artifact saver implementation
     *
     * @return Name of the Artifact saver
     */
    String getName();

}


text:
[![Build Status](https://travis-ci.org/ecbypi/puppet-rails.png?branch=master)](https://travis-ci.org/ecbypi/puppet-rails)

Allows you to manage your Rails deploys.

## Setup environment

Use the `rails::deploy` resource type to add your application user and create
your deploy path:

```puppet
rails::deploy { 'my-app-name':
  deploy_path => '/var/www/rails',
  app_user    => 'rails',
}
```

This will setup add the user `rails` and create the directory
`/var/www/rails/my-app-name` owned by `rails`. If `var` or `/var/www` do not
exist, they will be created and owned by the deploy user.

### database.yml

If relevant, you can manage the `database.yml` for your application by
specifying the relevant parameters:

```puppet
rails::deploy { 'my-app':
  rails_env         => 'staging',
  database_adapter  => 'mysql2',
  database_name     => 'my_app_db',
  database_host     => 'db.app.com',
  database_user     => 'rails_db',
  database_password => 'sekrit',
  database_charset  => 'latin1',
  database_pool     => 12,
}
```

Only `database_adapter` and `database_password` are required. The
`database_name` defaults to the application name underscored.


text:
<?php

abstract class PaymentController extends CController
{
    /**
     * @var string
     */
    public $managerId = 'payment';

    /**
     * @return array access filters.
     */
    public function filters()
    {
        return array(
            'accessControl',
        );
    }

    /**
     * @return array access control rules.
     */
    public function accessRules()
    {
        return array(
            array('allow', 'users' => array('@')),
            array('deny'),
        );
    }

    /**
     * @return PaymentManager
     * @throws CException
     */
    protected function getPaymentManager()
    {
        if (!Yii::app()->hasComponent($this->managerId)) {
            throw new CException(sprintf('PaytrailController.managerId is invalid.'));
        }
        return Yii::app()->getComponent($this->managerId);
    }
}