text:
// Copyright (c) 2013-2014 Peter Meyers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//  PMCollectionViewSwipeCell.h
//  Created by Peter Meyers on 8/21/14.
//
//

#import <UIKit/UIKit.h>
#import "PMSwipeCellDelegate.h"

@interface PMCollectionViewSwipeCell : UICollectionViewCell

/**
 *  A boolean value that controls whether the swiping functionality provided by this class is enabled.
 */
@property (nonatomic) BOOL swipeEnabled;

/**
 *  The view that sits below the content view when the content view is swipped right. The view sits in the coordinate system
 *	system of the cell. A common use of a utility view is a button which commits some action related to the cell, such as deleting
 *	it from the collection view.
 */
@property (nonatomic, strong) UIView *leftUtilityView;

/**
 *  The view that sits below the content view when the content view is swipped left. The view sits in the coordinate system
 *	system of the cell. A common use of a utility view is a button which commits some action related to the cell, such as deleting
 *	it from the collection view.
 */
@property (nonatomic, strong) UIView *rightUtilityView;

/**
 *  The object that acts as the delegate of the swipe cell. The delegate must adopt
 *	the PMCollectionViewSwipeCellDelegate protocol. The collection view maintains a weak reference to the delegate object.
 */
@property (nonatomic, weak) id<PMSwipeCellDelegate> delegate;

/**
 *  A Boolean value that controls whether the content view bounces past the right edge of the left utility view
 *	when swiping right, or the left edge of the right utility view when swiping left. Bouncing visually indicates that
 *	scrolling has reached an edge of the content. The default value is YES.
 */
@property (nonatomic) BOOL bouncesOpen;

/**
 *  The position of the content view. The content view is considered PMCellPositionCentered if its frame's
 *	origin is at (0,0) in the cell's cordinate system. A utility view is considered visible once it is completely visible.
 *	This property only changes once the cell is done transitioning to a new position.
 */
@property (nonatomic) PMCellPosition cellPosition;

/**
 *  Scrolls the content view to a position, allowing the scroll to animate.
 *
 *  @param position The position of the content view. The content view is considered PMCellPositionCentered if its frame's
 *	origin is at (0,0) in the cell's cordinate system.
 *  @param animated A flag indicating whether the transition to the new position should be animated.
 */
- (void) setCellPosition:(PMCellPosition)position animated:(BOOL)animated;

@end


text:
"""Application wrapper.

Use this script to run an instance of the app.
"""

import tornado.ioloop
from config import app_config
from optparse import OptionParser
from iheartgit.app import create_app

app = create_app(app_config)

if __name__ in ('main', '__main__'):
    parser = OptionParser()
    parser.add_option('-p', '--port', dest="port", help="port to bind to. Defaults to 8888.", action="store", type="int", default=8888)
    options, args = parser.parse_args()

    app.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

redpajama_set_name: RedPajamaGithub


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu_switch_mode"
        android:icon="@drawable/ic_action_turn_right"
        android:orderInCategory="115"
        android:showAsAction="ifRoom|withText"
        android:title="@string/menu_switch_mode" />

</menu>


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public ContentTypeBinding[] ContentTypeBindings { get; set; }
```

### Property Value
Type: [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.ContentTypeBinding[]](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.ContentTypeBinding.md)

## See also
- [ListInstance](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.ListInstance.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.md)


text:
cd $(pwd)/dbs/postgres/

echo "Executing query and insert script for version : $1"

name="$(basename $1)"

if [[ "$name" = hive-schema* ]]
then
  FROM_VER=`echo $name | cut -d'-' -f3 | sed -e 's/\.postgres.sql//g'`
  SCRIPT_INSERT="postgres-$FROM_VER-insert.sql"
else
  FROM_VER=`echo $name | cut -d'-' -f2`
  TO_VER=`echo $name | cut -d'-' -f4 | sed -e 's/\.postgres.sql//g'`
  SCRIPT_INSERT="postgres-$TO_VER-insert.sql"
  SCRIPT_QUERY="postgres-$FROM_VER-query.sql"
  QUERY_RESULT="postgres-$FROM_VER-results.txt"
fi

export PGPASSWORD=hivepw
if [[ -z "${SCRIPT_QUERY+x}" ]]
then
  echo "Nothing to query"
else
  echo "Test query script is $SCRIPT_QUERY"
  if [[ -e "$SCRIPT_QUERY" ]]
  then
    if [[ -e "$QUERY_RESULT" ]]
    then
      rm $QUERY_RESULT
    fi

    psql -h localhost -U hiveuser -d hive_hms_testing -f "$(pwd)/$SCRIPT_QUERY" -o "$(pwd)/$QUERY_RESULT"

    failures=`awk '/count/{nr[NR]; nr[NR+2]}; NR in nr' "$QUERY_RESULT" | grep "  0" | wc -l`
    if [[ "$failures" -ne 0 ]]
    then
      echo "***** FAILED ($failures failed queries) *******"
      echo "Check $(pwd)/$QUERY_RESULT for results of the test query"
      echo `awk '/SELECT\ COUNT/{nr[NR]; nr[NR+2]}; NR in nr' "$QUERY_RESULT" | grep -B 1 "  0"`
      exit 1
    fi

  else
    echo "$SCRIPT_QUERY does not exist, skipping ..."
  fi
fi

echo "Test insert script is $SCRIPT_INSERT"
if [[ -e "$SCRIPT_INSERT" ]]
then
  psql -h localhost -U hiveuser -d hive_hms_testing -f "$(pwd)/$SCRIPT_INSERT"
else
  echo "$SCRIPT_INSERT does not exist, skipping ..."
fi


text:
<?xml version='1.0' encoding='utf-8' ?>
<tocdata>
<item name="Problem List" url="Problem_List.htm" />
<item name="Customizing the Problem List" url="Problems_Customizing_the_Problems_List.htm" />
<item name="Adding a Problem" url="Adding_a_Problem.htm" />
<item name="Annotating a Problem" url="Annotating_a_Problem.htm" />
<item name="Changing a Problem" url="Changing_a_Problem.htm" />
<item name="Verifying a Problem" url="Verifying_a_Problem.htm" />
<item name="Making a Problem Inactive" url="Making_a_Problem_Inactive.htm" />
<item name="Removing a Problem" url="Removing_a_Problem.htm" />
<item name="Customizing the Problems List" url="Problems_Customizing_the_Problems_List.htm#bc-1" />

</tocdata>


text:
from future.utils import native

import flask_login
from flask_login import login_required, current_user, logout_user
from flask import flash
from wtforms import (
    Form, PasswordField, StringField)
from wtforms.validators import InputRequired

from ldap3 import Server, Connection, Tls, LEVEL, SUBTREE, BASE
import ssl

from flask import url_for, redirect

from airflow import models
from airflow import configuration
from airflow.configuration import AirflowConfigException
from airflow.utils.db import provide_session

import traceback
import re

from airflow.utils.log.logging_mixin import LoggingMixin

login_manager = flask_login.LoginManager()
login_manager.login_view = 'airflow.login'  # Calls login() below
login_manager.login_message = None

log = LoggingMixin().log

class AuthenticationError(Exception):
    pass

class LdapException(Exception):
    pass

def get_ldap_connection(dn=None, password=None):
    tls_configuration = None
    use_ssl = False
    try:
        cacert = configuration.conf.get("ldap", "cacert")
        tls_configuration = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=cacert)
        use_ssl = True
    except:
        pass

    server = Server(configuration.conf.get("ldap", "uri"), use_ssl, tls_configuration)
    conn = Connection(server, native(dn), native(password))

    if not conn.bind():
        log.error("Cannot bind to ldap server: %s ", conn.last_error)
        raise AuthenticationError("Cannot bind to ldap server")

    return conn

def group_contains_user(conn, search_base, group_filter, user_name_attr, username):
    search_filter = '(&({0}))'.format(group_filter)

    if not conn.search(native(search_base), native(search_filter),
                       attributes=[native(user_name_attr)]):
        log.warning("Unable to find group for %s %s", search_base, search_filter)
    else:
        for entry in conn.entries:
            if username.lower() in map(lambda attr: attr.lower(),
                                       getattr(entry, user_name_attr).values):
                return True

    return False

def groups_user(conn, search_base, user_filter, user_name_att, username):
    search_filter = "(&({0})({1}={2}))".format(user_filter, user_name_att, username)
    try:
        memberof_attr = configuration.conf.get("ldap", "group_member_attr")
    except:
        memberof_attr = "memberOf"
    res = conn.search(native(search_base), native(search_filter),
                      attributes=[native(memberof_attr)])
    if not res:
        log.info("Cannot find user %s", username)
        raise AuthenticationError("Invalid username or password")

    if conn.response and memberof_attr not in conn.response[0]["attributes"]:
        log.warning("""Missing attribute "%s" when looked-up in Ldap database.
        The user does not seem to be a member of a group and therefore won't see any dag
        if the option filter_by_owner=True and owner_mode=ldapgroup are set""",
                    memberof_attr)
        return []

    user_groups = conn.response[0]["attributes"][memberof_attr]

    regex = re.compile("cn=([^,]*).*", re.IGNORECASE)
    groups_list = []
    try:
        groups_list = [regex.search(i).group(1) for i in user_groups]
    except IndexError:
        log.warning("Parsing error when retrieving the user's group(s)."
                    " Check if the user belongs to at least one group"
                    " or if the user's groups name do not contain special characters")

    return groups_list

class LdapUser(models.User):
    def __init__(self, user):
        self.user = user
        self.ldap_groups = []

        # Load and cache superuser and data_profiler settings.
        conn = get_ldap_connection(configuration.conf.get("ldap", "bind_user"),
                                   configuration.conf.get("ldap", "bind_password"))

        superuser_filter = None
        data_profiler_filter = None
        try:
            superuser_filter = configuration.conf.get("ldap", "superuser_filter")
        except AirflowConfigException:
            pass

        if not superuser_filter:
            self.superuser = True
            log.debug("Missing configuration for superuser settings or empty. Skipping.")
        else:
            self.superuser = group_contains_user(conn,
                                                 configuration.conf.get("ldap", "basedn"),
                                                 superuser_filter,
                                                 configuration.conf.get("ldap",
                                                                        "user_name_attr"),
                                                 user.username)

        try:
            data_profiler_filter = configuration.conf.get("ldap", "data_profiler_filter")
        except AirflowConfigException:
            pass

        if not data_profiler_filter:
            self.data_profiler = True
            log.debug("Missing configuration for data profiler settings or empty. "
                      "Skipping.")
        else:
            self.data_profiler = group_contains_user(
                conn,
                configuration.conf.get("ldap", "basedn"),
                data_profiler_filter,
                configuration.conf.get("ldap",
                                       "user_name_attr"),
                user.username
            )

        # Load the ldap group(s) a user belongs to
        try:
            self.ldap_groups = groups_user(
                conn,
                configuration.conf.get("ldap", "basedn"),
                configuration.conf.get("ldap", "user_filter"),
                configuration.conf.get("ldap", "user_name_attr"),
                user.username
            )
        except AirflowConfigException:
            log.debug("Missing configuration for ldap settings. Skipping")

    @staticmethod
    def try_login(username, password):
        conn = get_ldap_connection(configuration.conf.get("ldap", "bind_user"),
                                   configuration.conf.get("ldap", "bind_password"))

        search_filter = "(&({0})({1}={2}))".format(
            configuration.conf.get("ldap", "user_filter"),
            configuration.conf.get("ldap", "user_name_attr"),
            username
        )

        search_scope = LEVEL
        if configuration.conf.has_option("ldap", "search_scope"):
            if configuration.conf.get("ldap", "search_scope") == "SUBTREE":
                search_scope = SUBTREE
            else:
                search_scope = LEVEL

        # todo: BASE or ONELEVEL?

        res = conn.search(native(configuration.conf.get("ldap", "basedn")),
                          native(search_filter),
                          search_scope=native(search_scope))

        # todo: use list or result?
        if not res:
            log.info("Cannot find user %s", username)
            raise AuthenticationError("Invalid username or password")

        entry = conn.response[0]

        conn.unbind()

        if 'dn' not in entry:
            # The search filter for the user did not return any values, so an
            # invalid user was used for credentials.
            raise AuthenticationError("Invalid username or password")

        try:
            conn = get_ldap_connection(entry['dn'], password)
        except KeyError:
            log.error("""
            Unable to parse LDAP structure. If you're using Active Directory
            and not specifying an OU, you must set search_scope=SUBTREE in airflow.cfg.
            %s
            """ % traceback.format_exc())
            raise LdapException(
                "Could not parse LDAP structure. "
                "Try setting search_scope in airflow.cfg, or check logs"
            )

        if not conn:
            log.info("Password incorrect for user %s", username)
            raise AuthenticationError("Invalid username or password")

    @property
    def is_active(self):
        """Required by flask_login"""
        return True

    @property
    def is_authenticated(self):
        """Required by flask_login"""
        return True

    @property
    def is_anonymous(self):
        """Required by flask_login"""
        return False

    def get_id(self):
        """Returns the current user id as required by flask_login"""
        return self.user.get_id()

    def data_profiling(self):
        """Provides access to data profiling tools"""
        return self.data_profiler

    def is_superuser(self):
        """Access all the things"""
        return self.superuser

@login_manager.user_loader
@provide_session
def load_user(userid, session=None):
    log.debug("Loading user %s", userid)
    if not userid or userid == 'None':
        return None

    user = session.query(models.User).filter(models.User.id == int(userid)).first()
    return LdapUser(user)

@provide_session
def login(self, request, session=None):
    if current_user.is_authenticated:
        flash("You are already logged in")
        return redirect(url_for('admin.index'))

    username = None
    password = None

    form = LoginForm(request.form)

    if request.method == 'POST' and form.validate():
        username = request.form.get("username")
        password = request.form.get("password")

    if not username or not password:
        return self.render('airflow/login.html',
                           title="Airflow - Login",
                           form=form)

    try:
        LdapUser.try_login(username, password)
        log.info("User %s successfully authenticated", username)

        user = session.query(models.User).filter(
            models.User.username == username).first()

        if not user:
            user = models.User(
                username=username,
                is_superuser=False)
            session.add(user)

        session.commit()
        session.merge(user)
        flask_login.login_user(LdapUser(user))
        session.commit()

        return redirect(request.args.get("next") or url_for("admin.index"))
    except (LdapException, AuthenticationError) as e:
        if type(e) == LdapException:
            flash(e, "error")
        else:
            flash("Incorrect login details")
        return self.render('airflow/login.html',
                           title="Airflow - Login",
                           form=form)

class LoginForm(Form):
    username = StringField('Username', [InputRequired()])
    password = PasswordField('Password', [InputRequired()])


text:
$(function () {

    var $commonHeader = $(".mobile-top-menu, .content-header");
    var $contentSection = $(".content-wrapper");

    var $mobileSideNav = $(".main-nav-m");
    var $navToggle = $(".ion-menu-icon, .ion-back-icon, .shadow");

    var lastScroll = 0;
    $contentSection.scroll(function () {
        var scrollTopPotision = $(this).scrollTop();
        if ((scrollTopPotision > lastScroll) && scrollTopPotision > $commonHeader.height()) {
            toggleHeader(true);
        } else {
            toggleHeader(false);
        }
        lastScroll = scrollTopPotision;
    });

    function toggleHeader(isSlideIn) {
        if (isSlideIn) {
            $commonHeader.addClass("slide-in");
            $commonHeader.removeClass("slide-out");
        } else {
            $commonHeader.addClass("slide-out");
            $commonHeader.removeClass("slide-in");
        }
    }
});


text:
#include <linux/module.h>
#include <linux/types.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/ethtool.h>
#include <linux/netdevice.h>
#include <asm/uaccess.h>

/*
 * Some useful ethtool_ops methods that're device independent.
 * If we find that all drivers want to do the same thing here,
 * we can turn these into dev_() function calls.
 */

u32 ethtool_op_get_link(struct net_device *dev)
{
	return netif_carrier_ok(dev) ? 1 : 0;
}

u32 ethtool_op_get_tx_csum(struct net_device *dev)
{
	return (dev->features & NETIF_F_ALL_CSUM) != 0;
}

int ethtool_op_set_tx_csum(struct net_device *dev, u32 data)
{
	if (data)
		dev->features |= NETIF_F_IP_CSUM;
	else
		dev->features &= ~NETIF_F_IP_CSUM;

	return 0;
}

int ethtool_op_set_tx_hw_csum(struct net_device *dev, u32 data)
{
	if (data)
		dev->features |= NETIF_F_HW_CSUM;
	else
		dev->features &= ~NETIF_F_HW_CSUM;

	return 0;
}
u32 ethtool_op_get_sg(struct net_device *dev)
{
	return (dev->features & NETIF_F_SG) != 0;
}

int ethtool_op_set_sg(struct net_device *dev, u32 data)
{
	if (data)
		dev->features |= NETIF_F_SG;
	else
		dev->features &= ~NETIF_F_SG;

	return 0;
}

u32 ethtool_op_get_tso(struct net_device *dev)
{
	return (dev->features & NETIF_F_TSO) != 0;
}

int ethtool_op_set_tso(struct net_device *dev, u32 data)
{
	if (data)
		dev->features |= NETIF_F_TSO;
	else
		dev->features &= ~NETIF_F_TSO;

	return 0;
}

int ethtool_op_get_perm_addr(struct net_device *dev, struct ethtool_perm_addr *addr, u8 *data)
{
	unsigned char len = dev->addr_len;
	if ( addr->size < len )
		return -ETOOSMALL;

	addr->size = len;
	memcpy(data, dev->perm_addr, len);
	return 0;
}

u32 ethtool_op_get_ufo(struct net_device *dev)
{
	return (dev->features & NETIF_F_UFO) != 0;
}

int ethtool_op_set_ufo(struct net_device *dev, u32 data)
{
	if (data)
		dev->features |= NETIF_F_UFO;
	else
		dev->features &= ~NETIF_F_UFO;
	return 0;
}

/* Handlers for each ethtool command */

static int ethtool_get_settings(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_cmd cmd = { ETHTOOL_GSET };
	int err;

	if (!dev->ethtool_ops->get_settings)
		return -EOPNOTSUPP;

	err = dev->ethtool_ops->get_settings(dev, &cmd);
	if (err < 0)
		return err;

	if (copy_to_user(useraddr, &cmd, sizeof(cmd)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_settings(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_cmd cmd;

	if (!dev->ethtool_ops->set_settings)
		return -EOPNOTSUPP;

	if (copy_from_user(&cmd, useraddr, sizeof(cmd)))
		return -EFAULT;

	return dev->ethtool_ops->set_settings(dev, &cmd);
}

static int ethtool_get_drvinfo(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_drvinfo info;
	const struct ethtool_ops *ops = dev->ethtool_ops;

	if (!ops->get_drvinfo)
		return -EOPNOTSUPP;

	memset(&info, 0, sizeof(info));
	info.cmd = ETHTOOL_GDRVINFO;
	ops->get_drvinfo(dev, &info);

	if (ops->self_test_count)
		info.testinfo_len = ops->self_test_count(dev);
	if (ops->get_stats_count)
		info.n_stats = ops->get_stats_count(dev);
	if (ops->get_regs_len)
		info.regdump_len = ops->get_regs_len(dev);
	if (ops->get_eeprom_len)
		info.eedump_len = ops->get_eeprom_len(dev);

	if (copy_to_user(useraddr, &info, sizeof(info)))
		return -EFAULT;
	return 0;
}

static int ethtool_get_regs(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_regs regs;
	const struct ethtool_ops *ops = dev->ethtool_ops;
	void *regbuf;
	int reglen, ret;

	if (!ops->get_regs || !ops->get_regs_len)
		return -EOPNOTSUPP;

	if (copy_from_user(&regs, useraddr, sizeof(regs)))
		return -EFAULT;

	reglen = ops->get_regs_len(dev);
	if (regs.len > reglen)
		regs.len = reglen;

	regbuf = kmalloc(reglen, GFP_USER);
	if (!regbuf)
		return -ENOMEM;

	ops->get_regs(dev, &regs, regbuf);

	ret = -EFAULT;
	if (copy_to_user(useraddr, &regs, sizeof(regs)))
		goto out;
	useraddr += offsetof(struct ethtool_regs, data);
	if (copy_to_user(useraddr, regbuf, regs.len))
		goto out;
	ret = 0;

 out:
	kfree(regbuf);
	return ret;
}

static int ethtool_get_wol(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_wolinfo wol = { ETHTOOL_GWOL };

	if (!dev->ethtool_ops->get_wol)
		return -EOPNOTSUPP;

	dev->ethtool_ops->get_wol(dev, &wol);

	if (copy_to_user(useraddr, &wol, sizeof(wol)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_wol(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_wolinfo wol;

	if (!dev->ethtool_ops->set_wol)
		return -EOPNOTSUPP;

	if (copy_from_user(&wol, useraddr, sizeof(wol)))
		return -EFAULT;

	return dev->ethtool_ops->set_wol(dev, &wol);
}

static int ethtool_get_msglevel(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GMSGLVL };

	if (!dev->ethtool_ops->get_msglevel)
		return -EOPNOTSUPP;

	edata.data = dev->ethtool_ops->get_msglevel(dev);

	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_msglevel(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata;

	if (!dev->ethtool_ops->set_msglevel)
		return -EOPNOTSUPP;

	if (copy_from_user(&edata, useraddr, sizeof(edata)))
		return -EFAULT;

	dev->ethtool_ops->set_msglevel(dev, edata.data);
	return 0;
}

static int ethtool_nway_reset(struct net_device *dev)
{
	if (!dev->ethtool_ops->nway_reset)
		return -EOPNOTSUPP;

	return dev->ethtool_ops->nway_reset(dev);
}

static int ethtool_get_link(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GLINK };

	if (!dev->ethtool_ops->get_link)
		return -EOPNOTSUPP;

	edata.data = dev->ethtool_ops->get_link(dev);

	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		return -EFAULT;
	return 0;
}

static int ethtool_get_eeprom(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_eeprom eeprom;
	const struct ethtool_ops *ops = dev->ethtool_ops;
	u8 *data;
	int ret;

	if (!ops->get_eeprom || !ops->get_eeprom_len)
		return -EOPNOTSUPP;

	if (copy_from_user(&eeprom, useraddr, sizeof(eeprom)))
		return -EFAULT;

	/* Check for wrap and zero */
	if (eeprom.offset + eeprom.len <= eeprom.offset)
		return -EINVAL;

	/* Check for exceeding total eeprom len */
	if (eeprom.offset + eeprom.len > ops->get_eeprom_len(dev))
		return -EINVAL;

	data = kmalloc(eeprom.len, GFP_USER);
	if (!data)
		return -ENOMEM;

	ret = -EFAULT;
	if (copy_from_user(data, useraddr + sizeof(eeprom), eeprom.len))
		goto out;

	ret = ops->get_eeprom(dev, &eeprom, data);
	if (ret)
		goto out;

	ret = -EFAULT;
	if (copy_to_user(useraddr, &eeprom, sizeof(eeprom)))
		goto out;
	if (copy_to_user(useraddr + sizeof(eeprom), data, eeprom.len))
		goto out;
	ret = 0;

 out:
	kfree(data);
	return ret;
}

static int ethtool_set_eeprom(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_eeprom eeprom;
	const struct ethtool_ops *ops = dev->ethtool_ops;
	u8 *data;
	int ret;

	if (!ops->set_eeprom || !ops->get_eeprom_len)
		return -EOPNOTSUPP;

	if (copy_from_user(&eeprom, useraddr, sizeof(eeprom)))
		return -EFAULT;

	/* Check for wrap and zero */
	if (eeprom.offset + eeprom.len <= eeprom.offset)
		return -EINVAL;

	/* Check for exceeding total eeprom len */
	if (eeprom.offset + eeprom.len > ops->get_eeprom_len(dev))
		return -EINVAL;

	data = kmalloc(eeprom.len, GFP_USER);
	if (!data)
		return -ENOMEM;

	ret = -EFAULT;
	if (copy_from_user(data, useraddr + sizeof(eeprom), eeprom.len))
		goto out;

	ret = ops->set_eeprom(dev, &eeprom, data);
	if (ret)
		goto out;

	if (copy_to_user(useraddr + sizeof(eeprom), data, eeprom.len))
		ret = -EFAULT;

 out:
	kfree(data);
	return ret;
}

static int ethtool_get_coalesce(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_coalesce coalesce = { ETHTOOL_GCOALESCE };

	if (!dev->ethtool_ops->get_coalesce)
		return -EOPNOTSUPP;

	dev->ethtool_ops->get_coalesce(dev, &coalesce);

	if (copy_to_user(useraddr, &coalesce, sizeof(coalesce)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_coalesce(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_coalesce coalesce;

	if (!dev->ethtool_ops->set_coalesce)
		return -EOPNOTSUPP;

	if (copy_from_user(&coalesce, useraddr, sizeof(coalesce)))
		return -EFAULT;

	return dev->ethtool_ops->set_coalesce(dev, &coalesce);
}

static int ethtool_get_ringparam(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_ringparam ringparam = { ETHTOOL_GRINGPARAM };

	if (!dev->ethtool_ops->get_ringparam)
		return -EOPNOTSUPP;

	dev->ethtool_ops->get_ringparam(dev, &ringparam);

	if (copy_to_user(useraddr, &ringparam, sizeof(ringparam)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_ringparam(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_ringparam ringparam;

	if (!dev->ethtool_ops->set_ringparam)
		return -EOPNOTSUPP;

	if (copy_from_user(&ringparam, useraddr, sizeof(ringparam)))
		return -EFAULT;

	return dev->ethtool_ops->set_ringparam(dev, &ringparam);
}

static int ethtool_get_pauseparam(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_pauseparam pauseparam = { ETHTOOL_GPAUSEPARAM };

	if (!dev->ethtool_ops->get_pauseparam)
		return -EOPNOTSUPP;

	dev->ethtool_ops->get_pauseparam(dev, &pauseparam);

	if (copy_to_user(useraddr, &pauseparam, sizeof(pauseparam)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_pauseparam(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_pauseparam pauseparam;

	if (!dev->ethtool_ops->set_pauseparam)
		return -EOPNOTSUPP;

	if (copy_from_user(&pauseparam, useraddr, sizeof(pauseparam)))
		return -EFAULT;

	return dev->ethtool_ops->set_pauseparam(dev, &pauseparam);
}

static int ethtool_get_rx_csum(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GRXCSUM };

	if (!dev->ethtool_ops->get_rx_csum)
		return -EOPNOTSUPP;

	edata.data = dev->ethtool_ops->get_rx_csum(dev);

	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_rx_csum(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata;

	if (!dev->ethtool_ops->set_rx_csum)
		return -EOPNOTSUPP;

	if (copy_from_user(&edata, useraddr, sizeof(edata)))
		return -EFAULT;

	dev->ethtool_ops->set_rx_csum(dev, edata.data);
	return 0;
}

static int ethtool_get_tx_csum(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GTXCSUM };

	if (!dev->ethtool_ops->get_tx_csum)
		return -EOPNOTSUPP;

	edata.data = dev->ethtool_ops->get_tx_csum(dev);

	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		return -EFAULT;
	return 0;
}

static int __ethtool_set_sg(struct net_device *dev, u32 data)
{
	int err;

	if (!data && dev->ethtool_ops->set_tso) {
		err = dev->ethtool_ops->set_tso(dev, 0);
		if (err)
			return err;
	}

	if (!data && dev->ethtool_ops->set_ufo) {
		err = dev->ethtool_ops->set_ufo(dev, 0);
		if (err)
			return err;
	}
	return dev->ethtool_ops->set_sg(dev, data);
}

static int ethtool_set_tx_csum(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata;
	int err;

	if (!dev->ethtool_ops->set_tx_csum)
		return -EOPNOTSUPP;

	if (copy_from_user(&edata, useraddr, sizeof(edata)))
		return -EFAULT;

	if (!edata.data && dev->ethtool_ops->set_sg) {
		err = __ethtool_set_sg(dev, 0);
		if (err)
			return err;
	}

	return dev->ethtool_ops->set_tx_csum(dev, edata.data);
}

static int ethtool_get_sg(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GSG };

	if (!dev->ethtool_ops->get_sg)
		return -EOPNOTSUPP;

	edata.data = dev->ethtool_ops->get_sg(dev);

	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_sg(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata;

	if (!dev->ethtool_ops->set_sg)
		return -EOPNOTSUPP;

	if (copy_from_user(&edata, useraddr, sizeof(edata)))
		return -EFAULT;

	if (edata.data &&
	    !(dev->features & NETIF_F_ALL_CSUM))
		return -EINVAL;

	return __ethtool_set_sg(dev, edata.data);
}

static int ethtool_get_tso(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GTSO };

	if (!dev->ethtool_ops->get_tso)
		return -EOPNOTSUPP;

	edata.data = dev->ethtool_ops->get_tso(dev);

	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		return -EFAULT;
	return 0;
}

static int ethtool_set_tso(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata;

	if (!dev->ethtool_ops->set_tso)
		return -EOPNOTSUPP;

	if (copy_from_user(&edata, useraddr, sizeof(edata)))
		return -EFAULT;

	if (edata.data && !(dev->features & NETIF_F_SG))
		return -EINVAL;

	return dev->ethtool_ops->set_tso(dev, edata.data);
}

static int ethtool_get_ufo(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GUFO };

	if (!dev->ethtool_ops->get_ufo)
		return -EOPNOTSUPP;
	edata.data = dev->ethtool_ops->get_ufo(dev);
	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		 return -EFAULT;
	return 0;
}

static int ethtool_set_ufo(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata;

	if (!dev->ethtool_ops->set_ufo)
		return -EOPNOTSUPP;
	if (copy_from_user(&edata, useraddr, sizeof(edata)))
		return -EFAULT;
	if (edata.data && !(dev->features & NETIF_F_SG))
		return -EINVAL;
	if (edata.data && !(dev->features & NETIF_F_HW_CSUM))
		return -EINVAL;
	return dev->ethtool_ops->set_ufo(dev, edata.data);
}

static int ethtool_get_gso(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata = { ETHTOOL_GGSO };

	edata.data = dev->features & NETIF_F_GSO;
	if (copy_to_user(useraddr, &edata, sizeof(edata)))
		 return -EFAULT;
	return 0;
}

static int ethtool_set_gso(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_value edata;

	if (copy_from_user(&edata, useraddr, sizeof(edata)))
		return -EFAULT;
	if (edata.data)
		dev->features |= NETIF_F_GSO;
	else
		dev->features &= ~NETIF_F_GSO;
	return 0;
}

static int ethtool_self_test(struct net_device *dev, char __user *useraddr)
{
	struct ethtool_test test;
	const struct ethtool_ops *ops = dev->ethtool_ops;
	u64 *data;
	int ret;

	if (!ops->self_test || !ops->self_test_count)
		return -EOPNOTSUPP;

	if (copy_from_user(&test, useraddr, sizeof(test)))
		return -EFAULT;

	test.len = ops->self_test_count(dev);
	data = kmalloc(test.len * sizeof(u64), GFP_USER);
	if (!data)
		return -ENOMEM;

	ops->self_test(dev, &test, data);

	ret = -EFAULT;
	if (copy_to_user(useraddr, &test, sizeof(test)))
		goto out;
	useraddr += sizeof(test);
	if (copy_to_user(useraddr, data, test.len * sizeof(u64)))
		goto out;
	ret = 0;

 out:
	kfree(data);
	return ret;
}

static int ethtool_get_strings(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_gstrings gstrings;
	const struct ethtool_ops *ops = dev->ethtool_ops;
	u8 *data;
	int ret;

	if (!ops->get_strings)
		return -EOPNOTSUPP;

	if (copy_from_user(&gstrings, useraddr, sizeof(gstrings)))
		return -EFAULT;

	switch (gstrings.string_set) {
	case ETH_SS_TEST:
		if (!ops->self_test_count)
			return -EOPNOTSUPP;
		gstrings.len = ops->self_test_count(dev);
		break;
	case ETH_SS_STATS:
		if (!ops->get_stats_count)
			return -EOPNOTSUPP;
		gstrings.len = ops->get_stats_count(dev);
		break;
	default:
		return -EINVAL;
	}

	data = kmalloc(gstrings.len * ETH_GSTRING_LEN, GFP_USER);
	if (!data)
		return -ENOMEM;

	ops->get_strings(dev, gstrings.string_set, data);

	ret = -EFAULT;
	if (copy_to_user(useraddr, &gstrings, sizeof(gstrings)))
		goto out;
	useraddr += sizeof(gstrings);
	if (copy_to_user(useraddr, data, gstrings.len * ETH_GSTRING_LEN))
		goto out;
	ret = 0;

 out:
	kfree(data);
	return ret;
}

static int ethtool_phys_id(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_value id;

	if (!dev->ethtool_ops->phys_id)
		return -EOPNOTSUPP;

	if (copy_from_user(&id, useraddr, sizeof(id)))
		return -EFAULT;

	return dev->ethtool_ops->phys_id(dev, id.data);
}

static int ethtool_get_stats(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_stats stats;
	const struct ethtool_ops *ops = dev->ethtool_ops;
	u64 *data;
	int ret;

	if (!ops->get_ethtool_stats || !ops->get_stats_count)
		return -EOPNOTSUPP;

	if (copy_from_user(&stats, useraddr, sizeof(stats)))
		return -EFAULT;

	stats.n_stats = ops->get_stats_count(dev);
	data = kmalloc(stats.n_stats * sizeof(u64), GFP_USER);
	if (!data)
		return -ENOMEM;

	ops->get_ethtool_stats(dev, &stats, data);

	ret = -EFAULT;
	if (copy_to_user(useraddr, &stats, sizeof(stats)))
		goto out;
	useraddr += sizeof(stats);
	if (copy_to_user(useraddr, data, stats.n_stats * sizeof(u64)))
		goto out;
	ret = 0;

 out:
	kfree(data);
	return ret;
}

static int ethtool_get_perm_addr(struct net_device *dev, void __user *useraddr)
{
	struct ethtool_perm_addr epaddr;
	u8 *data;
	int ret;

	if (!dev->ethtool_ops->get_perm_addr)
		return -EOPNOTSUPP;

	if (copy_from_user(&epaddr,useraddr,sizeof(epaddr)))
		return -EFAULT;

	data = kmalloc(epaddr.size, GFP_USER);
	if (!data)
		return -ENOMEM;

	ret = dev->ethtool_ops->get_perm_addr(dev,&epaddr,data);
	if (ret)
		return ret;

	ret = -EFAULT;
	if (copy_to_user(useraddr, &epaddr, sizeof(epaddr)))
		goto out;
	useraddr += sizeof(epaddr);
	if (copy_to_user(useraddr, data, epaddr.size))
		goto out;
	ret = 0;

 out:
	kfree(data);
	return ret;
}

/* The main entry point in this file.  Called from net/core/dev.c */

int dev_ethtool(struct ifreq *ifr)
{
	struct net_device *dev = __dev_get_by_name(ifr->ifr_name);
	void __user *useraddr = ifr->ifr_data;
	u32 ethcmd;
	int rc;
	unsigned long old_features;

	if (!dev || !netif_device_present(dev))
		return -ENODEV;

	if (!dev->ethtool_ops)
		goto ioctl;

	if (copy_from_user(&ethcmd, useraddr, sizeof (ethcmd)))
		return -EFAULT;

	/* Allow some commands to be done by anyone */
	switch(ethcmd) {
	case ETHTOOL_GDRVINFO:
	case ETHTOOL_GMSGLVL:
	case ETHTOOL_GCOALESCE:
	case ETHTOOL_GRINGPARAM:
	case ETHTOOL_GPAUSEPARAM:
	case ETHTOOL_GRXCSUM:
	case ETHTOOL_GTXCSUM:
	case ETHTOOL_GSG:
	case ETHTOOL_GSTRINGS:
	case ETHTOOL_GTSO:
	case ETHTOOL_GPERMADDR:
	case ETHTOOL_GUFO:
	case ETHTOOL_GGSO:
		break;
	default:
		if (!capable(CAP_NET_ADMIN))
			return -EPERM;
	}

	if(dev->ethtool_ops->begin)
		if ((rc = dev->ethtool_ops->begin(dev)) < 0)
			return rc;

	old_features = dev->features;

	switch (ethcmd) {
	case ETHTOOL_GSET:
		rc = ethtool_get_settings(dev, useraddr);
		break;
	case ETHTOOL_SSET:
		rc = ethtool_set_settings(dev, useraddr);
		break;
	case ETHTOOL_GDRVINFO:
		rc = ethtool_get_drvinfo(dev, useraddr);
		break;
	case ETHTOOL_GREGS:
		rc = ethtool_get_regs(dev, useraddr);
		break;
	case ETHTOOL_GWOL:
		rc = ethtool_get_wol(dev, useraddr);
		break;
	case ETHTOOL_SWOL:
		rc = ethtool_set_wol(dev, useraddr);
		break;
	case ETHTOOL_GMSGLVL:
		rc = ethtool_get_msglevel(dev, useraddr);
		break;
	case ETHTOOL_SMSGLVL:
		rc = ethtool_set_msglevel(dev, useraddr);
		break;
	case ETHTOOL_NWAY_RST:
		rc = ethtool_nway_reset(dev);
		break;
	case ETHTOOL_GLINK:
		rc = ethtool_get_link(dev, useraddr);
		break;
	case ETHTOOL_GEEPROM:
		rc = ethtool_get_eeprom(dev, useraddr);
		break;
	case ETHTOOL_SEEPROM:
		rc = ethtool_set_eeprom(dev, useraddr);
		break;
	case ETHTOOL_GCOALESCE:
		rc = ethtool_get_coalesce(dev, useraddr);
		break;
	case ETHTOOL_SCOALESCE:
		rc = ethtool_set_coalesce(dev, useraddr);
		break;
	case ETHTOOL_GRINGPARAM:
		rc = ethtool_get_ringparam(dev, useraddr);
		break;
	case ETHTOOL_SRINGPARAM:
		rc = ethtool_set_ringparam(dev, useraddr);
		break;
	case ETHTOOL_GPAUSEPARAM:
		rc = ethtool_get_pauseparam(dev, useraddr);
		break;
	case ETHTOOL_SPAUSEPARAM:
		rc = ethtool_set_pauseparam(dev, useraddr);
		break;
	case ETHTOOL_GRXCSUM:
		rc = ethtool_get_rx_csum(dev, useraddr);
		break;
	case ETHTOOL_SRXCSUM:
		rc = ethtool_set_rx_csum(dev, useraddr);
		break;
	case ETHTOOL_GTXCSUM:
		rc = ethtool_get_tx_csum(dev, useraddr);
		break;
	case ETHTOOL_STXCSUM:
		rc = ethtool_set_tx_csum(dev, useraddr);
		break;
	case ETHTOOL_GSG:
		rc = ethtool_get_sg(dev, useraddr);
		break;
	case ETHTOOL_SSG:
		rc = ethtool_set_sg(dev, useraddr);
		break;
	case ETHTOOL_GTSO:
		rc = ethtool_get_tso(dev, useraddr);
		break;
	case ETHTOOL_STSO:
		rc = ethtool_set_tso(dev, useraddr);
		break;
	case ETHTOOL_TEST:
		rc = ethtool_self_test(dev, useraddr);
		break;
	case ETHTOOL_GSTRINGS:
		rc = ethtool_get_strings(dev, useraddr);
		break;
	case ETHTOOL_PHYS_ID:
		rc = ethtool_phys_id(dev, useraddr);
		break;
	case ETHTOOL_GSTATS:
		rc = ethtool_get_stats(dev, useraddr);
		break;
	case ETHTOOL_GPERMADDR:
		rc = ethtool_get_perm_addr(dev, useraddr);
		break;
	case ETHTOOL_GUFO:
		rc = ethtool_get_ufo(dev, useraddr);
		break;
	case ETHTOOL_SUFO:
		rc = ethtool_set_ufo(dev, useraddr);
		break;
	case ETHTOOL_GGSO:
		rc = ethtool_get_gso(dev, useraddr);
		break;
	case ETHTOOL_SGSO:
		rc = ethtool_set_gso(dev, useraddr);
		break;
	default:
		rc =  -EOPNOTSUPP;
	}

	if(dev->ethtool_ops->complete)
		dev->ethtool_ops->complete(dev);

	if (old_features != dev->features)
		netdev_features_change(dev);

	return rc;

 ioctl:
	/* Keep existing behaviour for the moment.	 */
	if (!capable(CAP_NET_ADMIN))
		return -EPERM;

	if (dev->do_ioctl)
		return dev->do_ioctl(dev, ifr, SIOCETHTOOL);
	return -EOPNOTSUPP;
}

EXPORT_SYMBOL(dev_ethtool);
EXPORT_SYMBOL(ethtool_op_get_link);
EXPORT_SYMBOL_GPL(ethtool_op_get_perm_addr);
EXPORT_SYMBOL(ethtool_op_get_sg);
EXPORT_SYMBOL(ethtool_op_get_tso);
EXPORT_SYMBOL(ethtool_op_get_tx_csum);
EXPORT_SYMBOL(ethtool_op_set_sg);
EXPORT_SYMBOL(ethtool_op_set_tso);
EXPORT_SYMBOL(ethtool_op_set_tx_csum);
EXPORT_SYMBOL(ethtool_op_set_tx_hw_csum);
EXPORT_SYMBOL(ethtool_op_set_ufo);
EXPORT_SYMBOL(ethtool_op_get_ufo);


text:
package com.elsol.user.cheerup.adapter;

import android.view.View;

public interface ItemClickListener {

    void onItemClick(View v, int pos);
}


text:
'use strict';

app.controller('LoginCtrl', ['$scope', '$location', 'auth', 'authorize', 'redirect', 'notifier', function ($scope, $location, auth, authorize, redirect, notifier) {
    $scope.login = function login(options) {
        auth.providers['basic'].login(options || {})
            .then(function (user) {
                authorize.saveUser(user);
                $location.path('/');
            }, function (err) {
                $scope.error(err);
            });
    };

    $scope.loginSocial = function loginSocial(provider) {
        if (!auth.exist(provider)) {
            notifier.notifyError('Unknown social login provider "' + provider + '"!', {isSticky: true});
        } else {
            auth.providers[provider].login({provider: provider, location: '+login'});
        }
    };

    var params = redirect.getData();
    if (params) {
        var state = JSON.parse(params.state);
        auth.providers[state.provider].loginSocial({accessToken: params.access_token})
            .then(function (user) {
                authorize.saveUser(user);
                $location.path('/');
            }, function (err) {
                if (err.status === 403) {
                    $location.path('/register/social/' + state.provider + '/' + params.access_token);
                } else {
                    $scope.error(err, 'Authentication Error: ');
                    $location.path('/login');
                }
            });
    }
}]);


text:
/* TODO:
 * Tracing
 * Auto-terminate channels when both ends have finished writing (AutoCloseOnPipesClosureAsync)
 */

import CancellationToken from "cancellationtoken";
import caught = require("caught");
import { EventEmitter } from "events";
import { Channel, ChannelClass } from "./Channel";
import { ChannelOptions } from "./ChannelOptions";
import { ControlCode } from "./ControlCode";
import { Deferred } from "./Deferred";
import { FrameHeader } from "./FrameHeader";
import { IChannelOfferEventArgs } from "./IChannelOfferEventArgs";
import { IDisposableObservable } from "./IDisposableObservable";
import "./MultiplexingStreamOptions";
import { MultiplexingStreamOptions } from "./MultiplexingStreamOptions";
import { removeFromQueue, throwIfDisposed } from "./Utilities";
import {
    MultiplexingStreamFormatter,
    MultiplexingStreamV1Formatter,
    MultiplexingStreamV2Formatter,
    MultiplexingStreamV3Formatter,
} from "./MultiplexingStreamFormatters";
import { OfferParameters } from "./OfferParameters";
import { Semaphore } from 'await-semaphore';
import { QualifiedChannelId, ChannelSource } from "./QualifiedChannelId";

export abstract class MultiplexingStream implements IDisposableObservable {
    /**
     * The maximum length of a frame's payload.
     */
    static readonly framePayloadMaxLength = 20 * 1024;

    private static readonly recommendedDefaultChannelReceivingWindowSize = 5 * MultiplexingStream.framePayloadMaxLength;

    /** The default window size used for new channels that do not specify a value for ChannelOptions.ChannelReceivingWindowSize. */
    readonly defaultChannelReceivingWindowSize: number;

    protected readonly formatter: MultiplexingStreamFormatter;

    protected get disposalToken() {
        return this.disposalTokenSource.token;
    }

    /**
     * Gets a promise that is resolved or rejected based on how this stream is disposed or fails.
     */
    public get completion(): Promise<void> {
        return this._completionSource.promise;
    }

    /**
     * Gets a value indicating whether this instance has been disposed.
     */
    public get isDisposed(): boolean {
        return this.disposalTokenSource.token.isCancelled;
    }

    /**
     * Initializes a new instance of the `MultiplexingStream` class.
     * @param stream The duplex stream to read and write to.
     * Use `FullDuplexStream.Splice` if you have distinct input/output streams.
     * @param options Options to customize the behavior of the stream.
     * @param cancellationToken A token whose cancellation aborts the handshake with the remote end.
     * @returns The multiplexing stream, once the handshake is complete.
     */
    public static async CreateAsync(
        stream: NodeJS.ReadWriteStream,
        options?: MultiplexingStreamOptions,
        cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<MultiplexingStream> {

        if (!stream) {
            throw new Error("stream must be specified.");
        }

        options = options || {};
        options.protocolMajorVersion = options.protocolMajorVersion || 1;
        options.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize || MultiplexingStream.recommendedDefaultChannelReceivingWindowSize;
        if (options.protocolMajorVersion < 3 && options.seededChannels && options.seededChannels.length > 0) {
            throw new Error("Seeded channels require v3 of the protocol at least.");
        }

        // Send the protocol magic number, and a random 16-byte number to establish even/odd assignments.
        const formatter: MultiplexingStreamFormatter | undefined =
            options.protocolMajorVersion === 1 ? new MultiplexingStreamV1Formatter(stream) :
                options.protocolMajorVersion === 2 ? new MultiplexingStreamV2Formatter(stream) :
                    options.protocolMajorVersion === 3 ? new MultiplexingStreamV3Formatter(stream) :
                        undefined;
        if (!formatter) {
            throw new Error(`Protocol major version ${options.protocolMajorVersion} is not supported.`);
        }

        const writeHandshakeData = await formatter.writeHandshakeAsync();
        const handshakeResult = await formatter.readHandshakeAsync(writeHandshakeData, cancellationToken);
        formatter.isOdd = handshakeResult.isOdd;

        return new MultiplexingStreamClass(stream, handshakeResult.isOdd, options);
    }

    /**
     * The options to use for channels we create in response to incoming offers.
     * @description Whatever these settings are, they can be replaced when the channel is accepted.
     */
    protected static readonly defaultChannelOptions: ChannelOptions = {};

    /**
     * The encoding used for characters in control frames.
     */
    static readonly ControlFrameEncoding = "utf-8";

    protected readonly _completionSource = new Deferred<void>();

    /**
     * A dictionary of channels that were seeded, keyed by their ID.
     */
    protected readonly seededOpenChannels: { [id: number]: ChannelClass } = {};

    /**
     * A dictionary of channels that were offered locally, keyed by their ID.
     */
    protected readonly locallyOfferedOpenChannels: { [id: number]: ChannelClass } = {};

    /**
     * A dictionary of channels that were offered remotely, keyed by their ID.
     */
    protected readonly remotelyOfferedOpenChannels: { [id: number]: ChannelClass } = {};

    /**
     * The last number assigned to a channel.
     * Each use of this should increment by two if isOdd is defined.
     * It should never exceed uint32.MaxValue
     */
    protected abstract lastOfferedChannelId: number;

    /**
     * A map of channel names to queues of channels waiting for local acceptance.
     */
    protected readonly channelsOfferedByThemByName: { [name: string]: ChannelClass[] } = {};

    /**
     * A map of channel names to queues of Deferred<Channel> from waiting accepters.
     */
    protected readonly acceptingChannels: { [name: string]: Deferred<ChannelClass>[] } = {};

    /** The major version of the protocol being used for this connection. */
    protected readonly protocolMajorVersion: number;

    private readonly eventEmitter = new EventEmitter();

    private disposalTokenSource = CancellationToken.create();

    protected constructor(stream: NodeJS.ReadWriteStream, private readonly isOdd: boolean | undefined, options: MultiplexingStreamOptions) {
        this.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize ?? MultiplexingStream.recommendedDefaultChannelReceivingWindowSize;
        this.protocolMajorVersion = options.protocolMajorVersion ?? 1;
        const formatter: MultiplexingStreamFormatter | undefined =
            options.protocolMajorVersion === 1 ? new MultiplexingStreamV1Formatter(stream) :
                options.protocolMajorVersion === 2 ? new MultiplexingStreamV2Formatter(stream) :
                    options.protocolMajorVersion === 3 ? new MultiplexingStreamV3Formatter(stream) :
                        undefined;
        if (formatter === undefined) {
            throw new Error(`Unsupported major protocol version: ${options.protocolMajorVersion}`);
        }
        formatter.isOdd = isOdd;
        this.formatter = formatter;

        if (options.seededChannels) {
            for (let i = 0; i < options.seededChannels.length; i++) {
                const channelOptions = options.seededChannels[i];
                const id = { id: i, source: ChannelSource.Seeded };
                this.setOpenChannel(new ChannelClass(this as unknown as MultiplexingStreamClass, id, { name: '', remoteWindowSize: channelOptions.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize }));
            }
        }
    }

    /**
     * Creates an anonymous channel that may be accepted by <see cref="AcceptChannel(int, ChannelOptions)"/>.
     * Its existance must be communicated by other means (typically another, existing channel) to encourage acceptance.
     * @param options A set of options that describe local treatment of this channel.
     * @returns The anonymous channel.
     * @description Note that while the channel is created immediately, any local write to that channel will be
     * buffered locally until the remote party accepts the channel.
     */
    public createChannel(options?: ChannelOptions): Channel {
        const offerParameters: OfferParameters = {
            name: "",
            remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize
        };
        const payload = this.formatter.serializeOfferParameters(offerParameters);
        const channel = new ChannelClass(
            this as any as MultiplexingStreamClass,
            { id: this.getUnusedChannelId(), source: ChannelSource.Local },
            offerParameters);
        this.setOpenChannel(channel);

        this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.Offer, channel.qualifiedId), payload, this.disposalToken));
        return channel;
    }

    /**
     * Accepts a channel with a specific ID.
     * @param id The id of the channel to accept.
     * @param options A set of options that describe local treatment of this channel.
     * @description This method can be used to accept anonymous channels created with <see cref="CreateChannel"/>.
     * Unlike <see cref="AcceptChannelAsync(string, ChannelOptions, CancellationToken)"/> which will await
     * for a channel offer if a matching one has not been made yet, this method only accepts an offer
     * for a channel that has already been made.
     */
    public acceptChannel(id: number, options?: ChannelOptions): Channel {
        const channel = this.remotelyOfferedOpenChannels[id] || this.seededOpenChannels[id];
        if (!channel) {
            throw new Error("No channel with ID " + id);
        }

        this.removeChannelFromOfferedQueue(channel);

        this.acceptChannelOrThrow(channel, options);
        return channel;
    }

    /**
     * Rejects an offer for the channel with a specified ID.
     * @param id The ID of the channel whose offer should be rejected.
     */
    public rejectChannel(id: number) {
        const channel = this.remotelyOfferedOpenChannels[id];
        if (channel) {
            removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name]);
        } else {
            throw new Error("No channel with that ID found.");
        }

        // Rejecting a channel rejects a couple promises that we don't want the caller to have to observe
        // separately since they are explicitly stating they want to take this action now.
        caught(channel.acceptance);
        caught(channel.completion);

        channel.dispose();
    }

    /**
     * Offers a new, named channel to the remote party so they may accept it with
     * [acceptChannelAsync](#acceptChannelAsync).
     * @param name A name for the channel, which must be accepted on the remote end to complete creation.
     * It need not be unique, and may be empty but must not be null.
     * Any characters are allowed, and max length is determined by the maximum frame payload (based on UTF-8 encoding).
     * @param options A set of options that describe local treatment of this channel.
     * @param cancellationToken A cancellation token. Do NOT let this be a long-lived token
     * or a memory leak will result since we add continuations to its promise.
     * @returns A task that completes with the `Channel` if the offer is accepted on the remote end
     * or faults with `MultiplexingProtocolException` if the remote end rejects the channel.
     */
    public async offerChannelAsync(
        name: string,
        options?: ChannelOptions,
        cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<Channel> {

        if (name == null) {
            throw new Error("Name must be specified (but may be empty).");
        }

        cancellationToken.throwIfCancelled();
        throwIfDisposed(this);

        const offerParameters: OfferParameters = {
            name,
            remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
        };
        const payload = this.formatter.serializeOfferParameters(offerParameters);
        const channel = new ChannelClass(
            this as any as MultiplexingStreamClass,
            { id: this.getUnusedChannelId(), source: ChannelSource.Local },
            offerParameters);
        this.setOpenChannel(channel);

        const header = new FrameHeader(ControlCode.Offer, channel.qualifiedId);

        const unsubscribeFromCT = cancellationToken.onCancelled((reason) => this.offerChannelCanceled(channel, reason));
        try {
            // We *will* recognize rejection of this promise. But just in case sendFrameAsync completes synchronously,
            // we want to signify that we *will* catch it first to avoid node.js emitting warnings or crashing.
            caught(channel.acceptance);

            await this.sendFrameAsync(header, payload, cancellationToken);
            await channel.acceptance;

            return channel;
        } finally {
            unsubscribeFromCT();
        }
    }

    /**
     * Accepts a channel that the remote end has attempted or may attempt to create.
     * @param name The name of the channel to accept.
     * @param options A set of options that describe local treatment of this channel.
     * @param cancellationToken A token to indicate lost interest in accepting the channel.
     * Do NOT let this be a long-lived token
     * or a memory leak will result since we add continuations to its promise.
     * @returns The `Channel`, after its offer has been received from the remote party and accepted.
     * @description If multiple offers exist with the specified `name`, the first one received will be accepted.
     */
    public async acceptChannelAsync(
        name: string,
        options?: ChannelOptions,
        cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<Channel> {
        if (name == null) {
            throw new Error("Name must be specified (but may be empty).");
        }

        cancellationToken.throwIfCancelled();
        throwIfDisposed(this);

        let channel: ChannelClass | undefined;
        let pendingAcceptChannel: Deferred<ChannelClass>;
        const channelsOfferedByThem = this.channelsOfferedByThemByName[name] as ChannelClass[];
        if (channelsOfferedByThem) {
            while (channel === undefined && channelsOfferedByThem.length > 0) {
                channel = channelsOfferedByThem.shift()!;
                if (channel.isAccepted || channel.isRejectedOrCanceled) {
                    channel = undefined;
                    continue;
                }
            }
        }

        if (channel === undefined) {
            let acceptingChannels = this.acceptingChannels[name];
            if (!acceptingChannels) {
                this.acceptingChannels[name] = acceptingChannels = [];
            }

            pendingAcceptChannel = new Deferred<ChannelClass>(options);
            acceptingChannels.push(pendingAcceptChannel);
        }

        if (channel !== undefined) {
            this.acceptChannelOrThrow(channel, options);
            return channel;
        } else {
            const unsubscribeFromCT = cancellationToken.onCancelled(
                (reason) => this.acceptChannelCanceled(pendingAcceptChannel, name, reason));
            try {
                return await pendingAcceptChannel!.promise;
            } finally {
                unsubscribeFromCT();
            }
        }
    }

    /**
     * Disposes the stream.
     */
    public dispose() {
        this.disposalTokenSource.cancel();
        this._completionSource.resolve();
        this.formatter.end();
        [this.locallyOfferedOpenChannels, this.remotelyOfferedOpenChannels].forEach(cb => {
            for (const channelId in cb) {
                if (cb.hasOwnProperty(channelId)) {
                    const channel = cb[channelId];

                    // Acceptance gets rejected when a channel is disposed.
                    // Avoid a node.js crash or test failure for unobserved channels (e.g. offers for channels from the other party that no one cared to receive on this side).
                    caught(channel.acceptance);
                    channel.dispose();
                }
            }
        });
    }

    public on(event: "channelOffered", listener: (args: IChannelOfferEventArgs) => void) {
        this.eventEmitter.on(event, listener);
    }

    public off(event: "channelOffered", listener: (args: IChannelOfferEventArgs) => void) {
        this.eventEmitter.off(event, listener);
    }

    public once(event: "channelOffered", listener: (args: IChannelOfferEventArgs) => void) {
        this.eventEmitter.once(event, listener);
    }

    protected raiseChannelOffered(id: number, name: string, isAccepted: boolean) {
        const args: IChannelOfferEventArgs = {
            id,
            isAccepted,
            name,
        };
        try {
            this.eventEmitter.emit("channelOffered", args);
        } catch (err) {
            this._completionSource.reject(err);
        }
    }

    protected abstract sendFrameAsync(
        header: FrameHeader,
        payload: Buffer,
        cancellationToken: CancellationToken): Promise<void>;

    protected abstract sendFrame(code: ControlCode, channelId: QualifiedChannelId): Promise<void>;

    protected acceptChannelOrThrow(channel: ChannelClass, options?: ChannelOptions) {
        if (channel.tryAcceptOffer(options)) {
            const acceptanceParameters = {
                remoteWindowSize: options?.channelReceivingWindowSize ?? channel.localWindowSize ?? this.defaultChannelReceivingWindowSize,
            };
            if (acceptanceParameters.remoteWindowSize < this.defaultChannelReceivingWindowSize) {
                acceptanceParameters.remoteWindowSize = this.defaultChannelReceivingWindowSize;
            }

            if (channel.qualifiedId.source !== ChannelSource.Seeded) {
                const payload = this.formatter.serializeAcceptanceParameters(acceptanceParameters);
                this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.OfferAccepted, channel.qualifiedId), payload, this.disposalToken));
            }
        } else if (channel.isAccepted) {
            throw new Error("Channel is already accepted.");
        } else if (channel.isRejectedOrCanceled) {
            throw new Error("Channel is no longer available for acceptance.");
        } else {
            throw new Error("Channel could not be accepted.");
        }
    }

    /**
     * Disposes this instance if the specified promise is rejected.
     * @param promise The promise to check for failures.
     */
    protected async rejectOnFailure<T>(promise: Promise<T>) {
        try {
            await promise;
        } catch (err) {
            this._completionSource.reject(err);
        }
    }

    protected removeChannelFromOfferedQueue(channel: ChannelClass) {
        if (channel.name) {
            removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name]);
        }
    }

    protected getOpenChannel(qualifiedId: QualifiedChannelId): ChannelClass | undefined {
        return this.getChannelCollection(qualifiedId.source)[qualifiedId.id];
    }

    protected setOpenChannel(channel: ChannelClass) {
        this.getChannelCollection(channel.qualifiedId.source)[channel.qualifiedId.id] = channel;
    }

    protected deleteOpenChannel(qualifiedId: QualifiedChannelId) {
        delete this.getChannelCollection(qualifiedId.source)[qualifiedId.id];
    }

    private getChannelCollection(source: ChannelSource): { [id: number]: ChannelClass } {
        switch (source) {
            case ChannelSource.Local:
                return this.locallyOfferedOpenChannels;
            case ChannelSource.Remote:
                return this.remotelyOfferedOpenChannels;
            case ChannelSource.Seeded:
                return this.seededOpenChannels;
        }
    }

    /**
     * Cancels a prior call to acceptChannelAsync
     * @param channel The promise of a channel to be canceled.
     * @param name The name of the channel the caller was accepting.
     * @param reason The reason for cancellation.
     */
    private acceptChannelCanceled(channel: Deferred<ChannelClass>, name: string, reason: any) {
        if (channel.reject(new CancellationToken.CancellationError(reason))) {
            removeFromQueue(channel, this.acceptingChannels[name]);
        }
    }

    /**
     * Responds to cancellation of a prior call to offerChannelAsync.
     * @param channel The channel previously offered.
     */
    private offerChannelCanceled(channel: ChannelClass, reason: any) {
        channel.tryCancelOffer(reason);
    }

    /**
     * Gets a unique number that can be used to represent a channel.
     * @description The channel numbers increase by two in order to maintain odd or even numbers,
     * since each party is allowed to create only one or the other.
     */
    private getUnusedChannelId() {
        return this.lastOfferedChannelId += this.isOdd !== undefined ? 2 : 1;
    }
}

// tslint:disable-next-line:max-classes-per-file
export class MultiplexingStreamClass extends MultiplexingStream {
    protected lastOfferedChannelId: number;
    private readonly sendingSemaphore = new Semaphore(1);

    constructor(stream: NodeJS.ReadWriteStream, isOdd: boolean | undefined, options: MultiplexingStreamOptions) {
        super(stream, isOdd, options);

        this.lastOfferedChannelId = isOdd ? -1 : 0; // the first channel created should be 1 or 2
        this.lastOfferedChannelId += options.seededChannels?.length ?? 0;

        // Initiate reading from the transport stream. This will not end until the stream does, or we're disposed.
        // If reading the stream fails, we'll dispose ourselves.
        this.readFromStream(this.disposalToken).catch((err) => this._completionSource.reject(err));
    }

    get backpressureSupportEnabled(): boolean {
        return this.protocolMajorVersion > 1;
    }

    public async sendFrameAsync(
        header: FrameHeader,
        payload?: Buffer,
        cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<void> {

        if (!header) {
            throw new Error("Header is required.");
        }

        await this.sendingSemaphore.use(async () => {
            cancellationToken.throwIfCancelled();
            throwIfDisposed(this);

            await this.formatter.writeFrameAsync(header, payload);
        });
    }

    /**
     * Transmits a frame over the stream.
     * @param code The op code for the channel.
     * @param channelId The ID of the channel to receive the frame.
     * @description The promise returned from this function is always resolved (not rejected)
     * since it is anticipated that callers may not be awaiting its result.
     */
    public async sendFrame(code: ControlCode, channelId: QualifiedChannelId) {
        try {
            if (this._completionSource.isCompleted) {
                // Any frames that come in after we're done are most likely frames just informing that channels are
                // being terminated, which we do not need to communicate since the connection going down implies that.
                return;
            }

            const header = new FrameHeader(code, channelId);
            await this.sendFrameAsync(header);
        } catch (error) {
            // We mustn't throw back to our caller. So report the failure by disposing with failure.
            this._completionSource.reject(error);
        }
    }

    public onChannelWritingCompleted(channel: ChannelClass) {
        // Only inform the remote side if this channel has not already been terminated.
        if (!channel.isDisposed && this.getOpenChannel(channel.qualifiedId)) {
            this.sendFrame(ControlCode.ContentWritingCompleted, channel.qualifiedId);
        }
    }

    public onChannelDisposed(channel: ChannelClass) {
        if (!this._completionSource.isCompleted) {
            this.sendFrame(ControlCode.ChannelTerminated, channel.qualifiedId);
        }
    }

    public localContentExamined(channel: ChannelClass, bytesConsumed: number) {
        const payload = this.formatter.serializeContentProcessed(bytesConsumed);
        this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.ContentProcessed, channel.qualifiedId), payload));
    }

    private async readFromStream(cancellationToken: CancellationToken) {
        while (!this.isDisposed) {
            const frame = await this.formatter.readFrameAsync(cancellationToken);
            if (frame === null) {
                break;
            }

            frame.header.flipChannelPerspective();
            switch (frame.header.code) {
                case ControlCode.Offer:
                    this.onOffer(frame.header.requiredChannel, frame.payload);
                    break;
                case ControlCode.OfferAccepted:
                    this.onOfferAccepted(frame.header.requiredChannel, frame.payload);
                    break;
                case ControlCode.Content:
                    this.onContent(frame.header.requiredChannel, frame.payload);
                    break;
                case ControlCode.ContentProcessed:
                    this.onContentProcessed(frame.header.requiredChannel, frame.payload);
                    break;
                case ControlCode.ContentWritingCompleted:
                    this.onContentWritingCompleted(frame.header.requiredChannel);
                    break;
                case ControlCode.ChannelTerminated:
                    this.onChannelTerminated(frame.header.requiredChannel);
                    break;
                default:
                    break;
            }
        }

        this.dispose();
    }

    private onOffer(channelId: QualifiedChannelId, payload: Buffer) {
        const offerParameters = this.formatter.deserializeOfferParameters(payload);
        const channel = new ChannelClass(this, channelId, offerParameters);
        let acceptingChannelAlreadyPresent = false;
        let options: ChannelOptions | undefined;

        let acceptingChannels: Deferred<ChannelClass>[];
        if ((acceptingChannels = this.acceptingChannels[offerParameters.name]) !== undefined) {
            while (acceptingChannels.length > 0) {
                const candidate = acceptingChannels.shift()!;
                if (candidate.resolve(channel)) {
                    acceptingChannelAlreadyPresent = true;
                    options = candidate.state as ChannelOptions;
                    break;
                }
            }
        }

        if (!acceptingChannelAlreadyPresent) {
            if (offerParameters.name != null) {
                let offeredChannels: Channel[];
                if (!(offeredChannels = this.channelsOfferedByThemByName[offerParameters.name])) {
                    this.channelsOfferedByThemByName[offerParameters.name] = offeredChannels = [];
                }

                offeredChannels.push(channel);
            }
        }

        this.setOpenChannel(channel);

        if (acceptingChannelAlreadyPresent) {
            this.acceptChannelOrThrow(channel, options);
        }

        this.raiseChannelOffered(channel.id, channel.name, acceptingChannelAlreadyPresent);
    }

    private onOfferAccepted(channelId: QualifiedChannelId, payload: Buffer) {
        if (channelId.source !== ChannelSource.Local) {
            throw new Error("Remote party tried to accept a channel that they offered.");
        }

        const acceptanceParameter = this.formatter.deserializeAcceptanceParameters(payload);
        const channel = this.getOpenChannel(channelId);
        if (!channel) {
            throw new Error(`Unexpected channel created with ID ${QualifiedChannelId.toString(channelId)}`);
        }

        if (!channel.onAccepted(acceptanceParameter)) {
            // This may be an acceptance of a channel that we canceled an offer for, and a race condition
            // led to our cancellation notification crossing in transit with their acceptance notification.
            // In this case, do nothing since we already sent a channel termination message, and the remote side
            // should notice it soon.
        }
    }

    private onContent(channelId: QualifiedChannelId, payload: Buffer) {
        const channel = this.getOpenChannel(channelId);
        if (!channel) {
            throw new Error(`No channel with id ${channelId} found.`);
        }

        channel.onContent(payload);
    }

    private onContentProcessed(channelId: QualifiedChannelId, payload: Buffer) {
        const channel = this.getOpenChannel(channelId);
        if (!channel) {
            throw new Error(`No channel with id ${channelId} found.`);
        }

        const bytesProcessed = this.formatter.deserializeContentProcessed(payload);
        channel.onContentProcessed(bytesProcessed);
    }

    private onContentWritingCompleted(channelId: QualifiedChannelId) {
        const channel = this.getOpenChannel(channelId);
        if (!channel) {
            throw new Error(`No channel with id ${channelId} found.`);
        }

        channel.onContent(null); // signify that the remote is done writing.
    }

    /**
     * Occurs when the remote party has terminated a channel (including canceling an offer).
     * @param channelId The ID of the terminated channel.
     */
    private onChannelTerminated(channelId: QualifiedChannelId) {
        const channel = this.getOpenChannel(channelId);
        if (channel) {
            this.deleteOpenChannel(channelId);
            this.removeChannelFromOfferedQueue(channel);
            channel.dispose();
        }
    }
}


text:
package org.ldp4j.http;

import static com.google.common.base.Preconditions.checkArgument;

import java.nio.charset.Charset;

import com.google.common.base.MoreObjects;

final class ImmutableVariant implements Variant {

	private final ImmutableMediaType mediaType;
	private final ImmutableCharacterEncoding characterEncoding;
	private final ImmutableLanguage language;

	private ImmutableVariant(ImmutableMediaType mediaType, ImmutableCharacterEncoding characterEncoding, ImmutableLanguage language) {
		this.mediaType=mediaType;
		this.characterEncoding=characterEncoding;
		this.language=language;
	}

	ImmutableVariant type(final MediaType mediaType) {
		MediaType type=mediaType;
		CharacterEncoding charset=this.characterEncoding;
		if(mediaType!=null) {
			checkArgument(!mediaType.isWildcard(),"Type cannot be a wildcard media type (%s)",mediaType);
			final Charset typeCharset=mediaType.charset();
			if(typeCharset!=null) {
				type=MediaTypes.from(mediaType).withCharset(null).build();
				charset=CharacterEncodings.of(typeCharset);
			}
		}
		return new ImmutableVariant((ImmutableMediaType)type,ImmutableCharacterEncoding.copyOf(charset),this.language);
	}

	ImmutableVariant charset(CharacterEncoding charset) {
		checkArgument(charset==null || !charset.isWildcard(),"Charset cannot be a wildcard character encoding (%s)",charset);
		return new ImmutableVariant(this.mediaType,ImmutableCharacterEncoding.copyOf(charset),this.language);
	}

	ImmutableVariant language(Language language) {
		checkArgument(language==null || !language.isWildcard(),"Language cannot be a wildcard language (%s)",language);
		return new ImmutableVariant(this.mediaType,this.characterEncoding,ImmutableLanguage.copyOf(language));
	}

	@Override
	public ImmutableMediaType type() {
		return this.mediaType;
	}

	@Override
	public ImmutableCharacterEncoding charset() {
		return this.characterEncoding;
	}

	@Override
	public ImmutableLanguage language() {
		return this.language;
	}

	static ImmutableVariant newInstance() {
		return new ImmutableVariant(null,null,null);
	}

	@Override
	public String toString() {
		return
			MoreObjects.
				toStringHelper(getClass()).
					omitNullValues().
					add("type",this.mediaType).
					add("charset",this.characterEncoding).
					add("language",this.language).
					toString();
	}

	static ImmutableVariant copyOf(Variant other) {
		ImmutableVariant result=null;
		if(other instanceof ImmutableVariant) {
			result=(ImmutableVariant)other;
		} else if(other!=null) {
			result=
				new ImmutableVariant(
					ImmutableMediaType.copyOf(other.type()),
					ImmutableCharacterEncoding.copyOf(other.charset()),
					ImmutableLanguage.copyOf(other.language())
					);
		}
		return result;

	}

}


text:
class ApplicationController < ActionController::Base
  include ApplicationHelper

  protect_from_forgery with: :exception

end


text:
package com.sequenceiq.cloudbreak.cloud.gcp.group;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.compute.ComputeRequest;
import com.google.api.services.compute.model.Operation;
import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.gcp.AbstractGcpResourceBuilder;
import com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException;
import com.sequenceiq.cloudbreak.cloud.gcp.context.GcpContext;
import com.sequenceiq.cloudbreak.cloud.model.CloudResource;
import com.sequenceiq.cloudbreak.cloud.model.CloudResourceStatus;
import com.sequenceiq.cloudbreak.cloud.model.Group;
import com.sequenceiq.cloudbreak.cloud.model.Network;
import com.sequenceiq.cloudbreak.cloud.model.Security;
import com.sequenceiq.cloudbreak.cloud.template.GroupResourceBuilder;

public abstract class AbstractGcpGroupBuilder extends AbstractGcpResourceBuilder implements GroupResourceBuilder<GcpContext> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractGcpGroupBuilder.class);

    @Override
    public List<CloudResourceStatus> checkResources(GcpContext context, AuthenticatedContext auth, List<CloudResource> resources) {
        return checkResources(resourceType(), context, auth, resources);
    }

    @Override
    public CloudResourceStatus update(GcpContext context, AuthenticatedContext auth, Group group, Network network,
            Security security, CloudResource resource) {
        return null;
    }

    protected CloudResource executeOperationalRequest(CloudResource resource, ComputeRequest<Operation> request) throws IOException {
        try {
            Operation operation = request.execute();
            if (operation.getHttpErrorStatusCode() != null) {
                LOGGER.error("Error response in executing request, status {}, {}", operation.getHttpErrorStatusCode(), operation.getHttpErrorMessage());
                throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), resource.getName());
            }
            return createOperationAwareCloudResource(resource, operation);
        } catch (GoogleJsonResponseException e) {
            throw exceptionHandlerWithThrow(e, resource.getName(), resourceType());
        }
    }
}


text:
<?php

namespace ECM\Bundle\ModuleBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ECMModuleBundle extends Bundle
{
}


text:
(function(angular) {
    'use strict';

    angular.module('gitlabKBApp.board').factory('Stage',[function() {
            function Stage(label) {
                if (_.isEmpty(label)) {
                    return {
                        index: 0,
                        color: '#fffff'
                    }
                }

				return {
					id: label.id,
					name: label.name,
					index: label.order,
					color: label.color,
					viewName: label.name,
					wip: undefined
				};
            }

            return Stage;
        }]
    );
})(window.angular);


text:
<!DOCTYPE html>

    <title>Salem-Surgical-Colon Cancer</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="css/default.css">

(540) 772-3008

Our Location

Social Media

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

          </button>

 Home

 Business Hours

               Doctors

Dr. Madge Ellis

Dr. Bob Williams

Dr. Nadeem Khuri

               Practices

Hernia

Skin Cancer

Varicose Veins

Breast Lumps

Gallbladder Disease

Colon Cancer

 Financial Policy

 Patient Forms

 Directions

 Contact

Colon Cancer

Colon cancer strikes male and females equally. Around the world it is more frequent in industrialized countries, and this suggests genetic and environmental influences. In the United States it affects blacks and whites equally, but Native Americans have a much lower occurrence rate.

Among environmental factors, diet has been implicated frequently. It is felt that a high fiber diet, which speeds up the transit time through the colon, minimizes the contact time of dietary carcinogens to the colonic mucosa. This would then decrease the chances of developing colon cancer.

Genetics is closely related to colon cancer, and was first demonstrated in familial adenomatous polyposis. This condition accounts for less than 1% of colon cancer. It is linked to the APC gene which is located on the long arm of chromosome 5. HNPCC(hereditary nonpolyposis colorectal cancer) or Lynch Syndrome I is another genetic linked cause of colorectal cancer. Typically three or more family members will have had colon cancer, with one being diagnosed before the age of fifty.

Colon Cancer Prevention and Treatment

Currently, there is no effective prevention for colon cancer, but periodic screening can find precancerous lesions and remove them before they become a cancer. It is recommended that when you reach the age of fifty, you have a screening colonoscopy. Colonoscopy is a procedure using a flexible telescope to look at the inside of the rectum and colon. Additionally, your doctor can perform a yearly check of your stool for occult blood by doing a rectal exam. If you have a family history of early colon cancer(diagnosed before the age of fifty), than colonoscopy would be recommended before you reach the age of fifty. Be sure to let your family physician know about your family history so he or she can advise you when to start your screening.

The treatment for colon cancer is anatomical resection. After the removed portion of the colon has been examined by the pathologist, the cancer can be staged, and further treatment with chemotherapy may be recommended.

        <address class="col-sm-4">
          Salem Surgical Associates

          1898 Braeburn Dr

          Salem, VA 24153

           (540) 772-3008
        </address>

Business Hours

Monday-Friday: 8:30AM-5:00PM

Saturday-Sunday: Closed

Copyright © 2016 Salem Surgical Associates. All Rights Reserved. Site by Brett Ripley


text:
package slack

// @NOTE: Blocks are in beta and subject to change.

// More Information: https://api.slack.com/block-kit

// MessageBlockType defines a named string type to define each block type
// as a constant for use within the package.
type MessageBlockType string

const (
	MBTSection MessageBlockType = "section"
	MBTDivider MessageBlockType = "divider"
	MBTImage   MessageBlockType = "image"
	MBTAction  MessageBlockType = "actions"
	MBTContext MessageBlockType = "context"
	MBTInput   MessageBlockType = "input"
)

// Block defines an interface all block types should implement
// to ensure consistency between blocks.
type Block interface {
	BlockType() MessageBlockType
}

// Blocks is a convenience struct defined to allow dynamic unmarshalling of
// the "blocks" value in Slack's JSON response, which varies depending on block type
type Blocks struct {
	BlockSet []Block `json:"blocks,omitempty"`
}

// BlockAction is the action callback sent when a block is interacted with
type BlockAction struct {
	ActionID             string              `json:"action_id"`
	BlockID              string              `json:"block_id"`
	Type                 actionType          `json:"type"`
	Text                 TextBlockObject     `json:"text"`
	Value                string              `json:"value"`
	ActionTs             string              `json:"action_ts"`
	SelectedOption       OptionBlockObject   `json:"selected_option"`
	SelectedOptions      []OptionBlockObject `json:"selected_options"`
	SelectedUser         string              `json:"selected_user"`
	SelectedChannel      string              `json:"selected_channel"`
	SelectedConversation string              `json:"selected_conversation"`
	SelectedDate         string              `json:"selected_date"`
	InitialOption        OptionBlockObject   `json:"initial_option"`
	InitialUser          string              `json:"initial_user"`
	InitialChannel       string              `json:"initial_channel"`
	InitialConversation  string              `json:"initial_conversation"`
	InitialDate          string              `json:"initial_date"`
}

// actionType returns the type of the action
func (b BlockAction) actionType() actionType {
	return b.Type
}

// NewBlockMessage creates a new Message that contains one or more blocks to be displayed
func NewBlockMessage(blocks ...Block) Message {
	return Message{
		Msg: Msg{
			Blocks: Blocks{
				BlockSet: blocks,
			},
		},
	}
}

// AddBlockMessage appends a block to the end of the existing list of blocks
func AddBlockMessage(message Message, newBlk Block) Message {
	message.Msg.Blocks.BlockSet = append(message.Msg.Blocks.BlockSet, newBlk)
	return message
}


text: This is the logout view.


text:
package lila.monitor

import akka.actor._
import com.typesafe.config.Config
import scala.concurrent.duration._

import lila.common.PimpedConfig._
import lila.common.WindowCount

final class Env(
    config: Config,
    db: lila.db.Env,
    hub: lila.hub.Env,
    system: ActorSystem,
    scheduler: lila.common.Scheduler) {

  private val ActorName = config getString "actor.name"
  private val SocketName = config getString "socket.name"
  private val SocketUidTtl = config duration "socket.uid.ttl"

  private lazy val socket = system.actorOf(
    Props(new Socket(timeout = SocketUidTtl)), name = SocketName)

  lazy val socketHandler = new SocketHandler(socket, hub)

  val reporting = system.actorOf(
    Props(new Reporting(
      reqWindowCount = reqWindowCount,
      moveWindowCount = moveWindowCount,
      socket = socket,
      db = db,
      hub = hub
    )), name = ActorName)

  {
    import scala.concurrent.duration._

    scheduler.message(1 seconds) {
      reporting -> lila.hub.actorApi.monitor.Update
    }
  }

  // requests per second
  private lazy val reqWindowCount = new WindowCount(1 second)

  // moves per second
  private lazy val moveWindowCount = new WindowCount(1 second)
}

object Env {

  lazy val current = "monitor" boot new Env(
    config = lila.common.PlayApp loadConfig "monitor",
    db = lila.db.Env.current,
    hub = lila.hub.Env.current,
    system = lila.common.PlayApp.system,
    scheduler = lila.common.PlayApp.scheduler)
}


text:
package system // import "github.com/docker/docker/integration/system"

import (
	"net/http"
	"strings"
	"testing"

	"github.com/docker/docker/api/types/versions"
	"github.com/docker/docker/testutil/request"
	"gotest.tools/assert"
	"gotest.tools/skip"
)

func TestPingCacheHeaders(t *testing.T) {
	skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "skip test from new feature")
	defer setupTest(t)()

	res, _, err := request.Get("/_ping")
	assert.NilError(t, err)
	assert.Equal(t, res.StatusCode, http.StatusOK)

	assert.Equal(t, hdr(res, "Cache-Control"), "no-cache, no-store, must-revalidate")
	assert.Equal(t, hdr(res, "Pragma"), "no-cache")
}

func TestPingGet(t *testing.T) {
	defer setupTest(t)()

	res, body, err := request.Get("/_ping")
	assert.NilError(t, err)

	b, err := request.ReadBody(body)
	assert.NilError(t, err)
	assert.Equal(t, string(b), "OK")
	assert.Equal(t, res.StatusCode, http.StatusOK)
	assert.Check(t, hdr(res, "API-Version") != "")
}

func TestPingHead(t *testing.T) {
	skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "skip test from new feature")
	defer setupTest(t)()

	res, body, err := request.Head("/_ping")
	assert.NilError(t, err)

	b, err := request.ReadBody(body)
	assert.NilError(t, err)
	assert.Equal(t, 0, len(b))
	assert.Equal(t, res.StatusCode, http.StatusOK)
	assert.Check(t, hdr(res, "API-Version") != "")
}

func hdr(res *http.Response, name string) string {
	val, ok := res.Header[http.CanonicalHeaderKey(name)]
	if !ok || len(val) == 0 {
		return ""
	}
	return strings.Join(val, ", ")
}