text:
@charset "utf-8";
/*
 *name:dtt
 *time:2014.10.30
 *content:头部样式,包含登录条及导航
*/

/*基本样式,页面加载共用头部时,即其它样式不用import*/
@import url('../../../css/style.css');

/*首页头部*/
.header{ background:#e2e2e2; border-bottom:2px solid #dbdbdb; height:34px;text-align:center; padding-top:5px;}
.header .hd-content{ width:980px; margin:0 auto 5px; color:#5c5c5c; height:29px; line-height:29px;}
.header .tel,.header a.weibo,.header a.weibo:hover,.header .weixin,.header .cur,.name-news .msg,.name-news .bouns,.name-news .name,.name-news .bar i,span.help,.name-news .msg-no, .name-news .bouns-no,.set-list .my-set i,.set-list a.nv-set i{background:url(../img/header_icon.png) no-repeat;_background:url(../img/header_icon6.png) no-repeat;}
.header .tel{ display:inline-block; background-position:-2px 8px; padding-left:22px; vertical-align:middle; float:left; line-height:29px;}
.header .tel strong{font-size:18px; font-weight:normal; line-height:24px; margin-right:30px; vertical-align:text-bottom;}
.header a.weibo,.header .weixin{width:25px;height:25px;display:inline-block;vertical-align:middle;float:left;}
.header a.weibo{background-position:0 -61px; margin:2px 0 0 2px;}
.header a.weibo:hover{background-position:0 -26px;}
.header .weixin{background-position:0 -151px; position:relative; margin:2px 0 0 8px;}
.header .weixin i{ position:absolute; width:181px; height:200px; background:url(../img/top_weixin.png) no-repeat left top; left:-79px; top:24px; z-index:3; display:none;}
.header .cur{background-position:0 -109px;}
.login-grey{ float:right;}

.login-grey a{background:url(../img/top-btn.png) no-repeat;_background:url(../img/top-btn6.png) no-repeat;line-height:22px; height:22px;margin-left:2px;_vertical-align:middle;_margin-top:3px;color:#fff;font-size:14px; display:inline-block; width:57px;}
.login-grey a.login{background-position:0 -2px;}
.login-grey a.login:hover{background-position:0 -114px;text-decoration:none;}
.login-grey a.grey{background-position:0 -60px;}
.login-grey a.grey:hover{background-position:0 -164px;text-decoration:none;}

span.help{display:inline-block;height:22px; line-height:22px; margin-left:6px;background-position:0 -479px;padding:2px 0 0 8px;color:#888;font-size:12px;}
span.hp-mg{ background:none;float:right;}
span.hp-mg a{ margin-left:15px;}
span.help a{color:#5c5c5c;}
span.help a:hover{ color:#f00;}
a.ext{ color:#333; font-size:12px;margin-left:5px;}

.name-news{position:relative;font-size:14px;display:inline-block; float:right;height:26px; height:27px; line-height:27px; background:url(../img/ld.png) no-repeat left top; padding-left:16px;}
.name-news .ldto{ background:url(../img/ld.png) no-repeat 100% top; padding-right:16px;}
.name-news .bor-n{display:inline;}
.name-news .l{font-size:12px;}
.name-news .name{color:#ef6612; margin-right:8px; background-position:100% -346px; display:inline-block; padding-right:12px;}
.name-news .msg,.name-news .bouns{padding:1px 0 3px 18px; color:#ef6612; margin:0 5px; font-size:12px;}
.name-news .msg-no,.name-news .bouns-no{ padding:1px 0 3px 18px; color:#989898; margin:0 5px;}
.name-news .msg{ background-position:0 -212px;}
.name-news .bouns{ background-position:0 -265px;}
.name-news .msg-no{ background-position:0 -446px;}
.name-news .bouns-no{ background-position:0 -398px;}
.name-news a.msg:hover,.name-news a.bouns:hover,.name-news a.name:hover{ text-decoration:none;}
.name-news .bar {background:#fff;border: 1px solid #ccc;display: none;height: auto;left: -70px;padding: 5px;position: absolute;text-align: left;top: 26px;width: 200px;z-index: 10;}
.name-news .bar a{ width:90px; display:inline-block; padding-left:10px; float:left; color:#707070; height:24px; line-height:24px; overflow:hidden;}
.name-news .bar a:hover{ background:#dfc78f; color:#fff;text-decoration:none;}
.name-news .bar i{ position:absolute; width:11px; height:6px; display:inline-block; overflow:hidden; background-position:0 -317px; top:-6px; left:102px;}

 /*导航*/
.box{background:#fff; text-align:center;}
.nav-c{ height:60px; padding:12px 0;}
.logo{ width:420px; height:60px; background:url(../img/logo.png) no-repeat left top; float:left; overflow:hidden; text-indent:500px; font-size:0;}
.nav-c .nav{ float:right; display:inline-block; position:relative;}
.nav-bg-line{ position:absolute; top:45px; left:78px; width:0; height:3px; background:url(../img/nav-bg.png) no-repeat left top; display:inline-block;z-index:0;}
.nav-c .nav a{ font-size:16px; color:#333; line-height:60px; display:inline-block; margin-left:25px;}
.nav-c .nav .idx{float:left;}
.nav-c .nav a:hover{ color:#cfa74a; text-decoration:none;}
.nav-c .nav a.cur,.nav .cur .nv-set,.nav .cur .nv-set:hover{color:#ab6f00;}
.set-list{ display:inline-block; height:auto; position:relative;z-index:1;}
.set-list a.nv-set{display:inline-block; }
.nav .my-set-hover a.nv-set{background-position:100% -617px;}
.set-list .my-set{ position:absolute; top:48px; left:19px; width:84px; padding:5px 3px; border:1px solid #c7c7c7; border-top:none; background:#f6eedd; display:none;}
.set-list .my-set a{ height:32px; line-height:32px; text-align:center; color:#707070; display:block; margin:0;font-size:14px;}
.set-list .my-set a:hover{ background:#cfa74a; color:#fff;}
/*.set-list .my-set i{ position:absolute; left:50%; top:-7px; margin-left:-7px; width:14px; height:7px; display:inline-block; background-position:0 -559px; }*/
.nav .my-set-hover .my-set{ display:inline-block;}
.set-list a.nv-set i{width:12px; height:6px; display:inline-block;background-position:100% -560px;transition:.3s;-webkit-transition:.3s;-moz-transition:.3s;transform-origin: 50% 30%;-webkittransform-origin: 50% 30%;-moztransform-origin: 50% 30%;margin-left:5px;vertical-align:middle;}

/*登录页头部*/
.login-head{ border-top:6px solid #cfa74a; background:#f3f3f3; }
.return-home{ background:url(../../../project/login/img/lg-icon.png) no-repeat 0 -89px; float:right; padding-left:25px; margin-top:15px; display:inline-block; height:30px; line-height:30px; font-size:16px; color:#707070;}
.login-head .nav-c{position:relative;}
.login-head i{position:absolute; width:157px; height:6px; overflow:hidden; background:#ab6f00; top:-6px; left:0; z-index:10; display:inline-block;}
.login-head .logo{ margin-left:16px;}

/*导航底部内容区*/
.mail{ background:#f3f3f3 url(../img/ctn_bg.png) repeat-x left top; text-align:center;}
.path{ font-size:12px; line-height:20px; padding:18px 0 10px;}
.center{ height:auto; overflow:hidden;zoom:1;}


text:
#include "modules/webaudio/AudioBasicProcessorHandler.h"
#include "modules/webaudio/AudioNodeInput.h"
#include "modules/webaudio/AudioNodeOutput.h"
#include "platform/audio/AudioBus.h"
#include "platform/audio/AudioProcessor.h"

namespace blink {

AudioBasicProcessorHandler::AudioBasicProcessorHandler(NodeType nodeType, AudioNode& node, float sampleRate, PassOwnPtr<AudioProcessor> processor)
    : AudioHandler(nodeType, node, sampleRate)
    , m_processor(std::move(processor))
{
    addInput();
    addOutput(1);
}

PassRefPtr<AudioBasicProcessorHandler> AudioBasicProcessorHandler::create(NodeType nodeType, AudioNode& node, float sampleRate, PassOwnPtr<AudioProcessor> processor)
{
    return adoptRef(new AudioBasicProcessorHandler(nodeType, node, sampleRate, std::move(processor)));
}

AudioBasicProcessorHandler::~AudioBasicProcessorHandler()
{
    // Safe to call the uninitialize() because it's final.
    uninitialize();
}

void AudioBasicProcessorHandler::initialize()
{
    if (isInitialized())
        return;

    ASSERT(processor());
    processor()->initialize();

    AudioHandler::initialize();
}

void AudioBasicProcessorHandler::uninitialize()
{
    if (!isInitialized())
        return;

    ASSERT(processor());
    processor()->uninitialize();

    AudioHandler::uninitialize();
}

void AudioBasicProcessorHandler::process(size_t framesToProcess)
{
    AudioBus* destinationBus = output(0).bus();

    if (!isInitialized() || !processor() || processor()->numberOfChannels() != numberOfChannels()) {
        destinationBus->zero();
    } else {
        AudioBus* sourceBus = input(0).bus();

        // FIXME: if we take "tail time" into account, then we can avoid calling processor()->process() once the tail dies down.
        if (!input(0).isConnected())
            sourceBus->zero();

        processor()->process(sourceBus, destinationBus, framesToProcess);
    }
}

// Nice optimization in the very common case allowing for "in-place" processing
void AudioBasicProcessorHandler::pullInputs(size_t framesToProcess)
{
    // Render input stream - suggest to the input to render directly into output bus for in-place processing in process() if possible.
    input(0).pull(output(0).bus(), framesToProcess);
}

// As soon as we know the channel count of our input, we can lazily initialize.
// Sometimes this may be called more than once with different channel counts, in which case we must safely
// uninitialize and then re-initialize with the new channel count.
void AudioBasicProcessorHandler::checkNumberOfChannelsForInput(AudioNodeInput* input)
{
    ASSERT(context()->isAudioThread());
    ASSERT(context()->isGraphOwner());

    ASSERT(input == &this->input(0));
    if (input != &this->input(0))
        return;

    ASSERT(processor());
    if (!processor())
        return;

    unsigned numberOfChannels = input->numberOfChannels();

    if (isInitialized() && numberOfChannels != output(0).numberOfChannels()) {
        // We're already initialized but the channel count has changed.
        uninitialize();
    }

    if (!isInitialized()) {
        // This will propagate the channel count to any nodes connected further down the chain...
        output(0).setNumberOfChannels(numberOfChannels);

        // Re-initialize the processor with the new channel count.
        processor()->setNumberOfChannels(numberOfChannels);
        initialize();
    }

    AudioHandler::checkNumberOfChannelsForInput(input);
}

unsigned AudioBasicProcessorHandler::numberOfChannels()
{
    return output(0).numberOfChannels();
}

double AudioBasicProcessorHandler::tailTime() const
{
    return m_processor->tailTime();
}

double AudioBasicProcessorHandler::latencyTime() const
{
    return m_processor->latencyTime();
}

} // namespace blink

redpajama_set_name: RedPajamaGithub


text:
package org.openqa.grid.e2e.utils;

public class GridTestHelper {

//  public static SelfRegisteringRemote getRemoteWithoutCapabilities(Hub hub, GridRole role) {
//    return getRemoteWithoutCapabilities(hub.getUrl(), role);
//  }

//  public static SelfRegisteringRemote getRemoteWithoutCapabilities(URL hub, GridRole role) {
//    String[] args = {"-role", role.toString(),
//                     "-host","localhost",
//                     "-hub",hub.toString(),
//                     "-port",String.valueOf(PortProber.findFreePort())};
//    GridNodeCliOptions options = new GridNodeCliOptions();
//    JCommander.newBuilder().addObject(options).build().parse(args);
//    GridNodeConfiguration config = new GridNodeConfiguration(options);
//    RegistrationRequest req = RegistrationRequest.build(config);
//    SelfRegisteringRemote remote = new SelfRegisteringRemote(req);
//    remote.deleteAllBrowsers();
//    return remote;
//  }

//  public static DesiredCapabilities getSelenium1FirefoxCapability() {
//    DesiredCapabilities firefoxOnSeleniumCapability = new DesiredCapabilities();
//    firefoxOnSeleniumCapability.setBrowserName("*firefox");
//    firefoxOnSeleniumCapability.setCapability(RegistrationRequest.SELENIUM_PROTOCOL,
//                                              SeleniumProtocol.Selenium);
//    return firefoxOnSeleniumCapability;
//  }

//  public static DesiredCapabilities getDefaultBrowserCapability() {
//    String browser = System.getProperty("webdriver.gridtest.browser");
//    if (browser != null) {
//      DesiredCapabilities caps = new DesiredCapabilities();
//      caps.setBrowserName(browser);
//      return caps;
//    }
//    return new DesiredCapabilities(BrowserType.HTMLUNIT, "", Platform.ANY);
//  }

//  public static Hub getHub() {
//    return getHub(new GridHubConfiguration(), true);
//  }

//  public static Hub getHub(
//      GridHubConfiguration config,
//      boolean dynamicallyAllocatePortOnLocalHost) {
//    if (dynamicallyAllocatePortOnLocalHost) {
//      config.host = "localhost";
//      config.port = PortProber.findFreePort();
//    }
//    return getHub(config);
//  }

//  public static Hub getHub(GridHubConfiguration config) {
//    Hub hub = new Hub(config);
//    try {
//      hub.start();
//    } catch (Exception e) {
//      fail("Expected hub to start: " + Throwables.getStackTraceAsString(e));
//    }
//    return hub;
//  }

//  public static Hub prepareTestGrid(int nodeCount) {
//    return prepareTestGrid(getDefaultBrowserCapability(), nodeCount);
//  }

//  public static Hub prepareTestGrid(Capabilities caps, int nodeCount) {
//    Hub hub = GridTestHelper.getHub();
//
//    for (int i = 0; i < nodeCount; i++) {
//      SelfRegisteringRemote remote = GridTestHelper.getRemoteWithoutCapabilities(
//          hub.getUrl(),
//          GridRole.NODE);
//      remote.addBrowser(new DesiredCapabilities(caps), 1);
//
//      DesiredCapabilities capabilities = new DesiredCapabilities(caps);
//      capabilities.setCapability(RegistrationRequest.SELENIUM_PROTOCOL, SeleniumProtocol.WebDriver);
//
//      remote.addBrowser(capabilities, 1);
//
//      remote.setRemoteServer(new SeleniumServer(remote.getConfiguration()));
//
//      try {
//        remote.startRemoteServer();
//      } catch (Exception e) {
//        fail("Unable to start node: " + Throwables.getStackTraceAsString(e));
//      }
//
//      remote.getConfiguration().timeout = -1;
//      remote.sendRegistrationRequest();
//    }
//
//    RegistryTestHelper.waitForNode(hub.getRegistry(), nodeCount);
//    return hub;
//  }

//  public static RemoteWebDriver getRemoteWebDriver(Hub hub) {
//    return new RemoteWebDriver(hub.getWebDriverHubRequestURL(), getDefaultBrowserCapability());
//  }
}


text:
@interface ClassCreatorBridge : NSObject

- (_Nullable id)createClassFromName:(NSString * _Nonnull)className;

@end


text:
"""
HTML rendering for twisted.web.

@var VALID_HTML_TAG_NAMES: A list of recognized HTML tag names, used by the
    L{tag} object.

@var TEMPLATE_NAMESPACE: The XML namespace used to identify attributes and
    elements used by the templating system, which should be removed from the
    final output document.

@var tags: A convenience object which can produce L{Tag} objects on demand via
    attribute access.  For example: C{tags.div} is equivalent to C{Tag("div")}.
    Tags not specified in L{VALID_HTML_TAG_NAMES} will result in an
    L{AttributeError}.
"""

__all__ = [
    'TEMPLATE_NAMESPACE', 'VALID_HTML_TAG_NAMES', 'Element', 'TagLoader',
    'XMLString', 'XMLFile', 'renderer', 'flatten', 'flattenString', 'tags',
    'Comment', 'CDATA', 'Tag', 'slot', 'CharRef', 'renderElement'
    ]

import warnings
from zope.interface import implements

from cStringIO import StringIO
from xml.sax import make_parser, handler

from twisted.web._stan import Tag, slot, Comment, CDATA, CharRef
from twisted.python.filepath import FilePath

TEMPLATE_NAMESPACE = 'http://twistedmatrix.com/ns/twisted.web.template/0.1'

from twisted.web.iweb import ITemplateLoader
from twisted.python import log

# Go read the definition of NOT_DONE_YET. For lulz. This is totally
# equivalent. And this turns out to be necessary, because trying to import
# NOT_DONE_YET in this module causes a circular import which we cannot escape
# from. From which we cannot escape. Etc. glyph is okay with this solution for
# now, and so am I, as long as this comment stays to explain to future
# maintainers what it means. ~ C.
#
# See http://twistedmatrix.com/trac/ticket/5557 for progress on fixing this.
NOT_DONE_YET = 1

class _NSContext(object):
    """
    A mapping from XML namespaces onto their prefixes in the document.
    """

    def __init__(self, parent=None):
        """
        Pull out the parent's namespaces, if there's no parent then default to
        XML.
        """
        self.parent = parent
        if parent is not None:
            self.nss = dict(parent.nss)
        else:
            self.nss = {'http://www.w3.org/XML/1998/namespace':'xml'}

    def get(self, k, d=None):
        """
        Get a prefix for a namespace.

        @param d: The default prefix value.
        """
        return self.nss.get(k, d)

    def __setitem__(self, k, v):
        """
        Proxy through to setting the prefix for the namespace.
        """
        self.nss.__setitem__(k, v)

    def __getitem__(self, k):
        """
        Proxy through to getting the prefix for the namespace.
        """
        return self.nss.__getitem__(k)

class _ToStan(handler.ContentHandler, handler.EntityResolver):
    """
    A SAX parser which converts an XML document to the Twisted STAN
    Document Object Model.
    """

    def __init__(self, sourceFilename):
        """
        @param sourceFilename: the filename to load the XML out of.
        """
        self.sourceFilename = sourceFilename
        self.prefixMap = _NSContext()
        self.inCDATA = False

    def setDocumentLocator(self, locator):
        """
        Set the document locator, which knows about line and character numbers.
        """
        self.locator = locator

    def startDocument(self):
        """
        Initialise the document.
        """
        self.document = []
        self.current = self.document
        self.stack = []
        self.xmlnsAttrs = []

    def endDocument(self):
        """
        Document ended.
        """

    def processingInstruction(self, target, data):
        """
        Processing instructions are ignored.
        """

    def startPrefixMapping(self, prefix, uri):
        """
        Set up the prefix mapping, which maps fully qualified namespace URIs
        onto namespace prefixes.

        This gets called before startElementNS whenever an C{xmlns} attribute
        is seen.
        """

        self.prefixMap = _NSContext(self.prefixMap)
        self.prefixMap[uri] = prefix

        # Ignore the template namespace; we'll replace those during parsing.
        if uri == TEMPLATE_NAMESPACE:
            return

        # Add to a list that will be applied once we have the element.
        if prefix is None:
            self.xmlnsAttrs.append(('xmlns',uri))
        else:
            self.xmlnsAttrs.append(('xmlns:%s'%prefix,uri))

    def endPrefixMapping(self, prefix):
        """
        "Pops the stack" on the prefix mapping.

        Gets called after endElementNS.
        """
        self.prefixMap = self.prefixMap.parent

    def startElementNS(self, namespaceAndName, qname, attrs):
        """
        Gets called when we encounter a new xmlns attribute.

        @param namespaceAndName: a (namespace, name) tuple, where name
            determines which type of action to take, if the namespace matches
            L{TEMPLATE_NAMESPACE}.
        @param qname: ignored.
        @param attrs: attributes on the element being started.
        """

        filename = self.sourceFilename
        lineNumber = self.locator.getLineNumber()
        columnNumber = self.locator.getColumnNumber()

        ns, name = namespaceAndName
        if ns == TEMPLATE_NAMESPACE:
            if name == 'transparent':
                name = ''
            elif name == 'slot':
                try:
                    # Try to get the default value for the slot
                    default = attrs[(None, 'default')]
                except KeyError:
                    # If there wasn't one, then use None to indicate no
                    # default.
                    default = None
                el = slot(
                    attrs[(None, 'name')], default=default,
                    filename=filename, lineNumber=lineNumber,
                    columnNumber=columnNumber)
                self.stack.append(el)
                self.current.append(el)
                self.current = el.children
                return

        render = None

        attrs = dict(attrs)
        for k, v in attrs.items():
            attrNS, justTheName = k
            if attrNS != TEMPLATE_NAMESPACE:
                continue
            if justTheName == 'render':
                render = v
                del attrs[k]

        # nonTemplateAttrs is a dictionary mapping attributes that are *not* in
        # TEMPLATE_NAMESPACE to their values.  Those in TEMPLATE_NAMESPACE were
        # just removed from 'attrs' in the loop immediately above.  The key in
        # nonTemplateAttrs is either simply the attribute name (if it was not
        # specified as having a namespace in the template) or prefix:name,
        # preserving the xml namespace prefix given in the document.

        nonTemplateAttrs = {}
        for (attrNs, attrName), v in attrs.items():
            nsPrefix = self.prefixMap.get(attrNs)
            if nsPrefix is None:
                attrKey = attrName
            else:
                attrKey = '%s:%s' % (nsPrefix, attrName)
            nonTemplateAttrs[attrKey] = v

        if ns == TEMPLATE_NAMESPACE and name == 'attr':
            if not self.stack:
                # TODO: define a better exception for this?
                raise AssertionError(
                    '<{%s}attr> as top-level element' % (TEMPLATE_NAMESPACE,))
            if 'name' not in nonTemplateAttrs:
                # TODO: same here
                raise AssertionError(
                    '<{%s}attr> requires a name attribute' % (TEMPLATE_NAMESPACE,))
            el = Tag('', render=render, filename=filename,
                     lineNumber=lineNumber, columnNumber=columnNumber)
            self.stack[-1].attributes[nonTemplateAttrs['name']] = el
            self.stack.append(el)
            self.current = el.children
            return

        # Apply any xmlns attributes
        if self.xmlnsAttrs:
            nonTemplateAttrs.update(dict(self.xmlnsAttrs))
            self.xmlnsAttrs = []

        # Add the prefix that was used in the parsed template for non-template
        # namespaces (which will not be consumed anyway).
        if ns != TEMPLATE_NAMESPACE and ns is not None:
            prefix = self.prefixMap[ns]
            if prefix is not None:
                name = '%s:%s' % (self.prefixMap[ns],name)
        el = Tag(
            name, attributes=dict(nonTemplateAttrs), render=render,
            filename=filename, lineNumber=lineNumber,
            columnNumber=columnNumber)
        self.stack.append(el)
        self.current.append(el)
        self.current = el.children

    def characters(self, ch):
        """
        Called when we receive some characters.  CDATA characters get passed
        through as is.

        @type ch: C{string}
        """
        if self.inCDATA:
            self.stack[-1].append(ch)
            return
        self.current.append(ch)

    def endElementNS(self, name, qname):
        """
        A namespace tag is closed.  Pop the stack, if there's anything left in
        it, otherwise return to the document's namespace.
        """
        self.stack.pop()
        if self.stack:
            self.current = self.stack[-1].children
        else:
            self.current = self.document

    def startDTD(self, name, publicId, systemId):
        """
        DTDs are ignored.
        """

    def endDTD(self, *args):
        """
        DTDs are ignored.
        """

    def startCDATA(self):
        """
        We're starting to be in a CDATA element, make a note of this.
        """
        self.inCDATA = True
        self.stack.append([])

    def endCDATA(self):
        """
        We're no longer in a CDATA element.  Collect up the characters we've
        parsed and put them in a new CDATA object.
        """
        self.inCDATA = False
        comment = ''.join(self.stack.pop())
        self.current.append(CDATA(comment))

    def comment(self, content):
        """
        Add an XML comment which we've encountered.
        """
        self.current.append(Comment(content))

def _flatsaxParse(fl):
    """
    Perform a SAX parse of an XML document with the _ToStan class.

    @param fl: The XML document to be parsed.
    @type fl: A file object or filename.

    @return: a C{list} of Stan objects.
    """
    parser = make_parser()
    parser.setFeature(handler.feature_validation, 0)
    parser.setFeature(handler.feature_namespaces, 1)
    parser.setFeature(handler.feature_external_ges, 0)
    parser.setFeature(handler.feature_external_pes, 0)

    s = _ToStan(getattr(fl, "name", None))
    parser.setContentHandler(s)
    parser.setEntityResolver(s)
    parser.setProperty(handler.property_lexical_handler, s)

    parser.parse(fl)

    return s.document

class TagLoader(object):
    """
    An L{ITemplateLoader} that loads existing L{IRenderable} providers.

    @ivar tag: The object which will be loaded.
    @type tag: An L{IRenderable} provider.
    """
    implements(ITemplateLoader)

    def __init__(self, tag):
        """
        @param tag: The object which will be loaded.
        @type tag: An L{IRenderable} provider.
        """
        self.tag = tag

    def load(self):
        return [self.tag]

class XMLString(object):
    """
    An L{ITemplateLoader} that loads and parses XML from a string.

    @ivar _loadedTemplate: The loaded document.
    @type _loadedTemplate: a C{list} of Stan objects.
    """
    implements(ITemplateLoader)

    def __init__(self, s):
        """
        Run the parser on a StringIO copy of the string.

        @param s: The string from which to load the XML.
        @type s: C{str}
        """
        self._loadedTemplate = _flatsaxParse(StringIO(s))

    def load(self):
        """
        Return the document.

        @return: the loaded document.
        @rtype: a C{list} of Stan objects.
        """
        return self._loadedTemplate

class XMLFile(object):
    """
    An L{ITemplateLoader} that loads and parses XML from a file.

    @ivar _loadedTemplate: The loaded document, or C{None}, if not loaded.
    @type _loadedTemplate: a C{list} of Stan objects, or C{None}.

    @ivar _path: The L{FilePath}, file object, or filename that is being
        loaded from.
    """
    implements(ITemplateLoader)

    def __init__(self, path):
        """
        Run the parser on a file.

        @param path: The file from which to load the XML.
        @type path: L{FilePath}
        """
        if not isinstance(path, FilePath):
            warnings.warn(
                "Passing filenames or file objects to XMLFile is deprecated "
                "since Twisted 12.1.  Pass a FilePath instead.",
                category=DeprecationWarning, stacklevel=2)
        self._loadedTemplate = None
        self._path = path

    def _loadDoc(self):
        """
        Read and parse the XML.

        @return: the loaded document.
        @rtype: a C{list} of Stan objects.
        """
        if not isinstance(self._path, FilePath):
            return _flatsaxParse(self._path)
        else:
            f = self._path.open('r')
            try:
                return _flatsaxParse(f)
            finally:
                f.close()

    def __repr__(self):
        return '<XMLFile of %r>' % (self._path,)

    def load(self):
        """
        Return the document, first loading it if necessary.

        @return: the loaded document.
        @rtype: a C{list} of Stan objects.
        """
        if self._loadedTemplate is None:
            self._loadedTemplate = self._loadDoc()
        return self._loadedTemplate

# Last updated October 2011, using W3Schools as a reference. Link:
# http://www.w3schools.com/html5/html5_reference.asp
# Note that <xmp> is explicitly omitted; its semantics do not work with
# t.w.template and it is officially deprecated.
VALID_HTML_TAG_NAMES = set([
    'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside',
    'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'big', 'blockquote',
    'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code',
    'col', 'colgroup', 'command', 'datalist', 'dd', 'del', 'details', 'dfn',
    'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption',
    'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3',
    'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe',
    'img', 'input', 'ins', 'isindex', 'keygen', 'kbd', 'label', 'legend',
    'li', 'link', 'map', 'mark', 'menu', 'meta', 'meter', 'nav', 'noframes',
    'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param',
    'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script',
    'section', 'select', 'small', 'source', 'span', 'strike', 'strong',
    'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea',
    'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'tt', 'u', 'ul', 'var',
    'video', 'wbr',
])

class _TagFactory(object):
    """
    A factory for L{Tag} objects; the implementation of the L{tags} object.

    This allows for the syntactic convenience of C{from twisted.web.html import
    tags; tags.a(href="linked-page.html")}, where 'a' can be basically any HTML
    tag.

    The class is not exposed publicly because you only ever need one of these,
    and we already made it for you.

    @see: L{tags}
    """
    def __getattr__(self, tagName):
        if tagName == 'transparent':
            return Tag('')
        # allow for E.del as E.del_
        tagName = tagName.rstrip('_')
        if tagName not in VALID_HTML_TAG_NAMES:
            raise AttributeError('unknown tag %r' % (tagName,))
        return Tag(tagName)

tags = _TagFactory()

def renderElement(request, element,
                  doctype='<!DOCTYPE html>', _failElement=None):
    """
    Render an element or other C{IRenderable}.

    @param request: The C{Request} being rendered to.
    @param element: An C{IRenderable} which will be rendered.
    @param doctype: A C{str} which will be written as the first line of
        the request, or C{None} to disable writing of a doctype.  The C{string}
        should not include a trailing newline and will default to the HTML5
        doctype C{'<!DOCTYPE html>'}.

    @returns: NOT_DONE_YET

    @since: 12.1
    """
    if doctype is not None:
        request.write(doctype)
        request.write('\n')

    if _failElement is None:
        _failElement = twisted.web.util.FailureElement

    d = flatten(request, element, request.write)

    def eb(failure):
        log.err(failure, "An error occurred while rendering the response.")
        if request.site.displayTracebacks:
            return flatten(request, _failElement(failure), request.write)
        else:
            request.write(
                ('
An error occurred while rendering the response.
'))

    d.addErrback(eb)
    d.addBoth(lambda _: request.finish())
    return NOT_DONE_YET

from twisted.web._element import Element, renderer
from twisted.web._flatten import flatten, flattenString
import twisted.web.util


text:
package com.mxgraph.io.vsdx;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.mxgraph.io.mxVsdxCodec;
import com.mxgraph.io.vsdx.theme.QuickStyleVals;
import com.mxgraph.util.mxConstants;

public class Shape extends Style
{
	public final static long VSDX_START_TIME = -2209168800000L;//new Date("12/30/1899").getTime();
	/**
	 * The text element of the shape, if any
	 */
	protected Element text;

	/**
	 * The text fields of the shape, if any
	 */
	protected LinkedHashMap<String, String> fields;

	/**
	 * List of paragraphs in this shape
	 */
	protected LinkedHashMap<String,Paragraph> paragraphs = null;

	/**
	 * mxGraph cell style map
	 */
	protected Map<String, String> styleMap = new HashMap<String, String>();

	/**
	 * Width of shape
	 */
	protected double width = 0;

	/**
	 * Height of shape
	 */
	protected double height = 0;

	/**
	 * Cumulative rotation of shape, including parents
	 */
	protected double rotation = 0;

	protected double lastX = 0;

	protected double lastY = 0;

	protected double lastMoveX = 0;

	protected double lastMoveY = 0;

	protected double lastKnot = -1;

	protected List<Element> geom;

	protected mxVsdxGeometryList geomList = null;
	protected boolean geomListProcessed = false;

	protected Map<String, String> imageData;

	protected mxVsdxTheme theme;

	protected int themeVariant = 0;

	protected QuickStyleVals quickStyleVals;

	protected final static String UNICODE_LINE_SEP = new String(new char[]{(char)226, (char)128, (char)168});

	public mxPathDebug debug = null;

	public Shape(Element shape, mxVsdxModel model)
	{
		super(shape, model);
		this.width = getScreenNumericalValue(this.cellElements.get(mxVsdxConstants.WIDTH), 0);
		this.height = getScreenNumericalValue(this.cellElements.get(mxVsdxConstants.HEIGHT), 0);
	}

	public void setThemeAndVariant(mxVsdxTheme theme, int themeVariant)
	{
		this.theme = theme;
		this.themeVariant = themeVariant;
	}

	public mxVsdxTheme getTheme()
	{
		if (theme != null)
		{
			theme.setVariant(themeVariant);
		}
		return theme;
	}

	public QuickStyleVals getQuickStyleVals()
	{
		return quickStyleVals;
	}

	protected void processGeomList(mxVsdxGeometryList parentGeoList)
	{
		if (!geomListProcessed)
		{
			geomList = new mxVsdxGeometryList(parentGeoList);

			if (geom != null)
			{
				for (Element geoElem : geom)
				{
					geomList.addGeometry(geoElem);
				}
			}

			geomListProcessed = true;
		}
	}

	/**
	 * Caches the specified element
	 * @param elem the element to cache
	 */
	protected void parseShapeElem(Element elem, mxVsdxModel model)
	{
		super.parseShapeElem(elem, model);

		String childName = elem.getNodeName();

		if (childName.equals("ForeignData"))
		{
			String filename = elem.getOwnerDocument().getDocumentURI();
			String iType = elem.getAttribute("ForeignType");
			String compression = elem.getAttribute("CompressionType");

			if (iType.equals("Bitmap"))
			{
				compression = compression.toLowerCase();
			}
			else if (iType.equals("MetaFile"))
			{
				compression = "x-wmf";
			}
			else if (iType.equals("Enhanced Metafile") || iType.equals("EnhMetaFile"))
			{
				compression = "x-emf";
			}
			else
			{
				//TODO log and unsupported type
				return;
			}

			Node fdChild = elem.getFirstChild();

			if (fdChild != null)
			{
				if (fdChild instanceof Element)
				{
					Element fdElem = (Element) fdChild;
					String grandchildName = fdElem.getNodeName();

					if (grandchildName.toLowerCase().equals("rel"))
					{
						String rid = fdElem.getAttribute("r:id");

						if (rid != null && !rid.isEmpty())
						{
							// insert "_rel" into the path
							int index = filename.lastIndexOf('/');
							String pre = "";
							String post = "";

							try
							{
								pre = filename.substring(0, index);
								post = filename.substring(index, filename.length());
							}
							catch (IndexOutOfBoundsException e)
							{
								return;
							}

							Element relElem = model.getRelationship(rid, pre + "/_rels" + post + ".rels");

							if (relElem != null)
							{
								String target = relElem.getAttribute("Target");
								String type = relElem.getAttribute("Type");
								index = target.lastIndexOf('/');

								try
								{
									target = target.substring(index + 1, target.length());
								}
								catch (IndexOutOfBoundsException e)
								{
									return;
								}

								if (type != null && type.endsWith("image"))
								{
									this.imageData = new HashMap<String, String>();
									String iData = model.getMedia(mxVsdxCodec.vsdxPlaceholder + "/media/" + target);
									this.imageData.put("iData", iData);

									//since we convert BMP files to PNG, we set the compression to PNG
									if (target.toLowerCase().endsWith(".bmp"))
									{
										compression = "png";
									}
									else if (target.toLowerCase().endsWith(".emf"))
									{
										//emf can be a png or jpg or vector (which is not supported yet)
										//We use a number of bytes equal to file header length (which is safe as header in base64 requires 4n/3 bytes
										compression = iData.startsWith("iVBORw0K") ? "png" : (iData.startsWith("/9j/") ? "jpg" : compression);
									}

									this.imageData.put("iType", compression);
								}
							}
							else
							{
								//TODO log path issue
							}

							// more than one rel would break things
							return;
						}

					}
				}

				fdChild = fdChild.getNextSibling();
			}
		}
		else if (childName.equals(mxVsdxConstants.TEXT))
		{
			this.text = elem;
		}
	}

	/**
	 * Caches the specific section element
	 * @param elem the element to cache
	 */
	protected void parseSection(Element elem)
	{
		String n = elem.getAttribute("N");

		if (n.equals("Geometry"))
		{
			if (geom == null)
			{
				geom = new ArrayList<Element>();
			}

			this.geom.add(elem);
		}
		else if (n.equals("Field"))
		{
			ArrayList<Element> rows = mxVsdxUtils.getDirectChildNamedElements(elem, "Row");

			for (Element row : rows)
			{
				String ix = row.getAttribute("IX");

				if (!ix.isEmpty())
				{
					if (this.fields == null)
					{
						fields = new LinkedHashMap<String, String>();
					}

					String del = row.getAttribute("Del");

					//supporting deletion of a field by adding an empty string such that master field is not used
					if ("1".equals(del))
					{
						this.fields.put(ix, "");
						continue;
					}

					ArrayList<Element> cells = mxVsdxUtils.getDirectChildNamedElements(row, "Cell");

					String value = "", format = "", calendar = "", type = "";
					for (Element cell : cells)
					{
						n = cell.getAttribute("N");
						String v = cell.getAttribute("V");

						switch (n)
						{
							case "Value":
								value = v;
							break;
							case "Format":
								format = v;
							break;
							case "Calendar":
								calendar = v;
							break;
							case "Type":
								type = v;
							break;
						}
					}

					if (!value.isEmpty())
					{

						try
						{
							//TODO support other formats and calendars
							if (format.startsWith("{{"))
							{
								value = new SimpleDateFormat(
										format.replaceAll("\\{|\\}", ""))
										//the value is the number of days after 30/12/1899 (VSDX_START_TIME)
										.format(new Date(VSDX_START_TIME + (long)(Double.parseDouble(value) * 24 * 60 * 60 * 1000)));
							}
						}
						catch (Exception e)
						{
	//						System.out.println("Vsdx import: Unkown text format " + format + ". Error: " + e.getMessage());
						}
						this.fields.put(ix, value);
					}
				}
			}
		}
		else
		{
			super.parseSection(elem);
		}
	}

	/**
	 *
	 * @return mxGraph stencil XML or null or there is no displayed geometry
	 */
	protected String parseGeom()
	{
		if (!hasGeomList())
		{
			return "";
		}

		return geomList.getShapeXML(this);
	}

	/**
	 * Returns the value of the Text element.
	 * @return Value of the Text element.
	 */
	public String getText()
	{
		return this.text != null ? text.getTextContent() : null;
	}

	/**
	 * Returns the children Nodes of Text.
	 * @return List with the children of the Text element.
	 */
	public NodeList getTextChildren()
	{
		return this.text != null ? text.getChildNodes() : null;
	}

	/**
	 * Returns the value of the width element in pixels.
	 * @return Numerical value of the width element.
	 */
	public double getWidth()
	{
		//some shapes has zero width while the height is non-zero. Setting width to 1 fixed it.
		return this.width == 0 && this.height > 0 ? 1 : this.width;
	}

	/**
	 * Returns the value of the height element in pixels.
	 * @return Numerical value of the height element.
	 */
	public double getHeight()
	{
		//some shapes has zero height while the width is non-zero. Setting height to 1 fixed it.
		return this.height == 0 && this.width > 0 ? 1 : this.height;
	}

	/**
	 * Returns the value of the rotation.
	 * @return Numerical value of the rotation
	 */
	public double getRotation()
	{
		return this.rotation;
	}

	/**
	 * Returns the style map of this shape
	 * @return the style map
	 */
	public Map<String, String> getStyleMap()
	{
		return this.styleMap;
	}

	/**
	 * Returns whether or not this shape has a geometry defined, locally
	 * or inherited
	 * @return whether the shape has a geometry
	 */
	public boolean hasGeom()
	{
		return !(this.geom == null || this.geom.isEmpty());
	}

	/**
	 * Returns whether or not this shape or its master has a geometry defined
	 * @return whether the shape has a geometry
	 */
	public boolean hasGeomList()
	{
		return this.geomList != null && this.geomList.hasGeom();
	}

	/**
	 * Last cp IX referenced in the Text Element.
	 */
	String cp = "0";

	/**
	 * Last pp IX referenced in the Text Element.
	 */
	String pp = "0";

	/**
	 * Last tp IX referenced in the Text Element.
	 */
	String tp = "0";

	/**
	 * Last fld IX referenced in the Text Element.
	 */
	String fld = "0";

	/**
	 * Transform plain text into a HTML list if the Para element referenced by
	 * pp indicates it.
	 * @param text Text to be transformed.
	 * @param pp Reference to a Para element.
	 * @return Text like a HTML list.
	 */
	public String textToList(String text, String pp)
	{
		if (!pp.equals(""))
		{
			String bullet = getBullet(pp);

			if (!bullet.equals("0"))
			{
				String[] entries = text.split("\n");
				String ret = "";

				for (String entry : entries)
				{
					ret += mxVsdxUtils.surroundByTags(entry, "li");
				}

				ret = mxVsdxUtils.surroundByTags(ret, "ul");
				HashMap<String, String> styleMap = new HashMap<String, String>();

				if (bullet.equals("4"))
				{
					styleMap.put("list-style-type", "square");
				}
				else
				{
					styleMap.put("list-style-type", "disc");
				}

				ret = this.insertAttributes(ret, styleMap);

				return ret;
			}
		}

		return text;
	}

	/**
	 * Returns the paragraph formated according the properties in the last
	 * Para element referenced.
	 * @param para Paragraph to be formated
	 * @return Formated paragraph.
	 */
	public String getTextParagraphFormated(String para)
	{
		String ret = "";
		HashMap<String, String> styleMap = new HashMap<String, String>();
		styleMap.put("align", getHorizontalAlign(pp, true));
		styleMap.put("margin-left", getIndentLeft(pp));
		styleMap.put("margin-right", getIndentRight(pp));
		styleMap.put("margin-top", getSpBefore(pp) + "px");
		styleMap.put("margin-bottom", getSpAfter(pp) + "px");
		styleMap.put("text-indent", getIndentFirst(pp));
		styleMap.put("valign", getAlignVertical());
//		String spc = getSpcLine(pp);
		//TODO dividing by 0.71 gives very large line height in most of the cases. Probably we don't need it?
//		String spcNum = spc.replaceAll("[^\\d.]", "");
//		String postFix = spc.substring(spcNum.length(),spc.length());
		//double lineH = (Double.parseDouble(spcNum) / 0.71);
//		spc = Double.toString(lineH);
//
//		if (spc.contains("."))
//		{
//			spc = spc.substring(0, spc.lastIndexOf(".") + 3);
//		}
//
//		spc = spc + postFix;
//		styleMap.put("line-height", spc);
		styleMap.put("direction", getTextDirection(pp));
		ret += insertAttributes(para, styleMap);
		return ret;
	}

	/**
	 * Returns the text formated according the properties in the last
	 * Char element referenced.
	 * @param text Text to be formated
	 * @return Formated text.
	 */
	public String getTextCharFormated(String text)
	{
		String ret = "";
		String color = "color:" + getTextColor(cp) + ";";
		String size = "font-size:" + (Double.parseDouble(this.getTextSize(cp))) + "px;";
		String font = "font-family:" + this.getTextFont(cp) + ";";
		String direction = "direction:" + this.getRtlText(cp) + ";";
		String space = "letter-spacing:" + (Double.parseDouble(this.getLetterSpace(cp)) / 0.71) + "px;";
		String lineHeight = "line-height:" + getSpcLine(pp);
		String opacity = ";opacity:" + getTextOpacity(cp);
		String pos = this.getTextPos(cp);
		String tCase = getTextCase(cp);

		if (tCase.equals("1"))
		{
			text = text.toUpperCase();
		}
		else if (tCase.equals("2"))
		{
			text = mxVsdxUtils.toInitialCapital(text);
		}

		if (pos.equals("1"))
		{
			text = mxVsdxUtils.surroundByTags(text, "sup");
		}
		else if (pos.equals("2"))
		{
			text = mxVsdxUtils.surroundByTags(text, "sub");
		}

		text = this.isBold(cp) ? mxVsdxUtils.surroundByTags(text, "b") : text;
		text = this.isItalic(cp) ? mxVsdxUtils.surroundByTags(text, "i") : text;
		text = this.isUnderline(cp) ? mxVsdxUtils.surroundByTags(text, "u") : text;
		text = this.getTextStrike(cp) ? mxVsdxUtils.surroundByTags(text, "s") : text;
		text = this.isSmallCaps(cp) ? mxVsdxUtils.toSmallCaps(text, this.getTextSize(cp)) : text;

		ret += "" + text + "";
		return ret;
	}

	/**
	 * Returns the direction of the text. It may be right to left or left to right.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default style-sheet.
	 * @param index Index of the Para element that contains the Flags element.
	 * @return The direction of the text.
	 */
	public String getTextDirection(String index)
	{
		String direction = getFlags(index);

		if (direction.equals("0"))
		{
			direction = "ltr";
		}
		else if (direction.equals("1"))
		{
			direction = "rtl";
		}

		return direction;
	}

	/**
	 * Returns the space between lines in a paragraph.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default style-sheet.
	 * @param index Index of the Para element that contains the SpLine element.
	 * @return The space between lines n pixels.
	 */
	public String getSpcLine(String index)
	{
		String ret = "0";
		boolean isPercent = false;
		double space = getSpLine(index);

		if (space > 0)
		{
			space = space * mxVsdxUtils.conversionFactor;
		}
		else if (space == 0)
		{
			space = 100;
			isPercent = true;
		}
		else
		{
			space = Math.abs(space) * 100;
			isPercent = true;
		}

		ret = String.valueOf(space);
		ret += isPercent ? "%" : "px";

		return ret;
	}

	/**
	 * Returns the space before a paragraph.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default style-sheet.
	 * @param index Index of the Para element that contains the SpBefore element.
	 * @return The space before the paragraph in pixels.
	 */
	public String getSpcBefore(String index)
	{
		return getSpBefore(index);
	}

	/**
	 * Inserts the style attributes contained in attr into the text.

	 * The text must be surrounded by tags html.
	 * @param text Text where the attributes must be inserted.
	 * @param attr Map with the attributes.
	 * @return Text with the attributes applied like style.
	 */
	public String insertAttributes(String text, HashMap<String, String> attr)
	{
		if (text.contains(">"))
		{
			int i = text.indexOf(">");
			String tail = text.substring(i);
			String head = text.substring(0, i);

			String style = " style=\"" + mxVsdxUtils.getStyleString(attr, ":") + "\"";
			return head + style + tail;
		}

		return text;
	}

	/**
	 * Returns the direction of the text. It may be right to left or left to right.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default stylesheet.
	 * @param index Index of the Char element that contains the RTLText element.
	 * @return Direction of the text.
	 */
	public String getRtlText(String index)
	{
		Element rtlElem = getCellElement(mxVsdxConstants.RTL_TEXT, index, mxVsdxConstants.PARAGRAPH);
		String direction = getValue(rtlElem, "ltr");

		if (direction.equals("0"))
		{
			direction = "ltr";
		}
		else if (direction.equals("1"))
		{
			direction = "rtl";
		}

		return direction;
	}

	/**
	 * Checks if the style property of the Char element of index = 'index'
	 * indicates bold.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default stylesheet.
	 * @param index Index of the Char element that contains the Style element.
	 * @return Returns true if the style property of the Char element of
	 * index = 'index' indicates bold.
	 */
	public boolean isBold(String index)
	{
		boolean isBold = false;
		String style = getTextStyle(index);

		if (!style.equals(""))
		{
			if (style.toLowerCase().equals("themed"))
			{
				// TODO theme support
			}
			else
			{
				int value = Integer.parseInt(style);
				isBold = ((value & 1) == 1);
			}
		}

		return isBold;
	}

	/**
	 * Checks if the style property of the Char element of index = 'index'
	 * indicates italic.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default stylesheet.
	 * @param index Index of the Char element that contains the Style element.
	 * @return Returns true if the style property of the Char element of
	 * index = 'index' indicates italic.
	 */
	public boolean isItalic(String index)
	{
		boolean isItalic = false;
		String style = getTextStyle(index);

		if (!style.equals(""))
		{
			if (style.toLowerCase().equals("themed"))
			{
				// TODO theme support
			}
			else
			{
				int value = Integer.parseInt(style);
				isItalic = ((value & 2) == 2);
			}
		}

		return isItalic;
	}

	/**
	 * Checks if the style property of the Char element of index = 'index'
	 * indicates underline.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default stylesheet.
	 * @param index Index of the Char element that contains the Style element.
	 * @return Returns true if the style property of the Char element of
	 * index = 'index' indicates underline.
	 */
	public boolean isUnderline(String index)
	{
		boolean isUnderline = false;
		String style = getTextStyle(index);

		if (!style.equals(""))
		{
			if (style.toLowerCase().equals("themed"))
			{
				// TODO theme support
			}
			else
			{
				int value = Integer.parseInt(style);
				isUnderline = ((value & 4) == 4);
			}
		}

		return isUnderline;
	}

	/**
	 * Checks if the style property of the Char element of index = 'index'
	 * indicates small caps.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default stylesheet.
	 * @param index Index of the Char element that contains the Style element.
	 * @return Returns true if the style property of the Char element of
	 * index = 'index' indicates small caps.
	 */
	public boolean isSmallCaps(String index)
	{
		boolean isSmallCaps = false;
		String style = getTextStyle(index);

		if (!style.equals(""))
		{
			if (style.toLowerCase().equals("themed"))
			{
				// TODO theme support
			}
			else
			{
				int value = Integer.parseInt(style);
				isSmallCaps = ((value & 8) == 8);
			}
		}

		return isSmallCaps;
	}

	public String getTextOpacity(String index)
	{
		Element colorTrans = getCellElement(mxVsdxConstants.COLOR_TRANS, index, mxVsdxConstants.CHARACTER);
		String trans = getValue(colorTrans, "0");
		String result = "1";

		if (trans != null && !trans.isEmpty())
		{
			double tmp = 1.0 - Double.valueOf(trans);
			result = String.valueOf(tmp);
		}

		return result;
	}

	/**
	 * Returns the actual text size defined by the Char element referenced in cp.

	 * This property may to be founded in the shape, master shape, stylesheet or
	 * default stylesheet.
	 * @param index Index of the Char element that contains the Size element.
	 * @return Returns the size of the font in pixels.
	 */
	public String getTextSize(String index)
	{
		Element sizeElem = getCellElement(mxVsdxConstants.SIZE, index, mxVsdxConstants.CHARACTER);
		double size = getScreenNumericalValue(sizeElem, 12);

		return Double.toString(Math.round(size * 100) / 100);
	}

	/**
	 * Returns the vertical align of the label.

	 * The property may to be defined in master shape or text stylesheet.

	 * @return Vertical align (bottom, middle and top)
	 */
	public String getAlignVertical()
	{
		String vertical = mxConstants.ALIGN_MIDDLE;

		int align = Integer.parseInt(getValue(this.getCellElement(mxVsdxConstants.VERTICAL_ALIGN), "1"));

		if (align == 0)
		{
			vertical = mxConstants.ALIGN_TOP;
		}
		else if (align == 2)
		{
			vertical = mxConstants.ALIGN_BOTTOM;
		}

		return vertical;
	}

	public mxVsdxGeometryList getGeomList()
	{
		return geomList;
	}

	public double getLastX() {
		return lastX;
	}

	public double getLastY() {
		return lastY;
	}

	public double getLastMoveX() {
		return lastMoveX;
	}

	public double getLastMoveY() {
		return lastMoveY;
	}

	public double getLastKnot() {
		return lastKnot;
	}

	public void setLastX(double lastX) {
		this.lastX = lastX;
	}

	public void setLastY(double lastY) {
		this.lastY = lastY;
	}

	public void setLastMoveX(double lastMoveX) {
		this.lastMoveX = lastMoveX;
	}

	public void setLastMoveY(double lastMoveY) {
		this.lastMoveY = lastMoveY;
	}

	public void setLastKnot(double lastKnot) {
		this.lastKnot = lastKnot;
	}
}


text:
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.css" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/plugins/bootstrap-fileupload/bootstrap-fileupload.css" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/plugins/bootstrap-editable/bootstrap-editable/css/bootstrap-editable.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/plugins/bootstrap-editable/inputs-ext/address/address.css"/>

Data Barang

               <a href="<?php echo base_url('systems/modal_addbarang') ?>" class="btn green ajax-modals" data-toggle="modal">
                  Add New

               Columns

                  <input type="checkbox" checked data-column="0">Rendering engine
                  <input type="checkbox" checked data-column="1">Browser
                  <input type="checkbox" checked data-column="2">Platform(s)
                  <input type="checkbox" checked data-column="3">Engine version
                  <input type="checkbox" checked data-column="4">CSS grade


text:
<?php
/**
 * Thrown when an API call returns an exception.
 *
 * @author Naitik Shah <naitik@facebook.com>
 */
class Facebook_Exception extends Exception
{
  /**
   * The result from the API server that represents the exception information.
   */
  protected $result;

  /**
   * Make a new API Exception with the given result.
   *
   * @param Array $result the result from the API server
   */
  public function __construct($result) {
    $this->result = $result;

    $code = isset($result['error_code']) ? $result['error_code'] : 0;

    if (isset($result['error_description'])) {
      // OAuth 2.0 Draft 10 style
      $msg = $result['error_description'];
    } else if (isset($result['error']) && is_array($result['error'])) {
      // OAuth 2.0 Draft 00 style
      $msg = $result['error']['message'];
    } else if (isset($result['error_msg'])) {
      // Rest server style
      $msg = $result['error_msg'];
    } else {
      $msg = 'Unknown Error. Check getResult()';
    }

    parent::__construct($msg, $code);
  }

  /**
   * Return the associated result object returned by the API server.
   *
   * @returns Array the result from the API server
   */
  public function getResult() {
    return $this->result;
  }

  /**
   * Returns the associated type for the error. This will default to
   * 'Exception' when a type is not available.
   *
   * @return String
   */
  public function getType() {
    if (isset($this->result['error'])) {
      $error = $this->result['error'];
      if (is_string($error)) {
        // OAuth 2.0 Draft 10 style
        return $error;
      } else if (is_array($error)) {
        // OAuth 2.0 Draft 00 style
        if (isset($error['type'])) {
          return $error['type'];
        }
      }
    }
    return 'Exception';
  }

  /**
   * To make debugging easier.
   *
   * @returns String the string representation of the error
   */
  public function __toString() {
    $str = $this->getType() . ': ';
    if ($this->code != 0) {
      $str .= $this->code . ': ';
    }
    return $str . $this->message;
  }
}


text:
layout: page
title: Diamond Excellent Logistics Executive Retreat
date: 2016-05-24
author: Shirley Rivers
tags: weekly links, java
status: published
summary: Praesent eu dolor sit amet odio posuere.
banner: images/banner/office-01.jpg
booking:
  startDate: 04/27/2016
  endDate: 05/01/2016
  ctyhocn: BJXSGHX
  groupCode: DELER
published: true
---
Nam nulla orci, cursus sed massa sit amet, blandit euismod mi. Quisque aliquam dolor magna, ac bibendum nulla dignissim sed. Etiam bibendum ac tortor ut tempus. Ut urna ipsum, ornare porttitor convallis vitae, aliquam nec leo. Fusce dictum gravida bibendum. Fusce sollicitudin gravida molestie. Nulla ex magna, condimentum vitae pulvinar ut, aliquam eget arcu.

* Fusce non elit nec arcu molestie vehicula
* Fusce vitae ipsum eu nisi blandit tincidunt.

Curabitur et tellus elit. Praesent egestas mi nec enim euismod eleifend. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi eget ipsum vitae orci sodales rutrum. Nunc mattis cursus cursus. Fusce eget diam ac neque sagittis fringilla. Donec eu posuere orci. Duis ante nibh, facilisis semper ante non, maximus pulvinar nisi. Nunc sit amet mollis ante. Etiam sodales tristique leo a fermentum.
Quisque et odio nisl. Suspendisse potenti. Duis ut facilisis elit, dictum commodo purus. Nulla egestas mollis egestas. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec turpis felis, vehicula ut diam nec, iaculis convallis lectus. Duis ornare lorem id porttitor venenatis. Vivamus gravida semper tortor ac consequat. Vestibulum convallis eu sapien a finibus. Mauris vitae accumsan dui. Curabitur at pretium tellus, ac dapibus mi.


text:
[TOC]

### Movitations

`ScopeGuard` provides yet another option to enforce RAII-idiom for a specific resource, while not having to make a complete RAII-wrapper.

It is especially convenient for interacting with native resources.

### Execute On Exit

```c++
#include "kbase/scope_guard.h"

void SomeFunction()
{
    auto r = AllocateSomeResource();
    ON_SCOPE_EXIT {
        // will execute when goes out of the function.
        ReleaseSomeResource(r);
    };

    DoSometing(r);
}
```

Be noted that, all variables used within the guard are captured by reference.

Besides, the statements inside the guard are better to be `noexcept`, which aslo matches cleanup semantics.

### Halt the Execution If Necessary

Sometimes, we need to pull off the exit-callback when a certain conditions meet.

`ScopeGuard` offers you a `Dismiss()` method to work on this:

```c++
std::vector<int> v {1, 3, 5};

{
    auto guard = MAKE_SCOPE_GUARD { v.clear(); };
    if (v.size() < 5) {
        guard.Dismiss();
    }
}

ASSERT_TRUE(v.size() == 3);

v.push_back(7);
v.push_back(9);

{
    auto guard = MAKE_SCOPE_GUARD { v.clear(); };
    if (v.size() < 5) {
        guard.Dismiss();
    }
}

EXPECT_TRUE(v.empty());
```


text:
<?xml version="1.0"?>
<!DOCTYPE metaconfiguration SYSTEM "meta.dtd">

<metaconfiguration>

	<classes namespace="\Onphp\Log\Examples">

		<class name="Log" type="final">

			<properties>
				<identifier type="Integer" />

				<property name="date" type="Timestamp" required="true" />
				<property name="level" type="Integer" required="true" />
				<property name="message" type="String" size="5000" required="true" />

			</properties>

			<pattern name="StraightMapping" />

		</class>

	</classes>

</metaconfiguration>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ArrayUtil.Line3
</TITLE>

<META NAME="keywords" CONTENT="com.lgc.wsh.util.ArrayUtil.Line3 class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.lgc.wsh.util

Class ArrayUtil.Line3

java.lang.Object
  com.lgc.wsh.util.ArrayUtil.Line3

Enclosing class:
ArrayUtil

public static class ArrayUtil.Line3
extends java.lang.Object

Specify a line in 3D with a point and a direction.

Constructor Summary

ArrayUtil.Line3(float[] point,
                float[] direction)

          Specify point on line and direction of line

Method Summary

 float[]
intersect(ArrayUtil.Plane3 plane)

          Find the intersection of the line with the plane

 float[]
project(float[] p)

          Project a point onto the line.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ArrayUtil.Line3

public ArrayUtil.Line3(float[] point,
                       float[] direction)
                throws ArrayUtil.IllPosedException

Specify point on line and direction of line

Parameters:
point - Point on the line.
direction - Direction of line
        (Insensitive to magnitude and polarity)

Throws:

ArrayUtil.IllPosedException - bad geometry

Method Detail

project

public float[] project(float[] p)

Project a point onto the line.

Parameters:
p - The point to project.

Returns:
The projected point.

intersect

public float[] intersect(ArrayUtil.Plane3 plane)
                  throws ArrayUtil.IllPosedException

Find the intersection of the line with the plane

Parameters:
plane - intersect with this plane

Returns:
Point at which this line intersects with the plane.

Throws:

ArrayUtil.IllPosedException - bad geometry

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package definitions

type DetailedPresenceWithSIPNotification struct {
	Body           DetailedPresencewithSIPEvent `json:"body,omitempty"`
	Event          string                       `json:"event,omitempty"`
	SubscriptionID string                       `json:"subscriptionId,omitempty"`
	Timestamp      string                       `json:"timestamp,omitempty"`
	UUID           string                       `json:"uuid,omitempty"`
}


text:
import * as webdriver from 'selenium-webdriver';

import {BlockingProxy} from '../../lib/blockingproxy';

import {getTestEnv} from './environment';

const By = webdriver.By;

describe('disabling waiting as needed', function() {
  let driver: webdriver.WebDriver;
  let bp: BlockingProxy;

  beforeAll(() => {
    ({driver, bp} = getTestEnv());
  });

  beforeEach(async() => {
    await driver.get('http://localhost:8081/ng1/#/polling');
  });

  it('avoids timeouts', async() => {
    bp.waitBarrier.enabled = true;

    let startButton = await driver.findElement(By.id('pollstarter'));

    let count = await driver.findElement(By.id('count'));
    expect(await count.getText()).toEqual('0');

    await startButton.click();

    bp.waitBarrier.enabled = false;

    expect(await count.getText()).toBeGreaterThan(-1);

    await driver.sleep(2100);

    expect(await count.getText()).toBeGreaterThan(1);
  });
});


text:
from seleniumbase import BaseCase

class UserAgentTests(BaseCase):
    def test_user_agent(self):
        self.open("http://whatsmyuseragent.org/")
        user_agent_detected = self.get_text(".user-agent p")
        original_user_agent = user_agent_detected
        if not self.user_agent:
            # Using the built-in user-agent string
            self._print("\n\nUser-Agent: %s" % user_agent_detected)
        else:
            # User-agent was overridden using: --agent=STRING
            self._print("\n\nUser-Agent override: %s" % user_agent_detected)
        print("\n" + self.get_text(".ip-address p"))
        self.sleep(3)

        # Now change the user-agent using "execute_cdp_cmd()"
        if not self.is_chromium():
            msg = "\n* execute_cdp_cmd() is only for Chromium browsers"
            self._print(msg)
            self.skip(msg)
        print("\n--------------------------")
        try:
            self.driver.execute_cdp_cmd(
                "Network.setUserAgentOverride",
                {
                    "userAgent": "Mozilla/5.0 "
                    "(Nintendo Switch; WifiWebAuthApplet) "
                    "AppleWebKit/606.4 (KHTML, like Gecko) "
                    "NF/6.0.1.15.4 NintendoBrowser/5.1.0.20393"
                },
            )
            self.open("http://whatsmyuseragent.org/")
            user_agent_detected = self.get_text(".user-agent p")
            self._print("\nUser-Agent override: %s" % user_agent_detected)
            print("\n" + self.get_text(".ip-address p") + "\n")
            self.sleep(3)
        finally:
            # Reset the user-agent back to the original
            self.driver.execute_cdp_cmd(
                "Network.setUserAgentOverride",
                {"userAgent": original_user_agent},
            )


text:
#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonServiceRequestConfig.h>
#else
#import "../AmazonServiceRequestConfig.h"
#endif

/**
 * Set Load Balancer Policies Of Listener Request
 */

@interface ElasticLoadBalancingSetLoadBalancerPoliciesOfListenerRequest:AmazonServiceRequestConfig

{
    NSString       *loadBalancerName;
    NSNumber       *loadBalancerPort;
    NSMutableArray *policyNames;
}

/**
 * The name of the load balancer.
 */
@property (nonatomic, retain) NSString *loadBalancerName;

/**
 * The external port of the load balancer to associate the policy.
 */
@property (nonatomic, retain) NSNumber *loadBalancerPort;

/**
 * List of policies to be associated with the listener. If the list is
 * empty, the current policy is removed from the listener.
 */
@property (nonatomic, retain) NSMutableArray *policyNames;

/**
 * Default constructor for a new SetLoadBalancerPoliciesOfListenerRequest object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * Constructs a new SetLoadBalancerPoliciesOfListenerRequest object.
 * Callers should use properties to initialize any additional object members.
 *
 * @param theLoadBalancerName The name of the load balancer.
 * @param theLoadBalancerPort The external port of the load balancer to
 * associate the policy.
 * @param thePolicyNames List of policies to be associated with the
 * listener. If the list is empty, the current policy is removed from the
 * listener.
 */
-(id)initWithLoadBalancerName:(NSString *)theLoadBalancerName andLoadBalancerPort:(NSNumber *)theLoadBalancerPort andPolicyNames:(NSMutableArray *)thePolicyNames;

/**
 * Adds a single object to policyNames.
 * This function will alloc and init policyNames if not already done.
 */
-(void)addPolicyName:(NSString *)policyNameObject;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
a = 5
b = 10

# is equal
print a == b

# is not equal
print a != b

# greater than
print a > b

# greater than or equal
print a >= b

# is less than
print a < b

# is less than or equal
print a <= b

# make conditional descisions
# be carefull with the indetentation

if a < b:
    print "a is greater than b"

# if then else that
if a > b:
    print "a is less than b"
else:
    print "a is greater than b"

# if that else if aht else that
if a > b:
    print "a is less than b"
elif a == b:
    print "a is equal to b"
else:
    print "a is greater than b"

# combine conditions with boolean operators
# and or not
if a > b and a == 5:
    print "a is greater than b and a is equal to 5"

elif a > b or a == 5:
    print "a is greater than b or a is equal to 5"


text:
import Form from './form.vue'
import FormItem from './formItem.vue';
Form.FormItem = FormItem;
export default Form;


text:
namespace Microsoft.Practices.DataPipeline.ColdStorage
{
    using System;
    using System.Diagnostics;
    using System.Net;
    using System.Threading;

    using Microsoft.Practices.DataPipeline.ColdStorage.Instrumentation;
    using Microsoft.Practices.DataPipeline.Logging;
    using Microsoft.WindowsAzure.ServiceRuntime;

    public class WorkerRole : RoleEntryPoint
    {
        private static readonly ILogger Logger =
            LoggerFactory.GetLogger("Host");

        private readonly CancellationTokenSource _cancellationTokenSource =
            new CancellationTokenSource();

        private readonly ManualResetEvent _runCompleteEvent =
            new ManualResetEvent(false);

        private Configuration _configuration;
        private ColdStorageCoordinator _coordinator;

        public override bool OnStart()
        {
            try
            {
                // Set the maximum number of concurrent connections
                ServicePointManager.DefaultConnectionLimit = int.MaxValue;

                // Pull the configuration object from service and app configuration
                _configuration = Configuration.GetCurrentConfiguration();

                // Create the instrumentation (performance counter publisher)
                var instrumentationPublisher =
                    new ColdStorageInstrumentationManager(
                        instrumentationEnabled: true,
                        installInstrumentation: false)
                        .CreatePublisher("WaWorkerHost");

                // Activate the cold storage processor
                _coordinator = ColdStorageCoordinator.CreateAsync(
                    RoleEnvironment.CurrentRoleInstance.Id,
                    _configuration.EventHubName,
                    _configuration.ConsumerGroupName,
                    _configuration.EventHubConnectionString,
                    _configuration.CheckpointStorageAccount,
                    _configuration.MaxBatchSize,
                    _configuration.PreFetchCount,
                    _configuration.ReceiveTimeout,
                    new[] { _configuration.BlobWriterStorageAccount },
                    _configuration.ContainerName,
                    _configuration.RollSizeForBlobWriterMb,
                    _configuration.BlobPrefix,
                    _configuration.CircuitBreakerWarningLevel,
                    _configuration.CircuitBreakerTripLevel,
                    _configuration.CircuitBreakerStallInterval,
                    _configuration.CircuitBreakerLogCooldownInterval,
                    instrumentationPublisher
                    ).Result;

                bool result = base.OnStart();

                Trace.TraceInformation("Processor has been started");

                return result;
            }
            catch (Exception ex)
            {
                LogHelpers.HandleRoleException(Logger, "Run()", ex);
                throw;
            }
        }

        public override void Run()
        {
            try
            {
                Logger.Info("Cold storage processor is running");
                _cancellationTokenSource.Token.WaitHandle.WaitOne();
                _coordinator.Dispose();
                Logger.Info("Dispatching processor is complete");
            }
            catch (Exception ex)
            {
                LogHelpers.HandleRoleException(Logger, "Run()", ex);
            }
            finally
            {
                _runCompleteEvent.Set();
            }
        }

        public override void OnStop()
        {
            try
            {
                Logger.Info("OnStop() called for Cold Storage processor");

                _cancellationTokenSource.Cancel();
                _runCompleteEvent.WaitOne();

                base.OnStop();

                Logger.Info("OnStop() complete for Cold Storage processor");
            }
            catch (Exception ex)
            {
                LogHelpers.HandleRoleException(Logger, "OnStop()", ex);
                throw;
            }
        }
    }
}


text:
Project Name

Heading
CyberMines, a video-game

Sub-Heading
A turn based RPG

Summary
TBD

Problem
Boredom

Solution
Fun exciting gameplay

Quote from You
"It's so amazing we havn't even thought of it yet"

How to Get Started
Good question!

Customer Quote
"I totally exist, trust me"

Closing and Call to Action
"Play our game plz"


text:
<?php

include(__DIR__.'/config.php');

$mapo['title'] = "Hello World";

$mapo['header'] = Template::Header();

$mapo['main'] = <<< TEMPLATE

Hej Världen

Detta är en exempelsida som visar hur Mapo ser ut och fungerar.

TEMPLATE;

$mapo['footer'] = Template::Footer();

include(MAPO_THEME_PATH);


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=fn.derive_serialize.html">

Redirecting to fn.derive_serialize.html...


text:
package cfvbaibai.cardfantasy.web.beans;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cfvbaibai.cardfantasy.NonSerializableStrategy;
import cfvbaibai.cardfantasy.PlayerJsonSerializer;
import cfvbaibai.cardfantasy.engine.Player;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class JsonHandler {
    private class UtcDateSerializer implements JsonSerializer<Date>{
        private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @Override
        public JsonElement serialize(Date utcDate, Type type, JsonSerializationContext context) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(utcDate);
            calendar.add(Calendar.HOUR_OF_DAY, 8);
            Date localDate = calendar.getTime();
            String localTimeText = this.formatter.format(localDate);
            JsonPrimitive result = new JsonPrimitive(localTimeText);
            return result;
        }
    }

    private Gson gson;
    public JsonHandler() {
        this.gson = new GsonBuilder()
        .setExclusionStrategies(new NonSerializableStrategy())
        .registerTypeAdapter(Player.class, new PlayerJsonSerializer())
        .registerTypeAdapter(Date.class, new UtcDateSerializer())
        .setPrettyPrinting()
        .create();
    }

    public String toJson(Object obj) {
        return this.gson.toJson(obj);
    }

    public <T> T fromJson(String json, Class <T> clazz) {
        return this.gson.fromJson(json, clazz);
    }
}


text:
package org.apache.flink.contrib.streaming.state.iterator;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.contrib.streaming.state.RocksIteratorWrapper;
import org.apache.flink.core.memory.DataInputDeserializer;
import org.apache.flink.runtime.state.CompositeKeySerializationUtils;

import javax.annotation.Nonnull;

import java.io.IOException;

/**
 * Base class for iterators over RocksDB column families.
 *
 * @param <K> the type of the iterated objects, which are keys in RocksDB.
 */
@Internal
public abstract class AbstractRocksStateKeysIterator<K> implements AutoCloseable {

    @Nonnull protected final RocksIteratorWrapper iterator;

    @Nonnull protected final String state;

    @Nonnull protected final TypeSerializer<K> keySerializer;

    protected final boolean ambiguousKeyPossible;

    protected final int keyGroupPrefixBytes;

    protected final DataInputDeserializer byteArrayDataInputView;

    public AbstractRocksStateKeysIterator(
            @Nonnull RocksIteratorWrapper iterator,
            @Nonnull String state,
            @Nonnull TypeSerializer<K> keySerializer,
            int keyGroupPrefixBytes,
            boolean ambiguousKeyPossible) {
        this.iterator = iterator;
        this.state = state;
        this.keySerializer = keySerializer;
        this.keyGroupPrefixBytes = keyGroupPrefixBytes;
        this.ambiguousKeyPossible = ambiguousKeyPossible;
        this.byteArrayDataInputView = new DataInputDeserializer();
    }

    protected K deserializeKey(byte[] keyBytes, DataInputDeserializer readView) throws IOException {
        readView.setBuffer(keyBytes, keyGroupPrefixBytes, keyBytes.length - keyGroupPrefixBytes);
        return CompositeKeySerializationUtils.readKey(
                keySerializer, byteArrayDataInputView, ambiguousKeyPossible);
    }

    @Override
    public void close() {
        iterator.close();
    }
}


text:
package v1beta1

import (
	v1alpha1 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/clients/generated/apis/k8s/v1alpha1"
	runtime "k8s.io/apimachinery/pkg/runtime"
)

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DataFusionInstance) DeepCopyInto(out *DataFusionInstance) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	in.Status.DeepCopyInto(&out.Status)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DataFusionInstance.
func (in *DataFusionInstance) DeepCopy() *DataFusionInstance {
	if in == nil {
		return nil
	}
	out := new(DataFusionInstance)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DataFusionInstance) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DataFusionInstanceList) DeepCopyInto(out *DataFusionInstanceList) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ListMeta.DeepCopyInto(&out.ListMeta)
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]DataFusionInstance, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DataFusionInstanceList.
func (in *DataFusionInstanceList) DeepCopy() *DataFusionInstanceList {
	if in == nil {
		return nil
	}
	out := new(DataFusionInstanceList)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *DataFusionInstanceList) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DataFusionInstanceSpec) DeepCopyInto(out *DataFusionInstanceSpec) {
	*out = *in
	if in.DataprocServiceAccountRef != nil {
		in, out := &in.DataprocServiceAccountRef, &out.DataprocServiceAccountRef
		*out = new(v1alpha1.ResourceRef)
		**out = **in
	}
	if in.Description != nil {
		in, out := &in.Description, &out.Description
		*out = new(string)
		**out = **in
	}
	if in.DisplayName != nil {
		in, out := &in.DisplayName, &out.DisplayName
		*out = new(string)
		**out = **in
	}
	if in.EnableStackdriverLogging != nil {
		in, out := &in.EnableStackdriverLogging, &out.EnableStackdriverLogging
		*out = new(bool)
		**out = **in
	}
	if in.EnableStackdriverMonitoring != nil {
		in, out := &in.EnableStackdriverMonitoring, &out.EnableStackdriverMonitoring
		*out = new(bool)
		**out = **in
	}
	if in.NetworkConfig != nil {
		in, out := &in.NetworkConfig, &out.NetworkConfig
		*out = new(InstanceNetworkConfig)
		(*in).DeepCopyInto(*out)
	}
	if in.Options != nil {
		in, out := &in.Options, &out.Options
		*out = make(map[string]string, len(*in))
		for key, val := range *in {
			(*out)[key] = val
		}
	}
	if in.PrivateInstance != nil {
		in, out := &in.PrivateInstance, &out.PrivateInstance
		*out = new(bool)
		**out = **in
	}
	if in.ResourceID != nil {
		in, out := &in.ResourceID, &out.ResourceID
		*out = new(string)
		**out = **in
	}
	if in.Version != nil {
		in, out := &in.Version, &out.Version
		*out = new(string)
		**out = **in
	}
	if in.Zone != nil {
		in, out := &in.Zone, &out.Zone
		*out = new(string)
		**out = **in
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DataFusionInstanceSpec.
func (in *DataFusionInstanceSpec) DeepCopy() *DataFusionInstanceSpec {
	if in == nil {
		return nil
	}
	out := new(DataFusionInstanceSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DataFusionInstanceStatus) DeepCopyInto(out *DataFusionInstanceStatus) {
	*out = *in
	if in.Conditions != nil {
		in, out := &in.Conditions, &out.Conditions
		*out = make([]v1alpha1.Condition, len(*in))
		copy(*out, *in)
	}
	if in.AvailableVersion != nil {
		in, out := &in.AvailableVersion, &out.AvailableVersion
		*out = make([]InstanceAvailableVersionStatus, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DataFusionInstanceStatus.
func (in *DataFusionInstanceStatus) DeepCopy() *DataFusionInstanceStatus {
	if in == nil {
		return nil
	}
	out := new(DataFusionInstanceStatus)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *InstanceAvailableVersionStatus) DeepCopyInto(out *InstanceAvailableVersionStatus) {
	*out = *in
	if in.AvailableFeatures != nil {
		in, out := &in.AvailableFeatures, &out.AvailableFeatures
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InstanceAvailableVersionStatus.
func (in *InstanceAvailableVersionStatus) DeepCopy() *InstanceAvailableVersionStatus {
	if in == nil {
		return nil
	}
	out := new(InstanceAvailableVersionStatus)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *InstanceNetworkConfig) DeepCopyInto(out *InstanceNetworkConfig) {
	*out = *in
	if in.IpAllocation != nil {
		in, out := &in.IpAllocation, &out.IpAllocation
		*out = new(string)
		**out = **in
	}
	if in.NetworkRef != nil {
		in, out := &in.NetworkRef, &out.NetworkRef
		*out = new(v1alpha1.ResourceRef)
		**out = **in
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InstanceNetworkConfig.
func (in *InstanceNetworkConfig) DeepCopy() *InstanceNetworkConfig {
	if in == nil {
		return nil
	}
	out := new(InstanceNetworkConfig)
	in.DeepCopyInto(out)
	return out
}


text:
from django.core.urlresolvers import reverse
from django.forms.models import ModelForm
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from website.models import User
from website.view.account import UserIsAdminMixin, user_is_admin
# model
from website.models import Unit

# forms
class UnitForm(ModelForm):
    class Meta:
        model = Unit
        exclude = ()

# views
class ListUnitView(UserIsAdminMixin, ListView):
    model = Unit
    template_name = 'unit/list.html'
    paginate_by = 5

    def get_context_data(self, **kwargs):
        context = super(ListUnitView, self).get_context_data(**kwargs)
        context['is_admin'] = user_is_admin(self.request.user)
        context['active_menu'] = 'administration'
        return context

class CreateUnitView(UserIsAdminMixin, CreateView):
    form_class = UnitForm
    template_name = 'unit/edit.html'

    def get_success_url(self):
        return reverse('unit-list')

    def get_context_data(self, **kwargs):
        context = super(CreateUnitView, self).get_context_data(**kwargs)
        context['action'] = reverse('unit-new')
        context['is_admin'] = user_is_admin(self.request.user)
        context['active_menu'] = 'administration'
        return context

class UpdateUnitView(UserIsAdminMixin, UpdateView):
    model = Unit
    template_name = 'unit/edit.html'
    fields = ('__all__')

    def get_success_url(self):
        return reverse('unit-list')

    def get_context_data(self, **kwargs):
        context = super(UpdateUnitView, self).get_context_data(**kwargs)
        context['action'] = reverse('unit-edit', kwargs={'pk': self.get_object().id})
        context['is_admin'] = user_is_admin(self.request.user)
        context['active_menu'] = 'administration'
        return context

class DeleteUnitView(UserIsAdminMixin, DeleteView):
    model = Unit
    template_name = 'unit/delete.html'

    def get_success_url(self):
        return reverse('unit-list')

    def get_context_data(self, **kwargs):
        context = super(DeleteUnitView, self).get_context_data(**kwargs)
        context['is_admin'] = user_is_admin(self.request.user)
        context['active_menu'] = 'administration'
        return context


text:
RSpec.describe RuboCop::Cop::RSpec::ExampleWithoutDescription do
  let(:cop_config) do
    { 'EnforcedStyle' => enforced_style }
  end

  context 'with EnforcedStyle `always_allow`' do
    let(:enforced_style) { 'always_allow' }

    it 'flags empty strings for description' do
      expect_offense(<<-RUBY)
        it '' do
           ^^ Omit the argument when you want to have auto-generated description.
          expect(subject).to be_good
        end
      RUBY
    end

    it 'ignores `it` with a description' do
      expect_no_offenses(<<-RUBY)
        it 'is good' do
          expect(subject).to be_good
        end
      RUBY
    end

    it 'ignores `it` without an argument' do
      expect_no_offenses(<<-RUBY)
        it do
          expect(subject).to be_good
        end
      RUBY
    end
  end

  context 'with EnforcedStyle `single_line_only`' do
    let(:enforced_style) { 'single_line_only' }

    it 'flags missing description in multi-line examples' do
      expect_offense(<<-RUBY)
        it do
        ^^ Add a description.
          expect(subject).to be_good
        end
      RUBY
    end

    it 'ignores missing description in single-line examples' do
      expect_no_offenses(<<-RUBY)
        it { expect(subject).to be_good }
      RUBY
    end

    it 'flags example with an empty string for description' do
      expect_offense(<<-RUBY)
        it('') { expect(subject).to be_good }
           ^^ Omit the argument when you want to have auto-generated description.
      RUBY
    end
  end

  context 'with EnforcedStyle `disallow`' do
    let(:enforced_style) { 'disallow' }

    it 'flags missing description in multi-line examples' do
      expect_offense(<<-RUBY)
        it do
        ^^ Add a description.
          expect(subject).to be_good
        end
      RUBY
    end

    it 'flags missing description in single-line examples' do
      expect_offense(<<-RUBY)
        it { expect(subject).to be_good }
        ^^ Add a description.
      RUBY
    end

    it 'ignores `it` with a description' do
      expect_no_offenses(<<-RUBY)
        it 'is good' do
          expect(subject).to be_good
        end
      RUBY
    end
  end
end


text:
jQuery(document).ready(function(){
	var numSaves, _autoSaveChanges;
	module("TiddlyWiki options", {
		setup: function() {
			config.options.chkAutoSave = true;
			systemSettingSave = 0;
			_autoSaveChanges = autoSaveChanges;
			numSaves = 0;
			autoSaveChanges = function() {
				numSaves += 1;
				return _autoSaveChanges.apply(this, arguments);
			}
		},
		teardown: function() {
			numSaves = null;
			config.options.chkAutoSave = false;
			autoSaveChanges = _autoSaveChanges;
		}
	});

	test("save multiple system settings", function() {
		saveSystemSetting("foo", true);
		saveSystemSetting("foo", false);
		saveSystemSetting("foo", true);
		strictEqual(numSaves, 0, "The save is asynchronous so no saves have yet been made");
		strictEqual(systemSettingSave > 0, true, "However there should be a timeout in progress");
	});

});


text:
require "spec_helper"

describe Nacre::NominalCode do

  let!(:link) { Nacre::Connection.new }

  let(:params) do
    {
      id: 1,
      code: "0010",
      name: "Freehold Property",
      type: {
        id: 1
      },
      bank: false,
      expense: false,
      discount: false,
      editable: true,
      active: true,
      tax_code: 0,
      description: "",
      chart_map_code: "",
      reconcile: false
    }
  end

  subject { described_class.new(params) }

  it_behaves_like "Parametrizable"

  context "initialization" do

    describe ".new" do
      it "should have an id" do
        expect(subject.id).to eq params[:id]
      end

      it "should have a name" do
        expect(subject.name).to eq params[:name]
      end
    end

    describe ".from_json" do
      let(:json) { fixture_file_content("nominal_code.json") }

      subject { described_class.from_json(json) }

      it "has the correct id" do
        expect(subject.id).to eq 1
      end

      it "has the correct name" do
        expect(subject.name).to eq "Freehold Property"
      end

      it "has the correct code" do
        expect(subject.code).to eq "0010"
      end

      it "has the correct bank value" do
        expect(subject.bank).to eq false
      end

      it "has the correct tax code" do
        expect(subject.tax_code).to eq 0
      end

      it "has the correct default price list ID" do
        expect(subject.chart_map_code).to eq ""
      end
    end
  end

  context "API interactions" do
    let!(:link) { Nacre::Connection.new }

    let(:resource) { "accounting" }

    let(:api_details) do
      [
        Nacre.configuration.api_version,
        Nacre.configuration.user_id
      ]
    end

    describe ".get" do
      let(:resource_endpoint) {
        nominal_code_service_url
      }

      let(:range) { 1 }

      it "should make a request to the correct endpoint" do
        stub_request(:get, "#{resource_endpoint}/#{range}").
          to_return(
            status:  200,
            body:  fixture_file_content("nominal_code.json"),
            headers:  {}
          )

        nominal_code = described_class.get(range)

        expect(a_request(
          :get,
          "#{resource_endpoint}/#{range}"
        )).to have_been_made

        expect(nominal_code.id).to eql(range)
      end
    end
  end
end


text:
<!DOCTYPE html>

		<title>three.js webgl - materials - normal map [Lee Perry-Smith]</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js - webgl normalmap demo.
			Lee Perry-Smith head.

displacement mapping needs vertex textures (GPU with Shader Model 3.0)

			on Windows use Chrome --use-gl=desktop or Firefox 4

			please star this Chrome issue to get ANGLE support


text:
require 'json'
require 'net/http'

class PlaceResult
  attr_reader :name, :address, :google_place_id, :latitude, :longitude
  def initialize(args)
    @name = args[:name]
    @address = args[:address]
    @google_place_id = args[:google_place_id]
    @latitude = args[:latitude]
    @longitude = args[:longitude]
  end

  def self.get_API_response(endpoint)
    uri = URI.parse(URI.encode(endpoint))
    api_response = Net::HTTP.get(uri)
    JSON.parse(api_response)
  end

  def self.create_results(response)
    collection = []
    response["results"].each do |result|
      args = { name: result["name"],
               address: result["vicinity"],
               google_place_id: result["place_id"],
               latitude: result["geometry"]["location"]["lat"],
               longitude: result["geometry"]["location"]["lng"]
             }
      collection << PlaceResult.new(args)
    end
    collection
  end

  def self.search_and_retrieve(keyword, latitude, longitude)
    key = ENV['SEARCH_PLACES_API_KEY']
    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=#{key}&location=#{latitude},#{longitude}&radius=10000&keyword=#{keyword}"
    response = PlaceResult.get_API_response(url)
    PlaceResult.create_results(response)
  end
end


text:
package com.github.mrpowers.spark.examples

import com.holdenkarau.spark.testing.DataFrameSuiteBase
import org.scalatest.FunSpec
import org.apache.spark.sql.Column
import org.apache.spark.sql.functions._
import com.github.mrpowers.spark.daria.sql.ColumnExt._
import com.github.mrpowers.spark.daria.sql.SparkSessionExt._
import org.apache.spark.sql.types.StringType

object Goo {

def appendABC()(col: Column): Column = {
  concat(col, lit(" ABC"))
}

}

class ColumnChainSpec
    extends FunSpec
    with DataFrameSuiteBase {

  import spark.implicits._

  it("chains column functions") {

    spark.createDF(
      List(
        ("  HI THERE     "),
        (" I lIKe     ")
      ), List(
        ("aaa", StringType, true)
      )
    ).withColumn(
      "aaa",
      col("aaa")
        .chain(lower)
        .chain(trim)
        .chain(Goo.appendABC())
        .chain(regexp_replace(_, "A", "ZZZ"))
    ).show()

  }

  it("chains with rpad") {

    val wordsDf = Seq(
      ("hi  "),
      ("  ok")
    ).toDF("word")

    val actualDf = wordsDf.withColumn(
      "diff_word",
      col("word").chain(trim).chain(rpad(_, 5, "x"))
    )

    actualDf.show()

  }

}


text:
package com.glooory.flatreader.entity.ithome;

import org.simpleframework.xml.ElementList;

import java.util.ArrayList;

/**
 * Created by Glooory on 2016/10/12 0012 12:37.
 */

public class ITHomeChannelBean {

    @ElementList(inline = true, name = "items")
    ArrayList<ITHomeItemBean> items;

    public ArrayList<ITHomeItemBean> getItems() {
        return items;
    }

    public void setItems(ArrayList<ITHomeItemBean> items) {
        this.items = items;
    }
}


text:
import React, { Component } from 'react';
import { Link } from 'react-router';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Actions from '../../DataStore/Actions';

class TopActionComponent extends Component{

	render() {
		const floatStlye = {
			float: 'right',
			paddingRight: '10px',
			margin: '2px auto'
		};
		return (

				<Link
					to = {`/nyumbani/index.php/home/employee_timeline/MyBids/`}
					className = 'mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'
				>Bids
notifications
</Link>
				<Link
					to = {`/nyumbani/index.php/home/employee_timeline/Messages/`}
					className = 'mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'
				>Messages
notifications
</Link>

			);
	}
}

function mapStateToProps( state ){
	return {
		Bids: state.Bids,
		Messages: state.Messages
	};
}

function mapDispatchToProps(dispatch){
	return{
		Actions: bindActionCreators( Actions, dispatch )
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(TopActionComponent);


text:
package com.yongbeam.y_photopicker.util.photopicker.adapter;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.yongbeam.y_photopicker.R;
import com.yongbeam.y_photopicker.util.photopicker.PhotoPickerActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PhotoPagerAdapter extends PagerAdapter {

  private List<String> paths = new ArrayList<>();
  private Context mContext;
  private LayoutInflater mLayoutInflater;

  public PhotoPagerAdapter(Context mContext, List<String> paths) {
    this.mContext = mContext;
    this.paths = paths;
    mLayoutInflater = LayoutInflater.from(mContext);
  }

  @Override public Object instantiateItem(ViewGroup container, int position) {

    View itemView = mLayoutInflater.inflate(R.layout.util_item_pager, container, false);

    ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_pager);

    final String path = paths.get(position);
    final Uri uri;
    if (path.startsWith("http")) {
      uri = Uri.parse(path);
    } else {
      uri = FileProvider.getUriForFile(mContext, "com.yongbeam.y_photopicker.fileprovider", new File(path));
    }

    Glide.with(mContext)
            .load(uri)
            .thumbnail(0.4f)
            .apply(new RequestOptions()
                    .placeholder(R.color.img_loding_placeholder)
                    .error(R.drawable.ic_place_holder))
            .into(imageView);

    imageView.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        if (mContext instanceof PhotoPickerActivity) {
          if (!((Activity) mContext).isFinishing()) {
            ((Activity) mContext).onBackPressed();
          }
        }
      }
    });

    container.addView(itemView);

    return itemView;
  }

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

  @Override public boolean isViewFromObject(View view, Object object) {
    return view == object;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
  }

  @Override
  public int getItemPosition (Object object) { return POSITION_NONE; }

}


text:
<?php

/**
 * Put terminal into halfdelay mode
 *
 * @phpstub
 *
 * @param int $tenth
 *
 * @return int
 */
function ncurses_halfdelay($tenth)
{
}