/*
Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.

Neither the name of the Johns Hopkins University nor the names of its contributors
may be used to endorse or promote products derived from this software without specific
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

#include <float.h>
#include <string.h>

///////////////////
//  SparseMatrix //
///////////////////
///////////////////////////////////////
// SparseMatrix Methods and Memebers //
///////////////////////////////////////

template< class T >
void SparseMatrix< T >::_init( void )
{
	_contiguous = false;
	_maxEntriesPerRow = 0;
	rows = 0;
	rowSizes = NullPointer( int );
	m_ppElements = NullPointer( Pointer( MatrixEntry< T > ) );
}

template< class T > SparseMatrix< T >::SparseMatrix( void ){  _init(); }

template< class T > SparseMatrix< T >::SparseMatrix( int rows                        ){ _init() , Resize( rows ); }
template< class T > SparseMatrix< T >::SparseMatrix( int rows , int maxEntriesPerRow ){ _init() , Resize( rows , maxEntriesPerRow ); }

template< class T >
SparseMatrix< T >::SparseMatrix( const SparseMatrix& M )
{
	_init();
	if( M._contiguous ) Resize( M.rows , M._maxEntriesPerRow );
	else                Resize( M.rows );
	for( int i=0 ; i<rows ; i++ )
	{
		SetRowSize( i , M.rowSizes[i] );
		memcpy( (*this)[i] , M[i] , sizeof( MatrixEntry< T > ) * rowSizes[i] );
	}
}
template<class T>
int SparseMatrix<T>::Entries( void ) const
{
	int e = 0;
	for( int i=0 ; i<rows ; i++ ) e += int( rowSizes[i] );
	return e;
}
template<class T>
SparseMatrix<T>& SparseMatrix<T>::operator = (const SparseMatrix<T>& M)
{
	if( M._contiguous ) Resize( M.rows , M._maxEntriesPerRow );
	else                Resize( M.rows );
	for( int i=0 ; i<rows ; i++ )
	{
		SetRowSize( i , M.rowSizes[i] );
		memcpy( (*this)[i] , M[i] , sizeof( MatrixEntry< T > ) * rowSizes[i] );
	}
	return *this;
}

template<class T>
SparseMatrix<T>::~SparseMatrix( void ){ Resize( 0 ); }

template< class T >
bool SparseMatrix< T >::write( const char* fileName ) const
{
	FILE* fp = fopen( fileName , "wb" );
	if( !fp ) return false;
	bool ret = write( fp );
	fclose( fp );
	return ret;
}
template< class T >
bool SparseMatrix< T >::read( const char* fileName )
{
	FILE* fp = fopen( fileName , "rb" );
	if( !fp ) return false;
	bool ret = read( fp );
	fclose( fp );
	return ret;
}
template< class T >
bool SparseMatrix< T >::write( FILE* fp ) const
{
	if( fwrite( &rows , sizeof( int ) , 1 , fp )!=1 ) return false;
	if( fwrite( rowSizes , sizeof( int ) , rows , fp )!=rows ) return false;
	for( int i=0 ; i<rows ; i++ ) if( fwrite( (*this)[i] , sizeof( MatrixEntry< T > ) , rowSizes[i] , fp )!=rowSizes[i] ) return false;
	return true;
}
template< class T >
bool SparseMatrix< T >::read( FILE* fp )
{
	int r;
	if( fread( &r , sizeof( int ) , 1 , fp )!=1 ) return false;
	Resize( r );
	if( fread( rowSizes , sizeof( int ) , rows , fp )!=rows ) return false;
	for( int i=0 ; i<rows ; i++ )
	{
		r = rowSizes[i];
		rowSizes[i] = 0;
		SetRowSize( i , r );
		if( fread( (*this)[i] , sizeof( MatrixEntry< T > ) , rowSizes[i] , fp )!=rowSizes[i] ) return false;
	}
	return true;
}

template< class T >
void SparseMatrix< T >::Resize( int r )
{
	if( rows>0 )
	{
		if( _contiguous ){ if( _maxEntriesPerRow ) FreePointer( m_ppElements[0] ); }
		else for( int i=0 ; i<rows ; i++ ){ if( rowSizes[i] ) FreePointer( m_ppElements[i] ); }
		FreePointer( m_ppElements );
		FreePointer( rowSizes );
	}
	rows = r;
	if( r )
	{
		rowSizes = AllocPointer< int >( r );
		m_ppElements = AllocPointer< Pointer( MatrixEntry< T > ) >( r );
		memset( rowSizes , 0 , sizeof( int ) * r );
	}
	_contiguous = false;
	_maxEntriesPerRow = 0;
}
template< class T >
void SparseMatrix< T >::Resize( int r , int e )
{
	if( rows>0 )
	{
		if( _contiguous ){ if( _maxEntriesPerRow ) FreePointer( m_ppElements[0] ); }
		else for( int i=0 ; i<rows ; i++ ){ if( rowSizes[i] ) FreePointer( m_ppElements[i] ); }
		FreePointer( m_ppElements );
		FreePointer( rowSizes );
	}
	rows = r;
	if( r )
	{
		rowSizes = AllocPointer< int >( r );
		m_ppElements = AllocPointer< Pointer( MatrixEntry< T > ) >( r );
		m_ppElements[0] = AllocPointer< MatrixEntry< T > >( r * e );
		memset( rowSizes , 0 , sizeof( int ) * r );
		for( int i=1 ; i<r ; i++ ) m_ppElements[i] = m_ppElements[i-1] + e;
	}
	_contiguous = true;
	_maxEntriesPerRow = e;
}

template<class T>
void SparseMatrix< T >::SetRowSize( int row , int count )
{
	if( _contiguous )
	{
		if( count>_maxEntriesPerRow ) fprintf( stderr , "[ERROR] Cannot set row size on contiguous matrix: %d<=%d\n" , count , _maxEntriesPerRow ) , exit( 0 );
		rowSizes[row] = count;
	}
	else if( row>=0 && row<rows )
	{
		if( rowSizes[row] ) FreePointer( m_ppElements[row] );
		if( count>0 ) m_ppElements[row] = AllocPointer< MatrixEntry< T > >( count );
		// [WARNING] Why wasn't this line here before???
		rowSizes[row] = count;
	}
}

template<class T>
void SparseMatrix<T>::SetZero()
{
	Resize(this->m_N, this->m_M);
}

template<class T>
SparseMatrix<T> SparseMatrix<T>::operator * (const T& V) const
{
	SparseMatrix<T> M(*this);
	M *= V;
	return M;
}

template<class T>
SparseMatrix<T>& SparseMatrix<T>::operator *= (const T& V)
{
	for( int i=0 ; i<rows ; i++ ) for( int ii=0 ; ii<rowSizes[i] ; i++ ) m_ppElements[i][ii].Value *= V;
	return *this;
}

template< class T >
template< class T2 >
void SparseMatrix< T >::Multiply( ConstPointer( T2 ) in , Pointer( T2 ) out , int threads ) const
{
#pragma omp parallel for num_threads( threads )
	for( int i=0 ; i<rows ; i++ )
	{
		T2 _out(0);
		ConstPointer( MatrixEntry< T > ) start = m_ppElements[i];
		ConstPointer( MatrixEntry< T > ) end = start + rowSizes[i];
		ConstPointer( MatrixEntry< T > ) e;
		for( e=start ; e!=end ; e++ ) _out += in[ e->N ] * e->Value;
		out[i] = _out;
	}
}
template< class T >
template< class T2 >
void SparseMatrix< T >::MultiplyAndAddAverage( ConstPointer( T2 ) in , Pointer( T2 ) out , int threads ) const
{
	T2 average = 0;
	for( int i=0 ; i<rows ; i++ ) average += in[i];
	average /= rows;
	Multiply( in , out , threads );
#pragma omp parallel for num_threads( threads )
	for( int i=0 ; i<rows ; i++ ) out[i] += average;
}

template< class T >
template< class T2 >
int SparseMatrix<T>::SolveJacobi( const SparseMatrix<T>& M , ConstPointer( T2 ) diagonal , ConstPointer( T2 ) b , Pointer( T2 ) x , Pointer( T2 ) Mx , T2 sor , int threads )
{
	M.Multiply( x , Mx , threads );
#if ZERO_TESTING_JACOBI
	for( int j=0 ; j<int(M.rows) ; j++ ) if( diagonal[j] ) x[j] += ( b[j]-Mx[j] ) * sor / diagonal[j];
#else // !ZERO_TESTING_JACOBI
	for( int j=0 ; j<int(M.rows) ; j++ ) x[j] += ( b[j]-Mx[j] ) * sor / diagonal[j];
#endif // ZERO_TESTING_JACOBI
	return M.rows;
}
template< class T >
template< class T2 >
int SparseMatrix<T>::SolveJacobi( const SparseMatrix<T>& M , ConstPointer( T2 ) b , Pointer( T2 ) x , Pointer( T2 ) Mx , T2 sor , int threads )
{
	M.Multiply( x , Mx , threads );
#if ZERO_TESTING_JACOBI
	for( int j=0 ; j<int(M.rows) ; j++ )
	{
		T diagonal = M[j][0].Value;
		if( diagonal ) x[j] += ( b[j]-Mx[j] ) * sor / diagonal;
	}
#else // !ZERO_TESTING_JACOBI
	for( int j=0 ; j<int(M.rows) ; j++ ) x[j] += ( b[j]-Mx[j] ) * sor / M[j][0].Value;
#endif // ZERO_TESTING_JACOBI
	return M.rows;
}
template<class T>
template<class T2>
int SparseMatrix<T>::SolveGS( const SparseMatrix<T>& M , ConstPointer( T2 ) diagonal , ConstPointer( T2 ) b , Pointer( T2 ) x , bool forward )
{
#define ITERATE                                                         \
	{                                                                   \
		ConstPointer( MatrixEntry< T > ) start = M[j];                  \
		ConstPointer( MatrixEntry< T > ) end = start + M.rowSizes[j];   \
		ConstPointer( MatrixEntry< T > ) e;                             \
		T2 _b = b[j];                                                   \
		for( e=start ; e!=end ; e++ ) _b -= x[ e->N ] * e->Value;       \
		x[j] += _b / diagonal[j];                                       \
	}

#if ZERO_TESTING_JACOBI
	if( forward ) for( int j=0 ; j<int(M.rows)    ; j++ ){ if( diagonal[j] ){ ITERATE; } }
	else          for( int j=int(M.rows)-1 ; j>=0 ; j-- ){ if( diagonal[j] ){ ITERATE; } }
#else // !ZERO_TESTING_JACOBI
	if( forward ) for( int j=0 ; j<int(M.rows) ; j++ ){ ITERATE; }
	else          for( int j=int(M.rows)-1 ; j>=0 ; j-- ){ ITERATE; }
#endif // ZERO_TESTING_JACOBI
#undef ITERATE
	return M.rows;
}
template<class T>
template<class T2>
int SparseMatrix<T>::SolveGS( const std::vector< std::vector< int > >& mcIndices , const SparseMatrix<T>& M , ConstPointer( T2 ) diagonal , ConstPointer( T2 ) b , Pointer( T2 ) x , bool forward , int threads )
{
	int sum=0;
#ifdef _WIN32
#define SetOMPParallel __pragma( omp parallel for num_threads( threads ) )
#else // !_WIN32
#define SetOMPParallel _Pragma( "omp parallel for num_threads( threads )" )
#endif // _WIN32
#if ZERO_TESTING_JACOBI
#define ITERATE( indices )                                                        \
	{                                                                             \
SetOMPParallel                                                                    \
		for( int k=0 ; k<int( indices.size() ) ; k++ ) if( diagonal[indices[k]] ) \
		{                                                                         \
			int jj = indices[k];                                                  \
			ConstPointer( MatrixEntry< T > ) start = M[jj];                       \
			ConstPointer( MatrixEntry< T > ) end = start + M.rowSizes[jj];        \
			ConstPointer( MatrixEntry< T > ) e;                                   \
			T2 _b = b[jj];                                                        \
			for( e=start ; e!=end ; e++ ) _b -= x[ e->N ] * e->Value;             \
			x[jj] += _b / diagonal[jj];                                           \
		}                                                                         \
	}
#else // !ZERO_TESTING_JACOBI
#define ITERATE( indices )                                                  \
	{                                                                       \
SetOMPParallel                                                              \
		for( int k=0 ; k<int( indices.size() ) ; k++ )                      \
		{                                                                   \
			int jj = indices[k];                                            \
			ConstPointer( MatrixEntry< T > ) start = M[jj];                 \
			ConstPointer( MatrixEntry< T > ) end = start + M.rowSizes[jj];  \
			ConstPointer( MatrixEntry< T > ) e;                             \
			T2 _b = b[jj];                                                  \
			for( e=start ; e!=end ; e++ ) _b -= x[ e->N ] * e->Value;       \
			x[jj] += _b / diagonal[jj];                                     \
		}                                                                   \
	}
#endif // ZERO_TESTING_JACOBI
	if( forward ) for( int j=0 ; j<mcIndices.size()  ; j++ ){ sum += int( mcIndices[j].size() ) ; ITERATE( mcIndices[j] ); }
	else for( int j=int( mcIndices.size() )-1 ; j>=0 ; j-- ){ sum += int( mcIndices[j].size() ) ; ITERATE( mcIndices[j] ); }
#undef ITERATE
#undef SetOMPParallel
	return sum;
}
template<class T>
template<class T2>
int SparseMatrix<T>::SolveGS( const SparseMatrix<T>& M , ConstPointer( T2 ) b , Pointer( T2 ) x , bool forward )
{
	int start = forward ? 0 : M.rows-1 , end = forward ? M.rows : -1 , dir = forward ? 1 : -1;
	for( int j=start ; j!=end ; j+=dir )
	{
		T diagonal = M[j][0].Value;
#if ZERO_TESTING_JACOBI
		if( diagonal )
#endif // ZERO_TESTING_JACOBI
		{
			ConstPointer( MatrixEntry< T > ) start = M[j];
			ConstPointer( MatrixEntry< T > ) end = start + M.rowSizes[j];
			ConstPointer( MatrixEntry< T > ) e;
			start++;
			T2 _b = b[j];
			for( e=start ; e!=end ; e++ ) _b -= x[ e->N ] * e->Value;
			x[j] = _b / diagonal;
		}
	}
	return M.rows;
}
template<class T>
template<class T2>
int SparseMatrix<T>::SolveGS( const std::vector< std::vector< int > >& mcIndices , const SparseMatrix<T>& M , ConstPointer( T2 ) b , Pointer( T2 ) x , bool forward , int threads )
{
	int sum=0 , start = forward ? 0 : int( mcIndices.size() )-1 , end = forward ? int( mcIndices.size() ) : -1 , dir = forward ? 1 : -1;
	for( int j=start ; j!=end ; j+=dir )
	{
		const std::vector< int >& _mcIndices = mcIndices[j];
		sum += int( _mcIndices.size() );
		{
#pragma omp parallel for num_threads( threads )
			for( int k=0 ; k<int( _mcIndices.size() ) ; k++ )
			{
				int jj = _mcIndices[k];
				T diagonal = M[jj][0].Value;
#if ZERO_TESTING_JACOBI
				if( diagonal )
#endif // ZERO_TESTING_JACOBI
				{
					ConstPointer( MatrixEntry< T > ) start = M[jj];
					ConstPointer( MatrixEntry< T > ) end = start + M.rowSizes[jj];
					ConstPointer( MatrixEntry< T > ) e;
					start++;
					T2 _b = b[jj];
					for( e=start ; e!=end ; e++ ) _b -= x[ e->N ] * e->Value;
					x[jj] = _b / diagonal;
				}
			}
		}
	}
	return sum;
}

template< class T >
template< class T2 >
void SparseMatrix< T >::getDiagonal( Pointer( T2 ) diagonal , int threads ) const
{
#pragma omp parallel for num_threads( threads )
	for( int i=0 ; i<rows ; i++ )
	{
		T2 d = 0.;
		ConstPointer( MatrixEntry< T > ) start = m_ppElements[i];
		ConstPointer( MatrixEntry< T > ) end = start + rowSizes[i];
		ConstPointer( MatrixEntry< T > ) e;
		for( e=start ; e!=end ; e++ ) if( e->N==i ) d += e->Value;
		diagonal[i] = d;
	}
}
template< class T >
template< class T2 >
int SparseMatrix< T >::SolveCG( const SparseMatrix<T>& A , ConstPointer( T2 ) b , int iters , Pointer( T2 ) x , T2 eps , int reset , bool addDCTerm , bool solveNormal , int threads )
{
	eps *= eps;
	int dim = A.rows;
	Pointer( T2 ) r = AllocPointer< T2 >( dim );
	Pointer( T2 ) d = AllocPointer< T2 >( dim );
	Pointer( T2 ) q = AllocPointer< T2 >( dim );
	Pointer( T2 ) temp = NullPointer( T2 );
	if( reset ) memset( x , 0 , sizeof(T2)* dim );
	if( solveNormal ) temp = AllocPointer< T2 >( dim );

	double delta_new = 0 , delta_0;
	if( solveNormal )
	{
		if( addDCTerm ) A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )x , temp , threads ) , A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )temp , r , threads ) , A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )b , temp , threads );
		else            A.Multiply( ( ConstPointer( T2 ) )x , temp , threads ) , A.Multiply( ( ConstPointer( T2 ) )temp , r , threads ) , A.Multiply( ( ConstPointer( T2 ) )b , temp , threads );
#pragma omp parallel for num_threads( threads ) reduction( + : delta_new )
		for( int i=0 ; i<dim ; i++ ) d[i] = r[i] = temp[i] - r[i] , delta_new += r[i] * r[i];
	}
	else
	{
		if( addDCTerm ) A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )x , r , threads );
		else            A.Multiply( ( ConstPointer( T2 ) )x , r , threads );
#pragma omp parallel for num_threads( threads )  reduction ( + : delta_new )
		for( int i=0 ; i<dim ; i++ ) d[i] = r[i] = b[i] - r[i] , delta_new += r[i] * r[i];
	}
	delta_0 = delta_new;
	if( delta_new<eps )
	{
//		fprintf( stderr , "[WARNING] Initial residual too low: %g < %f\n" , delta_new , eps );
		FreePointer( r );
		FreePointer( d );
		FreePointer( q );
		FreePointer( temp );
		return 0;
	}
	int ii;
	for( ii=0 ; ii<iters && delta_new>eps*delta_0 ; ii++ )
	{
		if( solveNormal )
			if( addDCTerm ) A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )d , temp , threads ) , A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )temp , q , threads );
			else            A.Multiply( ( ConstPointer( T2 ) )d , temp , threads ) , A.Multiply( ( ConstPointer( T2 ) )temp , q , threads );
		else
			if( addDCTerm ) A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )d , q , threads );
			else            A.Multiply( ( ConstPointer( T2 ) )d , q , threads );
        double dDotQ = 0;
#pragma omp parallel for num_threads( threads ) reduction( + : dDotQ )
		for( int i=0 ; i<dim ; i++ ) dDotQ += d[i] * q[i];
		T2 alpha = T2( delta_new / dDotQ );
		double delta_old = delta_new;
		delta_new = 0;
		if( (ii%50)==(50-1) )
		{
#pragma omp parallel for num_threads( threads )
			for( int i=0 ; i<dim ; i++ ) x[i] += d[i] * alpha;
			if( solveNormal )
				if( addDCTerm ) A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )x , temp , threads ) , A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )temp , r , threads );
				else            A.Multiply( ( ConstPointer( T2 ) )x , temp , threads ) , A.Multiply( ( ConstPointer( T2 ) )temp , r , threads );
			else
				if( addDCTerm ) A.MultiplyAndAddAverage( ( ConstPointer( T2 ) )x , r , threads );
				else            A.Multiply( ( ConstPointer( T2 ) )x , r , threads );
#pragma omp parallel for num_threads( threads ) reduction( + : delta_new )
			for( int i=0 ; i<dim ; i++ ) r[i] = b[i] - r[i] , delta_new += r[i] * r[i] , x[i] += d[i] * alpha;
		}
		else
#pragma omp parallel for num_threads( threads ) reduction( + : delta_new )
			for( int i=0 ; i<dim ; i++ ) r[i] -= q[i] * alpha , delta_new += r[i] * r[i] ,  x[i] += d[i] * alpha;

		T2 beta = T2( delta_new / delta_old );
#pragma omp parallel for num_threads( threads )
		for( int i=0 ; i<dim ; i++ ) d[i] = r[i] + d[i] * beta;
	}
	FreePointer( r );
	FreePointer( d );
	FreePointer( q );
	FreePointer( temp );
	return ii;
}

{'repo_name': 'colmap/colmap', 'stars': '2132', 'repo_language': 'C', 'file_name': 'FindGlew.cmake', 'mime_type': 'text/plain', 'hash': -7647398255914305805, 'source_dataset': 'data'}


// Generated by delombok at Sat Jun 11 11:12:44 CEST 2016

import lombok.*;

class TrickyDoNothing {

	@interface Getter {
	}

	@Getter
	int x;
}

class TrickyDoNothing2 {
	@Getter
	int x;

	@interface Getter {
	}
}

class TrickySuccess {
	int x;

	@java.lang.SuppressWarnings("all")
	public int getX() {
		return this.x;
	}
}

class TrickyDoNothing3 {
	void test() {

		class val {
		}
		val x = null;
	}
}

class TrickyDoSomething {
	void test() {
		final java.lang.Object x = null;
		class val {
		}
	}
}

class DoubleTrickyDoNothing {
	void test() {

		class val {
		}
		for (int i = 10; i < 20; i++) {
			val y = null;
		}
	}
}

class DoubleTrickyDoSomething {
	void test() {
		for (int j = 10; j < 20; j++) {

			class val {
			}
		}
		for (int i = 10; i < 20; i++) {
			final java.lang.Object y = null;
		}
	}
}

{'repo_name': 'mplushnikov/lombok-intellij-plugin', 'stars': '2478', 'repo_language': 'Java', 'file_name': 'FieldNameConstants.java', 'mime_type': 'text/x-java', 'hash': -1417894113651690916, 'source_dataset': 'data'}


/*
Copyright 2020 Google LLC

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

    https://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.
*/

// Code generated by client-gen. DO NOT EDIT.

package v1beta2

import (
	"time"

	v1beta2 "github.com/GoogleCloudPlatform/gke-managed-certs/pkg/apis/networking.gke.io/v1beta2"
	scheme "github.com/GoogleCloudPlatform/gke-managed-certs/pkg/clientgen/clientset/versioned/scheme"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
)

// ManagedCertificatesGetter has a method to return a ManagedCertificateInterface.
// A group's client should implement this interface.
type ManagedCertificatesGetter interface {
	ManagedCertificates(namespace string) ManagedCertificateInterface
}

// ManagedCertificateInterface has methods to work with ManagedCertificate resources.
type ManagedCertificateInterface interface {
	Create(*v1beta2.ManagedCertificate) (*v1beta2.ManagedCertificate, error)
	Update(*v1beta2.ManagedCertificate) (*v1beta2.ManagedCertificate, error)
	UpdateStatus(*v1beta2.ManagedCertificate) (*v1beta2.ManagedCertificate, error)
	Delete(name string, options *v1.DeleteOptions) error
	DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
	Get(name string, options v1.GetOptions) (*v1beta2.ManagedCertificate, error)
	List(opts v1.ListOptions) (*v1beta2.ManagedCertificateList, error)
	Watch(opts v1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta2.ManagedCertificate, err error)
	ManagedCertificateExpansion
}

// managedCertificates implements ManagedCertificateInterface
type managedCertificates struct {
	client rest.Interface
	ns     string
}

// newManagedCertificates returns a ManagedCertificates
func newManagedCertificates(c *NetworkingV1beta2Client, namespace string) *managedCertificates {
	return &managedCertificates{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

// Get takes name of the managedCertificate, and returns the corresponding managedCertificate object, and an error if there is any.
func (c *managedCertificates) Get(name string, options v1.GetOptions) (result *v1beta2.ManagedCertificate, err error) {
	result = &v1beta2.ManagedCertificate{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("managedcertificates").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of ManagedCertificates that match those selectors.
func (c *managedCertificates) List(opts v1.ListOptions) (result *v1beta2.ManagedCertificateList, err error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	result = &v1beta2.ManagedCertificateList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("managedcertificates").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Do().
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested managedCertificates.
func (c *managedCertificates) Watch(opts v1.ListOptions) (watch.Interface, error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	opts.Watch = true
	return c.client.Get().
		Namespace(c.ns).
		Resource("managedcertificates").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Watch()
}

// Create takes the representation of a managedCertificate and creates it.  Returns the server's representation of the managedCertificate, and an error, if there is any.
func (c *managedCertificates) Create(managedCertificate *v1beta2.ManagedCertificate) (result *v1beta2.ManagedCertificate, err error) {
	result = &v1beta2.ManagedCertificate{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("managedcertificates").
		Body(managedCertificate).
		Do().
		Into(result)
	return
}

// Update takes the representation of a managedCertificate and updates it. Returns the server's representation of the managedCertificate, and an error, if there is any.
func (c *managedCertificates) Update(managedCertificate *v1beta2.ManagedCertificate) (result *v1beta2.ManagedCertificate, err error) {
	result = &v1beta2.ManagedCertificate{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("managedcertificates").
		Name(managedCertificate.Name).
		Body(managedCertificate).
		Do().
		Into(result)
	return
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().

func (c *managedCertificates) UpdateStatus(managedCertificate *v1beta2.ManagedCertificate) (result *v1beta2.ManagedCertificate, err error) {
	result = &v1beta2.ManagedCertificate{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("managedcertificates").
		Name(managedCertificate.Name).
		SubResource("status").
		Body(managedCertificate).
		Do().
		Into(result)
	return
}

// Delete takes name of the managedCertificate and deletes it. Returns an error if one occurs.
func (c *managedCertificates) Delete(name string, options *v1.DeleteOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("managedcertificates").
		Name(name).
		Body(options).
		Do().
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *managedCertificates) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	var timeout time.Duration
	if listOptions.TimeoutSeconds != nil {
		timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
	}
	return c.client.Delete().
		Namespace(c.ns).
		Resource("managedcertificates").
		VersionedParams(&listOptions, scheme.ParameterCodec).
		Timeout(timeout).
		Body(options).
		Do().
		Error()
}

// Patch applies the patch and returns the patched managedCertificate.
func (c *managedCertificates) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta2.ManagedCertificate, err error) {
	result = &v1beta2.ManagedCertificate{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("managedcertificates").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return
}

{'repo_name': 'GoogleCloudPlatform/gke-managed-certs', 'stars': '192', 'repo_language': 'Go', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': 558010669256052223, 'source_dataset': 'data'}


'use strict';

var utility = require('../utility');

describe('sub-languages', function() {
  before(function() {
    this.block = document.querySelector('#sublanguages');
  });

  it('should highlight XML with PHP and JavaScript', function(done) {
    var filename = utility.buildPath('expect', 'sublanguages.txt'),
        actual   = this.block.innerHTML;

    utility.expectedFile(filename, 'utf-8', actual, done);
  });
});

{'repo_name': 'facebookarchive/immutable-re', 'stars': '215', 'repo_language': 'OCaml', 'file_name': 'PerfTest.re', 'mime_type': 'text/plain', 'hash': 2744589212403083401, 'source_dataset': 'data'}


DoN AI Navigation Plugin (Flying AI /3D Aerial Pathfinding)

This plugin is a solution for 3D pathfinding for flying creatures.

	It uses voxel based navigation, supports dynamic collision updates and comes with a behavior tree task 'Fly to' which you may directly use in your behavior trees.

	Also provided is an API with pathfinding functions for custom navigation queries

{'repo_name': 'VSZue/DonAINavigation', 'stars': '164', 'repo_language': 'C++', 'file_name': 'FilterPlugin.ini', 'mime_type': 'text/plain', 'hash': -5791405007279267085, 'source_dataset': 'data'}


////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2002-2009  The Bochs Project
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

#ifndef BX_IODEV_BIOSDEV_H
#define BX_IODEV_BIOSDEV_H

#define BX_BIOS_MESSAGE_SIZE 80

#if BX_USE_BIOS_SMF
#  define BX_BIOS_SMF  static
#  define BX_BIOS_THIS theBiosDevice->
#else
#  define BX_BIOS_SMF
#  define BX_BIOS_THIS this->
#endif

class bx_biosdev_c : public bx_devmodel_c {
public:
  bx_biosdev_c();
  virtual ~bx_biosdev_c();

  virtual void init(void);
  virtual void reset(unsigned type) {}

private:

  static void   write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len);
#if !BX_USE_BIOS_SMF
  void   write(Bit32u address, Bit32u value, unsigned io_len);
#endif

  struct {
    Bit8u bios_message[BX_BIOS_MESSAGE_SIZE];
    unsigned int bios_message_i;
    bx_bool bios_panic_flag;

    Bit8u vgabios_message[BX_BIOS_MESSAGE_SIZE];
    unsigned int vgabios_message_i;
    bx_bool vgabios_panic_flag;
  } s;  // state information
};

#endif

{'repo_name': 'KyujuuAlpha/iBox-2', 'stars': '102', 'repo_language': 'C++', 'file_name': 'Info.plist', 'mime_type': 'text/xml', 'hash': -1467352668697532262, 'source_dataset': 'data'}


/*
 * Copyright (C) by Argonne National Laboratory
 *     See COPYRIGHT in top-level directory
 */

#include "mpiimpl.h"
#include "hcoll/api/hcoll_dte.h"
#include "hcoll_dtypes.h"

extern int hcoll_initialized;
extern int hcoll_enable;

static dte_data_representation_t mpi_predefined_derived_2_hcoll(MPI_Datatype datatype)
{
    MPI_Aint size;

    switch (datatype) {
        case MPI_FLOAT_INT:
            return DTE_FLOAT_INT;
        case MPI_DOUBLE_INT:
            return DTE_DOUBLE_INT;
        case MPI_LONG_INT:
            return DTE_LONG_INT;
        case MPI_SHORT_INT:
            return DTE_SHORT_INT;
        case MPI_LONG_DOUBLE_INT:
            return DTE_LONG_DOUBLE_INT;
        case MPI_2INT:
            return DTE_2INT;
#ifdef HAVE_FORTRAN_BINDING
#if HCOLL_API >= HCOLL_VERSION(3,7)
        case MPI_2INTEGER:
            MPIR_Datatype_get_size_macro(datatype, size);
            switch (size) {
                case 4:
                    return DTE_2INT;
                case 8:
                    return DTE_2INT64;
                default:
                    return DTE_ZERO;
            }
        case MPI_2REAL:
            MPIR_Datatype_get_size_macro(datatype, size);
            switch (size) {
                case 4:
                    return DTE_2FLOAT32;
                case 8:
                    return DTE_2FLOAT64;
                default:
                    return DTE_ZERO;
            }
        case MPI_2DOUBLE_PRECISION:
            MPIR_Datatype_get_size_macro(datatype, size);
            switch (size) {
                case 4:
                    return DTE_2FLOAT32;
                case 8:
                    return DTE_2FLOAT64;
                default:
                    return DTE_ZERO;
            }
#endif
#endif
        default:
            break;
    }
    return DTE_ZERO;
}

dte_data_representation_t mpi_dtype_2_hcoll_dtype(MPI_Datatype datatype, int count, const int mode)
{
    dte_data_representation_t dte_data_rep = DTE_ZERO;

    if (HANDLE_GET_KIND((datatype)) == HANDLE_KIND_BUILTIN) {
        /* Built-in type */
        dte_data_rep = mpi_dtype_2_dte_dtype(datatype);
    }
#if HCOLL_API >= HCOLL_VERSION(3,6)
    else if (TRY_FIND_DERIVED == mode) {

        /* Check for predefined derived types */
        dte_data_rep = mpi_predefined_derived_2_hcoll(datatype);
        if (HCOL_DTE_IS_ZERO(dte_data_rep)) {
            MPIR_Datatype *dt_ptr;

            /* Must be a non-predefined derived mapping, get it */
            MPIR_Datatype_get_ptr(datatype, dt_ptr);
            dte_data_rep = (dte_data_representation_t) dt_ptr->dev.hcoll_datatype;
        }
    }
#endif

    /* We always fall back, don't even think about forcing it! */
    /* XXX Fix me
     * if (HCOL_DTE_IS_ZERO(dte_data_rep) && TRY_FIND_DERIVED == mode
     * && !mca_coll_hcoll_component.hcoll_datatype_fallback) {
     * dte_data_rep = DTE_ZERO;
     * dte_data_rep.rep.in_line_rep.data_handle.in_line.in_line = 0;
     * dte_data_rep.rep.in_line_rep.data_handle.pointer_to_handle = (uint64_t) &datatype;
     * }
     */
    return dte_data_rep;
}

/* This will only get called once */
int hcoll_type_commit_hook(MPIR_Datatype * dtype_p)
{
    int mpi_errno, ret;

    if (0 == hcoll_initialized) {
        mpi_errno = hcoll_initialize();
        if (mpi_errno)
            return MPI_ERR_OTHER;
    }

    if (0 == hcoll_enable) {
        return MPI_SUCCESS;
    }

    dtype_p->dev.hcoll_datatype = mpi_predefined_derived_2_hcoll(dtype_p->handle);
    if (!HCOL_DTE_IS_ZERO(dtype_p->dev.hcoll_datatype)) {
        return MPI_SUCCESS;
    }

    dtype_p->dev.hcoll_datatype = DTE_ZERO;

    ret = hcoll_create_mpi_type((void *) (intptr_t) dtype_p->handle, &dtype_p->dev.hcoll_datatype);
    if (HCOLL_SUCCESS != ret) {
        return MPI_ERR_OTHER;
    }

    if (HCOL_DTE_IS_ZERO(dtype_p->dev.hcoll_datatype))
        MPIR_Datatype_add_ref_if_not_builtin(dtype_p->handle);

    return MPI_SUCCESS;
}

int hcoll_type_free_hook(MPIR_Datatype * dtype_p)
{
    if (0 == hcoll_enable) {
        return MPI_SUCCESS;
    }

    if (HCOL_DTE_IS_ZERO(dtype_p->dev.hcoll_datatype))
        MPIR_Datatype_release_if_not_builtin(dtype_p->handle);

    int rc = hcoll_dt_destroy(dtype_p->dev.hcoll_datatype);
    if (HCOLL_SUCCESS != rc) {
        return MPI_ERR_OTHER;
    }

    dtype_p->dev.hcoll_datatype = DTE_ZERO;

    return MPI_SUCCESS;
}

{'repo_name': 'pmodels/mpich', 'stars': '232', 'repo_language': 'C', 'file_name': 'design.tex', 'mime_type': 'text/x-tex', 'hash': -657712314135619190, 'source_dataset': 'data'}


'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
  "DATETIME_FORMATS": {
    "AMPMS": [
      "AM",
      "PM"
    ],
    "DAY": [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ],
    "MONTH": [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ],
    "SHORTDAY": [
      "Sun",
      "Mon",
      "Tue",
      "Wed",
      "Thu",
      "Fri",
      "Sat"
    ],
    "SHORTMONTH": [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ],
    "fullDate": "EEEE, d MMMM, y",
    "longDate": "d MMMM, y",
    "medium": "d MMM, y h:mm:ss a",
    "mediumDate": "d MMM, y",
    "mediumTime": "h:mm:ss a",
    "short": "d/M/yy h:mm a",
    "shortDate": "d/M/yy",
    "shortTime": "h:mm a"
  },
  "NUMBER_FORMATS": {
    "CURRENCY_SYM": "$",
    "DECIMAL_SEP": ".",
    "GROUP_SEP": ",",
    "PATTERNS": [
      {
        "gSize": 3,
        "lgSize": 3,
        "macFrac": 0,
        "maxFrac": 3,
        "minFrac": 0,
        "minInt": 1,
        "negPre": "-",
        "negSuf": "",
        "posPre": "",
        "posSuf": ""
      },
      {
        "gSize": 3,
        "lgSize": 3,
        "macFrac": 0,
        "maxFrac": 2,
        "minFrac": 2,
        "minInt": 1,
        "negPre": "(\u00a4",
        "negSuf": ")",
        "posPre": "\u00a4",
        "posSuf": ""
      }
    ]
  },
  "id": "en-hk",
  "pluralCat": function (n) {  if (n == 1) {   return PLURAL_CATEGORY.ONE;  }  return PLURAL_CATEGORY.OTHER;}
});
}]);

{'repo_name': 'martin-nikolov/Telerik-Academy', 'stars': '182', 'repo_language': 'C#', 'file_name': 'Readme.md', 'mime_type': 'text/plain', 'hash': -7285877504580093184, 'source_dataset': 'data'}


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>订单结算页 -宜立方商城</title>

<link rel="stylesheet" type="text/css" href="/css/jquery.alerts.css?v=20160713" />
<link rel="stylesheet" type="text/css" href="/css/head.css?v=20160713" />
<link rel="stylesheet" type="text/css" href="/css/order.css?v=20160713">

<jsp:include page="commons/header.jsp" />

<form id="orderForm" class="hide" action="/order/create.html" method="post">
	<input type="hidden" name="paymentType" value="2"/>
	<input type="hidden" name="postFee" value="10"/>
	<c:forEach items="${cartList }" var="cart" varStatus="status">
		<c:set var="totalPrice"  value="${ totalPrice + (cart.price * cart.num)}"/>
		<input type="hidden" name="orderItems[${status.index}].itemId" value="${cart.id}"/>
		<input type="hidden" name="orderItems[${status.index}].num" value="${cart.num }"/>
		<input type="hidden" name="orderItems[${status.index}].price" value="${cart.price}"/>
		<input type="hidden" name="orderItems[${status.index}].totalFee" value="${cart.price * cart.num}"/>
		<input type="hidden" name="orderItems[${status.index}].title" value="${cart.title}"/>
		<input type="hidden" name="orderItems[${status.index}].picPath" value="${cart.image}"/>
	</c:forEach>
	<input type="hidden" name="payment" value="<fmt:formatNumber groupingUsed="false" maxFractionDigits="2" minFractionDigits="2" value="${totalPrice/100 }"/>"/>
	<input type="hidden" name="orderShipping.receiverName" value="入云龙"/>
	<input type="hidden" name="orderShipping.receiverMobile" value="15800888888"/>
	<input type="hidden" name="orderShipping.receiverState" value="北京"/>
	<input type="hidden" name="orderShipping.receiverCity" value="北京"/>
	<input type="hidden" name="orderShipping.receiverDistrict" value="昌平区"/>
	<input type="hidden" name="orderShipping.receiverAddress" value="北京市昌平区北七家镇 修正大厦"/>
</form>

填写并核对订单信息

收货人信息：[修改]

入云龙    15800888888    北京市  昌平区  北七家镇 修正大厦

支付及配送方式：
  	[修改]

在线支付

					订单1

							宜立方速运负责配送。
商品下单后尽快为您发货

发票信息：[修改]

暂不需要发票

返回修改购物车

商品信息：

				商品下单后尽快为您发货

商品图片

商品名称

单价

返现

库存状态

数量

重量(含包装)

小计

				<c:forEach items="${cartList }" var="cart" varStatus="status">

						${cart.title }

						¥<fmt:formatNumber
							groupingUsed="false" maxFractionDigits="2"
							minFractionDigits="2" value="${cart.price / 100 }" />

¥0

现货

${cart.num}

0.72kg

¥${cart.price / 100 * cart.num}

				</c:forEach>

					运费小计： ¥10

商品总重量：0.72kg（含包装）

1 件商品，总商品金额：
¥
				<fmt:formatNumber value="${totalPrice / 100 }" maxFractionDigits="2" minFractionDigits="2" groupingUsed="true"/>

运费金额：
¥10

应付总额：
¥
            	<fmt:formatNumber value="${totalPrice / 100 + 10}" maxFractionDigits="2" minFractionDigits="2" groupingUsed="true"/>

      	<input id="save" name="save" onclick="$('#orderForm').submit()" class="submitBtn" value="提交订单 " type="button"/>

        应付总额：
        ¥
        	<fmt:formatNumber value="${totalPrice / 100 + 10}" maxFractionDigits="2" minFractionDigits="2" groupingUsed="true"/>

<jsp:include page="commons/footer.jsp" />

{'repo_name': 'catalinaLi/ideaTaotao', 'stars': '144', 'repo_language': 'JavaScript', 'file_name': 'CartController.java', 'mime_type': 'text/x-java', 'hash': -3323495047228010942, 'source_dataset': 'data'}


import * as jQuery from "jquery";
import { getPositionName, Node, Position } from "./node";
import { DropHint, HitArea, PositionInfo } from "./types";
import { NodeElement } from "./nodeElement";
import { JqTreeWidget } from "./tree.jquery";

interface Dimensions {
    left: number;
    top: number;
    right: number;
    bottom: number;
}

export class DragAndDropHandler {
    public hitAreas: HitArea[];
    public isDragging: boolean;
    public currentItem: NodeElement | null;
    public hoveredArea: HitArea | null;
    public positionInfo: PositionInfo | null;

    private treeWidget: JqTreeWidget;
    private dragElement: DragElement | null;
    private previousGhost: DropHint | null;
    private openFolderTimer: number | null;

    constructor(treeWidget: JqTreeWidget) {
        this.treeWidget = treeWidget;

        this.hoveredArea = null;
        this.hitAreas = [];
        this.isDragging = false;
        this.currentItem = null;
        this.positionInfo = null;
    }

    public mouseCapture(positionInfo: PositionInfo): boolean | null {
        const $element = jQuery(positionInfo.target);

        if (!this.mustCaptureElement($element)) {
            return null;
        }

        if (
            this.treeWidget.options.onIsMoveHandle &&
            !this.treeWidget.options.onIsMoveHandle($element)
        ) {
            return null;
        }

        let nodeElement = this.treeWidget._getNodeElement($element);

        if (nodeElement && this.treeWidget.options.onCanMove) {
            if (!this.treeWidget.options.onCanMove(nodeElement.node)) {
                nodeElement = null;
            }
        }

        this.currentItem = nodeElement;
        return this.currentItem != null;
    }

    public generateHitAreas(): void {
        if (!this.currentItem) {
            this.hitAreas = [];
        } else {
            const hitAreasGenerator = new HitAreasGenerator(
                this.treeWidget.tree,
                this.currentItem.node,
                this.getTreeDimensions().bottom
            );
            this.hitAreas = hitAreasGenerator.generate();
        }
    }

    public mouseStart(positionInfo: PositionInfo): boolean {
        if (
            !this.currentItem ||
            positionInfo.pageX === undefined ||
            positionInfo.pageY === undefined
        ) {
            return false;
        } else {
            this.refresh();

            const offset = jQuery(positionInfo.target).offset();
            const left = offset ? offset.left : 0;
            const top = offset ? offset.top : 0;

            const node = this.currentItem.node;

            this.dragElement = new DragElement(
                node.name,
                positionInfo.pageX - left,
                positionInfo.pageY - top,
                this.treeWidget.element,
                this.treeWidget.options.autoEscape ?? true
            );

            this.isDragging = true;
            this.positionInfo = positionInfo;
            this.currentItem.$element.addClass("jqtree-moving");
            return true;
        }
    }

    public mouseDrag(positionInfo: PositionInfo): boolean {
        if (
            !this.currentItem ||
            !this.dragElement ||
            positionInfo.pageX === undefined ||
            positionInfo.pageY === undefined
        ) {
            return false;
        } else {
            this.dragElement.move(positionInfo.pageX, positionInfo.pageY);
            this.positionInfo = positionInfo;

            const area = this.findHoveredArea(
                positionInfo.pageX,
                positionInfo.pageY
            );
            const canMoveTo = this.canMoveToArea(area);

            if (canMoveTo && area) {
                if (!area.node.isFolder()) {
                    this.stopOpenFolderTimer();
                }

                if (this.hoveredArea !== area) {
                    this.hoveredArea = area;

                    // If this is a closed folder, start timer to open it
                    if (this.mustOpenFolderTimer(area)) {
                        this.startOpenFolderTimer(area.node);
                    } else {
                        this.stopOpenFolderTimer();
                    }

                    this.updateDropHint();
                }
            } else {
                this.removeHover();
                this.removeDropHint();
                this.stopOpenFolderTimer();
            }

            if (!area) {
                if (this.treeWidget.options.onDragMove) {
                    this.treeWidget.options.onDragMove(
                        this.currentItem.node,
                        positionInfo.originalEvent
                    );
                }
            }

            return true;
        }
    }

    public mouseStop(positionInfo: PositionInfo): boolean {
        this.moveItem(positionInfo);
        this.clear();
        this.removeHover();
        this.removeDropHint();
        this.removeHitAreas();

        const currentItem = this.currentItem;

        if (this.currentItem) {
            this.currentItem.$element.removeClass("jqtree-moving");
            this.currentItem = null;
        }

        this.isDragging = false;
        this.positionInfo = null;

        if (!this.hoveredArea && currentItem) {
            if (this.treeWidget.options.onDragStop) {
                this.treeWidget.options.onDragStop(
                    currentItem.node,
                    positionInfo.originalEvent
                );
            }
        }

        return false;
    }

    public refresh(): void {
        this.removeHitAreas();

        if (this.currentItem) {
            this.generateHitAreas();

            this.currentItem = this.treeWidget._getNodeElementForNode(
                this.currentItem.node
            );

            if (this.isDragging) {
                this.currentItem.$element.addClass("jqtree-moving");
            }
        }
    }

    private mustCaptureElement($element: JQuery<HTMLElement>): boolean {
        return !$element.is("input,select,textarea");
    }

    private canMoveToArea(area: HitArea | null): boolean {
        if (!area || !this.currentItem) {
            return false;
        } else if (this.treeWidget.options.onCanMoveTo) {
            const positionName = getPositionName(area.position);

            return this.treeWidget.options.onCanMoveTo(
                this.currentItem.node,
                area.node,
                positionName
            );
        } else {
            return true;
        }
    }

    private removeHitAreas(): void {
        this.hitAreas = [];
    }

    private clear(): void {
        if (this.dragElement) {
            this.dragElement.remove();
            this.dragElement = null;
        }
    }

    private removeDropHint(): void {
        if (this.previousGhost) {
            this.previousGhost.remove();
        }
    }

    private removeHover(): void {
        this.hoveredArea = null;
    }

    private findHoveredArea(x: number, y: number): HitArea | null {
        const dimensions = this.getTreeDimensions();

        if (
            x < dimensions.left ||
            y < dimensions.top ||
            x > dimensions.right ||
            y > dimensions.bottom
        ) {
            return null;
        }

        let low = 0;
        let high = this.hitAreas.length;
        while (low < high) {
            const mid = (low + high) >> 1;
            const area = this.hitAreas[mid];

            if (y < area.top) {
                high = mid;
            } else if (y > area.bottom) {
                low = mid + 1;
            } else {
                return area;
            }
        }

        return null;
    }

    private mustOpenFolderTimer(area: HitArea): boolean {
        const node = area.node;

        return (
            node.isFolder() &&
            !node.is_open &&
            area.position === Position.Inside
        );
    }

    private updateDropHint(): void {
        if (!this.hoveredArea) {
            return;
        }

        // remove previous drop hint
        this.removeDropHint();

        // add new drop hint
        const nodeElement = this.treeWidget._getNodeElementForNode(
            this.hoveredArea.node
        );
        this.previousGhost = nodeElement.addDropHint(this.hoveredArea.position);
    }

    private startOpenFolderTimer(folder: Node): void {
        const openFolder = (): void => {
            this.treeWidget._openNode(
                folder,
                this.treeWidget.options.slide,
                () => {
                    this.refresh();
                    this.updateDropHint();
                }
            );
        };

        this.stopOpenFolderTimer();

        this.openFolderTimer = window.setTimeout(
            openFolder,
            this.treeWidget.options.openFolderDelay
        );
    }

    private stopOpenFolderTimer(): void {
        if (this.openFolderTimer) {
            clearTimeout(this.openFolderTimer);
            this.openFolderTimer = null;
        }
    }

    private moveItem(positionInfo: PositionInfo): void {
        if (
            this.currentItem &&
            this.hoveredArea &&
            this.hoveredArea.position !== Position.None &&
            this.canMoveToArea(this.hoveredArea)
        ) {
            const movedNode = this.currentItem.node;
            const targetNode = this.hoveredArea.node;
            const position = this.hoveredArea.position;
            const previousParent = movedNode.parent;

            if (position === Position.Inside) {
                this.hoveredArea.node.is_open = true;
            }

            const doMove = (): void => {
                this.treeWidget.tree.moveNode(movedNode, targetNode, position);
                this.treeWidget.element.empty();
                this.treeWidget._refreshElements(null);
            };

            const event = this.treeWidget._triggerEvent("tree.move", {
                move_info: {
                    moved_node: movedNode,
                    target_node: targetNode,
                    position: getPositionName(position),
                    previous_parent: previousParent,
                    do_move: doMove,
                    original_event: positionInfo.originalEvent,
                },
            });

            if (!event.isDefaultPrevented()) {
                doMove();
            }
        }
    }

    private getTreeDimensions(): Dimensions {
        // Return the dimensions of the tree. Add a margin to the bottom to allow
        // to drag-and-drop after the last element.
        const offset = this.treeWidget.element.offset();

        if (!offset) {
            return { left: 0, top: 0, right: 0, bottom: 0 };
        } else {
            const el = this.treeWidget.element;
            const width = el.width() || 0;
            const height = el.height() || 0;
            const left = offset.left + this.treeWidget._getScrollLeft();

            return {
                left,
                top: offset.top,
                right: left + width,
                bottom: offset.top + height + 16,
            };
        }
    }
}

abstract class VisibleNodeIterator {
    private tree: Node;

    constructor(tree: Node) {
        this.tree = tree;
    }

    protected iterate(): void {
        let isFirstNode = true;

        const _iterateNode = (node: Node, nextNode: Node | null): void => {
            let mustIterateInside =
                (node.is_open || !node.element) && node.hasChildren();

            let $element: JQuery<HTMLElement> | null = null;

            if (node.element) {
                $element = jQuery(node.element);

                if (!$element.is(":visible")) {
                    return;
                }

                if (isFirstNode) {
                    this.handleFirstNode(node);
                    isFirstNode = false;
                }

                if (!node.hasChildren()) {
                    this.handleNode(node, nextNode, $element);
                } else if (node.is_open) {
                    if (!this.handleOpenFolder(node, $element)) {
                        mustIterateInside = false;
                    }
                } else {
                    this.handleClosedFolder(node, nextNode, $element);
                }
            }

            if (mustIterateInside) {
                const childrenLength = node.children.length;
                node.children.forEach((_, i) => {
                    if (i === childrenLength - 1) {
                        _iterateNode(node.children[i], null);
                    } else {
                        _iterateNode(node.children[i], node.children[i + 1]);
                    }
                });

                if (node.is_open && $element) {
                    this.handleAfterOpenFolder(node, nextNode);
                }
            }
        };

        _iterateNode(this.tree, null);
    }

    protected abstract handleNode(
        node: Node,
        nextNode: Node | null,
        $element: JQuery
    ): void;

    /*
    override
    return
        - true: continue iterating
        - false: stop iterating
    */
    protected abstract handleOpenFolder(node: Node, $element: JQuery): boolean;

    protected abstract handleClosedFolder(
        node: Node,
        nextNode: Node | null,
        $element: JQuery
    ): void;

    protected abstract handleAfterOpenFolder(
        node: Node,
        nextNode: Node | null
    ): void;

    protected abstract handleFirstNode(node: Node): void;
}

export class HitAreasGenerator extends VisibleNodeIterator {
    private currentNode: Node;
    private treeBottom: number;
    private positions: HitArea[];
    private lastTop: number;

    constructor(tree: Node, currentNode: Node, treeBottom: number) {
        super(tree);

        this.currentNode = currentNode;
        this.treeBottom = treeBottom;
    }

    public generate(): HitArea[] {
        this.positions = [];
        this.lastTop = 0;

        this.iterate();

        return this.generateHitAreas(this.positions);
    }

    protected generateHitAreas(positions: HitArea[]): HitArea[] {
        let previousTop = -1;
        let group = [];
        const hitAreas: HitArea[] = [];

        for (const position of positions) {
            if (position.top !== previousTop && group.length) {
                if (group.length) {
                    this.generateHitAreasForGroup(
                        hitAreas,
                        group,
                        previousTop,
                        position.top
                    );
                }

                previousTop = position.top;
                group = [];
            }

            group.push(position);
        }

        this.generateHitAreasForGroup(
            hitAreas,
            group,
            previousTop,
            this.treeBottom
        );

        return hitAreas;
    }

    protected handleOpenFolder(node: Node, $element: JQuery): boolean {
        if (node === this.currentNode) {
            // Cannot move inside current item
            // Stop iterating
            return false;
        }

        // Cannot move before current item
        if (node.children[0] !== this.currentNode) {
            this.addPosition(node, Position.Inside, this.getTop($element));
        }

        // Continue iterating
        return true;
    }

    protected handleClosedFolder(
        node: Node,
        nextNode: Node,
        $element: JQuery
    ): void {
        const top = this.getTop($element);

        if (node === this.currentNode) {
            // Cannot move after current item
            this.addPosition(node, Position.None, top);
        } else {
            this.addPosition(node, Position.Inside, top);

            // Cannot move before current item
            if (nextNode !== this.currentNode) {
                this.addPosition(node, Position.After, top);
            }
        }
    }

    protected handleFirstNode(node: Node): void {
        if (node !== this.currentNode) {
            this.addPosition(
                node,
                Position.Before,
                this.getTop(jQuery(node.element))
            );
        }
    }

    protected handleAfterOpenFolder(node: Node, nextNode: Node): void {
        if (node === this.currentNode || nextNode === this.currentNode) {
            // Cannot move before or after current item
            this.addPosition(node, Position.None, this.lastTop);
        } else {
            this.addPosition(node, Position.After, this.lastTop);
        }
    }

    protected handleNode(node: Node, nextNode: Node, $element: JQuery): void {
        const top = this.getTop($element);

        if (node === this.currentNode) {
            // Cannot move inside current item
            this.addPosition(node, Position.None, top);
        } else {
            this.addPosition(node, Position.Inside, top);
        }

        if (nextNode === this.currentNode || node === this.currentNode) {
            // Cannot move before or after current item
            this.addPosition(node, Position.None, top);
        } else {
            this.addPosition(node, Position.After, top);
        }
    }

    private getTop($element: JQuery<HTMLElement>): number {
        const offset = $element.offset();

        return offset ? offset.top : 0;
    }

    private addPosition(node: Node, position: number, top: number): void {
        const area = {
            top,
            bottom: 0,
            node,
            position,
        };

        this.positions.push(area);
        this.lastTop = top;
    }

    private generateHitAreasForGroup(
        hitAreas: HitArea[],
        positionsInGroup: HitArea[],
        top: number,
        bottom: number
    ): void {
        // limit positions in group
        const positionCount = Math.min(positionsInGroup.length, 4);

        const areaHeight = Math.round((bottom - top) / positionCount);
        let areaTop = top;

        let i = 0;
        while (i < positionCount) {
            const position = positionsInGroup[i];

            hitAreas.push({
                top: areaTop,
                bottom: areaTop + areaHeight,
                node: position.node,
                position: position.position,
            });

            areaTop += areaHeight;
            i += 1;
        }
    }
}

class DragElement {
    private offsetX: number;
    private offsetY: number;
    private $element: JQuery;

    constructor(
        nodeName: string,
        offsetX: number,
        offsetY: number,
        $tree: JQuery,
        autoEscape: boolean
    ) {
        this.offsetX = offsetX;
        this.offsetY = offsetY;

        this.$element = jQuery("<span>").addClass(
            "jqtree-title jqtree-dragging"
        );

        if (autoEscape) {
            this.$element.text(nodeName);
        } else {
            this.$element.html(nodeName);
        }

        this.$element.css("position", "absolute");
        $tree.append(this.$element);
    }

    public move(pageX: number, pageY: number): void {
        this.$element.offset({
            left: pageX - this.offsetX,
            top: pageY - this.offsetY,
        });
    }

    public remove(): void {
        this.$element.remove();
    }
}

{'repo_name': 'mbraak/jqTree', 'stars': '962', 'repo_language': 'JavaScript', 'file_name': 'base.html', 'mime_type': 'text/html', 'hash': -8565171414011397283, 'source_dataset': 'data'}


# NOTE: Assertions have been autogenerated by utils/update_mca_test_checks.py
# RUN: llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=haswell -iterations=1 -timeline -resource-pressure=false < %s | FileCheck %s -check-prefix=ALL -check-prefix=HASWELL
# RUN: llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=broadwell -iterations=1 -timeline -resource-pressure=false < %s | FileCheck %s -check-prefix=ALL -check-prefix=BDWELL
# RUN: llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=skylake -iterations=1 -timeline -resource-pressure=false < %s | FileCheck %s -check-prefix=ALL -check-prefix=SKYLAKE
# RUN: llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=bdver2 -iterations=1 -timeline -resource-pressure=false < %s | FileCheck %s -check-prefix=ALL -check-prefix=BDVER2
# RUN: llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=btver2 -iterations=1 -timeline -resource-pressure=false < %s | FileCheck %s -check-prefix=ALL -check-prefix=BTVER2
# RUN: llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=znver1 -iterations=1 -timeline -resource-pressure=false < %s | FileCheck %s -check-prefix=ALL -check-prefix=ZNVER1

add     %edi, %esi
bextrl	%esi, (%rdi), %eax

# ALL:          Iterations:        1
# ALL-NEXT:     Instructions:      2

# BDVER2-NEXT:  Total Cycles:      9
# BDVER2-NEXT:  Total uOps:        3

# BDWELL-NEXT:  Total Cycles:      10
# BDWELL-NEXT:  Total uOps:        4

# BTVER2-NEXT:  Total Cycles:      7
# BTVER2-NEXT:  Total uOps:        2

# HASWELL-NEXT: Total Cycles:      10
# HASWELL-NEXT: Total uOps:        4

# SKYLAKE-NEXT: Total Cycles:      10
# SKYLAKE-NEXT: Total uOps:        4

# ZNVER1-NEXT:  Total Cycles:      8
# ZNVER1-NEXT:  Total uOps:        3

# BDVER2:       Dispatch Width:    4
# BDVER2-NEXT:  uOps Per Cycle:    0.33
# BDVER2-NEXT:  IPC:               0.22
# BDVER2-NEXT:  Block RThroughput: 1.0

# BDWELL:       Dispatch Width:    4
# BDWELL-NEXT:  uOps Per Cycle:    0.40
# BDWELL-NEXT:  IPC:               0.20
# BDWELL-NEXT:  Block RThroughput: 1.0

# BTVER2:       Dispatch Width:    2
# BTVER2-NEXT:  uOps Per Cycle:    0.29
# BTVER2-NEXT:  IPC:               0.29
# BTVER2-NEXT:  Block RThroughput: 1.0

# HASWELL:      Dispatch Width:    4
# HASWELL-NEXT: uOps Per Cycle:    0.40
# HASWELL-NEXT: IPC:               0.20
# HASWELL-NEXT: Block RThroughput: 1.0

# SKYLAKE:      Dispatch Width:    6
# SKYLAKE-NEXT: uOps Per Cycle:    0.40
# SKYLAKE-NEXT: IPC:               0.20
# SKYLAKE-NEXT: Block RThroughput: 0.7

# ZNVER1:       Dispatch Width:    4
# ZNVER1-NEXT:  uOps Per Cycle:    0.38
# ZNVER1-NEXT:  IPC:               0.25
# ZNVER1-NEXT:  Block RThroughput: 0.8

# ALL:          Instruction Info:
# ALL-NEXT:     [1]: #uOps
# ALL-NEXT:     [2]: Latency
# ALL-NEXT:     [3]: RThroughput
# ALL-NEXT:     [4]: MayLoad
# ALL-NEXT:     [5]: MayStore
# ALL-NEXT:     [6]: HasSideEffects (U)

# ALL:          [1]    [2]    [3]    [4]    [5]    [6]    Instructions:

# BDVER2-NEXT:   1      1     0.50                        addl	%edi, %esi
# BDVER2-NEXT:   2      6     0.50    *                   bextrl	%esi, (%rdi), %eax

# BDWELL-NEXT:   1      1     0.25                        addl	%edi, %esi
# BDWELL-NEXT:   3      7     0.50    *                   bextrl	%esi, (%rdi), %eax

# BTVER2-NEXT:   1      1     0.50                        addl	%edi, %esi
# BTVER2-NEXT:   1      4     1.00    *                   bextrl	%esi, (%rdi), %eax

# HASWELL-NEXT:  1      1     0.25                        addl	%edi, %esi
# HASWELL-NEXT:  3      7     0.50    *                   bextrl	%esi, (%rdi), %eax

# SKYLAKE-NEXT:  1      1     0.25                        addl	%edi, %esi
# SKYLAKE-NEXT:  3      7     0.50    *                   bextrl	%esi, (%rdi), %eax

# ZNVER1-NEXT:   1      1     0.25                        addl	%edi, %esi
# ZNVER1-NEXT:   2      5     0.50    *                   bextrl	%esi, (%rdi), %eax

# ALL:          Timeline view:

# BDVER2-NEXT:  Index     012345678
# BDWELL-NEXT:  Index     0123456789
# BTVER2-NEXT:  Index     0123456
# HASWELL-NEXT: Index     0123456789
# SKYLAKE-NEXT: Index     0123456789
# ZNVER1-NEXT:  Index     01234567

# BDVER2:       [0,0]     DeER .  .   addl	%edi, %esi
# BDVER2-NEXT:  [0,1]     DeeeeeeER   bextrl	%esi, (%rdi), %eax

# BDWELL:       [0,0]     DeER .   .   addl	%edi, %esi
# BDWELL-NEXT:  [0,1]     DeeeeeeeER   bextrl	%esi, (%rdi), %eax

# BTVER2:       [0,0]     DeER ..   addl	%edi, %esi
# BTVER2-NEXT:  [0,1]     DeeeeER   bextrl	%esi, (%rdi), %eax

# HASWELL:      [0,0]     DeER .   .   addl	%edi, %esi
# HASWELL-NEXT: [0,1]     DeeeeeeeER   bextrl	%esi, (%rdi), %eax

# SKYLAKE:      [0,0]     DeER .   .   addl	%edi, %esi
# SKYLAKE-NEXT: [0,1]     DeeeeeeeER   bextrl	%esi, (%rdi), %eax

# ZNVER1:       [0,0]     DeER . .   addl	%edi, %esi
# ZNVER1-NEXT:  [0,1]     DeeeeeER   bextrl	%esi, (%rdi), %eax

# ALL:          Average Wait times (based on the timeline view):
# ALL-NEXT:     [0]: Executions
# ALL-NEXT:     [1]: Average time spent waiting in a scheduler's queue
# ALL-NEXT:     [2]: Average time spent waiting in a scheduler's queue while ready
# ALL-NEXT:     [3]: Average time elapsed from WB until retire stage

# ALL:                [0]    [1]    [2]    [3]
# ALL-NEXT:     0.     1     1.0    1.0    0.0       addl	%edi, %esi
# ALL-NEXT:     1.     1     1.0    0.0    0.0       bextrl	%esi, (%rdi), %eax

{'repo_name': 'wsmoses/Tapir-LLVM', 'stars': '102', 'repo_language': 'LLVM', 'file_name': 'shuffle.ll', 'mime_type': 'text/plain', 'hash': 1301464071136035015, 'source_dataset': 'data'}


/* SCTP kernel implementation
 * (C) Copyright IBM Corp. 2001, 2004
 * Copyright (c) 1999-2000 Cisco, Inc.
 * Copyright (c) 1999-2001 Motorola, Inc.
 * Copyright (c) 2001 Intel Corp.
 * Copyright (c) 2001 Nokia, Inc.
 * Copyright (c) 2001 La Monte H.P. Yarroll
 *
 * These functions manipulate an sctp event.   The struct ulpevent is used
 * to carry notifications and data to the ULP (sockets).
 *
 * This SCTP implementation is free software;
 * you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This SCTP implementation is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
 *                 ************************
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU CC; see the file COPYING.  If not, write to
 * the Free Software Foundation, 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Please send any bug reports or fixes you make to the
 * email address(es):
 *    lksctp developers <lksctp-developers@lists.sourceforge.net>
 *
 * Or submit a bug report through the following website:
 *    http://www.sf.net/projects/lksctp
 *
 * Written or modified by:
 *    Jon Grimm             <jgrimm@us.ibm.com>
 *    La Monte H.P. Yarroll <piggy@acm.org>
 *    Ardelle Fan	    <ardelle.fan@intel.com>
 *    Sridhar Samudrala     <sri@us.ibm.com>
 *
 * Any bugs reported given to us we will try to fix... any fixes shared will
 * be incorporated into the next SCTP release.
 */

#include <linux/slab.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <net/sctp/structs.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>

static void sctp_ulpevent_receive_data(struct sctp_ulpevent *event,
				       struct sctp_association *asoc);
static void sctp_ulpevent_release_data(struct sctp_ulpevent *event);
static void sctp_ulpevent_release_frag_data(struct sctp_ulpevent *event);

/* Initialize an ULP event from an given skb.  */
SCTP_STATIC void sctp_ulpevent_init(struct sctp_ulpevent *event,
				    int msg_flags,
				    unsigned int len)
{
	memset(event, 0, sizeof(struct sctp_ulpevent));
	event->msg_flags = msg_flags;
	event->rmem_len = len;
}

/* Create a new sctp_ulpevent.  */
SCTP_STATIC struct sctp_ulpevent *sctp_ulpevent_new(int size, int msg_flags,
						    gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sk_buff *skb;

	skb = alloc_skb(size, gfp);
	if (!skb)
		goto fail;

	event = sctp_skb2event(skb);
	sctp_ulpevent_init(event, msg_flags, skb->truesize);

	return event;

fail:
	return NULL;
}

/* Is this a MSG_NOTIFICATION?  */
int sctp_ulpevent_is_notification(const struct sctp_ulpevent *event)
{
	return MSG_NOTIFICATION == (event->msg_flags & MSG_NOTIFICATION);
}

/* Hold the association in case the msg_name needs read out of
 * the association.
 */
static inline void sctp_ulpevent_set_owner(struct sctp_ulpevent *event,
					   const struct sctp_association *asoc)
{
	struct sk_buff *skb;

	/* Cast away the const, as we are just wanting to
	 * bump the reference count.
	 */
	sctp_association_hold((struct sctp_association *)asoc);
	skb = sctp_event2skb(event);
	event->asoc = (struct sctp_association *)asoc;
	atomic_add(event->rmem_len, &event->asoc->rmem_alloc);
	sctp_skb_set_owner_r(skb, asoc->base.sk);
}

/* A simple destructor to give up the reference to the association. */
static inline void sctp_ulpevent_release_owner(struct sctp_ulpevent *event)
{
	struct sctp_association *asoc = event->asoc;

	atomic_sub(event->rmem_len, &asoc->rmem_alloc);
	sctp_association_put(asoc);
}

/* Create and initialize an SCTP_ASSOC_CHANGE event.
 *
 * 5.3.1.1 SCTP_ASSOC_CHANGE
 *
 * Communication notifications inform the ULP that an SCTP association
 * has either begun or ended. The identifier for a new association is
 * provided by this notification.
 *
 * Note: There is no field checking here.  If a field is unused it will be
 * zero'd out.
 */
struct sctp_ulpevent  *sctp_ulpevent_make_assoc_change(
	const struct sctp_association *asoc,
	__u16 flags, __u16 state, __u16 error, __u16 outbound,
	__u16 inbound, struct sctp_chunk *chunk, gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_assoc_change *sac;
	struct sk_buff *skb;

	/* If the lower layer passed in the chunk, it will be
	 * an ABORT, so we need to include it in the sac_info.
	 */
	if (chunk) {
		/* Copy the chunk data to a new skb and reserve enough
		 * head room to use as notification.
		 */
		skb = skb_copy_expand(chunk->skb,
				      sizeof(struct sctp_assoc_change), 0, gfp);

		if (!skb)
			goto fail;

		/* Embed the event fields inside the cloned skb.  */
		event = sctp_skb2event(skb);
		sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize);

		/* Include the notification structure */
		sac = (struct sctp_assoc_change *)
			skb_push(skb, sizeof(struct sctp_assoc_change));

		/* Trim the buffer to the right length.  */
		skb_trim(skb, sizeof(struct sctp_assoc_change) +
			 ntohs(chunk->chunk_hdr->length) -
			 sizeof(sctp_chunkhdr_t));
	} else {
		event = sctp_ulpevent_new(sizeof(struct sctp_assoc_change),
				  MSG_NOTIFICATION, gfp);
		if (!event)
			goto fail;

		skb = sctp_event2skb(event);
		sac = (struct sctp_assoc_change *) skb_put(skb,
					sizeof(struct sctp_assoc_change));
	}

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * sac_type:
	 * It should be SCTP_ASSOC_CHANGE.
	 */
	sac->sac_type = SCTP_ASSOC_CHANGE;

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * sac_state: 32 bits (signed integer)
	 * This field holds one of a number of values that communicate the
	 * event that happened to the association.
	 */
	sac->sac_state = state;

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * sac_flags: 16 bits (unsigned integer)
	 * Currently unused.
	 */
	sac->sac_flags = 0;

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * sac_length: sizeof (__u32)
	 * This field is the total length of the notification data, including
	 * the notification header.
	 */
	sac->sac_length = skb->len;

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * sac_error:  32 bits (signed integer)
	 *
	 * If the state was reached due to a error condition (e.g.
	 * COMMUNICATION_LOST) any relevant error information is available in
	 * this field. This corresponds to the protocol error codes defined in
	 * [SCTP].
	 */
	sac->sac_error = error;

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * sac_outbound_streams:  16 bits (unsigned integer)
	 * sac_inbound_streams:  16 bits (unsigned integer)
	 *
	 * The maximum number of streams allowed in each direction are
	 * available in sac_outbound_streams and sac_inbound streams.
	 */
	sac->sac_outbound_streams = outbound;
	sac->sac_inbound_streams = inbound;

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * sac_assoc_id: sizeof (sctp_assoc_t)
	 *
	 * The association id field, holds the identifier for the association.
	 * All notifications for a given association have the same association
	 * identifier.  For TCP style socket, this field is ignored.
	 */
	sctp_ulpevent_set_owner(event, asoc);
	sac->sac_assoc_id = sctp_assoc2id(asoc);

	return event;

fail:
	return NULL;
}

/* Create and initialize an SCTP_PEER_ADDR_CHANGE event.
 *
 * Socket Extensions for SCTP - draft-01
 * 5.3.1.2 SCTP_PEER_ADDR_CHANGE
 *
 * When a destination address on a multi-homed peer encounters a change
 * an interface details event is sent.
 */
struct sctp_ulpevent *sctp_ulpevent_make_peer_addr_change(
	const struct sctp_association *asoc,
	const struct sockaddr_storage *aaddr,
	int flags, int state, int error, gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_paddr_change  *spc;
	struct sk_buff *skb;

	event = sctp_ulpevent_new(sizeof(struct sctp_paddr_change),
				  MSG_NOTIFICATION, gfp);
	if (!event)
		goto fail;

	skb = sctp_event2skb(event);
	spc = (struct sctp_paddr_change *)
		skb_put(skb, sizeof(struct sctp_paddr_change));

	/* Sockets API Extensions for SCTP
	 * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
	 *
	 * spc_type:
	 *
	 *    It should be SCTP_PEER_ADDR_CHANGE.
	 */
	spc->spc_type = SCTP_PEER_ADDR_CHANGE;

	/* Sockets API Extensions for SCTP
	 * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
	 *
	 * spc_length: sizeof (__u32)
	 *
	 * This field is the total length of the notification data, including
	 * the notification header.
	 */
	spc->spc_length = sizeof(struct sctp_paddr_change);

	/* Sockets API Extensions for SCTP
	 * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
	 *
	 * spc_flags: 16 bits (unsigned integer)
	 * Currently unused.
	 */
	spc->spc_flags = 0;

	/* Sockets API Extensions for SCTP
	 * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
	 *
	 * spc_state:  32 bits (signed integer)
	 *
	 * This field holds one of a number of values that communicate the
	 * event that happened to the address.
	 */
	spc->spc_state = state;

	/* Sockets API Extensions for SCTP
	 * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
	 *
	 * spc_error:  32 bits (signed integer)
	 *
	 * If the state was reached due to any error condition (e.g.
	 * ADDRESS_UNREACHABLE) any relevant error information is available in
	 * this field.
	 */
	spc->spc_error = error;

	/* Socket Extensions for SCTP
	 * 5.3.1.1 SCTP_ASSOC_CHANGE
	 *
	 * spc_assoc_id: sizeof (sctp_assoc_t)
	 *
	 * The association id field, holds the identifier for the association.
	 * All notifications for a given association have the same association
	 * identifier.  For TCP style socket, this field is ignored.
	 */
	sctp_ulpevent_set_owner(event, asoc);
	spc->spc_assoc_id = sctp_assoc2id(asoc);

	/* Sockets API Extensions for SCTP
	 * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
	 *
	 * spc_aaddr: sizeof (struct sockaddr_storage)
	 *
	 * The affected address field, holds the remote peer's address that is
	 * encountering the change of state.
	 */
	memcpy(&spc->spc_aaddr, aaddr, sizeof(struct sockaddr_storage));

	/* Map ipv4 address into v4-mapped-on-v6 address.  */
	sctp_get_pf_specific(asoc->base.sk->sk_family)->addr_v4map(
					sctp_sk(asoc->base.sk),
					(union sctp_addr *)&spc->spc_aaddr);

	return event;

fail:
	return NULL;
}

/* Create and initialize an SCTP_REMOTE_ERROR notification.
 *
 * Note: This assumes that the chunk->skb->data already points to the
 * operation error payload.
 *
 * Socket Extensions for SCTP - draft-01
 * 5.3.1.3 SCTP_REMOTE_ERROR
 *
 * A remote peer may send an Operational Error message to its peer.
 * This message indicates a variety of error conditions on an
 * association. The entire error TLV as it appears on the wire is
 * included in a SCTP_REMOTE_ERROR event.  Please refer to the SCTP
 * specification [SCTP] and any extensions for a list of possible
 * error formats.
 */
struct sctp_ulpevent *sctp_ulpevent_make_remote_error(
	const struct sctp_association *asoc, struct sctp_chunk *chunk,
	__u16 flags, gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_remote_error *sre;
	struct sk_buff *skb;
	sctp_errhdr_t *ch;
	__be16 cause;
	int elen;

	ch = (sctp_errhdr_t *)(chunk->skb->data);
	cause = ch->cause;
	elen = WORD_ROUND(ntohs(ch->length)) - sizeof(sctp_errhdr_t);

	/* Pull off the ERROR header.  */
	skb_pull(chunk->skb, sizeof(sctp_errhdr_t));

	/* Copy the skb to a new skb with room for us to prepend
	 * notification with.
	 */
	skb = skb_copy_expand(chunk->skb, sizeof(struct sctp_remote_error),
			      0, gfp);

	/* Pull off the rest of the cause TLV from the chunk.  */
	skb_pull(chunk->skb, elen);
	if (!skb)
		goto fail;

	/* Embed the event fields inside the cloned skb.  */
	event = sctp_skb2event(skb);
	sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize);

	sre = (struct sctp_remote_error *)
		skb_push(skb, sizeof(struct sctp_remote_error));

	/* Trim the buffer to the right length.  */
	skb_trim(skb, sizeof(struct sctp_remote_error) + elen);

	/* Socket Extensions for SCTP
	 * 5.3.1.3 SCTP_REMOTE_ERROR
	 *
	 * sre_type:
	 *   It should be SCTP_REMOTE_ERROR.
	 */
	sre->sre_type = SCTP_REMOTE_ERROR;

	/*
	 * Socket Extensions for SCTP
	 * 5.3.1.3 SCTP_REMOTE_ERROR
	 *
	 * sre_flags: 16 bits (unsigned integer)
	 *   Currently unused.
	 */
	sre->sre_flags = 0;

	/* Socket Extensions for SCTP
	 * 5.3.1.3 SCTP_REMOTE_ERROR
	 *
	 * sre_length: sizeof (__u32)
	 *
	 * This field is the total length of the notification data,
	 * including the notification header.
	 */
	sre->sre_length = skb->len;

	/* Socket Extensions for SCTP
	 * 5.3.1.3 SCTP_REMOTE_ERROR
	 *
	 * sre_error: 16 bits (unsigned integer)
	 * This value represents one of the Operational Error causes defined in
	 * the SCTP specification, in network byte order.
	 */
	sre->sre_error = cause;

	/* Socket Extensions for SCTP
	 * 5.3.1.3 SCTP_REMOTE_ERROR
	 *
	 * sre_assoc_id: sizeof (sctp_assoc_t)
	 *
	 * The association id field, holds the identifier for the association.
	 * All notifications for a given association have the same association
	 * identifier.  For TCP style socket, this field is ignored.
	 */
	sctp_ulpevent_set_owner(event, asoc);
	sre->sre_assoc_id = sctp_assoc2id(asoc);

	return event;

fail:
	return NULL;
}

/* Create and initialize a SCTP_SEND_FAILED notification.
 *
 * Socket Extensions for SCTP - draft-01
 * 5.3.1.4 SCTP_SEND_FAILED
 */
struct sctp_ulpevent *sctp_ulpevent_make_send_failed(
	const struct sctp_association *asoc, struct sctp_chunk *chunk,
	__u16 flags, __u32 error, gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_send_failed *ssf;
	struct sk_buff *skb;

	/* Pull off any padding. */
	int len = ntohs(chunk->chunk_hdr->length);

	/* Make skb with more room so we can prepend notification.  */
	skb = skb_copy_expand(chunk->skb,
			      sizeof(struct sctp_send_failed), /* headroom */
			      0,                               /* tailroom */
			      gfp);
	if (!skb)
		goto fail;

	/* Pull off the common chunk header and DATA header.  */
	skb_pull(skb, sizeof(struct sctp_data_chunk));
	len -= sizeof(struct sctp_data_chunk);

	/* Embed the event fields inside the cloned skb.  */
	event = sctp_skb2event(skb);
	sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize);

	ssf = (struct sctp_send_failed *)
		skb_push(skb, sizeof(struct sctp_send_failed));

	/* Socket Extensions for SCTP
	 * 5.3.1.4 SCTP_SEND_FAILED
	 *
	 * ssf_type:
	 * It should be SCTP_SEND_FAILED.
	 */
	ssf->ssf_type = SCTP_SEND_FAILED;

	/* Socket Extensions for SCTP
	 * 5.3.1.4 SCTP_SEND_FAILED
	 *
	 * ssf_flags: 16 bits (unsigned integer)
	 * The flag value will take one of the following values
	 *
	 * SCTP_DATA_UNSENT - Indicates that the data was never put on
	 *                    the wire.
	 *
	 * SCTP_DATA_SENT   - Indicates that the data was put on the wire.
	 *                    Note that this does not necessarily mean that the
	 *                    data was (or was not) successfully delivered.
	 */
	ssf->ssf_flags = flags;

	/* Socket Extensions for SCTP
	 * 5.3.1.4 SCTP_SEND_FAILED
	 *
	 * ssf_length: sizeof (__u32)
	 * This field is the total length of the notification data, including
	 * the notification header.
	 */
	ssf->ssf_length = sizeof(struct sctp_send_failed) + len;
	skb_trim(skb, ssf->ssf_length);

	/* Socket Extensions for SCTP
	 * 5.3.1.4 SCTP_SEND_FAILED
	 *
	 * ssf_error: 16 bits (unsigned integer)
	 * This value represents the reason why the send failed, and if set,
	 * will be a SCTP protocol error code as defined in [SCTP] section
	 * 3.3.10.
	 */
	ssf->ssf_error = error;

	/* Socket Extensions for SCTP
	 * 5.3.1.4 SCTP_SEND_FAILED
	 *
	 * ssf_info: sizeof (struct sctp_sndrcvinfo)
	 * The original send information associated with the undelivered
	 * message.
	 */
	memcpy(&ssf->ssf_info, &chunk->sinfo, sizeof(struct sctp_sndrcvinfo));

	/* Per TSVWG discussion with Randy. Allow the application to
	 * ressemble a fragmented message.
	 */
	ssf->ssf_info.sinfo_flags = chunk->chunk_hdr->flags;

	/* Socket Extensions for SCTP
	 * 5.3.1.4 SCTP_SEND_FAILED
	 *
	 * ssf_assoc_id: sizeof (sctp_assoc_t)
	 * The association id field, sf_assoc_id, holds the identifier for the
	 * association.  All notifications for a given association have the
	 * same association identifier.  For TCP style socket, this field is
	 * ignored.
	 */
	sctp_ulpevent_set_owner(event, asoc);
	ssf->ssf_assoc_id = sctp_assoc2id(asoc);
	return event;

fail:
	return NULL;
}

/* Create and initialize a SCTP_SHUTDOWN_EVENT notification.
 *
 * Socket Extensions for SCTP - draft-01
 * 5.3.1.5 SCTP_SHUTDOWN_EVENT
 */
struct sctp_ulpevent *sctp_ulpevent_make_shutdown_event(
	const struct sctp_association *asoc,
	__u16 flags, gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_shutdown_event *sse;
	struct sk_buff *skb;

	event = sctp_ulpevent_new(sizeof(struct sctp_shutdown_event),
				  MSG_NOTIFICATION, gfp);
	if (!event)
		goto fail;

	skb = sctp_event2skb(event);
	sse = (struct sctp_shutdown_event *)
		skb_put(skb, sizeof(struct sctp_shutdown_event));

	/* Socket Extensions for SCTP
	 * 5.3.1.5 SCTP_SHUTDOWN_EVENT
	 *
	 * sse_type
	 * It should be SCTP_SHUTDOWN_EVENT
	 */
	sse->sse_type = SCTP_SHUTDOWN_EVENT;

	/* Socket Extensions for SCTP
	 * 5.3.1.5 SCTP_SHUTDOWN_EVENT
	 *
	 * sse_flags: 16 bits (unsigned integer)
	 * Currently unused.
	 */
	sse->sse_flags = 0;

	/* Socket Extensions for SCTP
	 * 5.3.1.5 SCTP_SHUTDOWN_EVENT
	 *
	 * sse_length: sizeof (__u32)
	 * This field is the total length of the notification data, including
	 * the notification header.
	 */
	sse->sse_length = sizeof(struct sctp_shutdown_event);

	/* Socket Extensions for SCTP
	 * 5.3.1.5 SCTP_SHUTDOWN_EVENT
	 *
	 * sse_assoc_id: sizeof (sctp_assoc_t)
	 * The association id field, holds the identifier for the association.
	 * All notifications for a given association have the same association
	 * identifier.  For TCP style socket, this field is ignored.
	 */
	sctp_ulpevent_set_owner(event, asoc);
	sse->sse_assoc_id = sctp_assoc2id(asoc);

	return event;

fail:
	return NULL;
}

/* Create and initialize a SCTP_ADAPTATION_INDICATION notification.
 *
 * Socket Extensions for SCTP
 * 5.3.1.6 SCTP_ADAPTATION_INDICATION
 */
struct sctp_ulpevent *sctp_ulpevent_make_adaptation_indication(
	const struct sctp_association *asoc, gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_adaptation_event *sai;
	struct sk_buff *skb;

	event = sctp_ulpevent_new(sizeof(struct sctp_adaptation_event),
				  MSG_NOTIFICATION, gfp);
	if (!event)
		goto fail;

	skb = sctp_event2skb(event);
	sai = (struct sctp_adaptation_event *)
		skb_put(skb, sizeof(struct sctp_adaptation_event));

	sai->sai_type = SCTP_ADAPTATION_INDICATION;
	sai->sai_flags = 0;
	sai->sai_length = sizeof(struct sctp_adaptation_event);
	sai->sai_adaptation_ind = asoc->peer.adaptation_ind;
	sctp_ulpevent_set_owner(event, asoc);
	sai->sai_assoc_id = sctp_assoc2id(asoc);

	return event;

fail:
	return NULL;
}

/* A message has been received.  Package this message as a notification
 * to pass it to the upper layers.  Go ahead and calculate the sndrcvinfo
 * even if filtered out later.
 *
 * Socket Extensions for SCTP
 * 5.2.2 SCTP Header Information Structure (SCTP_SNDRCV)
 */
struct sctp_ulpevent *sctp_ulpevent_make_rcvmsg(struct sctp_association *asoc,
						struct sctp_chunk *chunk,
						gfp_t gfp)
{
	struct sctp_ulpevent *event = NULL;
	struct sk_buff *skb;
	size_t padding, len;
	int rx_count;

	/*
	 * check to see if we need to make space for this
	 * new skb, expand the rcvbuffer if needed, or drop
	 * the frame
	 */
	if (asoc->ep->rcvbuf_policy)
		rx_count = atomic_read(&asoc->rmem_alloc);
	else
		rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc);

	if (rx_count >= asoc->base.sk->sk_rcvbuf) {

		if ((asoc->base.sk->sk_userlocks & SOCK_RCVBUF_LOCK) ||
		    (!sk_rmem_schedule(asoc->base.sk, chunk->skb->truesize)))
			goto fail;
	}

	/* Clone the original skb, sharing the data.  */
	skb = skb_clone(chunk->skb, gfp);
	if (!skb)
		goto fail;

	/* Now that all memory allocations for this chunk succeeded, we
	 * can mark it as received so the tsn_map is updated correctly.
	 */
	if (sctp_tsnmap_mark(&asoc->peer.tsn_map,
			     ntohl(chunk->subh.data_hdr->tsn)))
		goto fail_mark;

	/* First calculate the padding, so we don't inadvertently
	 * pass up the wrong length to the user.
	 *
	 * RFC 2960 - Section 3.2  Chunk Field Descriptions
	 *
	 * The total length of a chunk(including Type, Length and Value fields)
	 * MUST be a multiple of 4 bytes.  If the length of the chunk is not a
	 * multiple of 4 bytes, the sender MUST pad the chunk with all zero
	 * bytes and this padding is not included in the chunk length field.
	 * The sender should never pad with more than 3 bytes.  The receiver
	 * MUST ignore the padding bytes.
	 */
	len = ntohs(chunk->chunk_hdr->length);
	padding = WORD_ROUND(len) - len;

	/* Fixup cloned skb with just this chunks data.  */
	skb_trim(skb, chunk->chunk_end - padding - skb->data);

	/* Embed the event fields inside the cloned skb.  */
	event = sctp_skb2event(skb);

	/* Initialize event with flags 0  and correct length
	 * Since this is a clone of the original skb, only account for
	 * the data of this chunk as other chunks will be accounted separately.
	 */
	sctp_ulpevent_init(event, 0, skb->len + sizeof(struct sk_buff));

	sctp_ulpevent_receive_data(event, asoc);

	event->stream = ntohs(chunk->subh.data_hdr->stream);
	event->ssn = ntohs(chunk->subh.data_hdr->ssn);
	event->ppid = chunk->subh.data_hdr->ppid;
	if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
		event->flags |= SCTP_UNORDERED;
		event->cumtsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map);
	}
	event->tsn = ntohl(chunk->subh.data_hdr->tsn);
	event->msg_flags |= chunk->chunk_hdr->flags;
	event->iif = sctp_chunk_iif(chunk);

	return event;

fail_mark:
	kfree_skb(skb);
fail:
	return NULL;
}

/* Create a partial delivery related event.
 *
 * 5.3.1.7 SCTP_PARTIAL_DELIVERY_EVENT
 *
 *   When a receiver is engaged in a partial delivery of a
 *   message this notification will be used to indicate
 *   various events.
 */
struct sctp_ulpevent *sctp_ulpevent_make_pdapi(
	const struct sctp_association *asoc, __u32 indication,
	gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_pdapi_event *pd;
	struct sk_buff *skb;

	event = sctp_ulpevent_new(sizeof(struct sctp_pdapi_event),
				  MSG_NOTIFICATION, gfp);
	if (!event)
		goto fail;

	skb = sctp_event2skb(event);
	pd = (struct sctp_pdapi_event *)
		skb_put(skb, sizeof(struct sctp_pdapi_event));

	/* pdapi_type
	 *   It should be SCTP_PARTIAL_DELIVERY_EVENT
	 *
	 * pdapi_flags: 16 bits (unsigned integer)
	 *   Currently unused.
	 */
	pd->pdapi_type = SCTP_PARTIAL_DELIVERY_EVENT;
	pd->pdapi_flags = 0;

	/* pdapi_length: 32 bits (unsigned integer)
	 *
	 * This field is the total length of the notification data, including
	 * the notification header.  It will generally be sizeof (struct
	 * sctp_pdapi_event).
	 */
	pd->pdapi_length = sizeof(struct sctp_pdapi_event);

	/*  pdapi_indication: 32 bits (unsigned integer)
	 *
	 * This field holds the indication being sent to the application.
	 */
	pd->pdapi_indication = indication;

	/*  pdapi_assoc_id: sizeof (sctp_assoc_t)
	 *
	 * The association id field, holds the identifier for the association.
	 */
	sctp_ulpevent_set_owner(event, asoc);
	pd->pdapi_assoc_id = sctp_assoc2id(asoc);

	return event;
fail:
	return NULL;
}

struct sctp_ulpevent *sctp_ulpevent_make_authkey(
	const struct sctp_association *asoc, __u16 key_id,
	__u32 indication, gfp_t gfp)
{
	struct sctp_ulpevent *event;
	struct sctp_authkey_event *ak;
	struct sk_buff *skb;

	event = sctp_ulpevent_new(sizeof(struct sctp_authkey_event),
				  MSG_NOTIFICATION, gfp);
	if (!event)
		goto fail;

	skb = sctp_event2skb(event);
	ak = (struct sctp_authkey_event *)
		skb_put(skb, sizeof(struct sctp_authkey_event));

	ak->auth_type = SCTP_AUTHENTICATION_INDICATION;
	ak->auth_flags = 0;
	ak->auth_length = sizeof(struct sctp_authkey_event);

	ak->auth_keynumber = key_id;
	ak->auth_altkeynumber = 0;
	ak->auth_indication = indication;

	/*
	 * The association id field, holds the identifier for the association.
	 */
	sctp_ulpevent_set_owner(event, asoc);
	ak->auth_assoc_id = sctp_assoc2id(asoc);

	return event;
fail:
	return NULL;
}

/* Return the notification type, assuming this is a notification
 * event.
 */
__u16 sctp_ulpevent_get_notification_type(const struct sctp_ulpevent *event)
{
	union sctp_notification *notification;
	struct sk_buff *skb;

	skb = sctp_event2skb(event);
	notification = (union sctp_notification *) skb->data;
	return notification->sn_header.sn_type;
}

/* Copy out the sndrcvinfo into a msghdr.  */
void sctp_ulpevent_read_sndrcvinfo(const struct sctp_ulpevent *event,
				   struct msghdr *msghdr)
{
	struct sctp_sndrcvinfo sinfo;

	if (sctp_ulpevent_is_notification(event))
		return;

	/* Sockets API Extensions for SCTP
	 * Section 5.2.2 SCTP Header Information Structure (SCTP_SNDRCV)
	 *
	 * sinfo_stream: 16 bits (unsigned integer)
	 *
	 * For recvmsg() the SCTP stack places the message's stream number in
	 * this value.
	*/
	sinfo.sinfo_stream = event->stream;
	/* sinfo_ssn: 16 bits (unsigned integer)
	 *
	 * For recvmsg() this value contains the stream sequence number that
	 * the remote endpoint placed in the DATA chunk.  For fragmented
	 * messages this is the same number for all deliveries of the message
	 * (if more than one recvmsg() is needed to read the message).
	 */
	sinfo.sinfo_ssn = event->ssn;
	/* sinfo_ppid: 32 bits (unsigned integer)
	 *
	 * In recvmsg() this value is
	 * the same information that was passed by the upper layer in the peer
	 * application.  Please note that byte order issues are NOT accounted
	 * for and this information is passed opaquely by the SCTP stack from
	 * one end to the other.
	 */
	sinfo.sinfo_ppid = event->ppid;
	/* sinfo_flags: 16 bits (unsigned integer)
	 *
	 * This field may contain any of the following flags and is composed of
	 * a bitwise OR of these values.
	 *
	 * recvmsg() flags:
	 *
	 * SCTP_UNORDERED - This flag is present when the message was sent
	 *                 non-ordered.
	 */
	sinfo.sinfo_flags = event->flags;
	/* sinfo_tsn: 32 bit (unsigned integer)
	 *
	 * For the receiving side, this field holds a TSN that was
	 * assigned to one of the SCTP Data Chunks.
	 */
	sinfo.sinfo_tsn = event->tsn;
	/* sinfo_cumtsn: 32 bit (unsigned integer)
	 *
	 * This field will hold the current cumulative TSN as
	 * known by the underlying SCTP layer.  Note this field is
	 * ignored when sending and only valid for a receive
	 * operation when sinfo_flags are set to SCTP_UNORDERED.
	 */
	sinfo.sinfo_cumtsn = event->cumtsn;
	/* sinfo_assoc_id: sizeof (sctp_assoc_t)
	 *
	 * The association handle field, sinfo_assoc_id, holds the identifier
	 * for the association announced in the COMMUNICATION_UP notification.
	 * All notifications for a given association have the same identifier.
	 * Ignored for one-to-one style sockets.
	 */
	sinfo.sinfo_assoc_id = sctp_assoc2id(event->asoc);

	/* context value that is set via SCTP_CONTEXT socket option. */
	sinfo.sinfo_context = event->asoc->default_rcv_context;

	/* These fields are not used while receiving. */
	sinfo.sinfo_timetolive = 0;

	put_cmsg(msghdr, IPPROTO_SCTP, SCTP_SNDRCV,
		 sizeof(struct sctp_sndrcvinfo), (void *)&sinfo);
}

/* Do accounting for bytes received and hold a reference to the association
 * for each skb.
 */
static void sctp_ulpevent_receive_data(struct sctp_ulpevent *event,
				       struct sctp_association *asoc)
{
	struct sk_buff *skb, *frag;

	skb = sctp_event2skb(event);
	/* Set the owner and charge rwnd for bytes received.  */
	sctp_ulpevent_set_owner(event, asoc);
	sctp_assoc_rwnd_decrease(asoc, skb_headlen(skb));

	if (!skb->data_len)
		return;

	/* Note:  Not clearing the entire event struct as this is just a
	 * fragment of the real event.  However, we still need to do rwnd
	 * accounting.
	 * In general, the skb passed from IP can have only 1 level of
	 * fragments. But we allow multiple levels of fragments.
	 */
	skb_walk_frags(skb, frag)
		sctp_ulpevent_receive_data(sctp_skb2event(frag), asoc);
}

/* Do accounting for bytes just read by user and release the references to
 * the association.
 */
static void sctp_ulpevent_release_data(struct sctp_ulpevent *event)
{
	struct sk_buff *skb, *frag;
	unsigned int	len;

	/* Current stack structures assume that the rcv buffer is
	 * per socket.   For UDP style sockets this is not true as
	 * multiple associations may be on a single UDP-style socket.
	 * Use the local private area of the skb to track the owning
	 * association.
	 */

	skb = sctp_event2skb(event);
	len = skb->len;

	if (!skb->data_len)
		goto done;

	/* Don't forget the fragments. */
	skb_walk_frags(skb, frag) {
		/* NOTE:  skb_shinfos are recursive. Although IP returns
		 * skb's with only 1 level of fragments, SCTP reassembly can
		 * increase the levels.
		 */
		sctp_ulpevent_release_frag_data(sctp_skb2event(frag));
	}

done:
	sctp_assoc_rwnd_increase(event->asoc, len);
	sctp_ulpevent_release_owner(event);
}

static void sctp_ulpevent_release_frag_data(struct sctp_ulpevent *event)
{
	struct sk_buff *skb, *frag;

	skb = sctp_event2skb(event);

	if (!skb->data_len)
		goto done;

	/* Don't forget the fragments. */
	skb_walk_frags(skb, frag) {
		/* NOTE:  skb_shinfos are recursive. Although IP returns
		 * skb's with only 1 level of fragments, SCTP reassembly can
		 * increase the levels.
		 */
		sctp_ulpevent_release_frag_data(sctp_skb2event(frag));
	}

done:
	sctp_ulpevent_release_owner(event);
}

/* Free a ulpevent that has an owner.  It includes releasing the reference
 * to the owner, updating the rwnd in case of a DATA event and freeing the
 * skb.
 */
void sctp_ulpevent_free(struct sctp_ulpevent *event)
{
	if (sctp_ulpevent_is_notification(event))
		sctp_ulpevent_release_owner(event);
	else
		sctp_ulpevent_release_data(event);

	kfree_skb(sctp_event2skb(event));
}

/* Purge the skb lists holding ulpevents. */
void sctp_queue_purge_ulpevents(struct sk_buff_head *list)
{
	struct sk_buff *skb;
	while ((skb = skb_dequeue(list)) != NULL)
		sctp_ulpevent_free(sctp_skb2event(skb));
}

{'repo_name': 'RMerl/asuswrt-merlin.ng', 'stars': '2126', 'repo_language': 'None', 'file_name': 'cpu_vect.h', 'mime_type': 'text/x-c', 'hash': -3068173235211219884, 'source_dataset': 'data'}


package me.tatarka.bindingcollectionadapter2;

import androidx.databinding.BindingAdapter;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.AsyncDifferConfig;
import androidx.recyclerview.widget.RecyclerView;
import me.tatarka.bindingcollectionadapter2.collections.AsyncDiffPagedObservableList;
import me.tatarka.bindingcollectionadapter2.paging.R;

/**
 * @see {@link BindingCollectionAdapters}
 */
public class PagedBindingRecyclerViewAdapters {
    // RecyclerView
    @SuppressWarnings("unchecked")
    @BindingAdapter(value = {"itemBinding", "items", "adapter", "itemIds", "viewHolder", "diffConfig"}, requireAll = false)
    public static <T> void setAdapter(RecyclerView recyclerView,
                                      ItemBinding<? super T> itemBinding,
                                      PagedList<T> items,
                                      BindingRecyclerViewAdapter<T> adapter,
                                      BindingRecyclerViewAdapter.ItemIds<? super T> itemIds,
                                      BindingRecyclerViewAdapter.ViewHolderFactory viewHolderFactory,
                                      AsyncDifferConfig<T> diffConfig) {
        if (itemBinding == null) {
            throw new IllegalArgumentException("itemBinding must not be null");
        }
        BindingRecyclerViewAdapter oldAdapter = (BindingRecyclerViewAdapter) recyclerView.getAdapter();
        if (adapter == null) {
            if (oldAdapter == null) {
                adapter = new BindingRecyclerViewAdapter<>();
            } else {
                adapter = oldAdapter;
            }
        }
        adapter.setItemBinding(itemBinding);

        if (diffConfig != null && items != null) {
            AsyncDiffPagedObservableList<T> list = (AsyncDiffPagedObservableList<T>) recyclerView.getTag(R.id.bindingcollectiondapter_list_id);
            if (list == null) {
                list = new AsyncDiffPagedObservableList<>(diffConfig);
                recyclerView.setTag(R.id.bindingcollectiondapter_list_id, list);
                adapter.setItems(list);
            }
            list.update(items);
        } else {
            adapter.setItems(items);
        }

        adapter.setItemIds(itemIds);
        adapter.setViewHolderFactory(viewHolderFactory);

        if (oldAdapter != adapter) {
            recyclerView.setAdapter(adapter);
        }
    }
}

{'repo_name': 'evant/binding-collection-adapter', 'stars': '1565', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -1610689015245154581, 'source_dataset': 'data'}