text:
    //
//  NewConnectionDetail.m
//  MudClientIpad4
//
//  Created by Gary Barnett on 8/2/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "NewConnectionDetail.h"
#import "MudAddConnections.h"
#import "MudClientIpad4AppDelegate.h"
#import "MudConnectionLocale.h"
#import "MudConnectionEncoding.h"
#import "NewConnectionFont.h"

@implementation NewConnectionDetail {
    int encoding;
	NSString *serverTitleStr;
	NSString *hostNameStr;
	NSString *tcpPortStr;
	NSString *characterNameStr;
	NSString *passwordStr;
	UIFont *characterFont;
    NSString *localeStr;
    CGFloat fontSizeFloat;
}

-(void)SaveButtonClicked {
	MudClientIpad4AppDelegate  *myAppDelegate = (MudClientIpad4AppDelegate *) [[UIApplication sharedApplication] delegate];

	int newChar = 0;

    if ( (!serverTitleStr) || ([serverTitleStr length] <1)) {
        return;
    }

    if ( (!hostNameStr) || ([hostNameStr length] <1)) {
        return;
    }

    if ( (!tcpPortStr) || ([tcpPortStr length] <1)) {
        return;
    }

    if ( (!localeStr) || ([localeStr length] <1)) {
        return;
    }

	int port = [tcpPortStr intValue];

	if ( (port <1) | (port >65535)) {
		return;
	}

	if (!self.element) {
		MudDataCharacters *char1 = (MudDataCharacters *)[NSEntityDescription insertNewObjectForEntityForName: @"MudDataCharacters" inManagedObjectContext:self.context];
		self.element = char1;
		MudAddConnections *pv = (MudAddConnections *)self.parentView;
		pv.element = char1;
		[self.element setSlotID:[NSNumber numberWithInt:[myAppDelegate findNewSlotID]]];
		newChar = 1;

	}

	[self.element setFont:[characterFont fontName]];
	[self.element setFontSize:[NSNumber numberWithFloat:fontSizeFloat]];

    NSLog(@"saved font: %@:%f", [characterFont fontName], [characterFont pointSize]);

	[self.element setEncoding:[NSNumber numberWithInt:encoding]];

	[self.element setSSL:@NO];

	[self.element setLang:localeStr];

	[self.element setServerTitle:serverTitleStr];
	[self.element setHostName:hostNameStr];
	[self.element setTcpPort:[NSNumber numberWithInt:[tcpPortStr intValue]]];
	[self.element setCharacterName:characterNameStr];
	[self.element setPassword:passwordStr];

	if (![[self.element slotID] boolValue]) {
		[self.element setSlotID:[NSNumber numberWithInt:[myAppDelegate findNewSlotID]]];
	}

	[(MudAddConnections *)self.parentView SaveAndUpdateView];

	if (newChar) {
		[myAppDelegate createInitialCharacterData:self.element];
	}

    [myAppDelegate saveCoreData];

	[self.navigationController popToRootViewControllerAnimated:YES];

}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    int t = textField.tag - 2000;

    int section = t / 10;
    int row = t - (section * 10);

    NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSLog(@"should change:%d:%d", section, row);
    if (section == 0) {
        switch (row) {
            case 0:
                serverTitleStr = updatedText;
                break;
            case 1:
                hostNameStr = updatedText;
                break;
            case 2:
                tcpPortStr = updatedText;
                break;
        }
    } else if (section == 1) {
        switch (row) {
            case 0:
                characterNameStr = updatedText;
                break;
            case 1:
                passwordStr = updatedText;
                break;
        }
    }

    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	// As many rows as there are obects in the events array.
	switch (section) {
		case 0:
#ifdef MCSSL
				return 7;
#else
				return 6;
#endif

		case 1:
			return 2;
	}

	return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

	switch (section) {
		case 0:
			return @"Server";
			break;
		case 1:
			return @"Character";
			break;
	}

	return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 50.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	int section = indexPath.section;
	int row = indexPath.row;

	NSString *labeltext = nil;
	NSString *hinttext = nil;
    NSString *textFieldText = nil;

	UILabel *label1 = nil;
	UITextField *textField = nil;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"character"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"character"];
    }

    while ([cell.contentView.subviews count]>0)  {
        [[cell.contentView.subviews objectAtIndex:0] removeFromSuperview];
    }

    label1 = [[UILabel alloc] initWithFrame:CGRectMake(20,10,140,30)];
    [cell.contentView addSubview:label1];
    label1.textAlignment = NSTextAlignmentRight;
    label1.font = [UIFont boldSystemFontOfSize:12];
    label1.backgroundColor = [UIColor clearColor];
    label1.tag = 1000;

    CGRect textFieldFrame = CGRectMake(180.0, 5.0, self.view.frame.size.width - 200, 40.0);

    textField = [[UITextField alloc] initWithFrame:textFieldFrame];
    textField.keyboardAppearance = UIKeyboardAppearanceDark;
    [cell.contentView addSubview:textField];

    [textField setTextColor:[UIColor blackColor]];
    [textField setFont:[UIFont boldSystemFontOfSize:14]];
    [textField setDelegate:self];
    [textField setAutocorrectionType:UITextAutocorrectionTypeNo];
    [textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];

    [textField setBackgroundColor:[UIColor clearColor]];
    textField.keyboardType = UIKeyboardTypeDefault;

	cell.accessoryType = UITableViewCellAccessoryNone;

    if (section == 0) {

        switch (row) {
            case 0:
            {
                labeltext = @"Name";
                hinttext = @"required";
                textFieldText = serverTitleStr;
            }
                break;
            case 1:
            {
                labeltext = @"Address";
                hinttext = @"required (hostname or ip address)";
                textFieldText = hostNameStr;
            }
                break;
            case 2:
            {
                labeltext = @"Port";
                hinttext = @"required (number)" ;
                textFieldText = tcpPortStr;
            }
                break;
            case 3:
            {
                labeltext = @"Locale";
                textFieldText = localeStr;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
                break;
            case 4:
            {
                labeltext = @"Encoding";

                NSString *encodingLabel = [MudConnectionEncoding encodingNameFromVal:encoding];

                textFieldText = encodingLabel;

                textField.userInteractionEnabled = NO;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

            }
                break;
            case 5:
            {
                labeltext = @"Font";
				textFieldText = characterFont.fontName;
                [textField setFont:characterFont];

                textField.userInteractionEnabled = NO;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

            }
                break;
#ifdef MCSSL
            case 6:
            {
                /*
                labeltext = @"Secure Connection";
                label1.frame = CGRectMake(20,15,140,20);
                textField.frame = CGRectZero;
                if (self.useSSL) {
                    [cell.contentView addSubview:self.useSSL];
                } else {
                    self.useSSL = [[UISwitch alloc] initWithFrame:CGRectMake(180.0, 10.0, 100.0, 20.0)];
                    [self.useSSL setOn:[[self.element SSL] boolValue]];
                    [cell.contentView addSubview:useSSL];
                }
                UILabel *SSLDetail = [[UILabel alloc] initWithFrame:CGRectMake(300,15,180,15)];
                [SSLDetail setText:@"SSL support required on host"];
                SSLDetail.font = [UIFont systemFontOfSize:12];
                SSLDetail.backgroundColor = [UIColor clearColor];
                [cell.contentView addSubview:SSLDetail];
                 */

            }
                break;
#endif

        }
    } else if (section == 1) {
        switch (row) {
            case 0:
            {
                labeltext = @"Character's Name";
                hinttext = @"optional; used by auto-login macro";
                textFieldText = characterNameStr;

            }

                break;
            case 1:{
                labeltext = @"Character's Password";
                hinttext = @"optional; used by auto-login macro";
                textFieldText = passwordStr;
                [textField setSecureTextEntry:YES];
            }break;
        }
    }

    [label1 setText:labeltext];
    [textField setPlaceholder:hinttext];
    [textField setText:textFieldText];

    textField.tag = (indexPath.section * 10 ) + indexPath.row + 2000;
    textField.enabled = (cell.accessoryType != UITableViewCellAccessoryDisclosureIndicator);
    cell.selectionStyle = (cell.accessoryType == UITableViewCellAccessoryDisclosureIndicator) ? UITableViewCellSelectionStyleBlue : UITableViewCellSelectionStyleNone;

    return cell;
}

- (void)viewWillAppear:(BOOL)animated {
	self.navigationController.toolbarHidden = YES;
    UIInterfaceOrientation iPadOrientation = [[UIApplication sharedApplication] statusBarOrientation];
	if ( (iPadOrientation == UIInterfaceOrientationLandscapeLeft) | (iPadOrientation == UIInterfaceOrientationLandscapeRight) ) {
		self.tableview.frame = CGRectMake(0,0,560,270);
		CGSize contentSize;
		contentSize.width = 560;
		contentSize.height = 290;
		self.preferredContentSize = contentSize;
	} else {
		self.tableview.frame = CGRectMake(0,0,560,600);
		CGSize contentSize;
		contentSize.width = 560;
		contentSize.height = 620;
		self.preferredContentSize = contentSize;
	}

	[self.tableview reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	[tableView deselectRowAtIndexPath:indexPath animated:NO];

    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 3:
            {
                MudConnectionLocale *uv = [[MudConnectionLocale alloc ] init];
                [self.navigationController pushViewController:uv animated:YES];
            }
                break;
            case 4:
            {
                MudConnectionEncoding *uv = [[MudConnectionEncoding alloc ] init];
				[self.navigationController pushViewController:uv animated:YES];

            }
                break;
            case 5:
            {
               	NewConnectionFont *uv = [[NewConnectionFont alloc ] init];
				[self.navigationController pushViewController:uv animated:YES];
            }
                break;
        }
    }

    return;

}

-(void)updateLocaleStr:(NSString *)str {
    if (str) {
        localeStr = str;
    }
    [self.tableview reloadData];
}

-(void)updateEncoding:(NSInteger)enc {
        encoding = enc;
    [self.tableview reloadData];
}

-(void)updateFont:(UIFont *)font atSize:(CGFloat )size {
    if (font) {
        characterFont = font;
        fontSizeFloat = size;
    }
    [self.tableview reloadData];
}

- (void)loadView {

	self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 560, 620)];
	self.view.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;

	MudAddConnections *v = [self.navigationController.viewControllers objectAtIndex:0];
	MudDataCharacters *e = v.element;

	self.element = e;
	self.context = v.context;
	self.parentView = v;

	if (self.element) {
		self.navigationItem.title = @"Edit Character";
		UIBarButtonItem *rb = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(SaveButtonClicked)];
		self.navigationItem.rightBarButtonItem = rb;

        encoding = [self.element.encoding integerValue];
        serverTitleStr = self.element.serverTitle;
        hostNameStr = self.element.hostName;
        tcpPortStr = [self.element.tcpPort stringValue];
        characterNameStr = self.element.characterName;
        passwordStr = self.element.password;
        characterFont = [UIFont fontWithName:self.element.font size:[self.element.fontSize floatValue]];
        fontSizeFloat = [self.element.fontSize floatValue];
        localeStr = self.element.lang;
	} else {
        encoding = 0;
        serverTitleStr = @"";
        hostNameStr = @"";
        tcpPortStr = @"";
        characterNameStr = @"";
        passwordStr = @"";
        characterFont = [UIFont fontWithName:@"Menlo-Regular" size:14.5];
        fontSizeFloat = 14.5;
        localeStr = @"en_US";

		self.navigationItem.title = @"Add Character";
		UIBarButtonItem *rb = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(SaveButtonClicked)];
		self.navigationItem.rightBarButtonItem = rb;
	}

	UITableView *tc = [[UITableView alloc] initWithFrame:CGRectMake(0,0,560,420) style:UITableViewStyleGrouped];
	tc.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;

	tc.delegate = self;
	tc.dataSource = self;

	[self.view addSubview:tc];

	self.tableview = tc;

}

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

@end


text:
package all

import (
	_ "github.com/StackExchange/blackbox/v2/pkg/vcs/git"
	_ "github.com/StackExchange/blackbox/v2/pkg/vcs/none"
)

redpajama_set_name: RedPajamaGithub


text:
namespace lua
{
	enum class type
	{
		nil = LUA_TNIL,
		boolean = LUA_TBOOLEAN,
		light_user_data = LUA_TLIGHTUSERDATA,
		number = LUA_TNUMBER,
		string = LUA_TSTRING,
		table = LUA_TTABLE,
		function = LUA_TFUNCTION,
		user_data = LUA_TUSERDATA,
		thread = LUA_TTHREAD
	};

	inline std::ostream &operator << (std::ostream &out, type value)
	{
		switch (value)
		{
		case type::nil: return out << "nil";
		case type::boolean: return out << "boolean";
		case type::light_user_data: return out << "light_user_data";
		case type::number: return out << "number";
		case type::string: return out << "string";
		case type::table: return out << "table";
		case type::function: return out << "function";
		case type::user_data: return out << "user_data";
		case type::thread: return out << "thread";
		}
		return out << "??";
	}
}

#endif


text:
<?php

namespace App;

use System\Template;

class HomeController
{
    private $template;

    public function __construct(Template $template)
    {
        $this->template = $template;
    }

    public function showIndex()
    {
        $msg = 'Welcome';
        $title = 'webdevlabs';

        $this->template->assign([
            'page_title'  => $title,
            'page_content'=> $msg,
        ]);
        $this->template->display('layout.tpl');
    }
}


text:
"""
Generalized Linear Models.
"""

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Olivier Grisel <olivier.grisel@ensta.org>
#         Vincent Michel <vincent.michel@inria.fr>
#         Peter Prettenhofer <peter.prettenhofer@gmail.com>
#         Mathieu Blondel <mathieu@mblondel.org>
#         Lars Buitinck
#         Maryan Morel <maryan.morel@polytechnique.edu>
#         Giorgio Patrini <giorgio.patrini@anu.edu.au>
# License: BSD 3 clause

from abc import ABCMeta, abstractmethod
import numbers
import warnings

import numpy as np
import scipy.sparse as sp
from scipy import linalg
from scipy import optimize
from scipy import sparse
from scipy.special import expit
from joblib import Parallel

from ..base import (BaseEstimator, ClassifierMixin, RegressorMixin,
                    MultiOutputMixin)
from ..utils import check_array
from ..utils.validation import FLOAT_DTYPES
from ..utils.validation import _deprecate_positional_args
from ..utils import check_random_state
from ..utils.extmath import safe_sparse_dot
from ..utils.sparsefuncs import mean_variance_axis, inplace_column_scale
from ..utils.fixes import sparse_lsqr
from ..utils._seq_dataset import ArrayDataset32, CSRDataset32
from ..utils._seq_dataset import ArrayDataset64, CSRDataset64
from ..utils.validation import check_is_fitted, _check_sample_weight
from ..utils.fixes import delayed
from ..preprocessing import normalize as f_normalize

# TODO: bayesian_ridge_regression and bayesian_regression_ard
# should be squashed into its respective objects.

SPARSE_INTERCEPT_DECAY = 0.01
# For sparse data intercept updates are scaled by this decay factor to avoid
# intercept oscillation.

def make_dataset(X, y, sample_weight, random_state=None):
    """Create ``Dataset`` abstraction for sparse and dense inputs.

    This also returns the ``intercept_decay`` which is different
    for sparse datasets.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Training data

    y : array-like, shape (n_samples, )
        Target values.

    sample_weight : numpy array of shape (n_samples,)
        The weight of each sample

    random_state : int, RandomState instance or None (default)
        Determines random number generation for dataset shuffling and noise.
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    dataset
        The ``Dataset`` abstraction
    intercept_decay
        The intercept decay
    """

    rng = check_random_state(random_state)
    # seed should never be 0 in SequentialDataset64
    seed = rng.randint(1, np.iinfo(np.int32).max)

    if X.dtype == np.float32:
        CSRData = CSRDataset32
        ArrayData = ArrayDataset32
    else:
        CSRData = CSRDataset64
        ArrayData = ArrayDataset64

    if sp.issparse(X):
        dataset = CSRData(X.data, X.indptr, X.indices, y, sample_weight,
                          seed=seed)
        intercept_decay = SPARSE_INTERCEPT_DECAY
    else:
        X = np.ascontiguousarray(X)
        dataset = ArrayData(X, y, sample_weight, seed=seed)
        intercept_decay = 1.0

    return dataset, intercept_decay

def _preprocess_data(X, y, fit_intercept, normalize=False, copy=True,
                     sample_weight=None, return_mean=False, check_input=True):
    """Center and scale data.

    Centers data to have mean zero along axis 0. If fit_intercept=False or if
    the X is a sparse matrix, no centering is done, but normalization can still
    be applied. The function returns the statistics necessary to reconstruct
    the input data, which are X_offset, y_offset, X_scale, such that the output

        X = (X - X_offset) / X_scale

    X_scale is the L2 norm of X - X_offset. If sample_weight is not None,
    then the weighted mean of X and y is zero, and not the mean itself. If
    return_mean=True, the mean, eventually weighted, is returned, independently
    of whether X was centered (option used for optimization with sparse data in
    coordinate_descend).

    This is here because nearly all linear models will want their data to be
    centered. This function also systematically makes y consistent with X.dtype
    """
    if isinstance(sample_weight, numbers.Number):
        sample_weight = None
    if sample_weight is not None:
        sample_weight = np.asarray(sample_weight)

    if check_input:
        X = check_array(X, copy=copy, accept_sparse=['csr', 'csc'],
                        dtype=FLOAT_DTYPES)
    elif copy:
        if sp.issparse(X):
            X = X.copy()
        else:
            X = X.copy(order='K')

    y = np.asarray(y, dtype=X.dtype)

    if fit_intercept:
        if sp.issparse(X):
            X_offset, X_var = mean_variance_axis(X, axis=0)
            if not return_mean:
                X_offset[:] = X.dtype.type(0)

            if normalize:

                # TODO: f_normalize could be used here as well but the function
                # inplace_csr_row_normalize_l2 must be changed such that it
                # can return also the norms computed internally

                # transform variance to norm in-place
                X_var *= X.shape[0]
                X_scale = np.sqrt(X_var, X_var)
                del X_var
                X_scale[X_scale == 0] = 1
                inplace_column_scale(X, 1. / X_scale)
            else:
                X_scale = np.ones(X.shape[1], dtype=X.dtype)

        else:
            X_offset = np.average(X, axis=0, weights=sample_weight)
            X -= X_offset
            if normalize:
                X, X_scale = f_normalize(X, axis=0, copy=False,
                                         return_norm=True)
            else:
                X_scale = np.ones(X.shape[1], dtype=X.dtype)
        y_offset = np.average(y, axis=0, weights=sample_weight)
        y = y - y_offset
    else:
        X_offset = np.zeros(X.shape[1], dtype=X.dtype)
        X_scale = np.ones(X.shape[1], dtype=X.dtype)
        if y.ndim == 1:
            y_offset = X.dtype.type(0)
        else:
            y_offset = np.zeros(y.shape[1], dtype=X.dtype)

    return X, y, X_offset, y_offset, X_scale

# TODO: _rescale_data should be factored into _preprocess_data.
# Currently, the fact that sag implements its own way to deal with
# sample_weight makes the refactoring tricky.

def _rescale_data(X, y, sample_weight):
    """Rescale data sample-wise by square root of sample_weight.

    For many linear models, this enables easy support for sample_weight.

    Returns
    -------
    X_rescaled : {array-like, sparse matrix}

    y_rescaled : {array-like, sparse matrix}
    """
    n_samples = X.shape[0]
    sample_weight = np.asarray(sample_weight)
    if sample_weight.ndim == 0:
        sample_weight = np.full(n_samples, sample_weight,
                                dtype=sample_weight.dtype)
    sample_weight = np.sqrt(sample_weight)
    sw_matrix = sparse.dia_matrix((sample_weight, 0),
                                  shape=(n_samples, n_samples))
    X = safe_sparse_dot(sw_matrix, X)
    y = safe_sparse_dot(sw_matrix, y)
    return X, y

class LinearModel(BaseEstimator, metaclass=ABCMeta):
    """Base class for Linear Models"""

    @abstractmethod
    def fit(self, X, y):
        """Fit model."""

    def _decision_function(self, X):
        check_is_fitted(self)

        X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
        return safe_sparse_dot(X, self.coef_.T,
                               dense_output=True) + self.intercept_

    def predict(self, X):
        """
        Predict using the linear model.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            Samples.

        Returns
        -------
        C : array, shape (n_samples,)
            Returns predicted values.
        """
        return self._decision_function(X)

    _preprocess_data = staticmethod(_preprocess_data)

    def _set_intercept(self, X_offset, y_offset, X_scale):
        """Set the intercept_
        """
        if self.fit_intercept:
            self.coef_ = self.coef_ / X_scale
            self.intercept_ = y_offset - np.dot(X_offset, self.coef_.T)
        else:
            self.intercept_ = 0.

    def _more_tags(self):
        return {'requires_y': True}

# XXX Should this derive from LinearModel? It should be a mixin, not an ABC.
# Maybe the n_features checking can be moved to LinearModel.
class LinearClassifierMixin(ClassifierMixin):
    """Mixin for linear classifiers.

    Handles prediction for sparse and dense X.
    """

    def decision_function(self, X):
        """
        Predict confidence scores for samples.

        The confidence score for a sample is the signed distance of that
        sample to the hyperplane.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            Samples.

        Returns
        -------
        array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)
            Confidence scores per (sample, class) combination. In the binary
            case, confidence score for self.classes_[1] where >0 means this
            class would be predicted.
        """
        check_is_fitted(self)

        X = check_array(X, accept_sparse='csr')

        n_features = self.coef_.shape[1]
        if X.shape[1] != n_features:
            raise ValueError("X has %d features per sample; expecting %d"
                             % (X.shape[1], n_features))

        scores = safe_sparse_dot(X, self.coef_.T,
                                 dense_output=True) + self.intercept_
        return scores.ravel() if scores.shape[1] == 1 else scores

    def predict(self, X):
        """
        Predict class labels for samples in X.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            Samples.

        Returns
        -------
        C : array, shape [n_samples]
            Predicted class label per sample.
        """
        scores = self.decision_function(X)
        if len(scores.shape) == 1:
            indices = (scores > 0).astype(int)
        else:
            indices = scores.argmax(axis=1)
        return self.classes_[indices]

    def _predict_proba_lr(self, X):
        """Probability estimation for OvR logistic regression.

        Positive class probabilities are computed as
        1. / (1. + np.exp(-self.decision_function(X)));
        multiclass is handled by normalizing that over all classes.
        """
        prob = self.decision_function(X)
        expit(prob, out=prob)
        if prob.ndim == 1:
            return np.vstack([1 - prob, prob]).T
        else:
            # OvR normalization, like LibLinear's predict_probability
            prob /= prob.sum(axis=1).reshape((prob.shape[0], -1))
            return prob

class SparseCoefMixin:
    """Mixin for converting coef_ to and from CSR format.

    L1-regularizing estimators should inherit this.
    """

    def densify(self):
        """
        Convert coefficient matrix to dense array format.

        Converts the ``coef_`` member (back) to a numpy.ndarray. This is the
        default format of ``coef_`` and is required for fitting, so calling
        this method is only required on models that have previously been
        sparsified; otherwise, it is a no-op.

        Returns
        -------
        self
            Fitted estimator.
        """
        msg = "Estimator, %(name)s, must be fitted before densifying."
        check_is_fitted(self, msg=msg)
        if sp.issparse(self.coef_):
            self.coef_ = self.coef_.toarray()
        return self

    def sparsify(self):
        """
        Convert coefficient matrix to sparse format.

        Converts the ``coef_`` member to a scipy.sparse matrix, which for
        L1-regularized models can be much more memory- and storage-efficient
        than the usual numpy.ndarray representation.

        The ``intercept_`` member is not converted.

        Returns
        -------
        self
            Fitted estimator.

        Notes
        -----
        For non-sparse models, i.e. when there are not many zeros in ``coef_``,
        this may actually *increase* memory usage, so use this method with
        care. A rule of thumb is that the number of zero elements, which can
        be computed with ``(coef_ == 0).sum()``, must be more than 50% for this
        to provide significant benefits.

        After calling this method, further fitting with the partial_fit
        method (if any) will not work until you call densify.
        """
        msg = "Estimator, %(name)s, must be fitted before sparsifying."
        check_is_fitted(self, msg=msg)
        self.coef_ = sp.csr_matrix(self.coef_)
        return self

class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel):
    """
    Ordinary least squares Linear Regression.

    LinearRegression fits a linear model with coefficients w = (w1, ..., wp)
    to minimize the residual sum of squares between the observed targets in
    the dataset, and the targets predicted by the linear approximation.

    Parameters
    ----------
    fit_intercept : bool, default=True
        Whether to calculate the intercept for this model. If set
        to False, no intercept will be used in calculations
        (i.e. data is expected to be centered).

    normalize : bool, default=False
        This parameter is ignored when ``fit_intercept`` is set to False.
        If True, the regressors X will be normalized before regression by
        subtracting the mean and dividing by the l2-norm.
        If you wish to standardize, please use
        :class:`~sklearn.preprocessing.StandardScaler` before calling ``fit``
        on an estimator with ``normalize=False``.

    copy_X : bool, default=True
        If True, X will be copied; else, it may be overwritten.

    n_jobs : int, default=None
        The number of jobs to use for the computation. This will only provide
        speedup for n_targets > 1 and sufficient large problems.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    positive : bool, default=False
        When set to ``True``, forces the coefficients to be positive. This
        option is only supported for dense arrays.

        .. versionadded:: 0.24

    Attributes
    ----------
    coef_ : array of shape (n_features, ) or (n_targets, n_features)
        Estimated coefficients for the linear regression problem.
        If multiple targets are passed during the fit (y 2D), this
        is a 2D array of shape (n_targets, n_features), while if only
        one target is passed, this is a 1D array of length n_features.

    rank_ : int
        Rank of matrix `X`. Only available when `X` is dense.

    singular_ : array of shape (min(X, y),)
        Singular values of `X`. Only available when `X` is dense.

    intercept_ : float or array of shape (n_targets,)
        Independent term in the linear model. Set to 0.0 if
        `fit_intercept = False`.

    See Also
    --------
    Ridge : Ridge regression addresses some of the
        problems of Ordinary Least Squares by imposing a penalty on the
        size of the coefficients with l2 regularization.
    Lasso : The Lasso is a linear model that estimates
        sparse coefficients with l1 regularization.
    ElasticNet : Elastic-Net is a linear regression
        model trained with both l1 and l2 -norm regularization of the
        coefficients.

    Notes
    -----
    From the implementation point of view, this is just plain Ordinary
    Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares
    (scipy.optimize.nnls) wrapped as a predictor object.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.linear_model import LinearRegression
    >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
    >>> # y = 1 * x_0 + 2 * x_1 + 3
    >>> y = np.dot(X, np.array([1, 2])) + 3
    >>> reg = LinearRegression().fit(X, y)
    >>> reg.score(X, y)
    1.0
    >>> reg.coef_
    array([1., 2.])
    >>> reg.intercept_
    3.0000...
    >>> reg.predict(np.array([[3, 5]]))
    array([16.])
    """
    @_deprecate_positional_args
    def __init__(self, *, fit_intercept=True, normalize=False, copy_X=True,
                 n_jobs=None, positive=False):
        self.fit_intercept = fit_intercept
        self.normalize = normalize
        self.copy_X = copy_X
        self.n_jobs = n_jobs
        self.positive = positive

    def fit(self, X, y, sample_weight=None):
        """
        Fit linear model.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training data

        y : array-like of shape (n_samples,) or (n_samples, n_targets)
            Target values. Will be cast to X's dtype if necessary

        sample_weight : array-like of shape (n_samples,), default=None
            Individual weights for each sample

            .. versionadded:: 0.17
               parameter *sample_weight* support to LinearRegression.

        Returns
        -------
        self : returns an instance of self.
        """

        n_jobs_ = self.n_jobs

        accept_sparse = False if self.positive else ['csr', 'csc', 'coo']

        X, y = self._validate_data(X, y, accept_sparse=accept_sparse,
                                   y_numeric=True, multi_output=True)

        if sample_weight is not None:
            sample_weight = _check_sample_weight(sample_weight, X,
                                                 dtype=X.dtype)

        X, y, X_offset, y_offset, X_scale = self._preprocess_data(
            X, y, fit_intercept=self.fit_intercept, normalize=self.normalize,
            copy=self.copy_X, sample_weight=sample_weight,
            return_mean=True)

        if sample_weight is not None:
            # Sample weight can be implemented via a simple rescaling.
            X, y = _rescale_data(X, y, sample_weight)

        if self.positive:
            if y.ndim < 2:
                self.coef_, self._residues = optimize.nnls(X, y)
            else:
                # scipy.optimize.nnls cannot handle y with shape (M, K)
                outs = Parallel(n_jobs=n_jobs_)(
                        delayed(optimize.nnls)(X, y[:, j])
                        for j in range(y.shape[1]))
                self.coef_, self._residues = map(np.vstack, zip(*outs))
        elif sp.issparse(X):
            X_offset_scale = X_offset / X_scale

            def matvec(b):
                return X.dot(b) - b.dot(X_offset_scale)

            def rmatvec(b):
                return X.T.dot(b) - X_offset_scale * np.sum(b)

            X_centered = sparse.linalg.LinearOperator(shape=X.shape,
                                                      matvec=matvec,
                                                      rmatvec=rmatvec)

            if y.ndim < 2:
                out = sparse_lsqr(X_centered, y)
                self.coef_ = out[0]
                self._residues = out[3]
            else:
                # sparse_lstsq cannot handle y with shape (M, K)
                outs = Parallel(n_jobs=n_jobs_)(
                    delayed(sparse_lsqr)(X_centered, y[:, j].ravel())
                    for j in range(y.shape[1]))
                self.coef_ = np.vstack([out[0] for out in outs])
                self._residues = np.vstack([out[3] for out in outs])
        else:
            self.coef_, self._residues, self.rank_, self.singular_ = \
                linalg.lstsq(X, y)
            self.coef_ = self.coef_.T

        if y.ndim == 1:
            self.coef_ = np.ravel(self.coef_)
        self._set_intercept(X_offset, y_offset, X_scale)
        return self

def _pre_fit(X, y, Xy, precompute, normalize, fit_intercept, copy,
             check_input=True, sample_weight=None):
    """Aux function used at beginning of fit in linear models

    Parameters
    ----------
    order : 'F', 'C' or None, default=None
        Whether X and y will be forced to be fortran or c-style. Only relevant
        if sample_weight is not None.
    """
    n_samples, n_features = X.shape

    if sparse.isspmatrix(X):
        # copy is not needed here as X is not modified inplace when X is sparse
        precompute = False
        X, y, X_offset, y_offset, X_scale = _preprocess_data(
            X, y, fit_intercept=fit_intercept, normalize=normalize,
            copy=False, return_mean=True, check_input=check_input)
    else:
        # copy was done in fit if necessary
        X, y, X_offset, y_offset, X_scale = _preprocess_data(
            X, y, fit_intercept=fit_intercept, normalize=normalize, copy=copy,
            check_input=check_input, sample_weight=sample_weight)
    if sample_weight is not None:
        X, y = _rescale_data(X, y, sample_weight=sample_weight)
    if hasattr(precompute, '__array__') and (
        fit_intercept and not np.allclose(X_offset, np.zeros(n_features)) or
            normalize and not np.allclose(X_scale, np.ones(n_features))):
        warnings.warn("Gram matrix was provided but X was centered"
                      " to fit intercept, "
                      "or X was normalized : recomputing Gram matrix.",
                      UserWarning)
        # recompute Gram
        precompute = 'auto'
        Xy = None

    # precompute if n_samples > n_features
    if isinstance(precompute, str) and precompute == 'auto':
        precompute = (n_samples > n_features)

    if precompute is True:
        # make sure that the 'precompute' array is contiguous.
        precompute = np.empty(shape=(n_features, n_features), dtype=X.dtype,
                              order='C')
        np.dot(X.T, X, out=precompute)

    if not hasattr(precompute, '__array__'):
        Xy = None  # cannot use Xy if precompute is not Gram

    if hasattr(precompute, '__array__') and Xy is None:
        common_dtype = np.find_common_type([X.dtype, y.dtype], [])
        if y.ndim == 1:
            # Xy is 1d, make sure it is contiguous.
            Xy = np.empty(shape=n_features, dtype=common_dtype, order='C')
            np.dot(X.T, y, out=Xy)
        else:
            # Make sure that Xy is always F contiguous even if X or y are not
            # contiguous: the goal is to make it fast to extract the data for a
            # specific target.
            n_targets = y.shape[1]
            Xy = np.empty(shape=(n_features, n_targets), dtype=common_dtype,
                          order='F')
            np.dot(y.T, X, out=Xy.T)

    return X, y, X_offset, y_offset, X_scale, precompute, Xy


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2016 Treasure Data Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <msgpack.h>
#include <fluent-bit/flb_input.h>
#include <fluent-bit/flb_config.h>
#include <fluent-bit/flb_pack.h>
#include <fluent-bit/flb_error.h>
#include "in_lib.h"

/* Initialize plugin */
int in_lib_init(struct flb_config *config)
{
    int ret;
    struct flb_in_lib_config *ctx;

    /* Allocate space for the configuration */
    ctx = malloc(sizeof(struct flb_in_lib_config));
    if (!ctx) {
        return -1;
    }

    ctx->buf_size = LIB_BUF_CHUNK;
    ctx->buf_data = calloc(1, LIB_BUF_CHUNK);
    ctx->buf_len = 0;

    if (!ctx->buf_data) {
        flb_utils_error_c("Could not allocate initial buf memory buffer");
    }

    ctx->msgp_size = LIB_BUF_CHUNK;
    ctx->msgp_data = malloc(LIB_BUF_CHUNK);
    ctx->msgp_len = 0;
    ctx->fd = config->ch_data[0];

    if (!ctx->msgp_data) {
        flb_utils_error_c("Could not allocate initial msgp memory buffer");
    }

    /* Set the context */
    ret = flb_input_set_context("lib", ctx, config);
    if (ret == -1) {
        flb_utils_error_c("Could not set configuration for STDIN input plugin");
    }

    /* Collect upon data available on the standard input */
    ret = flb_input_set_collector_event("lib",
                                        in_lib_collect,
                                        ctx->fd,
                                        config);
    if (ret == -1) {
        flb_utils_error_c("Could not set collector for LIB input plugin");
    }

    flb_pack_state_init(&ctx->state);
    return 0;
}

int in_lib_exit(void *data, struct flb_config *config)
{
    (void) config;
    struct flb_in_lib_config *ctx = data;

    if (ctx->buf_data) {
        free(ctx->buf_data);
    }

    if (ctx->msgp_data) {
        free(ctx->msgp_data);
    }

    free(ctx);
    return 0;
}

int in_lib_collect(struct flb_config *config, void *in_context)
{
    int n;
    int ret;
    int bytes;
    int out_size;
    int capacity;
    int size;
    char *ptr;
    char *pack;
    struct flb_in_lib_config *ctx = in_context;

    capacity = (ctx->buf_size - ctx->buf_len);

    /* Allocate memory as required (FIXME: this will be limited in later) */
    if (capacity == 0) {
        size = ctx->buf_size + LIB_BUF_CHUNK;
        ptr = realloc(ctx->buf_data, size);
        if (!ptr) {
            perror("realloc");
            return -1;
        }
        ctx->buf_data = ptr;
        ctx->buf_size = size;
        capacity = LIB_BUF_CHUNK;
    }

    bytes = read(ctx->fd,
                 ctx->buf_data + ctx->buf_len,
                 capacity);
    flb_debug("in_lib read() = %i", bytes);
    if (bytes == -1) {
        perror("read");
        if (errno == -EPIPE) {
            return -1;
        }
        return 0;
    }
    ctx->buf_len += bytes;

    /* initially we should support json input */
    ret = flb_pack_json_state(ctx->buf_data, ctx->buf_len,
                              &pack, &out_size, &ctx->state);
    if (ret == FLB_ERR_JSON_INVAL) {
        flb_debug("lib data invalid");
        return -1;
    }
    else if (ret == FLB_ERR_JSON_PART) {
        flb_debug("lib data incomplete, waiting for more data...");
        return 0;
    }
    ctx->buf_len = 0;

    capacity = (ctx->msgp_size - ctx->msgp_len);
    if (capacity < out_size) {
        n = ((out_size - capacity) / LIB_BUF_CHUNK) + 1;
        size = ctx->msgp_size + (LIB_BUF_CHUNK * n);
        ptr = realloc(ctx->msgp_data, size);
        if (!ptr) {
            perror("realloc");
            free(pack);
            return -1;
        }
        ctx->msgp_data = ptr;
        ctx->msgp_size = size;
    }

    memcpy(ctx->msgp_data + ctx->msgp_len, pack, out_size);
    ctx->msgp_len += out_size;
    free(pack);

    return 0;
}

void *in_lib_flush(void *in_context, int *size)
{
    char *buf;
    struct flb_in_lib_config *ctx = in_context;

    if (ctx->msgp_len == 0) {
        *size = 0;
        return NULL;
    }

    buf = malloc(ctx->msgp_len);
    memcpy(buf, ctx->msgp_data, ctx->msgp_len);
    *size = ctx->msgp_len;
    ctx->msgp_len = 0;

    return buf;
}

/* Plugin reference */
struct flb_input_plugin in_lib_plugin = {
    .name         = "lib",
    .description  = "Library mode Input",
    .cb_init      = in_lib_init,
    .cb_pre_run   = NULL,
    .cb_collect   = NULL,
    .cb_ingest    = NULL,
    .cb_flush_buf = in_lib_flush,
    .cb_exit      = in_lib_exit
};


text:
// Code generated by GoVPP's binapi-generator. DO NOT EDIT.
// source: /usr/share/vpp/api/core/gre.api.json

/*
Package gre is a generated VPP binary API for 'gre' module.

It consists of:
	  5 enums
	  6 aliases
	  7 types
	  1 union
	  4 messages
	  2 services
*/
package gre

import (
	bytes "bytes"
	context "context"
	api "git.fd.io/govpp.git/api"
	struc "github.com/lunixbochs/struc"
	io "io"
	strconv "strconv"
)

const (
	// ModuleName is the name of this module.
	ModuleName = "gre"
	// APIVersion is the API version of this module.
	APIVersion = "2.0.0"
	// VersionCrc is the CRC of this module.
	VersionCrc = 0x77bcd2e5
)

// AddressFamily represents VPP binary API enum 'address_family'.
type AddressFamily uint32

const (
	ADDRESS_IP4 AddressFamily = 0
	ADDRESS_IP6 AddressFamily = 1
)

var AddressFamily_name = map[uint32]string{
	0: "ADDRESS_IP4",
	1: "ADDRESS_IP6",
}

var AddressFamily_value = map[string]uint32{
	"ADDRESS_IP4": 0,
	"ADDRESS_IP6": 1,
}

func (x AddressFamily) String() string {
	s, ok := AddressFamily_name[uint32(x)]
	if ok {
		return s
	}
	return strconv.Itoa(int(x))
}

// GreTunnelType represents VPP binary API enum 'gre_tunnel_type'.
type GreTunnelType uint32

const (
	GRE_API_TUNNEL_TYPE_L3     GreTunnelType = 0
	GRE_API_TUNNEL_TYPE_TEB    GreTunnelType = 1
	GRE_API_TUNNEL_TYPE_ERSPAN GreTunnelType = 2
)

var GreTunnelType_name = map[uint32]string{
	0: "GRE_API_TUNNEL_TYPE_L3",
	1: "GRE_API_TUNNEL_TYPE_TEB",
	2: "GRE_API_TUNNEL_TYPE_ERSPAN",
}

var GreTunnelType_value = map[string]uint32{
	"GRE_API_TUNNEL_TYPE_L3":     0,
	"GRE_API_TUNNEL_TYPE_TEB":    1,
	"GRE_API_TUNNEL_TYPE_ERSPAN": 2,
}

func (x GreTunnelType) String() string {
	s, ok := GreTunnelType_name[uint32(x)]
	if ok {
		return s
	}
	return strconv.Itoa(int(x))
}

// IPDscp represents VPP binary API enum 'ip_dscp'.
type IPDscp uint8

const (
	IP_API_DSCP_CS0  IPDscp = 0
	IP_API_DSCP_CS1  IPDscp = 8
	IP_API_DSCP_AF11 IPDscp = 10
	IP_API_DSCP_AF12 IPDscp = 12
	IP_API_DSCP_AF13 IPDscp = 14
	IP_API_DSCP_CS2  IPDscp = 16
	IP_API_DSCP_AF21 IPDscp = 18
	IP_API_DSCP_AF22 IPDscp = 20
	IP_API_DSCP_AF23 IPDscp = 22
	IP_API_DSCP_CS3  IPDscp = 24
	IP_API_DSCP_AF31 IPDscp = 26
	IP_API_DSCP_AF32 IPDscp = 28
	IP_API_DSCP_AF33 IPDscp = 30
	IP_API_DSCP_CS4  IPDscp = 32
	IP_API_DSCP_AF41 IPDscp = 34
	IP_API_DSCP_AF42 IPDscp = 36
	IP_API_DSCP_AF43 IPDscp = 38
	IP_API_DSCP_CS5  IPDscp = 40
	IP_API_DSCP_EF   IPDscp = 46
	IP_API_DSCP_CS6  IPDscp = 48
	IP_API_DSCP_CS7  IPDscp = 50
)

var IPDscp_name = map[uint8]string{
	0:  "IP_API_DSCP_CS0",
	8:  "IP_API_DSCP_CS1",
	10: "IP_API_DSCP_AF11",
	12: "IP_API_DSCP_AF12",
	14: "IP_API_DSCP_AF13",
	16: "IP_API_DSCP_CS2",
	18: "IP_API_DSCP_AF21",
	20: "IP_API_DSCP_AF22",
	22: "IP_API_DSCP_AF23",
	24: "IP_API_DSCP_CS3",
	26: "IP_API_DSCP_AF31",
	28: "IP_API_DSCP_AF32",
	30: "IP_API_DSCP_AF33",
	32: "IP_API_DSCP_CS4",
	34: "IP_API_DSCP_AF41",
	36: "IP_API_DSCP_AF42",
	38: "IP_API_DSCP_AF43",
	40: "IP_API_DSCP_CS5",
	46: "IP_API_DSCP_EF",
	48: "IP_API_DSCP_CS6",
	50: "IP_API_DSCP_CS7",
}

var IPDscp_value = map[string]uint8{
	"IP_API_DSCP_CS0":  0,
	"IP_API_DSCP_CS1":  8,
	"IP_API_DSCP_AF11": 10,
	"IP_API_DSCP_AF12": 12,
	"IP_API_DSCP_AF13": 14,
	"IP_API_DSCP_CS2":  16,
	"IP_API_DSCP_AF21": 18,
	"IP_API_DSCP_AF22": 20,
	"IP_API_DSCP_AF23": 22,
	"IP_API_DSCP_CS3":  24,
	"IP_API_DSCP_AF31": 26,
	"IP_API_DSCP_AF32": 28,
	"IP_API_DSCP_AF33": 30,
	"IP_API_DSCP_CS4":  32,
	"IP_API_DSCP_AF41": 34,
	"IP_API_DSCP_AF42": 36,
	"IP_API_DSCP_AF43": 38,
	"IP_API_DSCP_CS5":  40,
	"IP_API_DSCP_EF":   46,
	"IP_API_DSCP_CS6":  48,
	"IP_API_DSCP_CS7":  50,
}

func (x IPDscp) String() string {
	s, ok := IPDscp_name[uint8(x)]
	if ok {
		return s
	}
	return strconv.Itoa(int(x))
}

// IPEcn represents VPP binary API enum 'ip_ecn'.
type IPEcn uint8

const (
	IP_API_ECN_NONE IPEcn = 0
	IP_API_ECN_ECT0 IPEcn = 1
	IP_API_ECN_ECT1 IPEcn = 2
	IP_API_ECN_CE   IPEcn = 3
)

var IPEcn_name = map[uint8]string{
	0: "IP_API_ECN_NONE",
	1: "IP_API_ECN_ECT0",
	2: "IP_API_ECN_ECT1",
	3: "IP_API_ECN_CE",
}

var IPEcn_value = map[string]uint8{
	"IP_API_ECN_NONE": 0,
	"IP_API_ECN_ECT0": 1,
	"IP_API_ECN_ECT1": 2,
	"IP_API_ECN_CE":   3,
}

func (x IPEcn) String() string {
	s, ok := IPEcn_name[uint8(x)]
	if ok {
		return s
	}
	return strconv.Itoa(int(x))
}

// IPProto represents VPP binary API enum 'ip_proto'.
type IPProto uint32

const (
	IP_API_PROTO_HOPOPT   IPProto = 0
	IP_API_PROTO_ICMP     IPProto = 1
	IP_API_PROTO_IGMP     IPProto = 2
	IP_API_PROTO_TCP      IPProto = 6
	IP_API_PROTO_UDP      IPProto = 17
	IP_API_PROTO_GRE      IPProto = 47
	IP_API_PROTO_AH       IPProto = 50
	IP_API_PROTO_ESP      IPProto = 51
	IP_API_PROTO_EIGRP    IPProto = 88
	IP_API_PROTO_OSPF     IPProto = 89
	IP_API_PROTO_SCTP     IPProto = 132
	IP_API_PROTO_RESERVED IPProto = 255
)

var IPProto_name = map[uint32]string{
	0:   "IP_API_PROTO_HOPOPT",
	1:   "IP_API_PROTO_ICMP",
	2:   "IP_API_PROTO_IGMP",
	6:   "IP_API_PROTO_TCP",
	17:  "IP_API_PROTO_UDP",
	47:  "IP_API_PROTO_GRE",
	50:  "IP_API_PROTO_AH",
	51:  "IP_API_PROTO_ESP",
	88:  "IP_API_PROTO_EIGRP",
	89:  "IP_API_PROTO_OSPF",
	132: "IP_API_PROTO_SCTP",
	255: "IP_API_PROTO_RESERVED",
}

var IPProto_value = map[string]uint32{
	"IP_API_PROTO_HOPOPT":   0,
	"IP_API_PROTO_ICMP":     1,
	"IP_API_PROTO_IGMP":     2,
	"IP_API_PROTO_TCP":      6,
	"IP_API_PROTO_UDP":      17,
	"IP_API_PROTO_GRE":      47,
	"IP_API_PROTO_AH":       50,
	"IP_API_PROTO_ESP":      51,
	"IP_API_PROTO_EIGRP":    88,
	"IP_API_PROTO_OSPF":     89,
	"IP_API_PROTO_SCTP":     132,
	"IP_API_PROTO_RESERVED": 255,
}

func (x IPProto) String() string {
	s, ok := IPProto_name[uint32(x)]
	if ok {
		return s
	}
	return strconv.Itoa(int(x))
}

// AddressWithPrefix represents VPP binary API alias 'address_with_prefix'.
type AddressWithPrefix Prefix

// InterfaceIndex represents VPP binary API alias 'interface_index'.
type InterfaceIndex uint32

// IP4Address represents VPP binary API alias 'ip4_address'.
type IP4Address [4]uint8

// IP4AddressWithPrefix represents VPP binary API alias 'ip4_address_with_prefix'.
type IP4AddressWithPrefix IP4Prefix

// IP6Address represents VPP binary API alias 'ip6_address'.
type IP6Address [16]uint8

// IP6AddressWithPrefix represents VPP binary API alias 'ip6_address_with_prefix'.
type IP6AddressWithPrefix IP6Prefix

// Address represents VPP binary API type 'address'.
type Address struct {
	Af AddressFamily
	Un AddressUnion
}

func (*Address) GetTypeName() string { return "address" }

// GreTunnel represents VPP binary API type 'gre_tunnel'.
type GreTunnel struct {
	ClientIndex uint32
	Context     uint32
	SessionID   uint16
	Type        GreTunnelType
	Instance    uint32
	OuterFibID  uint32
	SwIfIndex   InterfaceIndex
	Src         Address
	Dst         Address
}

func (*GreTunnel) GetTypeName() string { return "gre_tunnel" }

// IP4Prefix represents VPP binary API type 'ip4_prefix'.
type IP4Prefix struct {
	Address IP4Address
	Len     uint8
}

func (*IP4Prefix) GetTypeName() string { return "ip4_prefix" }

// IP6Prefix represents VPP binary API type 'ip6_prefix'.
type IP6Prefix struct {
	Address IP6Address
	Len     uint8
}

func (*IP6Prefix) GetTypeName() string { return "ip6_prefix" }

// Mprefix represents VPP binary API type 'mprefix'.
type Mprefix struct {
	Af               AddressFamily
	GrpAddressLength uint16
	GrpAddress       AddressUnion
	SrcAddress       AddressUnion
}

func (*Mprefix) GetTypeName() string { return "mprefix" }

// Prefix represents VPP binary API type 'prefix'.
type Prefix struct {
	Address Address
	Len     uint8
}

func (*Prefix) GetTypeName() string { return "prefix" }

// PrefixMatcher represents VPP binary API type 'prefix_matcher'.
type PrefixMatcher struct {
	Le uint8
	Ge uint8
}

func (*PrefixMatcher) GetTypeName() string { return "prefix_matcher" }

// AddressUnion represents VPP binary API union 'address_union'.
type AddressUnion struct {
	XXX_UnionData [16]byte
}

func (*AddressUnion) GetTypeName() string { return "address_union" }

func AddressUnionIP4(a IP4Address) (u AddressUnion) {
	u.SetIP4(a)
	return
}
func (u *AddressUnion) SetIP4(a IP4Address) {
	var b = new(bytes.Buffer)
	if err := struc.Pack(b, &a); err != nil {
		return
	}
	copy(u.XXX_UnionData[:], b.Bytes())
}
func (u *AddressUnion) GetIP4() (a IP4Address) {
	var b = bytes.NewReader(u.XXX_UnionData[:])
	struc.Unpack(b, &a)
	return
}

func AddressUnionIP6(a IP6Address) (u AddressUnion) {
	u.SetIP6(a)
	return
}
func (u *AddressUnion) SetIP6(a IP6Address) {
	var b = new(bytes.Buffer)
	if err := struc.Pack(b, &a); err != nil {
		return
	}
	copy(u.XXX_UnionData[:], b.Bytes())
}
func (u *AddressUnion) GetIP6() (a IP6Address) {
	var b = bytes.NewReader(u.XXX_UnionData[:])
	struc.Unpack(b, &a)
	return
}

// GreTunnelAddDel represents VPP binary API message 'gre_tunnel_add_del'.
type GreTunnelAddDel struct {
	IsAdd  bool
	Tunnel GreTunnel
}

func (m *GreTunnelAddDel) Reset()                        { *m = GreTunnelAddDel{} }
func (*GreTunnelAddDel) GetMessageName() string          { return "gre_tunnel_add_del" }
func (*GreTunnelAddDel) GetCrcString() string            { return "4bf7bdec" }
func (*GreTunnelAddDel) GetMessageType() api.MessageType { return api.RequestMessage }

// GreTunnelAddDelReply represents VPP binary API message 'gre_tunnel_add_del_reply'.
type GreTunnelAddDelReply struct {
	Retval    int32
	SwIfIndex InterfaceIndex
}

func (m *GreTunnelAddDelReply) Reset()                        { *m = GreTunnelAddDelReply{} }
func (*GreTunnelAddDelReply) GetMessageName() string          { return "gre_tunnel_add_del_reply" }
func (*GreTunnelAddDelReply) GetCrcString() string            { return "5383d31f" }
func (*GreTunnelAddDelReply) GetMessageType() api.MessageType { return api.ReplyMessage }

// GreTunnelDetails represents VPP binary API message 'gre_tunnel_details'.
type GreTunnelDetails struct {
	Tunnel GreTunnel
}

func (m *GreTunnelDetails) Reset()                        { *m = GreTunnelDetails{} }
func (*GreTunnelDetails) GetMessageName() string          { return "gre_tunnel_details" }
func (*GreTunnelDetails) GetCrcString() string            { return "1c6696b1" }
func (*GreTunnelDetails) GetMessageType() api.MessageType { return api.ReplyMessage }

// GreTunnelDump represents VPP binary API message 'gre_tunnel_dump'.
type GreTunnelDump struct {
	SwIfIndex InterfaceIndex
}

func (m *GreTunnelDump) Reset()                        { *m = GreTunnelDump{} }
func (*GreTunnelDump) GetMessageName() string          { return "gre_tunnel_dump" }
func (*GreTunnelDump) GetCrcString() string            { return "f9e6675e" }
func (*GreTunnelDump) GetMessageType() api.MessageType { return api.RequestMessage }

func init() {
	api.RegisterMessage((*GreTunnelAddDel)(nil), "gre.GreTunnelAddDel")
	api.RegisterMessage((*GreTunnelAddDelReply)(nil), "gre.GreTunnelAddDelReply")
	api.RegisterMessage((*GreTunnelDetails)(nil), "gre.GreTunnelDetails")
	api.RegisterMessage((*GreTunnelDump)(nil), "gre.GreTunnelDump")
}

// Messages returns list of all messages in this module.
func AllMessages() []api.Message {
	return []api.Message{
		(*GreTunnelAddDel)(nil),
		(*GreTunnelAddDelReply)(nil),
		(*GreTunnelDetails)(nil),
		(*GreTunnelDump)(nil),
	}
}

// RPCService represents RPC service API for gre module.
type RPCService interface {
	DumpGreTunnel(ctx context.Context, in *GreTunnelDump) (RPCService_DumpGreTunnelClient, error)
	GreTunnelAddDel(ctx context.Context, in *GreTunnelAddDel) (*GreTunnelAddDelReply, error)
}

type serviceClient struct {
	ch api.Channel
}

func NewServiceClient(ch api.Channel) RPCService {
	return &serviceClient{ch}
}

func (c *serviceClient) DumpGreTunnel(ctx context.Context, in *GreTunnelDump) (RPCService_DumpGreTunnelClient, error) {
	stream := c.ch.SendMultiRequest(in)
	x := &serviceClient_DumpGreTunnelClient{stream}
	return x, nil
}

type RPCService_DumpGreTunnelClient interface {
	Recv() (*GreTunnelDetails, error)
}

type serviceClient_DumpGreTunnelClient struct {
	api.MultiRequestCtx
}

func (c *serviceClient_DumpGreTunnelClient) Recv() (*GreTunnelDetails, error) {
	m := new(GreTunnelDetails)
	stop, err := c.MultiRequestCtx.ReceiveReply(m)
	if err != nil {
		return nil, err
	}
	if stop {
		return nil, io.EOF
	}
	return m, nil
}

func (c *serviceClient) GreTunnelAddDel(ctx context.Context, in *GreTunnelAddDel) (*GreTunnelAddDelReply, error) {
	out := new(GreTunnelAddDelReply)
	err := c.ch.SendRequest(in).ReceiveReply(out)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// This is a compile-time assertion to ensure that this generated file
// is compatible with the GoVPP api package it is being compiled against.
// A compilation error at this line likely means your copy of the
// GoVPP api package needs to be updated.
const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package

// Reference imports to suppress errors if they are not otherwise used.
var _ = api.RegisterMessage
var _ = bytes.NewBuffer
var _ = context.Background
var _ = io.Copy
var _ = strconv.Itoa
var _ = struc.Pack


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.fasterxml.jackson.databind.introspect.VisibilityChecker.Std (jackson-databind 2.4.0 API)</title>
<meta name="date" content="2014-06-02">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.fasterxml.jackson.databind.introspect.VisibilityChecker.Std

Packages that use VisibilityChecker.Std

Package
Description

com.fasterxml.jackson.databind.introspect

Functionality needed for Bean introspection, required for detecting
 accessors and mutators for Beans, as well as locating and handling
 method annotations.

Uses of VisibilityChecker.Std in com.fasterxml.jackson.databind.introspect

Fields in com.fasterxml.jackson.databind.introspect declared as VisibilityChecker.Std

Modifier and Type
Field and Description

protected static VisibilityChecker.Std
VisibilityChecker.Std.DEFAULT

This is the canonical base instance, configured with default
 visibility values

Methods in com.fasterxml.jackson.databind.introspect that return VisibilityChecker.Std

Modifier and Type
Method and Description

static VisibilityChecker.Std
VisibilityChecker.Std.defaultInstance()

VisibilityChecker.Std
VisibilityChecker.Std.with(JsonAutoDetect.Visibility v)

VisibilityChecker.Std
VisibilityChecker.Std.with(JsonAutoDetect ann)

VisibilityChecker.Std
VisibilityChecker.Std.withCreatorVisibility(JsonAutoDetect.Visibility v)

VisibilityChecker.Std
VisibilityChecker.Std.withFieldVisibility(JsonAutoDetect.Visibility v)

VisibilityChecker.Std
VisibilityChecker.Std.withGetterVisibility(JsonAutoDetect.Visibility v)

VisibilityChecker.Std
VisibilityChecker.Std.withIsGetterVisibility(JsonAutoDetect.Visibility v)

VisibilityChecker.Std
VisibilityChecker.Std.withSetterVisibility(JsonAutoDetect.Visibility v)

VisibilityChecker.Std
VisibilityChecker.Std.withVisibility(PropertyAccessor method,
              JsonAutoDetect.Visibility v)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 FasterXML. All Rights Reserved.


text:
package bsw

import (
	"strings"
)

// MX returns the A record for any MX records for a domain.
func MX(domain, serverAddr string) (string, Results, error) {
	task := "mx"
	results := Results{}
	servers, err := LookupMX(domain, serverAddr)
	if err != nil {
		return task, results, err
	}
	for _, s := range servers {
		ip, err := LookupName(s, serverAddr)
		if err != nil || ip == "" {
			continue
		}
		results = append(results, Result{
			Source:   task,
			IP:       ip,
			Hostname: strings.TrimRight(s, "."),
		})
	}
	return task, results, nil
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" name="viewport" content="IE=edge, width=device-width, initial-scale=1">
	<title>Which College can I get? | GATE 2016 | Gateoverflow.in</title>

	<link rel="stylesheet" href="bootstrap-custom-theme/dark/dark-min.css">
	<link rel="stylesheet" type="text/css" href="bootstrap-custom-theme/ring.css">

	<link rel="stylesheet" href="ScoreToColleges/ScoreToColleges-dark.css">

		<form class="form-inline" onsubmit="populate_contents(true); return false;">

				<input type="text" placeholder="Enter score here.." class="form-control" oninput="populate_contents()" tabindex="0" id="my-score" value="<?php if(isset($_GET["score"])){echo $_GET["score"];} ?>">

Invalid Score!

GATE Scores are out of 1000.

					(Click here to know your Score estimate)

					(Click here to know your Score estimate)

			            <input name="category-ph" type="checkbox" id="cat-ph"> PH

			            <input name="category" type="radio" id="cat-gen" checked> Gen/OBC Creamy
			            <input name="category" type="radio" id="cat-obc"> OBC Non-Creamy
			            <input name="category" type="radio" id="cat-sc"> SC
			            <input name="category" type="radio" id="cat-st"> ST

		</form>

What I won't get

Chances are pretty slim.

 Due to unavailability of data, this list might be innacurate for the PH category

What I might get

Definitely apply to all these.

What I can get

You're very likely to get any of these.

Also consider the blue list, as it lists better colleges.

Code

				[Github]

Author: Pragy Agarwal

				[Facebook]
				[Email]

Special Thanks:

Arjun Suresh, Shyam Singh


text:
package com.ibm.wala.util.intset;

import java.util.Iterator;
import java.util.Set;

import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;

/**
 * Utilities for dealing with {@link IntSet}s
 */
public class IntSetUtil {

  public static final String INT_SET_FACTORY_CONFIG_PROPERTY_NAME = "com.ibm.wala.mutableIntSetFactory";

  private static MutableIntSetFactory<?> defaultIntSetFactory;

  static {
    MutableIntSetFactory<?> defaultFactory = new MutableSharedBitVectorIntSetFactory();
    if (System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME) != null) {
      try {
        Class<?> intSetFactoryClass = Class.forName(System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME));
        MutableIntSetFactory<?> intSetFactory = (MutableIntSetFactory<?>) intSetFactoryClass.newInstance();
        setDefaultIntSetFactory(intSetFactory);
      } catch (Exception e) {
        System.err.println(("Cannot use int set factory " + System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME)));
        setDefaultIntSetFactory(defaultFactory);
      }
    } else {
      setDefaultIntSetFactory(defaultFactory);
    }
    assert defaultIntSetFactory != null;
  }

  public static MutableIntSet make() {
    return defaultIntSetFactory.make();
  }

  public static MutableIntSet make(int[] initial) {
	    return defaultIntSetFactory.make(initial);
  }

  public static IntSet make(Set<Integer> x) {
    int[] vals = new int[ x.size() ];
    Iterator<Integer> vs = x.iterator();
    for(int i = 0; i < vals.length; i++) {
      vals[i] = vs.next();
    }
    return make(vals);
  }

  private final static boolean DEBUG = false;

  // there's no reason to instantiate this class
  private IntSetUtil() {
  }

  /**
   * This method constructs an appropriate mutable copy of set.
   *
   * @return a new {@link MutableIntSet} object with the same value as set
   * @throws UnimplementedError if we haven't supported the set type yet.
   * @throws IllegalArgumentException if set == null
   */
  public static MutableIntSet makeMutableCopy(IntSet set) throws IllegalArgumentException, UnimplementedError {
    if (set == null) {
      throw new IllegalArgumentException("set == null");
    }
    if (set instanceof SparseIntSet) {
      return MutableSparseIntSet.make(set);
    } else if (set instanceof BitVectorIntSet) {
      return new BitVectorIntSet(set);
    } else if (set instanceof BimodalMutableIntSet) {
      return BimodalMutableIntSet.makeCopy(set);
    } else if (set instanceof MutableSharedBitVectorIntSet) {
      return new MutableSharedBitVectorIntSet((MutableSharedBitVectorIntSet) set);
    } else if (set instanceof SemiSparseMutableIntSet) {
      return new SemiSparseMutableIntSet((SemiSparseMutableIntSet) set);
    } else if (set instanceof DebuggingMutableIntSet) {
      MutableIntSet pCopy = makeMutableCopy(((DebuggingMutableIntSet) set).primaryImpl);
      MutableIntSet sCopy = makeMutableCopy(((DebuggingMutableIntSet) set).secondaryImpl);
      return new DebuggingMutableIntSet(pCopy, sCopy);
    } else if (set instanceof EmptyIntSet) {
      return IntSetUtil.make();
    } else {
      Assertions.UNREACHABLE(set.getClass().toString());
      return null;
    }
  }

  /**
   * Compute the asymmetric difference of two sets, a \ b.
   */
  public static IntSet diff(IntSet A, IntSet B) {
    if (A == null) {
      throw new IllegalArgumentException("null A");
    }
    if (B == null) {
      throw new IllegalArgumentException("null B");
    }
    return diff(A, B, IntSetUtil.getDefaultIntSetFactory());
  }

  private static IntSet defaultSlowDiff(IntSet A, IntSet B, MutableIntSetFactory<?> factory) {
    // TODO: this is slow ... optimize please.
    MutableIntSet result = factory.makeCopy(A);
    if (DEBUG) {
      System.err.println(("initial result " + result + " " + result.getClass()));
    }
    for (IntIterator it = B.intIterator(); it.hasNext();) {
      int I = it.next();
      result.remove(I);
      if (DEBUG) {
        System.err.println(("removed " + I + " now is " + result));
      }
    }
    if (DEBUG) {
      System.err.println(("return " + result));
    }
    return result;
  }

  /**
   * Compute the asymmetric difference of two sets, a \ b.
   */
  public static IntSet diff(IntSet A, IntSet B, MutableIntSetFactory<?> factory) {
    if (factory == null) {
      throw new IllegalArgumentException("null factory");
    }
    if (A == null) {
      throw new IllegalArgumentException("null A");
    }
    if (B == null) {
      throw new IllegalArgumentException("null B");
    }
    if (A instanceof SparseIntSet && B instanceof SparseIntSet) {
      return SparseIntSet.diff((SparseIntSet) A, (SparseIntSet) B);
    } else if (A instanceof SemiSparseMutableIntSet && B instanceof SemiSparseMutableIntSet) {
      IntSet d = SemiSparseMutableIntSet.diff((SemiSparseMutableIntSet) A, (SemiSparseMutableIntSet) B);
      return d;
    } else {
      return defaultSlowDiff(A, B, factory);
    }
  }

  /**
   * Subtract two sets, i.e. a = a \ b.
   *
   * @throws IllegalArgumentException if B == null
   */
  public static MutableIntSet removeAll(MutableIntSet A, IntSet B) throws IllegalArgumentException {
    if (A == null) {
      throw new IllegalArgumentException("A == null");
    }
    if (B == null) {
      throw new IllegalArgumentException("B == null");
    }
    if (A instanceof SemiSparseMutableIntSet && B instanceof SemiSparseMutableIntSet) {
      if (DEBUG) {
        System.err.println("call SemiSparseMutableIntSet.removeAll");
      }
      return ((SemiSparseMutableIntSet) A).removeAll((SemiSparseMutableIntSet) B);
    } else {
      for (IntIterator it = B.intIterator(); it.hasNext();) {
        int I = it.next();
        A.remove(I);
        if (DEBUG) {
          System.err.println(("removed " + I + " now is " + A));
        }
      }
      if (DEBUG) {
        System.err.println(("return " + A));
      }
      return A;
    }
  }

  /**
   * @return index \in [low,high] s.t. data[index] = key, or -1 if not found
   */
  public static int binarySearch(int[] data, int key, int low, int high) throws IllegalArgumentException {
    if (data == null) {
      throw new IllegalArgumentException("null array");
    }
    if (data.length == 0) {
      return -1;
    }
    if (low <= high && (low < 0 || high < 0)) {
      throw new IllegalArgumentException("can't search negative indices " + low + " " + high);
    }
    if (high > data.length - 1) {
      high = data.length - 1;
    }
    if (low <= high) {
      int mid = (low + high) / 2;
      int midValue = data[mid];
      if (midValue == key) {
        return mid;
      } else if (midValue > key) {
        return binarySearch(data, key, low, mid - 1);
      } else {
        return binarySearch(data, key, mid + 1, high);
      }
    } else {
      return -1;
    }
  }

  /**
   * @return Returns the defaultIntSetFactory.
   */
  public static MutableIntSetFactory<?> getDefaultIntSetFactory() {
    return defaultIntSetFactory;
  }

  /**
   * @param defaultIntSetFactory The defaultIntSetFactory to set.
   */
  public static void setDefaultIntSetFactory(MutableIntSetFactory<?> defaultIntSetFactory) {
    if (defaultIntSetFactory == null) {
      throw new IllegalArgumentException("null defaultIntSetFactory");
    }
    IntSetUtil.defaultIntSetFactory = defaultIntSetFactory;
  }

  /**
   * @return a new sparse int set which adds j to s
   * @throws IllegalArgumentException if s == null
   */
  public static IntSet add(IntSet s, int j) throws IllegalArgumentException {
    if (s == null) {
      throw new IllegalArgumentException("s == null");
    }
    if (s instanceof SparseIntSet) {
      SparseIntSet sis = (SparseIntSet) s;
      return SparseIntSet.add(sis, j);
    } else {
      // really slow. optimize as needed.
      MutableSparseIntSet result = MutableSparseIntSet.make(s);
      result.add(j);
      return result;
    }
  }

  public static int[] toArray(IntSet s) {
    int i = 0;
    int[] result = new int[ s.size() ];
    IntIterator x = s.intIterator();
    while (x.hasNext()) {
      result[i++] = x.next();
    }
    assert ! x.hasNext();
    return result;
  }

}


text:
'use strict';

var $ = require('jquery');
var _ = require('underscore');

function Sorter(header){
    var inverse = false;
    header.click(function() {
        var table = header.closest('table');
        var thIndex = $(this).index();

        var unsorted = table.find('tbody tr');
        var tbody = table.find('tbody');
        unsorted.detach();
        var sorted = _.sortBy(unsorted, function(e){
            return $(e).find('td:nth-child('+parseInt(thIndex+1)+')').text().toLowerCase();
        })
        if (inverse) {
            sorted = sorted.reverse();
            inverse = false;
        } else {
            inverse = true;
        }
        tbody.append(sorted);
    });
}

$(document).ready(function () {
    var th = $('th.sortable');
    var sorter = new Sorter(th);
});


text:
package dk.statsbiblioteket.doms.client.impl.relations;

import dk.statsbiblioteket.doms.client.exceptions.ServerOperationFailed;
import dk.statsbiblioteket.doms.client.impl.ontology.OWLObjectProperty;
import dk.statsbiblioteket.doms.client.impl.ontology.OWLRestriction;
import dk.statsbiblioteket.doms.client.objects.ContentModelObject;
import dk.statsbiblioteket.doms.client.objects.DigitalObject;
import dk.statsbiblioteket.doms.client.objects.DigitalObjectFactory;
import dk.statsbiblioteket.doms.client.relations.RelationDeclaration;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: abr
 * Date: 10/31/11
 * Time: 4:37 PM
 * To change this template use File | Settings | File Templates.
 */
public class RelationDeclarationImpl implements RelationDeclaration {

    private String predicate;
    private Set<String> viewAngles;
    private Set<String> inverseViewAngles;
    private DigitalObjectFactory factory;

    private Set<ContentModelObject> firstLevelModels;

    private int max = Integer.MAX_VALUE;
    private int exact = -1;
    private int min = -1;

    public RelationDeclarationImpl(String predicate, OWLObjectProperty owlObjectProperty, Set<String> viewAngles,
                                   Set<String> inverseViewAngles, DigitalObjectFactory factory) throws
                                                                                ServerOperationFailed {
        this.predicate = predicate;
        if (viewAngles == null) {
            viewAngles = new HashSet<String>();
        }
        if (inverseViewAngles == null) {
            inverseViewAngles = new HashSet<String>();
        }
        this.viewAngles = viewAngles;
        this.inverseViewAngles = inverseViewAngles;
        this.factory = factory;

        firstLevelModels = new HashSet<ContentModelObject>();
        for (OWLRestriction owlRestriction : owlObjectProperty.getOwlRestrictions()) {
            int tmp = owlRestriction.getMinCardinality();
            if (tmp > min) {
                min = tmp;
            }
            tmp = owlRestriction.getMaxCardinality();
            if (tmp > 0 && tmp < max) {
                max = tmp;
            }

            tmp = owlRestriction.getCardinality();
            if (tmp >= 0) {
                if (exact < 0) {
                    exact = tmp;
                } else {
                    //TODO we have a problem, cannot be satisfied
                }
            }
            String allValuesFrom = owlRestriction.getAllValuesFrom();
            if (allValuesFrom != null) {
                allValuesFrom = allValuesFrom.replace("#class", "");//Strip class decl
                DigitalObject object = factory.getDigitalObject(allValuesFrom);
                if (object instanceof ContentModelObject) {
                    ContentModelObject contentModelObject = (ContentModelObject) object;
                    firstLevelModels.add(contentModelObject);
                }

            }

        }
    }

    @Override
    public Set<String> getViewAngles() {
        return Collections.unmodifiableSet(viewAngles);
    }

    @Override
    public Set<String> getInverseViewAngles() {
        return Collections.unmodifiableSet(inverseViewAngles);
    }

    @Override
    public int getMinCardinality() {
        return min;
    }

    @Override
    public int getExactCardinality() {
        return exact;
    }

    @Override
    public int getMaxCardinality() {
        return max;
    }

    @Override
    public Set<ContentModelObject> getFirstLevelModels() {
        return Collections.unmodifiableSet(firstLevelModels);
    }

    @Override
    public String getPredicate() {
        return predicate;
    }

    @Override
    public String toString() {
        return predicate.toString();
    }
}


text:
package com.tx.core.service.bind;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.tx.core.ServiceAidl;

import rx.Subscriber;
import rx.Subscription;
import rx.subjects.BehaviorSubject;

/**
 * Created by mykolakoshurenko on 8/10/16.
 */
public class ServiceBindImpl {
    private BehaviorSubject<ServiceAidl> connectSbj = BehaviorSubject.create();
    private IBinder mServiceBinder;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mServiceBinder = service;
            connectSbj.onNext(ServiceAidl.Stub.asInterface(service));
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            connectSbj.onCompleted();
        }
    };

    private Intent mServiceIntent;
    private Context mContext;

    public ServiceBindImpl(Context context, Class serviceClazz) {
        mContext = context;
        mServiceIntent = new Intent(context, serviceClazz);
    }

    public void reconnect() {
        connectSbj = BehaviorSubject.create();
        bind();
    }

    public boolean isBinderAlive() {
        return null != mServiceBinder && mServiceBinder.isBinderAlive() && mServiceBinder.pingBinder();
    }

    public void bind() {
        mContext.bindService(mServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
    }

    public void unbind() {
        mContext.unbindService(mConnection);
    }

    public Subscription subscribe(Subscriber subscriber) {
        return connectSbj.subscribe(subscriber);
    }
}