text:
function Get-JiraIssueWatcher {
    # .ExternalHelp ..\JiraPS-help.xml
    [CmdletBinding()]
    param(
        [Parameter( Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName )]
        [ValidateNotNullOrEmpty()]
        [ValidateScript(
            {
                if (("JiraPS.Issue" -notin $_.PSObject.TypeNames) -and (($_ -isnot [String]))) {
                    $exception = ([System.ArgumentException]"Invalid Type for Parameter") #fix code highlight]
                    $errorId = 'ParameterType.NotJiraIssue'
                    $errorCategory = 'InvalidArgument'
                    $errorTarget = $_
                    $errorItem = New-Object -TypeName System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $errorTarget
                    $errorItem.ErrorDetails = "Wrong object type provided for Issue. Expected [JiraPS.Issue] or [String], but was $($_.GetType().Name)"
                    $PSCmdlet.ThrowTerminatingError($errorItem)
                    <#
                      #ToDo:CustomClass
                      Once we have custom classes, this check can be done with Type declaration
                    #>
                }
                else {
                    return $true
                }
            }
        )]
        [Alias('Key')]
        [Object]
        $Issue,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = [System.Management.Automation.PSCredential]::Empty
    )

    begin {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Function started"
    }

    process {
        Write-DebugMessage "[$($MyInvocation.MyCommand.Name)] ParameterSetName: $($PsCmdlet.ParameterSetName)"
        Write-DebugMessage "[$($MyInvocation.MyCommand.Name)] PSBoundParameters: $($PSBoundParameters | Out-String)"

        # Find the proper object for the Issue
        $issueObj = Resolve-JiraIssueObject -InputObject $Issue -Credential $Credential

        foreach ($issue in $issueObj) {
            $parameter = @{
                URI        = "{0}/watchers" -f $issue.RestURL
                Method     = "GET"
                Credential = $Credential
            }
            Write-Debug "[$($MyInvocation.MyCommand.Name)] Invoking JiraMethod with `$parameter"
            if ($result = Invoke-JiraMethod @parameter) {
                Write-Output $result.watchers
                # TODO: are these users?
            }
        }
    }

    end {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Complete"
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Porphyrellus atrafuscus E.A. Dick & Snell

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
SSH_USER=${SSH_USERNAME:-vagrant}
SSH_USER_HOME=${SSH_USER_HOME:-/home/${SSH_USER}}

install_vmware_tools_centos_70()
{
    cd /tmp
    mkdir -p /mnt/cdrom
    mount -o loop $SSH_USER_HOME/linux.iso /mnt/cdrom
    tar zxf /mnt/cdrom/VMwareTools-*.tar.gz -C /tmp/

    mkdir -p /mnt/floppy
    modprobe floppy
    mount -t vfat /dev/fd0 /mnt/floppy

    cd /tmp/vmware-tools-distrib

    if [[ -f /mnt/cdrom/VMwareTools-9.6.2-1688356.tar.gz ]]
    then
        pushd lib/modules/source
        if [ ! -f vmhgfs.tar.orig ]
        then
            cp vmhgfs.tar vmhgfs.tar.orig
        fi
        rm -rf vmhgfs-only
        tar xf vmhgfs.tar
        pushd vmhgfs-only/shared
        patch -p1 < /mnt/floppy/vmware9.compat_dcache.h.patch
        popd
        tar cf vmhgfs.tar vmhgfs-only
        rm -rf vmhgfs-only
        popd
    fi

    /tmp/vmware-tools-distrib/vmware-install.pl --default
    rm $SSH_USER_HOME/linux.iso
    umount /mnt/cdrom
    rmdir /mnt/cdrom
    rm -rf /tmp/VMwareTools-*

    echo "==> Removing packages needed for building guest tools"
    yum -y remove gcc cpp kernel-devel kernel-headers perl

    exit
}

if [[ $PACKER_BUILDER_TYPE =~ vmware ]]; then
    echo "==> Installing VMware Tools"
    cat /etc/redhat-release
    if grep -q -i "release 7" /etc/redhat-release ; then
        install_vmware_tools_centos_70
    fi
    if grep -q -i "release 6" /etc/redhat-release ; then
        # Uninstall fuse to fake out the vmware install so it won't try to
        # enable the VMware blocking filesystem
        yum erase -y fuse
    fi
    # Assume that we've installed all the prerequisites:
    # kernel-headers-$(uname -r) kernel-devel-$(uname -r) gcc make perl
    # from the install media via ks.cfg

    # On RHEL 5, add /sbin to PATH because vagrant does a probe for
    # vmhgfs with lsmod sans PATH
    if grep -q -i "release 5" /etc/redhat-release ; then
        echo "export PATH=$PATH:/usr/sbin:/sbin" >> $SSH_USER_HOME/.bashrc
    fi

    cd /tmp
    mkdir -p /mnt/cdrom
    mount -o loop $SSH_USER_HOME/linux.iso /mnt/cdrom
    tar zxf /mnt/cdrom/VMwareTools-*.tar.gz -C /tmp/
    /tmp/vmware-tools-distrib/vmware-install.pl --default
    rm $SSH_USER_HOME/linux.iso
    umount /mnt/cdrom
    rmdir /mnt/cdrom
    rm -rf /tmp/VMwareTools-*
fi

if [[ $PACKER_BUILDER_TYPE =~ virtualbox ]]; then
    echo "==> Installing VirtualBox guest additions"
    # Assume that we've installed all the prerequisites:
    # kernel-headers-$(uname -r) kernel-devel-$(uname -r) gcc make perl
    # from the install media via ks.cfg

    VBOX_VERSION=$(cat $SSH_USER_HOME/.vbox_version)
    mount -o loop $SSH_USER_HOME/VBoxGuestAdditions_$VBOX_VERSION.iso /mnt
    sh /mnt/VBoxLinuxAdditions.run --nox11
    umount /mnt
    rm -rf $SSH_USER_HOME/VBoxGuestAdditions_$VBOX_VERSION.iso
    rm -f $SSH_USER_HOME/.vbox_version

    if [[ $VBOX_VERSION = "4.3.10" ]]; then
        ln -s /opt/VBoxGuestAdditions-4.3.10/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions
    fi
fi

if [[ $PACKER_BUILDER_TYPE =~ parallels ]]; then
    echo "==> Installing Parallels tools"

    mount -o loop $SSH_USER_HOME/prl-tools-lin.iso /mnt
    sh /mnt/install --install-unattended-with-deps
    umount /mnt
    rm -rf $SSH_USER_HOME/prl-tools-lin.iso
    rm -f $SSH_USER_HOME/.prlctl_version
fi

echo "==> Removing packages needed for building guest tools"
yum -y remove gcc cpp libmpc mpfr kernel-devel kernel-headers perl


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package uml;

/**
 *
 * @author PCVirtual
 */
public class Planilla {
    private int id;
    private String mes;

    public Planilla() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getMes() {
        return mes;
    }

    public void setMes(String mes) {
        this.mes = mes;
        /**/
    }

}


text:
class Client < ApplicationRecord
  belongs_to :user
  has_many :projects

end


text:
package retrofit.client;

import com.google.common.io.ByteStreams;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import retrofit.TestingUtils;
import retrofit.mime.TypedOutput;
import retrofit.mime.TypedString;

import static org.assertj.core.api.Assertions.assertThat;
import static retrofit.TestingUtils.assertBytes;

public class UrlConnectionClientTest {
  private static final String HOST = "http://example.com";

  private UrlConnectionClient client = new UrlConnectionClient() {
    @Override protected HttpURLConnection openConnection(Request request) throws IOException {
      return new DummyHttpUrlConnection(request.getUrl());
    }
  };

  @Test public void get() throws Exception {
    Request request = new Request("GET", HOST + "/foo/bar/?kit=kat", null, null);

    HttpURLConnection connection = client.openConnection(request);
    client.prepareRequest(connection, request);

    assertThat(connection.getRequestMethod()).isEqualTo("GET");
    assertThat(connection.getURL().toString()).isEqualTo(HOST + "/foo/bar/?kit=kat");
    assertThat(connection.getHeaderFields()).isEmpty();
  }

  @Test public void post() throws Exception {
    TypedString body = new TypedString("hi");
    Request request = new Request("POST", HOST + "/foo/bar/", null, body);

    DummyHttpUrlConnection connection = (DummyHttpUrlConnection) client.openConnection(request);
    client.prepareRequest(connection, request);

    assertThat(connection.getRequestMethod()).isEqualTo("POST");
    assertThat(connection.getURL().toString()).isEqualTo(HOST + "/foo/bar/");
    assertThat(connection.getRequestProperties()).hasSize(2);
    assertThat(connection.getRequestProperty("Content-Type")) //
        .isEqualTo("text/plain; charset=UTF-8");
    assertThat(connection.getRequestProperty("Content-Length")).isEqualTo("2");
    assertBytes(connection.getOutputStream().toByteArray(), "hi");
  }

  @Test public void multipart() throws Exception {
    Map<String, TypedOutput> bodyParams = new LinkedHashMap<String, TypedOutput>();
    bodyParams.put("foo", new TypedString("bar"));
    bodyParams.put("ping", new TypedString("pong"));
    TypedOutput body = TestingUtils.createMultipart(bodyParams);
    Request request = new Request("POST", HOST + "/that/", null, body);

    DummyHttpUrlConnection connection = (DummyHttpUrlConnection) client.openConnection(request);
    client.prepareRequest(connection, request);

    byte[] output = connection.getOutputStream().toByteArray();

    assertThat(connection.getRequestMethod()).isEqualTo("POST");
    assertThat(connection.getURL().toString()).isEqualTo(HOST + "/that/");
    assertThat(connection.getRequestProperties()).hasSize(2);
    assertThat(connection.getRequestProperty("Content-Type")).startsWith("multipart/form-data;");
    assertThat(connection.getRequestProperty("Content-Length")).isEqualTo(String.valueOf(output.length));
    assertThat(output.length).isGreaterThan(0);
  }

  @Test public void headers() throws Exception {
    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("kit", "kat"));
    headers.add(new Header("foo", "bar"));
    Request request = new Request("GET", HOST + "/this/", headers, null);

    HttpURLConnection connection = client.openConnection(request);
    client.prepareRequest(connection, request);

    assertThat(connection.getRequestProperties()).hasSize(2);
    assertThat(connection.getRequestProperty("kit")).isEqualTo("kat");
    assertThat(connection.getRequestProperty("foo")).isEqualTo("bar");
  }

  @Test public void response() throws Exception {
    DummyHttpUrlConnection connection = new DummyHttpUrlConnection(HOST);
    connection.setResponseCode(200);
    connection.setResponseMessage("OK");
    connection.addResponseHeader("Content-Type", "text/plain");
    connection.addResponseHeader("foo", "bar");
    connection.addResponseHeader("kit", "kat");
    connection.setInputStream(new ByteArrayInputStream("hello".getBytes("UTF-8")));
    Response response = client.readResponse(connection);

    assertThat(response.getUrl()).isEqualTo(HOST);
    assertThat(response.getStatus()).isEqualTo(200);
    assertThat(response.getReason()).isEqualTo("OK");
    assertThat(response.getHeaders()).hasSize(3) //
        .containsOnly(new Header("foo", "bar"), new Header("kit", "kat"),
            new Header("Content-Type", "text/plain"));
    assertBytes(ByteStreams.toByteArray(response.getBody().in()), "hello");
  }

  @Test public void createdResponse() throws Exception {
    DummyHttpUrlConnection connection = new DummyHttpUrlConnection(HOST);
    connection.setResponseCode(201);
    connection.setResponseMessage("OK");
    connection.addResponseHeader("Content-Type", "text/plain");
    connection.addResponseHeader("foo", "bar");
    connection.addResponseHeader("kit", "kat");
    connection.setInputStream(new ByteArrayInputStream("hello".getBytes("UTF-8")));
    Response response = client.readResponse(connection);

    assertThat(response.getUrl()).isEqualTo(HOST);
    assertThat(response.getStatus()).isEqualTo(201);
    assertThat(response.getReason()).isEqualTo("OK");
    assertThat(response.getHeaders()).hasSize(3) //
        .containsOnly(new Header("foo", "bar"), new Header("kit", "kat"),
            new Header("Content-Type", "text/plain"));
    assertBytes(ByteStreams.toByteArray(response.getBody().in()), "hello");
  }

  @Test public void errorResponse() throws Exception {
    DummyHttpUrlConnection connection = new DummyHttpUrlConnection(HOST);
    connection.setResponseCode(401);
    connection.setResponseMessage("Not Authorized");
    connection.addResponseHeader("Content-Type", "text/plain");
    connection.setInputStream(new ByteArrayInputStream("input".getBytes("UTF-8")));
    connection.setErrorStream(new ByteArrayInputStream("error".getBytes("UTF-8")));
    Response response = client.readResponse(connection);

    assertBytes(ByteStreams.toByteArray(response.getBody().in()), "error");
  }

  @Test public void emptyResponse() throws Exception {
    DummyHttpUrlConnection connection = new DummyHttpUrlConnection(HOST);
    connection.setResponseCode(200);
    connection.setResponseMessage("OK");
    connection.addResponseHeader("foo", "bar");
    connection.addResponseHeader("kit", "kat");
    Response response = client.readResponse(connection);

    assertThat(response.getUrl()).isEqualTo(HOST);
    assertThat(response.getStatus()).isEqualTo(200);
    assertThat(response.getReason()).isEqualTo("OK");
    assertThat(response.getHeaders()).hasSize(2) //
        .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  }

  @Test public void noReasonMessage() throws Exception {
    DummyHttpUrlConnection connection = new DummyHttpUrlConnection(HOST);
    connection.setResponseCode(504);
    connection.setResponseMessage(null);
    Response response = client.readResponse(connection);

    assertThat(response.getUrl()).isEqualTo(HOST);
    assertThat(response.getStatus()).isEqualTo(504);
    assertThat(response.getReason()).isEmpty();
  }
}


text:
WXS.THREE Openlayers example

        <input id="clickMe" type="button" value="Make 3D-model" onclick="doFunction();" />


text:
import base64
import codecs
import collections
import errno
from random import Random
from socket import error as SocketError
import string
import struct
import sys
import time

import zlib

try:
    from hashlib import md5, sha1
except ImportError:  # pragma NO COVER
    from md5 import md5
    from sha import sha as sha1

from eventlet import semaphore
from eventlet import wsgi
from eventlet.green import socket
from eventlet.support import get_errno
import six

# Python 2's utf8 decoding is more lenient than we'd like
# In order to pass autobahn's testsuite we need stricter validation
# if available...
for _mod in ('wsaccel.utf8validator', 'autobahn.utf8validator'):
    # autobahn has it's own python-based validator. in newest versions
    # this prefers to use wsaccel, a cython based implementation, if available.
    # wsaccel may also be installed w/out autobahn, or with a earlier version.
    try:
        utf8validator = __import__(_mod, {}, {}, [''])
    except ImportError:
        utf8validator = None
    else:
        break

ACCEPTABLE_CLIENT_ERRORS = set((errno.ECONNRESET, errno.EPIPE))

__all__ = ["WebSocketWSGI", "WebSocket"]
PROTOCOL_GUID = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
VALID_CLOSE_STATUS = set(
    list(range(1000, 1004)) +
    list(range(1007, 1012)) +
    # 3000-3999: reserved for use by libraries, frameworks,
    # and applications
    list(range(3000, 4000)) +
    # 4000-4999: reserved for private use and thus can't
    # be registered
    list(range(4000, 5000))
)

class BadRequest(Exception):
    def __init__(self, status='400 Bad Request', body=None, headers=None):
        super(Exception, self).__init__()
        self.status = status
        self.body = body
        self.headers = headers

class WebSocketWSGI(object):
    """Wraps a websocket handler function in a WSGI application.

    Use it like this::

      @websocket.WebSocketWSGI
      def my_handler(ws):
          from_browser = ws.wait()
          ws.send("from server")

    The single argument to the function will be an instance of
    :class:`WebSocket`.  To close the socket, simply return from the
    function.  Note that the server will log the websocket request at
    the time of closure.
    """

    def __init__(self, handler):
        self.handler = handler
        self.protocol_version = None
        self.support_legacy_versions = True
        self.supported_protocols = []
        self.origin_checker = None

    @classmethod
    def configured(cls,
                   handler=None,
                   supported_protocols=None,
                   origin_checker=None,
                   support_legacy_versions=False):
        def decorator(handler):
            inst = cls(handler)
            inst.support_legacy_versions = support_legacy_versions
            inst.origin_checker = origin_checker
            if supported_protocols:
                inst.supported_protocols = supported_protocols
            return inst
        if handler is None:
            return decorator
        return decorator(handler)

    def __call__(self, environ, start_response):
        http_connection_parts = [
            part.strip()
            for part in environ.get('HTTP_CONNECTION', '').lower().split(',')]
        if not ('upgrade' in http_connection_parts and
                environ.get('HTTP_UPGRADE', '').lower() == 'websocket'):
            # need to check a few more things here for true compliance
            start_response('400 Bad Request', [('Connection', 'close')])
            return []

        try:
            if 'HTTP_SEC_WEBSOCKET_VERSION' in environ:
                ws = self._handle_hybi_request(environ)
            elif self.support_legacy_versions:
                ws = self._handle_legacy_request(environ)
            else:
                raise BadRequest()
        except BadRequest as e:
            status = e.status
            body = e.body or b''
            headers = e.headers or []
            start_response(status,
                           [('Connection', 'close'), ] + headers)
            return [body]

        try:
            self.handler(ws)
        except socket.error as e:
            if get_errno(e) not in ACCEPTABLE_CLIENT_ERRORS:
                raise
        # Make sure we send the closing frame
        ws._send_closing_frame(True)
        # use this undocumented feature of eventlet.wsgi to ensure that it
        # doesn't barf on the fact that we didn't call start_response
        return wsgi.ALREADY_HANDLED

    def _handle_legacy_request(self, environ):
        if 'eventlet.input' in environ:
            sock = environ['eventlet.input'].get_socket()
        elif 'gunicorn.socket' in environ:
            sock = environ['gunicorn.socket']
        else:
            raise Exception('No eventlet.input or gunicorn.socket present in environ.')

        if 'HTTP_SEC_WEBSOCKET_KEY1' in environ:
            self.protocol_version = 76
            if 'HTTP_SEC_WEBSOCKET_KEY2' not in environ:
                raise BadRequest()
        else:
            self.protocol_version = 75

        if self.protocol_version == 76:
            key1 = self._extract_number(environ['HTTP_SEC_WEBSOCKET_KEY1'])
            key2 = self._extract_number(environ['HTTP_SEC_WEBSOCKET_KEY2'])
            # There's no content-length header in the request, but it has 8
            # bytes of data.
            environ['wsgi.input'].content_length = 8
            key3 = environ['wsgi.input'].read(8)
            key = struct.pack(">II", key1, key2) + key3
            response = md5(key).digest()

        # Start building the response
        scheme = 'ws'
        if environ.get('wsgi.url_scheme') == 'https':
            scheme = 'wss'
        location = '%s://%s%s%s' % (
            scheme,
            environ.get('HTTP_HOST'),
            environ.get('SCRIPT_NAME'),
            environ.get('PATH_INFO')
        )
        qs = environ.get('QUERY_STRING')
        if qs is not None:
            location += '?' + qs
        if self.protocol_version == 75:
            handshake_reply = (
                b"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
                b"Upgrade: WebSocket\r\n"
                b"Connection: Upgrade\r\n"
                b"WebSocket-Origin: " + six.b(environ.get('HTTP_ORIGIN')) + b"\r\n"
                b"WebSocket-Location: " + six.b(location) + b"\r\n\r\n"
            )
        elif self.protocol_version == 76:
            handshake_reply = (
                b"HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
                b"Upgrade: WebSocket\r\n"
                b"Connection: Upgrade\r\n"
                b"Sec-WebSocket-Origin: " + six.b(environ.get('HTTP_ORIGIN')) + b"\r\n"
                b"Sec-WebSocket-Protocol: " +
                six.b(environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', 'default')) + b"\r\n"
                b"Sec-WebSocket-Location: " + six.b(location) + b"\r\n"
                b"\r\n" + response
            )
        else:  # pragma NO COVER
            raise ValueError("Unknown WebSocket protocol version.")
        sock.sendall(handshake_reply)
        return WebSocket(sock, environ, self.protocol_version)

    def _parse_extension_header(self, header):
        if header is None:
            return None
        res = {}
        for ext in header.split(","):
            parts = ext.split(";")
            config = {}
            for part in parts[1:]:
                key_val = part.split("=")
                if len(key_val) == 1:
                    config[key_val[0].strip().lower()] = True
                else:
                    config[key_val[0].strip().lower()] = key_val[1].strip().strip('"').lower()
            res.setdefault(parts[0].strip().lower(), []).append(config)
        return res

    def _negotiate_permessage_deflate(self, extensions):
        if not extensions:
            return None
        deflate = extensions.get("permessage-deflate")
        if deflate is None:
            return None
        for config in deflate:
            # We'll evaluate each config in the client's preferred order and pick
            # the first that we can support.
            want_config = {
                # These are bool options, we can support both
                "server_no_context_takeover": config.get("server_no_context_takeover", False),
                "client_no_context_takeover": config.get("client_no_context_takeover", False)
            }
            # These are either bool OR int options. True means the client can accept a value
            # for the option, a number means the client wants that specific value.
            max_wbits = min(zlib.MAX_WBITS, 15)
            mwb = config.get("server_max_window_bits")
            if mwb is not None:
                if mwb is True:
                    want_config["server_max_window_bits"] = max_wbits
                else:
                    want_config["server_max_window_bits"] = \
                        int(config.get("server_max_window_bits", max_wbits))
                    if not (8 <= want_config["server_max_window_bits"] <= 15):
                        continue
            mwb = config.get("client_max_window_bits")
            if mwb is not None:
                if mwb is True:
                    want_config["client_max_window_bits"] = max_wbits
                else:
                    want_config["client_max_window_bits"] = \
                        int(config.get("client_max_window_bits", max_wbits))
                    if not (8 <= want_config["client_max_window_bits"] <= 15):
                        continue
            return want_config
        return None

    def _format_extension_header(self, parsed_extensions):
        if not parsed_extensions:
            return None
        parts = []
        for name, config in parsed_extensions.items():
            ext_parts = [six.b(name)]
            for key, value in config.items():
                if value is False:
                    pass
                elif value is True:
                    ext_parts.append(six.b(key))
                else:
                    ext_parts.append(six.b("%s=%s" % (key, str(value))))
            parts.append(b"; ".join(ext_parts))
        return b", ".join(parts)

    def _handle_hybi_request(self, environ):
        if 'eventlet.input' in environ:
            sock = environ['eventlet.input'].get_socket()
        elif 'gunicorn.socket' in environ:
            sock = environ['gunicorn.socket']
        else:
            raise Exception('No eventlet.input or gunicorn.socket present in environ.')

        hybi_version = environ['HTTP_SEC_WEBSOCKET_VERSION']
        if hybi_version not in ('8', '13', ):
            raise BadRequest(status='426 Upgrade Required',
                             headers=[('Sec-WebSocket-Version', '8, 13')])
        self.protocol_version = int(hybi_version)
        if 'HTTP_SEC_WEBSOCKET_KEY' not in environ:
            # That's bad.
            raise BadRequest()
        origin = environ.get(
            'HTTP_ORIGIN',
            (environ.get('HTTP_SEC_WEBSOCKET_ORIGIN', '')
             if self.protocol_version <= 8 else ''))
        if self.origin_checker is not None:
            if not self.origin_checker(environ.get('HTTP_HOST'), origin):
                raise BadRequest(status='403 Forbidden')
        protocols = environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', None)
        negotiated_protocol = None
        if protocols:
            for p in (i.strip() for i in protocols.split(',')):
                if p in self.supported_protocols:
                    negotiated_protocol = p
                    break

        key = environ['HTTP_SEC_WEBSOCKET_KEY']
        response = base64.b64encode(sha1(six.b(key) + PROTOCOL_GUID).digest())
        handshake_reply = [b"HTTP/1.1 101 Switching Protocols",
                           b"Upgrade: websocket",
                           b"Connection: Upgrade",
                           b"Sec-WebSocket-Accept: " + response]
        if negotiated_protocol:
            handshake_reply.append(b"Sec-WebSocket-Protocol: " + six.b(negotiated_protocol))

        parsed_extensions = {}
        extensions = self._parse_extension_header(environ.get("HTTP_SEC_WEBSOCKET_EXTENSIONS"))

        deflate = self._negotiate_permessage_deflate(extensions)
        if deflate is not None:
            parsed_extensions["permessage-deflate"] = deflate

        formatted_ext = self._format_extension_header(parsed_extensions)
        if formatted_ext is not None:
            handshake_reply.append(b"Sec-WebSocket-Extensions: " + formatted_ext)

        sock.sendall(b'\r\n'.join(handshake_reply) + b'\r\n\r\n')
        return RFC6455WebSocket(sock, environ, self.protocol_version,
                                protocol=negotiated_protocol,
                                extensions=parsed_extensions)

    def _extract_number(self, value):
        """
        Utility function which, given a string like 'g98sd  5[]221@1', will
        return 9852211. Used to parse the Sec-WebSocket-Key headers.
        """
        out = ""
        spaces = 0
        for char in value:
            if char in string.digits:
                out += char
            elif char == " ":
                spaces += 1
        return int(out) // spaces

class WebSocket(object):
    """A websocket object that handles the details of
    serialization/deserialization to the socket.

    The primary way to interact with a :class:`WebSocket` object is to
    call :meth:`send` and :meth:`wait` in order to pass messages back
    and forth with the browser.  Also available are the following
    properties:

    path
        The path value of the request.  This is the same as the WSGI PATH_INFO variable,
        but more convenient.
    protocol
        The value of the Websocket-Protocol header.
    origin
        The value of the 'Origin' header.
    environ
        The full WSGI environment for this request.

    """

    def __init__(self, sock, environ, version=76):
        """
        :param socket: The eventlet socket
        :type socket: :class:`eventlet.greenio.GreenSocket`
        :param environ: The wsgi environment
        :param version: The WebSocket spec version to follow (default is 76)
        """
        self.log = environ.get('wsgi.errors', sys.stderr)
        self.log_context = 'server={shost}/{spath} client={caddr}:{cport}'.format(
            shost=environ.get('HTTP_HOST'),
            spath=environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', ''),
            caddr=environ.get('REMOTE_ADDR'), cport=environ.get('REMOTE_PORT'),
        )
        self.socket = sock
        self.origin = environ.get('HTTP_ORIGIN')
        self.protocol = environ.get('HTTP_WEBSOCKET_PROTOCOL')
        self.path = environ.get('PATH_INFO')
        self.environ = environ
        self.version = version
        self.websocket_closed = False
        self._buf = b""
        self._msgs = collections.deque()
        self._sendlock = semaphore.Semaphore()

    def _pack_message(self, message):
        """Pack the message inside ``00`` and ``FF``

        As per the dataframing section (5.3) for the websocket spec
        """
        if isinstance(message, six.text_type):
            message = message.encode('utf-8')
        elif not isinstance(message, six.binary_type):
            message = six.b(str(message))
        packed = b"\x00" + message + b"\xFF"
        return packed

    def _parse_messages(self):
        """ Parses for messages in the buffer *buf*.  It is assumed that
        the buffer contains the start character for a message, but that it
        may contain only part of the rest of the message.

        Returns an array of messages, and the buffer remainder that
        didn't contain any full messages."""
        msgs = []
        end_idx = 0
        buf = self._buf
        while buf:
            frame_type = six.indexbytes(buf, 0)
            if frame_type == 0:
                # Normal message.
                end_idx = buf.find(b"\xFF")
                if end_idx == -1:  # pragma NO COVER
                    break
                msgs.append(buf[1:end_idx].decode('utf-8', 'replace'))
                buf = buf[end_idx + 1:]
            elif frame_type == 255:
                # Closing handshake.
                assert six.indexbytes(buf, 1) == 0, "Unexpected closing handshake: %r" % buf
                self.websocket_closed = True
                break
            else:
                raise ValueError("Don't understand how to parse this type of message: %r" % buf)
        self._buf = buf
        return msgs

    def send(self, message):
        """Send a message to the browser.

        *message* should be convertable to a string; unicode objects should be
        encodable as utf-8.  Raises socket.error with errno of 32
        (broken pipe) if the socket has already been closed by the client."""
        packed = self._pack_message(message)
        # if two greenthreads are trying to send at the same time
        # on the same socket, sendlock prevents interleaving and corruption
        self._sendlock.acquire()
        try:
            self.socket.sendall(packed)
        finally:
            self._sendlock.release()

    def wait(self):
        """Waits for and deserializes messages.

        Returns a single message; the oldest not yet processed. If the client
        has already closed the connection, returns None.  This is different
        from normal socket behavior because the empty string is a valid
        websocket message."""
        while not self._msgs:
            # Websocket might be closed already.
            if self.websocket_closed:
                return None
            # no parsed messages, must mean buf needs more data
            delta = self.socket.recv(8096)
            if delta == b'':
                return None
            self._buf += delta
            msgs = self._parse_messages()
            self._msgs.extend(msgs)
        return self._msgs.popleft()

    def _send_closing_frame(self, ignore_send_errors=False):
        """Sends the closing frame to the client, if required."""
        if self.version == 76 and not self.websocket_closed:
            try:
                self.socket.sendall(b"\xff\x00")
            except SocketError:
                # Sometimes, like when the remote side cuts off the connection,
                # we don't care about this.
                if not ignore_send_errors:  # pragma NO COVER
                    raise
            self.websocket_closed = True

    def close(self):
        """Forcibly close the websocket; generally it is preferable to
        return from the handler method."""
        try:
            self._send_closing_frame(True)
            self.socket.shutdown(True)
        except SocketError as e:
            if e.errno != errno.ENOTCONN:
                self.log.write('{ctx} socket shutdown error: {e}'.format(ctx=self.log_context, e=e))
        finally:
            self.socket.close()

class ConnectionClosedError(Exception):
    pass

class FailedConnectionError(Exception):
    def __init__(self, status, message):
        super(FailedConnectionError, self).__init__(status, message)
        self.message = message
        self.status = status

class ProtocolError(ValueError):
    pass

class RFC6455WebSocket(WebSocket):
    def __init__(self, sock, environ, version=13, protocol=None, client=False, extensions=None):
        super(RFC6455WebSocket, self).__init__(sock, environ, version)
        self.iterator = self._iter_frames()
        self.client = client
        self.protocol = protocol
        self.extensions = extensions or {}

        self._deflate_enc = None
        self._deflate_dec = None

    class UTF8Decoder(object):
        def __init__(self):
            if utf8validator:
                self.validator = utf8validator.Utf8Validator()
            else:
                self.validator = None
            decoderclass = codecs.getincrementaldecoder('utf8')
            self.decoder = decoderclass()

        def reset(self):
            if self.validator:
                self.validator.reset()
            self.decoder.reset()

        def decode(self, data, final=False):
            if self.validator:
                valid, eocp, c_i, t_i = self.validator.validate(data)
                if not valid:
                    raise ValueError('Data is not valid unicode')
            return self.decoder.decode(data, final)

    def _get_permessage_deflate_enc(self):
        options = self.extensions.get("permessage-deflate")
        if options is None:
            return None

        def _make():
            return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -options.get("client_max_window_bits" if self.client
                                                 else "server_max_window_bits",
                                                 zlib.MAX_WBITS))

        if options.get("client_no_context_takeover" if self.client
                       else "server_no_context_takeover"):
            # This option means we have to make a new one every time
            return _make()
        else:
            if self._deflate_enc is None:
                self._deflate_enc = _make()
            return self._deflate_enc

    def _get_permessage_deflate_dec(self, rsv1):
        options = self.extensions.get("permessage-deflate")
        if options is None or not rsv1:
            return None

        def _make():
            return zlib.decompressobj(-options.get("server_max_window_bits" if self.client
                                                   else "client_max_window_bits",
                                                   zlib.MAX_WBITS))

        if options.get("server_no_context_takeover" if self.client
                       else "client_no_context_takeover"):
            # This option means we have to make a new one every time
            return _make()
        else:
            if self._deflate_dec is None:
                self._deflate_dec = _make()
            return self._deflate_dec

    def _get_bytes(self, numbytes):
        data = b''
        while len(data) < numbytes:
            d = self.socket.recv(numbytes - len(data))
            if not d:
                raise ConnectionClosedError()
            data = data + d
        return data

    class Message(object):
        def __init__(self, opcode, decoder=None, decompressor=None):
            self.decoder = decoder
            self.data = []
            self.finished = False
            self.opcode = opcode
            self.decompressor = decompressor

        def push(self, data, final=False):
            self.finished = final
            self.data.append(data)

        def getvalue(self):
            data = b"".join(self.data)
            if not self.opcode & 8 and self.decompressor:
                data = self.decompressor.decompress(data + b'\x00\x00\xff\xff')
            if self.decoder:
                data = self.decoder.decode(data, self.finished)
            return data

    @staticmethod
    def _apply_mask(data, mask, length=None, offset=0):
        if length is None:
            length = len(data)
        cnt = range(length)
        return b''.join(six.int2byte(six.indexbytes(data, i) ^ mask[(offset + i) % 4]) for i in cnt)

    def _handle_control_frame(self, opcode, data):
        if opcode == 8:  # connection close
            if not data:
                status = 1000
            elif len(data) > 1:
                status = struct.unpack_from('!H', data)[0]
                if not status or status not in VALID_CLOSE_STATUS:
                    raise FailedConnectionError(
                        1002,
                        "Unexpected close status code.")
                try:
                    data = self.UTF8Decoder().decode(data[2:], True)
                except (UnicodeDecodeError, ValueError):
                    raise FailedConnectionError(
                        1002,
                        "Close message data should be valid UTF-8.")
            else:
                status = 1002
            self.close(close_data=(status, ''))
            raise ConnectionClosedError()
        elif opcode == 9:  # ping
            self.send(data, control_code=0xA)
        elif opcode == 0xA:  # pong
            pass
        else:
            raise FailedConnectionError(
                1002, "Unknown control frame received.")

    def _iter_frames(self):
        fragmented_message = None
        try:
            while True:
                message = self._recv_frame(message=fragmented_message)
                if message.opcode & 8:
                    self._handle_control_frame(
                        message.opcode, message.getvalue())
                    continue
                if fragmented_message and message is not fragmented_message:
                    raise RuntimeError('Unexpected message change.')
                fragmented_message = message
                if message.finished:
                    data = fragmented_message.getvalue()
                    fragmented_message = None
                    yield data
        except FailedConnectionError:
            exc_typ, exc_val, exc_tb = sys.exc_info()
            self.close(close_data=(exc_val.status, exc_val.message))
        except ConnectionClosedError:
            return
        except Exception:
            self.close(close_data=(1011, 'Internal Server Error'))
            raise

    def _recv_frame(self, message=None):
        recv = self._get_bytes

        # Unpacking the frame described in Section 5.2 of RFC6455
        # (https://tools.ietf.org/html/rfc6455#section-5.2)
        header = recv(2)
        a, b = struct.unpack('!BB', header)
        finished = a >> 7 == 1
        rsv123 = a >> 4 & 7
        rsv1 = rsv123 & 4
        if rsv123:
            if rsv1 and "permessage-deflate" not in self.extensions:
                # must be zero - unless it's compressed then rsv1 is true
                raise FailedConnectionError(
                    1002,
                    "RSV1, RSV2, RSV3: MUST be 0 unless an extension is"
                    " negotiated that defines meanings for non-zero values.")
        opcode = a & 15
        if opcode not in (0, 1, 2, 8, 9, 0xA):
            raise FailedConnectionError(1002, "Unknown opcode received.")
        masked = b & 128 == 128
        if not masked and not self.client:
            raise FailedConnectionError(1002, "A client MUST mask all frames"
                                        " that it sends to the server")
        length = b & 127
        if opcode & 8:
            if not finished:
                raise FailedConnectionError(1002, "Control frames must not"
                                            " be fragmented.")
            if length > 125:
                raise FailedConnectionError(
                    1002,
                    "All control frames MUST have a payload length of 125"
                    " bytes or less")
        elif opcode and message:
            raise FailedConnectionError(
                1002,
                "Received a non-continuation opcode within"
                " fragmented message.")
        elif not opcode and not message:
            raise FailedConnectionError(
                1002,
                "Received continuation opcode with no previous"
                " fragments received.")
        if length == 126:
            length = struct.unpack('!H', recv(2))[0]
        elif length == 127:
            length = struct.unpack('!Q', recv(8))[0]
        if masked:
            mask = struct.unpack('!BBBB', recv(4))
        received = 0
        if not message or opcode & 8:
            decoder = self.UTF8Decoder() if opcode == 1 else None
            decompressor = self._get_permessage_deflate_dec(rsv1)
            message = self.Message(opcode, decoder=decoder, decompressor=decompressor)
        if not length:
            message.push(b'', final=finished)
        else:
            while received < length:
                d = self.socket.recv(length - received)
                if not d:
                    raise ConnectionClosedError()
                dlen = len(d)
                if masked:
                    d = self._apply_mask(d, mask, length=dlen, offset=received)
                received = received + dlen
                try:
                    message.push(d, final=finished)
                except (UnicodeDecodeError, ValueError):
                    raise FailedConnectionError(
                        1007, "Text data must be valid utf-8")
        return message

    def _pack_message(self, message, masked=False,
                      continuation=False, final=True, control_code=None):
        is_text = False
        if isinstance(message, six.text_type):
            message = message.encode('utf-8')
            is_text = True

        compress_bit = 0
        compressor = self._get_permessage_deflate_enc()
        if message and compressor:
            message = compressor.compress(message)
            message += compressor.flush(zlib.Z_SYNC_FLUSH)
            assert message[-4:] == b"\x00\x00\xff\xff"
            message = message[:-4]
            compress_bit = 1 << 6

        length = len(message)
        if not length:
            # no point masking empty data
            masked = False
        if control_code:
            if control_code not in (8, 9, 0xA):
                raise ProtocolError('Unknown control opcode.')
            if continuation or not final:
                raise ProtocolError('Control frame cannot be a fragment.')
            if length > 125:
                raise ProtocolError('Control frame data too large (>125).')
            header = struct.pack('!B', control_code | 1 << 7)
        else:
            opcode = 0 if continuation else ((1 if is_text else 2) | compress_bit)
            header = struct.pack('!B', opcode | (1 << 7 if final else 0))
        lengthdata = 1 << 7 if masked else 0
        if length > 65535:
            lengthdata = struct.pack('!BQ', lengthdata | 127, length)
        elif length > 125:
            lengthdata = struct.pack('!BH', lengthdata | 126, length)
        else:
            lengthdata = struct.pack('!B', lengthdata | length)
        if masked:
            # NOTE: RFC6455 states:
            # A server MUST NOT mask any frames that it sends to the client
            rand = Random(time.time())
            mask = [rand.getrandbits(8) for _ in six.moves.xrange(4)]
            message = RFC6455WebSocket._apply_mask(message, mask, length)
            maskdata = struct.pack('!BBBB', *mask)
        else:
            maskdata = b''

        return b''.join((header, lengthdata, maskdata, message))

    def wait(self):
        for i in self.iterator:
            return i

    def _send(self, frame):
        self._sendlock.acquire()
        try:
            self.socket.sendall(frame)
        finally:
            self._sendlock.release()

    def send(self, message, **kw):
        kw['masked'] = self.client
        payload = self._pack_message(message, **kw)
        self._send(payload)

    def _send_closing_frame(self, ignore_send_errors=False, close_data=None):
        if self.version in (8, 13) and not self.websocket_closed:
            if close_data is not None:
                status, msg = close_data
                if isinstance(msg, six.text_type):
                    msg = msg.encode('utf-8')
                data = struct.pack('!H', status) + msg
            else:
                data = ''
            try:
                self.send(data, control_code=8)
            except SocketError:
                # Sometimes, like when the remote side cuts off the connection,
                # we don't care about this.
                if not ignore_send_errors:  # pragma NO COVER
                    raise
            self.websocket_closed = True

    def close(self, close_data=None):
        """Forcibly close the websocket; generally it is preferable to
        return from the handler method."""
        try:
            self._send_closing_frame(close_data=close_data, ignore_send_errors=True)
            self.socket.shutdown(socket.SHUT_WR)
        except SocketError as e:
            if e.errno != errno.ENOTCONN:
                self.log.write('{ctx} socket shutdown error: {e}'.format(ctx=self.log_context, e=e))
        finally:
            self.socket.close()


text:
package de.skuzzle.inject.conf;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.servlet.ServletContext;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Singleton;

public class BindingIntegrationTest {

    @Rule
    public final TemporaryFolder tempFolder = new TemporaryFolder();

    @Inject
    private JsonInterface jsonContent;
    @Inject
    private String textContent;
    @Inject
    private PropertiesInterface propertiesContent;
    @Inject
    private Properties props;
    @Inject
    @Named("fromServlet")
    private String fromServlet;
    @Inject
    private Object object;
    @Inject
    @Named("tempFile")
    private Provider<String> tempString;
    @Inject
    @Named("bufferedFile")
    private Provider<String> bufferedString;

    private File tempFile;

    private static final Object TEST_OBJECT = new Object();

    public static class TestTextContentType implements TextContentType {

        @Override
        public <T> T createInstance(Class<T> type, TextResource resource) {
            return type.cast(TEST_OBJECT);
        }

    }

    @Before
    public void setup() throws IOException {
        this.tempFile = this.tempFolder.newFile();

        Guice.createInjector(new AbstractModule() {

            @Override
            protected void configure() {
                final ServletContext mockCtx = mock(ServletContext.class);
                try {
                    when(mockCtx.getResource(Mockito.anyString()))
                            .thenAnswer(new Answer<URL>() {

                                @Override
                                public URL answer(InvocationOnMock invocation)
                                        throws Throwable {
                                    final String s = invocation.getArgumentAt(0,
                                            String.class);
                                    return getClass().getClassLoader().getResource(s);
                                }
                            });
                } catch (final MalformedURLException e) {
                    e.printStackTrace();
                }

                bind(ServletContext.class).toInstance(mockCtx);

                try {
                    final File file = new File(getClass().getResource(
                            "/test.properties").toURI());
                    Resources.bind()
                            .fileResource(file)
                            .containing(TestTextContentType.class)
                            .to(Object.class)
                            .using(binder());

                    writeString("test");
                    Resources.bind().cached(new TimestampCacheStrategy())
                            .fileResource(BindingIntegrationTest.this.tempFile)
                            .encodedWithSystemDefaultCharset()
                            .containingText()
                            .named("tempFile")
                            .using(binder());
                    Resources.bind().constant()
                            .fileResource(BindingIntegrationTest.this.tempFile)
                            .encodedWithProvidedCharset()
                            .containingText()
                            .named("bufferedFile")
                            .using(binder());
                } catch (final IOException | URISyntaxException e) {
                    throw new RuntimeException(e);
                }

                Resources.bind().constant()
                        .servletResource("test.properties")
                        .containingText()
                        .named("fromServlet")
                        .in(Singleton.class)
                        .using(binder());

                Resources.bind().changing()
                        .classPathResource("test.json")
                        .encodedWith(StandardCharsets.ISO_8859_1)
                        .containingJson()
                        .to(JsonInterface.class)
                        .using(binder());

                Resources.bind().cached(new TestCachingStrategy())
                        .classPathResource("test.txt")
                        .encodedWith("UTF-8")
                        .containingText()
                        .using(binder());

                Resources.bind().changing()
                        .classPathResource("test.properties")
                        .containingProperties()
                        .to(Properties.class)
                        .using(binder());

                Resources.bind().changing()
                        .classPathResource("test.properties")
                        .containingProperties()
                        .to(PropertiesInterface.class)
                        .using(binder());

            }
        }).injectMembers(this);
    }

    private void writeString(String s) throws IOException {
        try (Writer w = new OutputStreamWriter(new FileOutputStream(this.tempFile))) {
            w.write(s);
        }
    }

    @Test
    public void testCustomTextContentType() throws Exception {
        assertEquals(TEST_OBJECT, this.object);
    }

    @Test
    public void testArrayFromJson() throws Exception {
        assertArrayEquals(new int[] { 1, 2, 3 }, this.jsonContent.getArray());
    }

    @Test
    public void testIsoEncoding() throws Exception {
        assertEquals("xyzö", this.jsonContent.getBar());
    }

    @Test
    public void testInterfaceObjectFromJson() throws Exception {
        assertEquals("abc", this.jsonContent.getSample().getObject());
    }

    @Test
    public void testPlainText() throws Exception {
        assertEquals("just a text file öäü\n:D", this.textContent);
    }

    @Test
    public void testConvertedObjectFromJson() throws Exception {
        assertArrayEquals(new String[] { "a", "b", "c" },
                this.jsonContent.getSampleObject().getContent());
    }

    @Test
    public void testConvertedObjectFromProperties() throws Exception {
        assertArrayEquals(new String[] { "a", "b", "c" },
                this.propertiesContent.getSampleObject().getContent());
    }

    @Test
    public void testReloadCachedResource() throws Exception {
        assertEquals("test", this.tempString.get());
        writeString("foobar");
        assertEquals("foobar", this.tempString.get());
    }

    @Test
    public void testConstantResource() throws Exception {
        assertEquals("test", this.bufferedString.get());
        writeString("foobar");
        assertEquals("test", this.bufferedString.get());
    }
}


text:
package com.sinmin.rest.beans.request;

public class WildCard {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Evento.Repository;
using Evento.Tests.Fakes;
using EventStore.ClientAPI;
using Moq;
using NUnit.Framework;

namespace Evento.Tests
{
    [TestFixture]
    public class DomainRepositoryTests
    {
        [Test]
        public void When_I_save_an_aggregate_I_should_receive_the_saved_events()
        {
            // Assign
            const string correlationId = "correlationidexample-123";
            const string testString = "test";
            var cmd = new CreateFakeCommand(testString, new Dictionary<string, string>{{"$correlationId", correlationId}});
            var mockConnection = new Mock<IEventStoreConnection>();
            var repository = new EventStoreDomainRepository("domain", mockConnection.Object);

            // Act
            var results = repository.Save(new FakeHandler().Handle(cmd));

            // Assert
            Assert.IsTrue(((FakeAggregateCreated)results.Single()).Metadata["$correlationId"].Equals(correlationId));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/cheerleader_banner_height"
    android:background="@drawable/red_canvas_background"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="-18dp"
        android:fontFamily="sans-serif-thin"
        android:text="@string/cheerleader_banner_title"
        android:textColor="@color/banner_title"
        android:textSize="30sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_gravity="center"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:background="@color/banner_line" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="12dp"
        android:fontFamily="sans-serif-thin"
        android:text="@string/cheerleader_banner_subtitle"
        android:textColor="@color/banner_subtitle"
        android:textSize="15sp" />

</FrameLayout>


text:
using HETSAPI.Models;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace HETSAPI.Import
{
    /// <summary>
    /// Pair
    /// </summary>
    public class Pair
    {
        /// <summary>
        /// Hours
        /// </summary>
        public float Hours { get; set; }

        /// <summary>
        /// Rate
        /// </summary>
        public float Rate  { get; set; }

        /// <summary>
        /// Pair Constructir
        /// </summary>
        /// <param name="hour"></param>
        /// <param name="rate"></param>
        public Pair (float hour, float rate)
        {
            Hours = hour;
            Rate = rate;
        }
    }

    /// <summary>
    /// Import Utility
    /// </summary>
    public static class ImportUtility
    {
        /// <summary>
        /// Utility function to add a new ImportMap to the database
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldTable"></param>
        /// <param name="oldKey"></param>
        /// <param name="newTable"></param>
        /// <param name="newKey"></param>
        public static void AddImportMap(DbAppContext dbContext, string oldTable, string oldKey, string newTable, int newKey)
        {
            ImportMap importMap = new ImportMap
            {
                OldTable = oldTable,
                OldKey = oldKey,
                NewTable = newTable,
                NewKey = newKey,
                AppCreateTimestamp = DateTime.Now,
                AppLastUpdateTimestamp = DateTime.Now
            };

            dbContext.ImportMaps.Add(importMap);
        }

        /// <summary>
        /// This is recording where the last import was stopped for specific table
        /// Use BCBidImport.todayDate as newTable entry
        /// Please note that NewTable enrty of the Import_Map table is aleats today's dat: BCBidImport.todayDate for identifying purpose. This means the restarting point inly carew
        /// what has done for today, not in the past.
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldTable"></param>   This is lile "Owner_Progress" for th eimport progress entry (row) of Import_Map table
        /// <param name="oldKey"></param>  This is where stopped last time in string If this is "388888", then complete
        /// <param name="newKey"></param>
        /// <param name="newTable"></param>
        public static void AddImportMapForProgress(DbAppContext dbContext, string oldTable, string oldKey, int newKey, string newTable)
        {
            List<ImportMap> importMapList = dbContext.ImportMaps
                .Where(x => x.OldTable == oldTable &&
                            x.NewKey == newKey &&
                            x.NewTable == newTable)
                .ToList();

            if (importMapList.Count == 0)
            {
                AddImportMap(dbContext, oldTable, oldKey, newTable, newKey);
            }
            else
            {
                // Sometimes there are multiple progress entries exists for the same xml file import.
                // In that case, the extra one should be deleted and the correct one should be updated.
                int maxProgressCount = importMapList.Max(t => int.Parse(t.OldKey));

                foreach (ImportMap importMap in importMapList)
                {
                    if (importMap.OldKey == maxProgressCount.ToString())
                    {
                        importMap.NewTable = newTable;
                        importMap.OldKey = Math.Max(int.Parse(oldKey), maxProgressCount).ToString();
                        importMap.AppLastUpdateTimestamp = DateTime.Now;
                        dbContext.ImportMaps.Update(importMap);
                    }
                    else
                    {
                        dbContext.ImportMaps.Remove(importMap);
                    }
                }
            }
        }

        /// <summary>
        /// Return startPoint:  0 - if ImportMap entry with oldTable == "%%%%%_Progress" does not exist
        ///                     sigId - if ImportMap entry with oldTable == "%%%%%_Progress" exist, and oldKey = signId.toString()
        ///                     Other int - if ImportMap entry with oldTable == "%%%%%_Progress" exist, and oldKey != signId.toString()
        /// The Import_Table entry for this kind of record has NewTable as  BCBidImport.todayDate.
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldTableProgress"></param>
        /// <param name="sigId"></param>
        /// <param name="newTable"></param>
        /// <returns></returns>
        public static int CheckInterMapForStartPoint(DbAppContext dbContext, string oldTableProgress, int sigId, string newTable)
        {
            ImportMap importMap = (
                        from u in dbContext.ImportMaps
                        where u.OldTable == oldTableProgress &&
                              u.NewKey == sigId &&
                              u.NewTable == newTable
                        orderby int.Parse(u.OldKey) descending
                        select u)
                    .FirstOrDefault();

            // OlkdKey is recorded where the import progress stopped last time
            // when it stores the value of sigId, it signals the completion of the import of the corresponding xml file
            int startPoint = importMap != null ? int.Parse(importMap.OldKey) : 0;

            return startPoint;
        }

        /// <summary>
        /// Returns Memory stream from the input xml file
        /// </summary>
        /// <returns></returns>
        public static MemoryStream MemoryStreamGenerator(string xmlFileName, string oldTable, string fileLocation, string rootAttr)
        {
            string fullPath = fileLocation + Path.DirectorySeparatorChar + xmlFileName;

            // remove all new lines
            string contents = Regex.Replace(File.ReadAllText(fullPath), @"\r\n?|\n|s/\x00//g|[\x00-\x08\x0B\x0C\x0E-\x1F\x26]", "");

            // determine if the file has not been processed.
            string fixedXml;

            if (contents.IndexOf(rootAttr, StringComparison.Ordinal) == -1) // it has not been processed
            {
                // get the contents of the first tag
                int startPos = contents.IndexOf('<') + 1;
                int endPos = contents.IndexOf('>');
                string tag = contents.Substring(startPos, endPos - startPos);

                contents = contents.Replace(tag, oldTable);
                contents = contents.Replace("<" + oldTable, "\r\n<" + oldTable);

                fixedXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
                                  "<" + rootAttr + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
                                  contents + "\r\n</" + rootAttr + ">";

                string fixedPath = fullPath + ".fixed.xml";
                File.WriteAllText(fixedPath, fixedXml);
            }
            else
            {
                fixedXml = contents;
            }

            MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(fixedXml));
            return memoryStream;
        }

        public static void CreateObfuscationDestination (string fileLocation)
        {
            Directory.CreateDirectory(fileLocation);
        }

        public static FileStream GetObfuscationDestination(string xmlFileName, string fileLocation)
        {
            string destinationPath = fileLocation + Path.DirectorySeparatorChar + xmlFileName;
            FileStream fs = new FileStream(destinationPath, FileMode.Create, FileAccess.Write);
            return fs;
        }

        /// <summary>
        /// Given a userString like: "Espey, Carol (IDIR\cespey)" - frmat the user and add the user if no in the database
        /// Return the user or a default system user called "SYSTEM_HETS" as smSystemId
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="userString"></param>
        /// <param name="smSystemId"></param>
        /// <returns></returns>
        public static User AddUserFromString(DbAppContext dbContext, string userString, string smSystemId)
        {
            // find the smUserId for the <Modified_By>
            int index;

            try
            {
                index = userString.IndexOf(@"(IDIR\", StringComparison.Ordinal);
            }
            catch
            {
                return dbContext.Users.FirstOrDefault(x => string.Equals(x.SmUserId, smSystemId, StringComparison.OrdinalIgnoreCase));
            }

            if (index >= 0)
            {
                try
                {
                    int commaPos = userString.IndexOf(@",", StringComparison.Ordinal);
                    int leftBreakPos = userString.IndexOf(@"(", StringComparison.Ordinal);
                    int startPos = userString.IndexOf(@"\", StringComparison.Ordinal);
                    int rightBreakPos = userString.IndexOf(@")", StringComparison.Ordinal);
                    string surName = userString.Substring(0, commaPos).Trim();
                    string givenName = userString.Substring(commaPos + 2, leftBreakPos - commaPos - 2).Trim();
                    string smUserId = userString.Substring(startPos + 1, rightBreakPos - startPos - 1).Trim().ToLower();

                    User user = dbContext.Users.FirstOrDefault(x => string.Equals(x.SmUserId, smUserId, StringComparison.OrdinalIgnoreCase));

                    if (user == null)
                    {
                        // always add as inactive!
                        user = new User
                        {
                            Surname = surName,
                            GivenName = givenName,
                            SmUserId = smUserId,
                            Active = false,
                            AppCreateTimestamp = DateTime.UtcNow,
                            AppCreateUserid = smSystemId,
                            AppLastUpdateTimestamp = DateTime.UtcNow,
                            AppLastUpdateUserid = smSystemId
                        };

                        dbContext.Users.Add(user);
                        dbContext.SaveChangesForImport();
                    }
                    else if (user.Surname == null && surName.Length >= 1)
                    {
                        user.Surname = surName;
                        user.GivenName = givenName;
                        user.AppLastUpdateTimestamp = DateTime.UtcNow;
                        user.AppLastUpdateUserid = smSystemId;

                        dbContext.Users.Update(user);
                    }

                    return user;
                }
                catch
                {
                    return dbContext.Users.FirstOrDefault(x => x.SmUserId == smSystemId);
                }
            }

            return dbContext.Users.FirstOrDefault(x => x.SmUserId == smSystemId);
        }

        /// <summary>
        /// Add a user with smUserId as systemId if not in the database
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="systemId"></param>
        public static void InsertSystemUser(DbAppContext dbContext, string systemId)
        {
            try
            {
                User sysUser = dbContext.Users.FirstOrDefault(x => x.SmUserId == systemId);

                if (sysUser == null)
                {
                    sysUser = new User
                    {
                        SmUserId = systemId,
                        Surname = "System",
                        GivenName = "HETS",
                        Initials = "SH",
                        Active = true,
                        AppCreateTimestamp = DateTime.UtcNow,
                        AppLastUpdateTimestamp = DateTime.UtcNow,
                        AppCreateUserid = systemId,
                        AppLastUpdateUserid = systemId
                    };

                    dbContext.Users.Add(sysUser);
                    dbContext.SaveChangesForImport();
                }
            }
            catch
            {
                // do nothing
            }
        }

        public static DateTime? CleanDateTime(string dateTimeField)
        {
            if (dateTimeField != null && dateTimeField != "1900-01-01T00:00:00")
            {
                dateTimeField = dateTimeField.Trim();

                if (dateTimeField.Length >= 10)
                {
                    return DateTime.ParseExact(dateTimeField.Substring(0, 10), "yyyy-MM-dd", CultureInfo.InvariantCulture);
                }
            }

            return null;
        }

        public static float? GetFloatValue(string floatField)
        {
            if (!string.IsNullOrEmpty(floatField))
            {
                floatField = floatField.Trim();

                if (float.TryParse(floatField, out float temp))
                {
                    return temp;
                }
            }

            return null;
        }

        public static int? GetIntValue(string intField)
        {
            if (!string.IsNullOrEmpty(intField))
            {
                intField = intField.Trim();

                if (int.TryParse(intField, out int temp))
                {
                    return temp;
                }
            }

            return null;
        }

        public static string CleanString(string textField)
        {
            if (textField == null) { return ""; }

            string temp = textField.Trim().ToLower();
            temp = temp.Replace(@"#x0d;", "");
            temp = temp.Replace(@"#x20;", "");
            temp = temp.Replace(@"amp;", "&");
            temp = temp.Replace("unknown", "");
            temp = temp.Replace(@"?", "");

            return temp;
        }

        public static string GetCapitalCase(string textField)
        {
            return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(textField.ToLower());
        }

        public static string GetUppercaseFirst(string textField)
        {
            if (string.IsNullOrEmpty(textField))
            {
                return string.Empty;
            }

            char[] a = textField.ToCharArray();
            a[0] = char.ToUpper(a[0]);

            // check if we have any periods (".")
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] == '.' && i < a.Length - 1)
                {
                    a[i + 1] = char.ToUpper(a[0]);
                }
            }

            // return result
            return new string(a);
        }

        // assumes name is broken up by a specific seperator type (e.g. " ")
        public static string GetNamePart(string fullName, int part, string seperator = " ")
        {
            string[] nameParts = fullName.Split(seperator);

            string tempNamePart = "";

            if (nameParts.Length >= part)
            {
                tempNamePart = nameParts[part - 1].Trim();
                return GetCapitalCase(tempNamePart);
            }

            return tempNamePart;
        }

        public static string FormatPhone(string countryCode, string areaCode, string number, string extension)
        {
            string tempNumber = "";

            // ignoring country code - no room in the database (can add back after switch to new db model)
            areaCode = CleanString(areaCode).ToLower();
            number = CleanString(number).ToLower();
            extension = CleanString(extension).ToLower();

            if (!string.IsNullOrEmpty(areaCode))
            {
                areaCode = areaCode.Replace("(", "");
                areaCode = areaCode.Replace(")", "");

                tempNumber = areaCode;
            }

            if (!string.IsNullOrEmpty(number))
            {
                number = number.Replace("-", "");
                number = number.Replace(" ", "");

                bool parseNumebr = Int32.TryParse(number, out int numberInt);

                if (parseNumebr)
                {
                    number = string.Format("{0:###-####}", numberInt);
                }
                else if (number.Length == 7)
                {
                    string temp1 = number.Substring(0, 3);
                    string temp2 = number.Substring(3, 4);
                    number = temp1 + "-" + temp2;
                }

                if (!string.IsNullOrEmpty(tempNumber))
                {
                    tempNumber = tempNumber + "-" + number;
                }
                else
                {
                    tempNumber = number;
                }
            }

            if (!string.IsNullOrEmpty(extension))
            {
                extension = extension.Replace("x", "");
                extension = extension.Replace("ext.", "");
                extension = extension.Replace("ext", "");
                extension = "x" + extension;

                if (!string.IsNullOrEmpty(tempNumber))
                {
                    tempNumber = tempNumber + " " + extension;
                }
                else
                {
                    tempNumber = extension;
                }
            }

            return tempNumber;
        }

        public static void UnknownElement(object sender, XmlElementEventArgs e)
        {
            Console.WriteLine("Unexpected element: {0} as line {1}, column {2}", e.Element.Name, e.LineNumber, e.LinePosition);
        }

        public static void UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
            Console.WriteLine("Unexpected attribute: {0} as line {1}, column {2}", e.Attr.Name, e.LineNumber, e.LinePosition);
        }

        // string scramble function from https://www.codeproject.com/Articles/820667/Sample-code-to-scramble-a-Word-using-Csharp-String

        /// <summary>
        /// Scramble a String
        /// </summary>
        /// <param name="input">A string</param>
        /// <returns>The string scrambled</returns>
        public static string ScrambleString (string input)
        {
            if (input != null)
            {
                char[] chars = new char[input.Length];
                Random rand = new Random(10000);
                int index = 0;

                while (input.Length > 0)
                {
                    // get a random number between 0 and the length of the word.
                    int next = rand.Next(0, input.Length - 1); // Take the character from the random position
                                                               // and add to our char array.
                    chars[index] = input[next];                // Remove the character from the word.
                    input = input.Substring(0, next) + input.Substring(next + 1);
                    ++index;
                }

                return new String(chars);
            }

            return null;
        }

        public static void WriteImportRecordsToExcel (string destinationLocation, List<ImportMapRecord> records, string tableName)
        {

            using (var fs = new FileStream(Path.Combine(destinationLocation, tableName + ".xlsx"), FileMode.Create, FileAccess.Write))
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet excelSheet = workbook.CreateSheet(tableName + " Map");

                // Create the header row.
                IRow row = excelSheet.CreateRow(0);
                row.CreateCell(0).SetCellValue("Table Name");
                row.CreateCell(1).SetCellValue("Mapped Column");
                row.CreateCell(2).SetCellValue("Original Value");
                row.CreateCell(3).SetCellValue("New Value");

                // use the import class to get data.
                int currentRow = 1;

                // convert the list to an excel spreadsheet.
                foreach (ImportMapRecord record in records)
                {
                    IRow newRow = excelSheet.CreateRow(currentRow);
                    newRow.CreateCell(0).SetCellValue(record.TableName);
                    newRow.CreateCell(1).SetCellValue(record.MappedColumn);
                    newRow.CreateCell(2).SetCellValue(record.OriginalValue);
                    newRow.CreateCell(3).SetCellValue(record.NewValue);
                    currentRow++;
                }

                workbook.Write(fs);
            }
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  An Integrated Approach to Understanding and Reducing Fat, Oil, and Grease (FOG) Deposit Formation for Sustainable Sewer Collection Systems|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2009-08-10" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Project Research Results

2013 Progress Report

2012 Progress Report

2010 Progress Report

                      21 publications for this project

                        4 journal articles for this project

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      An Integrated Approach to Understanding and Reducing Fat, Oil, and Grease (FOG) Deposit Formation for Sustainable Sewer Collection Systems

    EPA Grant Number: R834264

    Title: An Integrated Approach to Understanding and Reducing Fat, Oil, and Grease (FOG) Deposit Formation for Sustainable Sewer Collection Systems

    Investigators:
     Ducoste, Joel

    Institution:

      North Carolina State University

    	EPA Project Officer:

           Page, Angela

      Project Period:
      August 1, 2009 through
        July 31, 2012
          (Extended to July 31, 2014)

        Project Amount:

          $569,568

      RFA:
      Innovative and Integrative Approaches for Advancing Public Health Protection Through Water Infrastructure Sustainability (2008)

        		RFA Text |
          Recipients Lists

      Research Category:

          Pollution Prevention/Sustainable Development
          ,
          Sustainability
          ,
          Water

Objective:

The proposed project seeks to understand and reduce the formation of FOG deposits that lead to environmentally detrimental SSOs in sewer collection systems by achieving the following objectives: a) perform detailed bench scale tests that attempt to recreate FOG deposits and determine parameters that significantly influence their formation rate, b) perform bench scale tests to explore treatment options that improve FOG deposit chemical precursor removal with grease interceptors, c) perform pilot scale experiments on a continuous flow sewer collection system that characterizes spatial variations in FOG deposit formation, and d) develop a model to predict FOG deposit formation in sewer collection systems.

Approach:

The proposed project approach involves several tasks to achieve these objectives. Tasks associated with objective (a) include: initiating saponification reactions with different concentrations of oils and fats over a range of temperatures, pH, calcium concentrations, and mixing intensities and assess the physical and chemical characteristics of the metal soap formed. The data will then be used to develop a FOG deposit kinetics model. Tasks associated with objective (b) will consist of performing jar tests on restaurant waste streams using metal coagulants and polymers at different concentrations over a range of pH. Finally, tasks associated with Objectives (c) and (d) will measure the amount of FOG deposits formed at different locations in a pilot sewer collection system. The data from pilot tests will then be used to validate a model that predicts FOG deposit formation in sewer collection systems.

Expected Results:

The results of the proposed study are expected to provide new tools to assist utilities in meeting CWA requirements and provide better management of sewer collection systems. The sewer collection system model along with better knowledge of what influences and reduces the FOG deposit formation rate will help utilities and design engineers assess the impact of new residential and commercial development on existing and future sewer infrastructure and the potential for FOG related SSOs.

Publications and Presentations:

        Publications have been submitted on this project: View all 21 publications for this project

Journal Articles:

          Journal Articles have been submitted on this project: View all 4 journal articles for this project

Supplemental Keywords:

      Wastewater, treatment, separation, engineering, modeling, pollution prevention, sewer collection system, SSO, FOG, chemical transport,

Progress and Final Reports:

                2010 Progress Report

                2012 Progress Report

                2013 Progress Report

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Monday, August 10, 2009


text:
{% extends "../question.html" %}

{% block content %}

    <form method="post">

      {{ govukRadios({
        idPrefix: "residence-sticker-issued",
        name: type + "[residenceStickerIssued]",
        fieldset: {
          legend: {
            text: "Where was the document issued?",
            isPageHeading: true,
            classes: "govuk-fieldset__legend--l"
          }
        },
        items: [
          {
            value: "croydon",
            text: "Croydon",
            checked: checked("['" + type + "'].residenceStickerIssued", "croydon")
          },
          {
            value: "liverpool",
            text: "Liverpool",
            checked: checked("['" + type + "'].residenceStickerIssued", "liverpool")
          },
          {
            value: "sheffield",
            text: "Sheffield",
            checked: checked("['" + type + "'].residenceStickerIssued", "sheffield")
          },
          {
            divider: "or"
          },
          {
            value: "none",
            text: "None of the above",
            checked: checked("['" + type + "'].residenceStickerIssued", "none")
          }
        ]
      }) }}

      {{ govukButton({
        text: "Continue"
      }) }}

    </form>

        Example of where these words can be found

{% endblock %}


text:
package v1beta1

import (
	"testing"

	"github.com/google/go-cmp/cmp"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/kube-scheduler/config/v1beta1"
	"k8s.io/kubernetes/pkg/scheduler/apis/config"
	"k8s.io/utils/pointer"
)

func TestV1beta1ToConfigKubeSchedulerConfigurationConversion(t *testing.T) {
	cases := []struct {
		name   string
		config v1beta1.KubeSchedulerConfiguration
		want   config.KubeSchedulerConfiguration
	}{
		{
			name:   "default conversion v1beta1 to config",
			config: v1beta1.KubeSchedulerConfiguration{},
			want:   config.KubeSchedulerConfiguration{AlgorithmSource: config.SchedulerAlgorithmSource{Provider: pointer.StringPtr(v1beta1.SchedulerDefaultProviderName)}},
		},
	}

	scheme := runtime.NewScheme()
	if err := AddToScheme(scheme); err != nil {
		t.Fatal(err)
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			var got config.KubeSchedulerConfiguration
			if err := scheme.Convert(&tc.config, &got, nil); err != nil {
				t.Errorf("failed to convert: %+v", err)
			}
			if diff := cmp.Diff(tc.want, got); diff != "" {
				t.Errorf("unexpected conversion (-want, +got):\n%s", diff)
			}
		})
	}
}


text:
WhosDown is an open-source Windows 10 client for WhatsApp.  More specifically, it's a wrapper for WhatsApp Web.

## Why would I want to use this?

WhosDown provides several advantages over just using web.whatsapp.com in your browser.

1. Windows Action Center notifications on unread messages.
2. Minimal window chrome.
3. A WhatsApp-like color theme.
4. Can easily be pinned to taskbar or start menu.

## Where can I get it?

It's [right here in the Windows Store](https://www.microsoft.com/store/apps/9NBLGGH5G8JS).

## I have a problem or idea!

Great!  [Create an issue](https://github.com/CamSoper/WhosDown/issues), or, better yet, fork the project and contribute!  I'm not much of an app developer (I'm more of a web guy, and I'm way out of my element with XAML...  I didn't even *attempt* MVVM!) so I appreciate whatever you want to add.


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\TranslateBundle\Entity;

/**
 * Location.
 */
class Location
{
    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $name;

    /**
     * @var \Sulu\Bundle\TranslateBundle\Entity\Package
     */
    private $package;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $codes;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->codes = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name.
     *
     * @param string $name
     *
     * @return Location
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set package.
     *
     * @param \Sulu\Bundle\TranslateBundle\Entity\Package $package
     *
     * @return Location
     */
    public function setPackage(\Sulu\Bundle\TranslateBundle\Entity\Package $package)
    {
        $this->package = $package;

        return $this;
    }

    /**
     * Get package.
     *
     * @return \Sulu\Bundle\TranslateBundle\Entity\Package
     */
    public function getPackage()
    {
        return $this->package;
    }

    /**
     * Add codes.
     *
     * @param \Sulu\Bundle\TranslateBundle\Entity\Code $codes
     *
     * @return Location
     */
    public function addCode(\Sulu\Bundle\TranslateBundle\Entity\Code $codes)
    {
        $this->codes[] = $codes;

        return $this;
    }

    /**
     * Remove codes.
     *
     * @param \Sulu\Bundle\TranslateBundle\Entity\Code $codes
     */
    public function removeCode(\Sulu\Bundle\TranslateBundle\Entity\Code $codes)
    {
        $this->codes->removeElement($codes);
    }

    /**
     * Get codes.
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCodes()
    {
        return $this->codes;
    }
}


text:
'use strict';

let React;
let ReactNative;
let createReactNativeComponentClass;
let computeComponentStackForErrorReporting;

function normalizeCodeLocInfo(str) {
  return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
}

describe('ReactNativeError', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNative = require('react-native-renderer');
    createReactNativeComponentClass = require('ReactNativeViewConfigRegistry')
      .register;
    computeComponentStackForErrorReporting =
      ReactNative.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        .computeComponentStackForErrorReporting;
  });

  it('should be able to extract a component stack from a native view', () => {
    const View = createReactNativeComponentClass('View', () => ({
      validAttributes: {foo: true},
      uiViewClassName: 'View',
    }));

    const ref = React.createRef();

    function FunctionalComponent(props) {
      return props.children;
    }

    class ClassComponent extends React.Component {
      render() {
        return (
          <FunctionalComponent>
            <View foo="test" ref={ref} />
          </FunctionalComponent>
        );
      }
    }

    ReactNative.render(<ClassComponent />, 1);

    let reactTag = ReactNative.findNodeHandle(ref.current);

    let componentStack = normalizeCodeLocInfo(
      computeComponentStackForErrorReporting(reactTag),
    );

    if (__DEV__) {
      expect(componentStack).toBe(
        '\n' +
          '    in View (at **)\n' +
          '    in FunctionalComponent (at **)\n' +
          '    in ClassComponent (at **)',
      );
    } else {
      expect(componentStack).toBe(
        '\n' +
          '    in View\n' +
          '    in FunctionalComponent\n' +
          '    in ClassComponent',
      );
    }
  });
});


text:
require "librarian/resolver"
require "librarian/spec_change_set"
require "librarian/action/base"
require "librarian/action/persist_resolution_mixin"

module Librarian
  module Action
    class Resolve < Base
      include PersistResolutionMixin

      def run
        if force? || !lockfile_path.exist?
          spec = specfile.read
          manifests = []
        else
          lock = lockfile.read
          spec = specfile.read(lock.sources)
          changes = spec_change_set(spec, lock)
          if changes.same?
            debug { "The specfile is unchanged: nothing to do." }
            return
          end
          manifests = changes.analyze
        end

        spec.dependencies, duplicated = Dependency.remove_duplicate_dependencies(spec.dependencies)
        duplicated.each do |name, dependencies_same_name|
          environment.logger.info { "Dependency '#{name}' duplicated for module, merging: #{dependencies_same_name.map{|d| d.to_s}}" }
        end

        resolution = resolver.resolve(spec, manifests)
        persist_resolution(resolution)
        resolution
      end

    private

      def force?
        options[:force]
      end

      def resolver
        Resolver.new(environment)
      end

      def spec_change_set(spec, lock)
        SpecChangeSet.new(environment, spec, lock)
      end

    end
  end
end


text:
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width initial-scale=1">

  <!-- Favicon -->
  <link rel="shortcut icon" type="image/png" href="{{ site.favicon }}"/>

  <!-- Title -->
  <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %} • {{ site.description }}</title>

  <!-- Stylesheet -->
  <link rel="stylesheet" type="text/css" href="{% if site.baseurl %}{{ site.baseurl }}{% endif %}/assets/css/main.css">

  <!-- Author -->
  <link rel="author" href="https://plus.google.com/+{{ site.googleplus_username }}"/>

  <!-- Feed -->
  <link rel="alternate" type="application/atom+xml" title="{{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}" />

  <!-- Meta -->
  <meta name="generator" content="Jekyll v{{ site.version }}" />
  <meta name="author" content="{{ site.author.name }}" />
  <meta name="description" content="{% if page.description %}{{ page.description }}{% else %}{{ site.description }}{% endif%}" />
  <link rel="canonical" href="{{ site.url }}{% if page.url %}{{ page.url }}{% endif %}" />

  <!-- Open Graph -->
  <meta property="og:title" content="{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}" />
  <meta property="og:description" content="{% if page.description %}{{ page.description }}{% else %}{{ site.description }}{% endif%}" />
  <meta property="og:url" content="{{ site.url }}{% if page.url %}{{ page.url }}{% endif %}" />
  <meta property="og:site_name" content="{{ site.title }}" />
  <meta property="og:image" content="{{ site.url }}{% if page.image.path %}{{ page.image.path }}{% else %}/assets/images/theme/blog-cover.jpg{% endif %}" />
  <meta property="og:image:alt" content="{% if page.image.alt %}{{ page.image.alt }}{% else %}Duas estantes fixadas na parede com objetos em cima, como vasos de planta e uma câmera. No canto inferior direito há uma mesa com um iMac, um pote com lápis, livros e um grampeador.{% endif %}">
  <meta property="og:locale" content="{{ site.lang }}" />
  <meta property="og:type" content="{% if page.url == '/' %}website{% else %}article{% endif %}">

  <!-- Twitter Cards -->
  <meta name="twitter:card" content="{{ site.twitter.card }}" />
  <meta name="twitter:site" content="{{ site.twitter.username }}" />
  <meta name="twitter:creator" content="{{ site.twitter.username }}" />

  <!-- Search Verification Code -->
  <meta name="google-site-verification" content="{{ site.webmaster.google }}" />
  <meta name="msvalidate.01" content="{{ site.webmaster.bing}}" />
  <meta name="yandex-verification" content="{{ site.webmaster.yandex }}" />

  <!-- Structured Data -->
  <script type="application/ld+json">
    {% if page.layout == "page" %}
      {
        "@context": "http://schema.org",
        "@type": "WebPage",
        "headline": "{{ page.title }}",
        "description": "{{ page.description }}",
        "publisher": {
          "@type": "Organization",
          "name": "{{ site.title }}",
          "logo": {
            "@type": "ImageObject",
            "url": "{{ site.url }}{{ site.logo }}",
            "name": "{{ site.title }}"
          }
        },
        "url": "{{ site.url }}{{ page.url }}"
      }
    {% elsif page.layout == "post" or page.layout == "portfolio" or page.layout == "poemas" %}
      {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "{{ page.title }}",
        "mainEntityOfPage": {
          "@type": "WebPage",
          "@id": "{{ site.url }}{{ page.url }}"
        },
        "image": {
          "@type": "ImageObject",
          "url": "{{ site.url }}{{ page.image.path }}",
          "name": "{{ page.image.alt }}"
        },
        "datePublished": "{{ page.date }}",
        "dateModified": "{{ page.date }}",
        "description": "{{ page.description }}",
        "url": "{{ site.url }}{{ page.url }}",
        "publisher": {
          "@type": "Organization",
          "name": "{{ site.title }}",
          "logo": {
            "@type": "ImageObject",
            "url": "{{ site.url }}{{ site.logo }}",
            "name": "{{ site.title }}"
          }
        },
        "author": {
          "@type": "Person",
          "name": "{{ site.author.name }}",
          "sameAs": [
            "https://twitter.com/{{ site.twitter_username }}",
            "https://instagram.com/{{ site.instagram_username }}",
            "https://www.linkedin.com/in/{{ site.linkedin_username }}",
            "https://youtube.com/{{ site.youtube_username }}",
            "https://pinterest.com/{{ site.pinterest_username }}"
          ]
        }
      }
    {% elsif page_layout == "default" or page.url == "/" %}
      {
        "@context": "http://schema.org",
        "@type": "WebSite",
        "name": "{{ site.title }}",
        "headline": "{{ site.title }}",
        "image": "{{ site.url }}{{ site.image }}",
        "description": "{{ site.description }}",
        "publisher": {
          "@type": "Organization",
          "name": "{{ site.title }}",
          "logo": {
            "@type": "ImageObject",
            "url": "{{ site.url }}{{ site.logo }}",
            "name": "{{ site.title }}"
          }
        },
        "url": "{{ site.url }}"
      }
    {% endif %}
  </script>
</head>


text:
package io.cloudslang.runtime.impl.python.external;

public class ExternalPythonScriptException extends RuntimeException {
    ExternalPythonScriptException(String message) {
        super(message);
    }
}