// ----------------------------------------------------------------------------
// format_implementation.hpp  Implementation of the basic_format class
// ----------------------------------------------------------------------------

//  Copyright Samuel Krempp 2003. Use, modification, and distribution are
//  subject to the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/format for library home page

// ----------------------------------------------------------------------------

#ifndef BOOST_FORMAT_IMPLEMENTATION_HPP
#define BOOST_FORMAT_IMPLEMENTATION_HPP

#include <boost/config.hpp>
#include <boost/throw_exception.hpp>
#include <boost/assert.hpp>
#include <boost/format/format_class.hpp>
#include <algorithm> // std::swap

namespace boost {

// ---  basic_format implementation -----------------------------------------//

    template< class Ch, class Tr, class Alloc>
    basic_format<Ch, Tr, Alloc>:: basic_format(const Ch* s)
        : style_(0), cur_arg_(0), num_args_(0), dumped_(false),
          exceptions_(io::all_error_bits)
    {
        if( s)
            parse( s );
    }

#if !defined(BOOST_NO_STD_LOCALE)
    template< class Ch, class Tr, class Alloc>
    basic_format<Ch, Tr, Alloc>:: basic_format(const Ch* s, const std::locale & loc)
        : style_(0), cur_arg_(0), num_args_(0), dumped_(false),
          exceptions_(io::all_error_bits), loc_(loc)
    {
        if(s) parse( s );
    }

    template< class Ch, class Tr, class Alloc>
    basic_format<Ch, Tr, Alloc>:: basic_format(const string_type& s, const std::locale & loc)
        : style_(0), cur_arg_(0), num_args_(0), dumped_(false),
          exceptions_(io::all_error_bits), loc_(loc)
    {
        parse(s);
    }
#endif // ! BOOST_NO_STD_LOCALE
    template< class Ch, class Tr, class Alloc>
    io::detail::locale_t basic_format<Ch, Tr, Alloc>::
    getloc() const {
        return loc_ ? loc_.get() : io::detail::locale_t();
    }

    template< class Ch, class Tr, class Alloc>
    basic_format<Ch, Tr, Alloc>:: basic_format(const string_type& s)
        : style_(0), cur_arg_(0), num_args_(0), dumped_(false),
          exceptions_(io::all_error_bits)
    {
        parse(s);
    }

    template< class Ch, class Tr, class Alloc> // just don't copy the buf_ member
    basic_format<Ch, Tr, Alloc>:: basic_format(const basic_format& x)
        : items_(x.items_), bound_(x.bound_), style_(x.style_),
          cur_arg_(x.cur_arg_), num_args_(x.num_args_), dumped_(x.dumped_),
          prefix_(x.prefix_), exceptions_(x.exceptions_), loc_(x.loc_)
    {
    }

    template< class Ch, class Tr, class Alloc>  // just don't copy the buf_ member
    basic_format<Ch, Tr, Alloc>& basic_format<Ch, Tr, Alloc>::
    operator= (const basic_format& x) {
        if(this == &x)
            return *this;
        (basic_format<Ch, Tr, Alloc>(x)).swap(*this);
        return *this;
    }
    template< class Ch, class Tr, class Alloc>
    void  basic_format<Ch, Tr, Alloc>::
    swap (basic_format & x) {
        std::swap(exceptions_, x.exceptions_);
        std::swap(style_, x.style_);
        std::swap(cur_arg_, x.cur_arg_);
        std::swap(num_args_, x.num_args_);
        std::swap(dumped_, x.dumped_);

        items_.swap(x.items_);
        prefix_.swap(x.prefix_);
        bound_.swap(x.bound_);
    }

    template< class Ch, class Tr, class Alloc>
    unsigned char basic_format<Ch,Tr, Alloc>:: exceptions() const {
        return exceptions_;
    }

    template< class Ch, class Tr, class Alloc>
    unsigned char basic_format<Ch,Tr, Alloc>:: exceptions(unsigned char newexcept) {
        unsigned char swp = exceptions_;
        exceptions_ = newexcept;
        return swp;
    }

    template<class Ch, class Tr, class Alloc>
    void basic_format<Ch, Tr, Alloc>::
    make_or_reuse_data (std::size_t nbitems) {
#if !defined(BOOST_NO_STD_LOCALE)
        Ch fill = ( BOOST_USE_FACET(std::ctype<Ch>, getloc()) ). widen(' ');
#else
        Ch fill = ' ';
#endif
        if(items_.size() == 0)
            items_.assign( nbitems, format_item_t(fill) );
        else {
            if(nbitems>items_.size())
                items_.resize(nbitems, format_item_t(fill));
            bound_.resize(0);
            for(std::size_t i=0; i < nbitems; ++i)
                items_[i].reset(fill); //  strings are resized, instead of reallocated
        }
        prefix_.resize(0);
    }

    template< class Ch, class Tr, class Alloc>
    basic_format<Ch,Tr, Alloc>& basic_format<Ch,Tr, Alloc>::
    clear () {
        // empty the string buffers (except bound arguments)
        // and make the format object ready for formatting a new set of arguments

        BOOST_ASSERT( bound_.size()==0 || num_args_ == static_cast<int>(bound_.size()) );

        for(unsigned long i=0; i<items_.size(); ++i) {
            // clear converted strings only if the corresponding argument is not  bound :
            if( bound_.size()==0 || items_[i].argN_<0 || !bound_[ items_[i].argN_ ] )
                items_[i].res_.resize(0);
        }
        cur_arg_=0; dumped_=false;
        // maybe first arg is bound:
        if(bound_.size() != 0) {
            for(; cur_arg_ < num_args_ && bound_[cur_arg_]; ++cur_arg_)
                {}
        }
        return *this;
    }

    template< class Ch, class Tr, class Alloc>
    basic_format<Ch,Tr, Alloc>& basic_format<Ch,Tr, Alloc>::
    clear_binds () {
        // remove all binds, then clear()
        bound_.resize(0);
        clear();
        return *this;
    }

    template< class Ch, class Tr, class Alloc>
    basic_format<Ch,Tr, Alloc>& basic_format<Ch,Tr, Alloc>::
    clear_bind (int argN) {
        // remove the bind of ONE argument then clear()
        if(argN<1 || argN > num_args_ || bound_.size()==0 || !bound_[argN-1] ) {
            if( exceptions() & io::out_of_range_bit)
                boost::throw_exception(io::out_of_range(argN, 1, num_args_+1 ) );
            else return *this;
        }
        bound_[argN-1]=false;
        clear();
        return *this;
    }

    template< class Ch, class Tr, class Alloc>
    int basic_format<Ch,Tr, Alloc>::
    bound_args() const {
        if(bound_.size()==0)
            return 0;
        int n=0;
        for(int i=0; i<num_args_ ; ++i)
            if(bound_[i])
                ++n;
        return n;
    }

    template< class Ch, class Tr, class Alloc>
    int basic_format<Ch,Tr, Alloc>::
    fed_args() const {
        if(bound_.size()==0)
            return cur_arg_;
        int n=0;
        for(int i=0; i<cur_arg_ ; ++i)
            if(!bound_[i])
                ++n;
        return n;
    }

    template< class Ch, class Tr, class Alloc>
    int basic_format<Ch,Tr, Alloc>::
    cur_arg() const {
      return cur_arg_+1; }

    template< class Ch, class Tr, class Alloc>
    int basic_format<Ch,Tr, Alloc>::
    remaining_args() const {
        if(bound_.size()==0)
            return num_args_-cur_arg_;
        int n=0;
        for(int i=cur_arg_; i<num_args_ ; ++i)
            if(!bound_[i])
                ++n;
        return n;
    }

    template< class Ch, class Tr, class Alloc>
    typename basic_format<Ch, Tr, Alloc>::string_type
    basic_format<Ch,Tr, Alloc>::
    str () const {
        if(items_.size()==0)
            return prefix_;
        if( cur_arg_ < num_args_)
            if( exceptions() & io::too_few_args_bit )
                // not enough variables supplied
                boost::throw_exception(io::too_few_args(cur_arg_, num_args_));

        unsigned long i;
        string_type res;
        res.reserve(size());
        res += prefix_;
        for(i=0; i < items_.size(); ++i) {
            const format_item_t& item = items_[i];
            res += item.res_;
            if( item.argN_ == format_item_t::argN_tabulation) {
                BOOST_ASSERT( item.pad_scheme_ & format_item_t::tabulation);
                if( static_cast<size_type>(item.fmtstate_.width_) > res.size() )
                    res.append( static_cast<size_type>(item.fmtstate_.width_) - res.size(),
                                        item.fmtstate_.fill_ );
            }
            res += item.appendix_;
        }
        dumped_=true;
        return res;
    }
    template< class Ch, class Tr, class Alloc>
    typename std::basic_string<Ch, Tr, Alloc>::size_type  basic_format<Ch,Tr, Alloc>::
    size () const {
#ifdef BOOST_MSVC
       // If std::min<unsigned> or std::max<unsigned> are already instantiated
       // at this point then we get a blizzard of warning messages when we call
       // those templates with std::size_t as arguments.  Weird and very annoyning...
#pragma warning(push)
#pragma warning(disable:4267)
#endif
        BOOST_USING_STD_MAX();
        size_type sz = prefix_.size();
        unsigned long i;
        for(i=0; i < items_.size(); ++i) {
            const format_item_t& item = items_[i];
            sz += item.res_.size();
            if( item.argN_ == format_item_t::argN_tabulation)
                sz = max BOOST_PREVENT_MACRO_SUBSTITUTION (sz,
                                        static_cast<size_type>(item.fmtstate_.width_) );
            sz += item.appendix_.size();
        }
        return sz;
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
    }

namespace io {
namespace detail {

    template<class Ch, class Tr, class Alloc, class T>
    basic_format<Ch, Tr, Alloc>&
    bind_arg_body (basic_format<Ch, Tr, Alloc>& self, int argN, const T& val) {
        // bind one argument to a fixed value
        // this is persistent over clear() calls, thus also over str() and <<
        if(self.dumped_)
            self.clear(); // needed because we will modify cur_arg_
        if(argN<1 || argN > self.num_args_) {
            if( self.exceptions() & io::out_of_range_bit )
                boost::throw_exception(io::out_of_range(argN, 1, self.num_args_+1 ) );
            else return self;
        }
        if(self.bound_.size()==0)
            self.bound_.assign(self.num_args_,false);
        else
            BOOST_ASSERT( self.num_args_ == static_cast<signed int>(self.bound_.size()) );
        int o_cur_arg = self.cur_arg_;
        self.cur_arg_ = argN-1; // arrays begin at 0

        self.bound_[self.cur_arg_]=false; // if already set, we unset and re-sets..
        self.operator%(val); // put val at the right place, because cur_arg is set

        // Now re-position cur_arg before leaving :
        self.cur_arg_ = o_cur_arg;
        self.bound_[argN-1]=true;
        if(self.cur_arg_ == argN-1 ) {
            // hum, now this arg is bound, so move to next free arg
            while(self.cur_arg_ < self.num_args_ && self.bound_[self.cur_arg_])
                ++self.cur_arg_;
        }
        // In any case, we either have all args, or are on an unbound arg :
        BOOST_ASSERT( self.cur_arg_ >= self.num_args_ || ! self.bound_[self.cur_arg_]);
        return self;
    }

    template<class Ch, class Tr, class Alloc, class T> basic_format<Ch, Tr, Alloc>&
    modify_item_body (basic_format<Ch, Tr, Alloc>& self, int itemN, T manipulator) {
        // applies a manipulator to the format_item describing a given directive.
        // this is a permanent change, clear or reset won't cancel that.
        if(itemN<1 || itemN > static_cast<signed int>(self.items_.size() )) {
            if( self.exceptions() & io::out_of_range_bit )
                boost::throw_exception(io::out_of_range(itemN, 1, static_cast<int>(self.items_.size()) ));
            else return self;
        }
        self.items_[itemN-1].fmtstate_. template apply_manip<T> ( manipulator );
        return self;
    }

} // namespace detail
} // namespace io
} // namespace boost

#endif  // BOOST_FORMAT_IMPLEMENTATION_HPP


fileFormatVersion: 2
guid: f4cccc7e0b9325d4796b57409ad6633a
folderAsset: yes
timeCreated: 1505907135
licenseType: Free
DefaultImporter:
  userData:
  assetBundleName:
  assetBundleVariant:


const SamlStrategy = require('passport-saml').Strategy;

class Auth {
  constructor(options) {
    this.users = Object.create(null);
    this.passport = require('passport');

    this.passport.serializeUser((user, done) => {
      this.users[user.nameID] = user;

      return done(null, user.nameID);
    });

    this.passport.deserializeUser((id, done) => done(null, this.users[id]));

    this.guard = function guard(req, res, next) {
      if (req.isAuthenticated()) {
        return next();
      }
      res.json({
        redirect: options.entryPoint,
      });
    };
  }

  initialize() {
    return this.passport.initialize();
  }

  session() {
    return this.passport.session();
  }

  authenticate(type, options) {
    return this.passport.authenticate(type, options);
  }

  configure(options) {
    const samlCallback = (profile, done) => done(null, profile);

    this.passport.use(new SamlStrategy(options, samlCallback));
  }
}

module.exports = Auth;


/**
******************************************************************************
* @file       matekplugin.h
* @author     Tau Labs, http://taulabs.org, Copyright (C) 2013
*
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup Boards_MatekPlugin Matek boards support Plugin
* @{
* @brief Plugin to support Matek boards
*****************************************************************************/

/*
* This program 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 3 of the License, or
* (at your option) any later version.
*
* This program 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 this program; if not, see <http://www.gnu.org/licenses/>
*/

#ifndef MATEKPLUGIN_H
#define MATEKPLUGIN_H

#include <extensionsystem/iplugin.h>

class MatekPlugin : public ExtensionSystem::IPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.dronin.plugins.Matek")

public:
    MatekPlugin();
    ~MatekPlugin();

    void extensionsInitialized();
    bool initialize(const QStringList &arguments, QString *errorString);
    void shutdown();
};

#endif // MATEKPLUGIN_H


/* crypto/asn1/f_int.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 *
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 *
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 *
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
 *
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <stdio.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/asn1.h>

int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a)
	{
	int i,n=0;
	static const char *h="0123456789ABCDEF";
	char buf[2];

	if (a == NULL) return(0);

	if (a->type & V_ASN1_NEG)
		{
		if (BIO_write(bp, "-", 1) != 1) goto err;
		n = 1;
		}

	if (a->length == 0)
		{
		if (BIO_write(bp,"00",2) != 2) goto err;
		n += 2;
		}
	else
		{
		for (i=0; i<a->length; i++)
			{
			if ((i != 0) && (i%35 == 0))
				{
				if (BIO_write(bp,"\\\n",2) != 2) goto err;
				n+=2;
				}
			buf[0]=h[((unsigned char)a->data[i]>>4)&0x0f];
			buf[1]=h[((unsigned char)a->data[i]   )&0x0f];
			if (BIO_write(bp,buf,2) != 2) goto err;
			n+=2;
			}
		}
	return(n);
err:
	return(-1);
	}

int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size)
	{
	int ret=0;
	int i,j,k,m,n,again,bufsize;
	unsigned char *s=NULL,*sp;
	unsigned char *bufp;
	int num=0,slen=0,first=1;

	bs->type=V_ASN1_INTEGER;

	bufsize=BIO_gets(bp,buf,size);
	for (;;)
		{
		if (bufsize < 1) goto err_sl;
		i=bufsize;
		if (buf[i-1] == '\n') buf[--i]='\0';
		if (i == 0) goto err_sl;
		if (buf[i-1] == '\r') buf[--i]='\0';
		if (i == 0) goto err_sl;
		again=(buf[i-1] == '\\');

		for (j=0; j<i; j++)
			{
#ifndef CHARSET_EBCDIC
			if (!(	((buf[j] >= '0') && (buf[j] <= '9')) ||
				((buf[j] >= 'a') && (buf[j] <= 'f')) ||
				((buf[j] >= 'A') && (buf[j] <= 'F'))))
#else
			/* This #ifdef is not strictly necessary, since
			 * the characters A...F a...f 0...9 are contiguous
			 * (yes, even in EBCDIC - but not the whole alphabet).
			 * Nevertheless, isxdigit() is faster.
			 */
			if (!isxdigit(buf[j]))
#endif
				{
				i=j;
				break;
				}
			}
		buf[i]='\0';
		/* We have now cleared all the crap off the end of the
		 * line */
		if (i < 2) goto err_sl;

		bufp=(unsigned char *)buf;
		if (first)
			{
			first=0;
			if ((bufp[0] == '0') && (buf[1] == '0'))
				{
				bufp+=2;
				i-=2;
				}
			}
		k=0;
		i-=again;
		if (i%2 != 0)
			{
			ASN1err(ASN1_F_A2I_ASN1_INTEGER,ASN1_R_ODD_NUMBER_OF_CHARS);
			goto err;
			}
		i/=2;
		if (num+i > slen)
			{
			if (s == NULL)
				sp=(unsigned char *)OPENSSL_malloc(
					(unsigned int)num+i*2);
			else
				sp=OPENSSL_realloc_clean(s,slen,num+i*2);
			if (sp == NULL)
				{
				ASN1err(ASN1_F_A2I_ASN1_INTEGER,ERR_R_MALLOC_FAILURE);
				if (s != NULL) OPENSSL_free(s);
				goto err;
				}
			s=sp;
			slen=num+i*2;
			}
		for (j=0; j<i; j++,k+=2)
			{
			for (n=0; n<2; n++)
				{
				m=bufp[k+n];
				if ((m >= '0') && (m <= '9'))
					m-='0';
				else if ((m >= 'a') && (m <= 'f'))
					m=m-'a'+10;
				else if ((m >= 'A') && (m <= 'F'))
					m=m-'A'+10;
				else
					{
					ASN1err(ASN1_F_A2I_ASN1_INTEGER,ASN1_R_NON_HEX_CHARACTERS);
					goto err;
					}
				s[num+j]<<=4;
				s[num+j]|=m;
				}
			}
		num+=i;
		if (again)
			bufsize=BIO_gets(bp,buf,size);
		else
			break;
		}
	bs->length=num;
	bs->data=s;
	ret=1;
err:
	if (0)
		{
err_sl:
		ASN1err(ASN1_F_A2I_ASN1_INTEGER,ASN1_R_SHORT_LINE);
		}
	return(ret);
	}


Matrix4i m = Matrix4i::Random();
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Here is m.bottomLeftCorner(2, 2):" << endl;
cout << m.bottomLeftCorner(2, 2) << endl;
m.bottomLeftCorner(2, 2).setZero();
cout << "Now the matrix m is:" << endl << m << endl;


# $Id: makefile.aux 13297 2003-11-25 06:46:01Z jpf $
#
#            T H E    P I N E    M A I L   S Y S T E M
#
#   Laurence Lundblade and Mike Seibel
#   Networks and Distributed Computing
#   Computing and Communications
#   University of Washington
#   Administration Building, AG-44
#   Seattle, Washington, 98195, USA
#   Internet: lgl@CAC.Washington.EDU
#             mikes@CAC.Washington.EDU
#
#   Please address all bugs and comments to "pine-bugs@cac.washington.edu"
#
#
#   Pine and Pico are registered trademarks of the University of Washington.
#   No commercial use of these trademarks may be made without prior written
#   permission of the University of Washington.
#
#   Pine, Pico, and Pilot software and its included text are Copyright
#   1989-2001 by the University of Washington.
#
#   The full text of our legal notices is contained in the file called
#   CPYRIGHT, included with this distribution.
#
#
#   Pine is in part based on The Elm Mail System:
#    ***********************************************************************
#    *  The Elm Mail System  -  Revision: 2.13                             *
#    *                                                                     *
#    * 			Copyright (c) 1986, 1987 Dave Taylor               *
#    * 			Copyright (c) 1988, 1989 USENET Community Trust    *
#    ***********************************************************************
#
#

#
#     Make file for the Pine mail system for A/UX.
#
#   Most commonly fiddled flags for compiler.
#   Uncomment the setttings desired here
#
RM=          rm -f
LN=          ln -s
MAKE=        make
OPTIMIZE=    # -O
PROFILE=     # -pg
DEBUG=       -g -DDEBUG

CCLIENTDIR=  ../c-client
PICODIR=     ../pico

# Only need to uncomment next two lines if you run make from this directory
# and you don't want to supply them as arguments to the make.
#LDAPLIBS=    ../ldap/libraries/libldap.a ../ldap/libraries/liblber.a
#LDAPCFLAGS=  -DENABLE_LDAP -I../ldap/include
# Object files that need to be rebuilt if ENABLE_LDAP gets defined.
LDAPOFILES=   addrbook.o adrbkcmd.o args.o bldaddr.o init.o \
	      mailview.o other.o pine.o strings.o takeaddr.o

STDLIBS=     -ltermcap -lc -lposix
LOCLIBS=     $(PICODIR)/libpico.a $(CCLIENTDIR)/c-client.a
LIBS=        $(LOCLIBS) $(LDAPLIBS) $(STDLIBS) \
             `cat $(CCLIENTDIR)/LDFLAGS`

STDCFLAGS=   -Dconst= -DAUX -DSYSTYPE=\"AUX\" -DMOUSE
CFLAGS=      $(OPTIMIZE) $(PROFILE) $(DEBUG) $(EXTRACFLAGS) $(LDAPCFLAGS) \
	     $(LOCALPINECFLAGS) $(STDCFLAGS)

OFILES=	addrbook.o adrbkcmd.o adrbklib.o args.o bldaddr.o context.o filter.o \
	folder.o help.o helptext.o imap.o init.o mailcap.o mailcmd.o \
	mailindx.o mailpart.o mailview.o newmail.o other.o pine.o \
	reply.o screen.o send.o signals.o status.o strings.o takeaddr.o \
	os.o

HFILES=	headers.h os.h pine.h context.h helptext.h \
	$(PICODIR)/headers.h $(PICODIR)/estruct.h \
	$(PICODIR)/edef.h $(PICODIR)/efunc.h \
	$(PICODIR)/pico.h $(PICODIR)/os.h \
	$(CCLIENTDIR)/mail.h $(CCLIENTDIR)/osdep.h \
	$(CCLIENTDIR)/rfc822.h $(CCLIENTDIR)/misc.h

all:	pine rpload rpdump

pine:  $(OFILES) $(LOCLIBS)
	echo "char datestamp[]="\"`date`\"";" > date.c
	echo "char hoststamp[]="\"`hostname`\"";" >> date.c
	$(CC) $(LDFLAGS) $(CFLAGS) -o pine $(OFILES) date.c $(LIBS)

rpload:	rpload.o $(CCLIENTDIR)/c-client.a
	$(CC) $(LDFLAGS) $(CFLAGS) -o rpload rpload.o $(LIBS)

rpdump:	rpdump.o $(CCLIENTDIR)/c-client.a
	$(CC) $(LDFLAGS) $(CFLAGS) -o rpdump rpdump.o $(LIBS)

pine-use:	pine-use.c
	$(CC) -o pine-use pine-use.c

clean:
	$(RM) *.o os.h os.c helptext.c helptext.h pine rpdump rpload
	cd osdep; make clean; cd ..

os.h:	osdep/os-aux.h
	$(RM) os.h
	$(LN) osdep/os-aux.h os.h

os.c:	osdep/os-aux.c
	$(RM) os.c
	$(LN) osdep/os-aux.c os.c

$(OFILES):						$(HFILES)
addrbook.o adrbkcmd.o adrbklib.o bldaddr.o takeaddr.o:	adrbklib.h
context.o:						$(CCLIENTDIR)/misc.h
send.o:							$(CCLIENTDIR)/smtp.h
#$(LDAPOFILES):						$(LDAPLIBS)

helptext.c:	pine.hlp
		./cmplhelp.sh  < pine.hlp > helptext.c

helptext.h:	pine.hlp
		./cmplhlp2.sh  < pine.hlp > helptext.h

osdep/os-aux.c:	osdep/bld_path osdep/canacces osdep/canonicl \
		osdep/chnge_pw osdep/coredump osdep/creatdir \
		osdep/diskquot.non osdep/domnames osdep/err_desc \
		osdep/expnfldr osdep/fgetpos.non osdep/filesize osdep/fltrname \
		osdep/fnexpand osdep/header osdep/hostname \
		osdep/jobcntrl osdep/lstcmpnt osdep/mimedisp osdep/pipe \
		osdep/print osdep/pw_stuff osdep/readfile osdep/debuging \
		osdep/rename.hom osdep/tempfile osdep/writ_dir \
		osdep/termin.unx osdep/termout.unx \
		osdep/termin.gen osdep/termout.gen \
		osdep/sendmail osdep/execview osdep/os-aux.ic
		cd osdep; $(MAKE) includer os-aux.c; cd ..


/*
 * Copyright (c) 2007, 2018 Oracle and/or its affiliates. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0, which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the
 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
 * version 2 with the GNU Classpath Exception, which is available at
 * https://www.gnu.org/software/classpath/license.html.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
 */

package org.jvnet.hk2.config.generator;

import com.sun.codemodel.*;
import com.sun.enterprise.tools.apt.ContractFinder;
import org.jvnet.hk2.annotations.InhabitantAnnotation;
import org.jvnet.hk2.annotations.Service;
import org.jvnet.hk2.config.*;
import org.jvnet.hk2.config.Element;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.SimpleElementVisitor6;
import javax.lang.model.util.SimpleTypeVisitor6;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.StandardLocation;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.*;

import static javax.tools.StandardLocation.CLASS_PATH;
import static javax.tools.StandardLocation.SOURCE_PATH;

/**
 * Generates {@link ConfigInjector} implementations for {@link Configured} objects
 * and {@link ConfigBeanProxy} subtypes.
 *
 * @author Kohsuke Kawaguchi
 */

public class ConfigInjectorGenerator extends AbstractProcessor {

    private JCodeModel cm;

    private TypeMath math;
    /**
     * Reference to the {@link ConfigBeanProxy} type.
     */
    private TypeElement configBeanProxy;

    private final GeneratorVisitor visitor = new GeneratorVisitor();

    public ConfigInjectorGenerator() {
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latest(); // to avoid version warnings
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        return Collections.singleton(Configured.class.getName());
    }

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        this.math = new TypeMath(processingEnv);
        configBeanProxy = processingEnv.getElementUtils().getTypeElement(ConfigBeanProxy.class.getName());
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        cm = new JCodeModel();

        for (TypeElement annotation : annotations) {
            for(javax.lang.model.element.Element d : roundEnv.getElementsAnnotatedWith(annotation)) {
                d.accept(visitor, null);
            }

            try {
                cm.build(new FilerCodeWriter(processingEnv.getFiler()));
            } catch (IOException e) {
                throw new Error(e);
            }
        }
        return true;
    }

    private class GeneratorVisitor extends SimpleElementVisitor6<Void, Void> {

        @Override
        public Void visitType(TypeElement element, Void aVoid) {
            switch (element.getKind()) {
                /**
                 * For each {@link ConfigBeanProxy} annotated with {@link Configured}.
                 */
                case INTERFACE: {
                    try {
                        if(!isSubType(element,configBeanProxy)) {
                            printError(element.getQualifiedName() + " has @Configured but doesn't extend ConfigBeanProxy", element);
                        } else
                            new ClassGenerator(element,true).generate();
                    } catch (JClassAlreadyExistsException ex) {
                        printError(ex.toString(), element);
                    }
                    break;
                }
                /**
                 * For each class annotated with {@link Configured}.
                 */
                case CLASS: {
                    try {
                        new ClassGenerator(element,false).generate();
                    } catch (JClassAlreadyExistsException ex) {
                        printError(ex.toString(), element);
                    }
                    break;
                }
                default:
                    break;
            }
            return null;
        }
    }

    private boolean isSubType(TypeElement subType, TypeElement baseType) {
        Types types = processingEnv.getTypeUtils();
        return types.isSubtype(types.getDeclaredType(subType), types.getDeclaredType(baseType));
    }

    private static void addToMetadata(TreeMap<String,List<String>> metadata, String key, String value) {
        List<String> inner = metadata.get(key);
        if (inner == null) {
            inner = new LinkedList<String>();

            metadata.put(key, inner);
        }

        inner.add(value);
    }

    /**
     * @return the map as "key=value1,key=value2,...."
     */
    private static String toCommaSeparatedString(TreeMap<String,List<String>> metadata) {
        StringBuilder buf = new StringBuilder();
        for (Map.Entry<String, List<String>> e : metadata.entrySet()) {
            for (String v : e.getValue()) {
                if (buf.length() > 0) {
                    buf.append(',');
                }
                buf.append(e.getKey()).append('=').append(v);
            }
        }
        return buf.toString();
    }

    /*package*/ class ClassGenerator {
        final TypeElement clz;
        final JDefinedClass injector;
        final JClass targetType;
        final JAnnotationUse service;
        final JMethod injectMethod,injectAttributeMethod,injectElementMethod;
        final TreeMap<String,List<String>> metadata = new TreeMap<String,List<String>>();
        /**
         * Key property that has {@link Element#key()} or {@link Attribute#key()}
         */
        private Property key=null;

        /**
         * If true, generate a ConfigInjector that extends from {@link NoopConfigInjector}.
         * This is used as the metadata place holder for {@link ConfigBeanProxy}s.
         *

         * If false, generate a real {@link ConfigInjector}.
         *
         *

         * See the test-config test module for this difference in action.
         */
        private final boolean generateNoopConfigInjector;

        public ClassGenerator(TypeElement clz, boolean generateNoopConfigInjector) throws JClassAlreadyExistsException {
            this.clz = clz;
            this.generateNoopConfigInjector = generateNoopConfigInjector;
            Configured c = clz.getAnnotation(Configured.class);

            String name = clz.getQualifiedName().toString();
            targetType = cm.ref(name);

            // [RESULT]
            // @Service(name='...')
            // @InjectionTarget(target)
            // public class XYZInjector extends ConfigInjector<XYZ>
            injector = cm._class(name+"Injector");
            String elementName = c.name();
            if(c.local()) {
                if(elementName.length()>0) {
                    printError("@Configured.local and @Configured.name is mutually exclusive", clz);
                    elementName = ""; // error recovery
                }
            } else {
                if(elementName.length()==0) // infer default
                    elementName = Dom.convertName(clz.getSimpleName().toString());
            }

            service = injector.annotate(Service.class).param("name",elementName);
            injector.annotate(InjectionTarget.class).param("value",targetType);

            Set<String> targetHabitats = new HashSet<String>();
            for (AnnotationMirror am : clz.getAnnotationMirrors()) {
                InhabitantAnnotation ia = am.getAnnotationType().asElement().getAnnotation(InhabitantAnnotation.class);
                if (ia != null) {
                    targetHabitats.add(ia.value());
                }
            }

            if(generateNoopConfigInjector) {
                injector._extends(cm.ref(NoopConfigInjector.class));
                injectAttributeMethod = null;
                injectMethod = null;
                injectElementMethod = null;
            } else {
                injector._extends(cm.ref(ConfigInjector.class).narrow(targetType));

                // [RESULT]
                // public void inject(Dom dom, Property target) { ... }
                injectMethod = injector.method(JMod.PUBLIC, void.class, "inject");
                injectMethod.param(Dom.class, "dom");
                injectMethod.param(targetType, "target");
                injectMethod.body();

                injectAttributeMethod = injector.method(JMod.PUBLIC,void.class,"injectAttribute");
                addReinjectionParam(injectAttributeMethod);

                injectElementMethod = injector.method(JMod.PUBLIC,void.class,"injectElement");
                addReinjectionParam(injectElementMethod);
            }

            addToMetadata(metadata, ConfigMetadata.TARGET,name);

            // locate additional contracts for the target.
            for (TypeElement t : ContractFinder.find(clz))
                addToMetadata(metadata, ConfigMetadata.TARGET_CONTRACTS,t.getQualifiedName().toString());
            if (targetHabitats.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (String h : targetHabitats) {
                    sb.append(h).append(";");
                }
                addToMetadata(metadata, ConfigMetadata.TARGET_HABITATS, sb.toString());
            }
        }

        private void addReinjectionParam(JMethod method) {
            method.param(Dom.class,"dom");
            method.param(String.class,"name");
            method.param(targetType, "target");
        }

        /**
         * Visits all annotated fields/methods and
         * generates the body of the {@link ConfigInjector#inject(Dom, Object)} code.
         */
        public void generate() {
            Stack<TypeElement> q = new Stack<TypeElement>();
            Set<TypeElement> visited = new HashSet<TypeElement>();
            q.push(clz);

            while(!q.isEmpty()) {
                TypeElement t = q.pop();
                if(!visited.add(t)) continue;   // been here already
                for (javax.lang.model.element.Element child : t.getEnclosedElements()) {
                    switch (child.getKind()) {
                        case FIELD: { // ElementFilter.fieldsIn
                            generate(new Property.Field((VariableElement) child));
                            break;
                        }
                        case METHOD: {
                            generate(new Property.Method((ExecutableElement) child));
                        }
                        default:
                            continue;
                    }
                }

                for (TypeMirror it : clz.getInterfaces())
                    q.add((TypeElement) ((DeclaredType)it).asElement());

                if (ElementKind.CLASS.equals(t.getKind())) {
                    TypeMirror sc = t.getSuperclass();
                    if(!TypeKind.NONE.equals(sc.getKind()))
                        q.add((TypeElement) ((DeclaredType) sc).asElement());
                }
            }

            service.param("metadata", toCommaSeparatedString(metadata));
        }

        private void generate(Property p) {
            Attribute a = p.getAnnotation(Attribute.class);
            Element e = p.getAnnotation(Element.class);

            if(a!=null) {
                new AttributeMethodGenerator(p,a).generate();
                if(e!=null)
                    printError("Cannot have both @Element and @Attribute at the same time", p.decl());
            } else {
                if(e!=null)
                    new ElementMethodGenerator(p,e).generate();
            }

            // Updates #key with error check.
            if(p.isKey()) {
                if(key!=null) {
                    printError("Multiple key properties", p.decl());
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Another one is at here", key.decl());
                }
                key = p;
            }
        }

        /**
         * Generates a single injection method, which inject
         * value(s) of a particular element/attribute name.
         */
        private abstract class MethodGenerator {
            final JBlock body;
            final JVar $dom;
            final JVar $target;
            /**
             * Element name or attribute name.
             * A special case is "*" for elements that indicate substitute-by-type.
             */
            final String xmlName;
            final Property p;
            private int iota=1;
            /**
             * Erasure of {@code p.type()}
             */
            final TypeMirror erasure;
            /**
             * If this is a multi-value property, the packer knows how to create a collection value.
             */
            final Packer packer;
            /**
             * The type of individual item. If this is a multi-value property, this is a type of the collection
             * item, otherwise the same as {@link #erasure}.
             */
            final TypeMirror itemType;
            /**
             * Converter for {@link #itemType}.
             */
            /*semi-final*/ Converter conv;

            MethodGenerator(String methodNamePrefix, JMethod reinjectionMethod, Property p, String xmlName) {
                this.xmlName = p.inferName(xmlName);
                this.p = p;

                if(generateNoopConfigInjector) {
                    body = null;
                    $dom = null;
                    $target = null;
                } else {
                    JMethod m = injector.method(JMod.PUBLIC,void.class, methodNamePrefix+p.seedName());
                    $dom = m.param(Dom.class,"dom");
                    $target = m.param(targetType,"target");
                    body = m.body();

                    injectMethod.body().invoke(m).arg($dom).arg($target);

                    reinjectionMethod.body()._if(JExpr.lit(this.xmlName).invoke("equals").arg(JExpr.ref("name")))
                        ._then().invoke(m).arg($dom).arg($target);
                }

                erasure = erasure(p.type());
                packer = createPacker(p.type(),erasure);

                itemType = packer==null ? erasure : erasure(packer.itemType());
            }

            private void assign(JExpression rhs) {
                p.assign($target,body,rhs);
            }

            /**
             * Returns '@xmlName' for attributes and '<xmlName>' for elements.
             */
            protected abstract String xmlTokenName();

            protected void generate() {
                conv = createConverter(itemType);
                conv.addMetadata(xmlTokenName(),itemType);

                if(!isVariableExpansion() && toJtype.visit(itemType,null)!=cm.ref(String.class))
                    printError("variableExpansion=false is only allowed on String", p.decl());

                if(!generateNoopConfigInjector) {
                    JVar value = var(
                        packer!=null ? cm.ref(List.class).narrow(conv.sourceType()) : conv.sourceType(),getXmlValue());

                    if(!isRequired())
                        body._if(value.eq(JExpr._null()))._then()._return();

                    if(packer!=null)
                        handleMultiValue(value);
                    else
                        assign(conv.as(value,itemType));
                }

                if(p.isKey())
                    addKey();
            }

            /**
             * Returns true if the property must have a value, or if it's optional.
             */
            protected abstract boolean isRequired();

            /**
             * Returns true if the property is a reference to another element
             */
            protected abstract boolean isReference();

            /**
             * Returns true if the property is a a subject of variable expansion.
             */
            protected abstract boolean isVariableExpansion();

            /**
             * Return true if this property is {@code @FromElement("*")},
             * which means finding a match by types
             */
            protected abstract boolean isAllElementMatch();

            /**
             * Obtains the source value(s) from {@link Dom}.
             */
            protected abstract JExpression getXmlValue();

            private void addKey() {
                addToMetadata(metadata, ConfigMetadata.KEY, xmlTokenName());
                addToMetadata(metadata, ConfigMetadata.KEYED_AS, ((TypeElement) p.decl().getEnclosingElement()).getQualifiedName().toString());
            }

            /**
             * Invokes a method on DOM by adjusting the name for plural.
             */
            final JInvocation invokeDom(String methodName) {
                if(packer!=null)    methodName+='s';
                return $dom.invoke(methodName);
            }

            private void handleMultiValue(JVar values) {
                // [RESULT]
                // List<S> values = dom.leafElements("...");
                // <packer init>
                // for( S v : values ) {
                //   <packer set>(<as>(v));
                // }
                //  ... assign ...
                packer.start(values.invoke("size"));
                JForEach forEach = body.forEach(conv.sourceType(), id(), values);
                packer.pack(forEach.body(),conv.as(forEach.var(),packer.itemType()), forEach.var());
                assign(packer.end());
            }

            /**
             * Creates a variable
             */
            protected JVar var(JType t, JExpression init) {
                return body.decl(t,id(),init);
            }

            protected JVar var(Class t, JExpression init) {
                return var(cm.ref(t),init);
            }

            /**
             * Creates an unique id.
             */
            private String id() {
                return "v"+(iota++);
            }

            private Packer createPacker(TypeMirror type, TypeMirror erasure) {
                if(erasure.getKind() == TypeKind.ARRAY) {
                    // T=X[]
                    return new ArrayPacker((ArrayType)erasure);
                }

                TypeMirror itemType = math.isCollection(type);
                if(itemType!=null) {
                    // T=Collection[]
                    return new ListPacker(type,itemType);
                }

                TypeMirror mapType = math.baseClassFinder.visit(type, processingEnv.getElementUtils().getTypeElement(Map.class.getName()));
                if(mapType!=null) {
                    // T=Map<...>
                    DeclaredType d = (DeclaredType)mapType;
                    List<? extends TypeMirror> itr = d.getTypeArguments();
                    return new MapPacker(itr.get(1));
                }

                return null;
            }

            abstract class Packer {
                abstract TypeMirror itemType();
                /**
                 * Starts packing.
                 */
                abstract void start(JExpression $valueSize);
                /**
                 * Adds one more item to the pack.
                 */
                abstract void pack(JBlock block, JExpression item, JExpression sourceValue);

                /**
                 * Returns the packed value to be set.
                 */
                abstract JExpression end();
            }

            final class ArrayPacker extends Packer {
                private JVar $array,$index;
                private final JType arrayT;
                private final JType componentT;
                private final ArrayType at;

                public ArrayPacker(ArrayType t) {
                    this.at = t;
                    this.componentT = toJtype.visit(itemType(), null);
                    this.arrayT = componentT.array();
                }

                TypeMirror itemType() {
                    return at.getComponentType();
                }

                void start(JExpression $valueSize) {
                    // [RESULT]
                    // T[] x = new T[values.size()];
                    $array = var(arrayT, JExpr.newArray(componentT, $valueSize));
                    $index = var(int.class,JExpr.lit(0));
                }

                void pack(JBlock block, JExpression item, JExpression sourceValue) {
                    // [RESULT]
                    // x[i++] = <rhs>;
                    block.assign($array.component($index.incr()),item);
                }

                JExpression end() {
                    return $array;
                }
            }

            final class ListPacker extends Packer {
                private JVar $list;
                private final JClass collectionType,itemType;
                private final TypeMirror itemT;

                public ListPacker(TypeMirror collectionType, TypeMirror itemType) {
                    this.collectionType = toJtype.visit(collectionType, null).boxify();
                    this.itemType       = toJtype.visit(itemType, null).boxify();
                    this.itemT = itemType;
                }

                TypeMirror itemType() {
                    return itemT;
                }

                void start(JExpression $valueSize) {
                    // [RESULT]
                    // T x = new ArrayList<T>(values.size());
                    $list = var(collectionType,JExpr._new(implType()).arg($valueSize));
                }

                /**
                 * Figure out the concrete implementation class to be used.
                 */
                JType implType() {
                    if(cm.ref(Set.class).isAssignableFrom(collectionType))
                        return cm.ref(HashSet.class).narrow(itemType);
                    return cm.ref(ArrayList.class).narrow(itemType);
                }

                void pack(JBlock block, JExpression item, JExpression sourceValue) {
                    // [RESULT]
                    // x.add(<rhs>);
                    block.invoke($list,"add").arg(item);
                }

                JExpression end() {
                    return $list;
                }
            }

            final class MapPacker extends Packer {
                private JVar $map;
                private final TypeMirror itemT;

                public MapPacker(TypeMirror itemType) {
                    this.itemT = itemType;
                }

                TypeMirror itemType() {
                    return itemT;
                }

                void start(JExpression $valueSize) {
                    // [RESULT]
                    // T x = new HashMap<T>();
                    $map = var(Map.class,JExpr._new(cm.ref(HashMap.class)).arg($valueSize));
                }

                void pack(JBlock block, JExpression item, JExpression itemDom) {
                    // [RESULT]
                    // x.put(dom.getKey(),<rhs>);
                    block.invoke($map,"put").arg(itemDom.invoke("getKey")).arg(item);
                }

                JExpression end() {
                    return $map;
                }
            }

            private Converter createConverter(TypeMirror itemType) {
                try {
                    // is this a leaf value?
                    math.simpleValueConverter.visit(itemType, JExpr._null());
                    return new LeafConverter();
                } catch (UnsupportedOperationException e) {
                    // nope
                }

                // try to handle it as a reference
                if (TypeKind.DECLARED.equals(itemType.getKind())) {
                    TypeElement decl = (TypeElement) ((DeclaredType)itemType).asElement();
                    Configured cfg = decl.getAnnotation(Configured.class);
                    if(cfg!=null) {
                        // node value
                        if(isReference())
                            return new ReferenceConverter();
                        else
                            return new NodeConverter();
                    }
                }

                if(isAllElementMatch()) {
                    return new NodeByTypeConverter(itemType);
                }

                printError("I don't know how to inject "+itemType+" from configuration", p.decl());
                return new NodeConverter(); // error recovery
            }

            /**
             * Encapsulates the source value representation in {@link Dom}.
             */
            abstract class Converter {
                /**
                 * Generates an expression that converts 'rhs'.
                 *
                 * @param targetType
                 *      The expected type of the expression, so that the generated expression
                 *      can contain cast operation if necessary.
                 */
                abstract JExpression as(JExpression rhs, TypeMirror targetType);
                /**
                 * Source value type as returned by {@link Dom}.
                 */
                abstract JClass sourceType();

                /**
                 * True if the XML representation of the source value is a leaf (string value)
                 * as opposed to node (an XML fragment.)
                 */
                abstract boolean isLeaf();

                abstract void addMetadata(String key,TypeMirror itemType);

                protected final String makeCollectionIfNecessary(String s) {
                    if(packer!=null)    return "collection:"+s;
                    else                return s;
                }
            }

            class LeafConverter extends Converter {
                JExpression as(JExpression rhs, TypeMirror targetType) {
                    return math.simpleValueConverter.visit(targetType, rhs);
                }
                JClass sourceType() {
                    return cm.ref(String.class);
                }

                boolean isLeaf() {
                    return true;
                }

                void addMetadata(String key,TypeMirror itemType) {
                    addToMetadata(metadata, key,makeCollectionIfNecessary("leaf"));
                }
            }

            class NodeConverter extends Converter {
                JExpression as(JExpression rhs, TypeMirror targetType) {
                    return JExpr.cast(toJtype.visit(targetType, null), rhs.invoke("get"));
                }
                JClass sourceType() {
                    return cm.ref(Dom.class);
                }

                boolean isLeaf() {
                    return false;
                }

                void addMetadata(String key,TypeMirror itemType) {
                   String typeName;
                    if (itemType.getKind() == TypeKind.DECLARED) {
                        typeName=((DeclaredType)itemType).asElement().toString();
                   } else {
                        typeName=itemType.toString();
                   }

                    addToMetadata(metadata, key,makeCollectionIfNecessary(typeName));
                }
            }

            class NodeByTypeConverter extends Converter {
                final JClass sourceType;

                NodeByTypeConverter(TypeMirror sourceType) {
                    this.sourceType = toJtype.visit(sourceType, null).boxify();
                }

                JExpression as(JExpression rhs, TypeMirror targetType) {
                    return rhs;
                }
                JClass sourceType() {
                    return sourceType;
                }
                boolean isLeaf() {
                    return false;
                }
                void addMetadata(String key,TypeMirror itemType) {
                    // TODO: we need to indicate that there's open-ended match here
                }
            }

            class ReferenceConverter extends Converter {
                JExpression as(JExpression rhs, TypeMirror targetType) {
                    return JExpr.invoke("reference").arg($dom).arg(rhs).arg(toJtype.visit(targetType, null).boxify().dotclass());
                }
                JClass sourceType() {
                    return cm.ref(String.class);
                }

                boolean isLeaf() {
                    return true;
                }

                void addMetadata(String key,TypeMirror itemType) {
                    addToMetadata(metadata, key,makeCollectionIfNecessary("leaf"));
                    addToMetadata(metadata, key, "reference");
                }
            }
        }

        private final class AttributeMethodGenerator extends MethodGenerator {
            private final Attribute a;

            private AttributeMethodGenerator(Property p, Attribute a) {
                super("attribute_", injectAttributeMethod, p, a.value());
                this.a = a;
            }

            protected String xmlTokenName() {
                return '@'+xmlName;
            }

            protected boolean isRequired() {
                return a.required();
            }

            protected boolean isReference() {
                return a.reference();
            }

            protected boolean isVariableExpansion() {
                return a.variableExpansion();
            }

            protected boolean isAllElementMatch() {
                return false;
            }

            protected boolean hasDefault() {
                boolean noDefaultValue =
                    a.defaultValue().length() == 1 && a.defaultValue().charAt(0) == '\u0000';
                return (!noDefaultValue);
            }
            /**
             * Generates the injector that reads an attribute and sets the value.
             */
            @Override
            protected void generate() {
                addToMetadata(metadata, xmlTokenName(),isRequired()?"required":"optional");
                if (this.hasDefault()) {
                    if (a.defaultValue().indexOf(',')!=-1) {
                        addToMetadata(metadata, xmlTokenName(), '"' + "default:" + a.defaultValue() + '"');
                    } else {
                        addToMetadata(metadata, xmlTokenName(), "default:" + a.defaultValue());
                    }
                }
                String ant = "";
                try {
                    a.dataType();
                } catch(MirroredTypeException me) { //hack?
                     ant = getCanonicalTypeFrom(me);
                }
                if (ant.length() == 0) { //take it from the return type of method
                    Property.Method m = (Property.Method)p; // Method needn't be Property's inner class
                    String typeReturnedByMethodDecl = m.method.getReturnType().toString();
                    addToMetadata(metadata, xmlTokenName(), "datatype:" + typeReturnedByMethodDecl);
                } else {
                    addToMetadata(metadata, xmlTokenName(), "datatype:" + ant);
                }
                super.generate();
            }

            protected JExpression getXmlValue() {
                if(!isVariableExpansion() && packer!=null) {
                    printError("collection attribute property is inconsistent with variableExpansion=false", p.decl());
                }
                return invokeDom(isVariableExpansion()?"attribute":"rawAttribute").arg(xmlName);
            }
        }

        private final class ElementMethodGenerator extends MethodGenerator {
            private final Element e;
            private ElementMethodGenerator(Property p, Element e) {
                super("element_", injectElementMethod, p, e.value());
                this.e = e;
            }

            protected String xmlTokenName() {
                return '<'+xmlName+'>';
            }

            protected JExpression getXmlValue() {
                String name;
                if(conv.isLeaf()) {
                    if(isVariableExpansion())
                        name = "leafElement";
                    else
                        name = "rawLeafElement";
                } else {
                    assert isVariableExpansion();   // this error is checked earlier.
                    if(xmlName.equals("*")) {
                        return invokeDom("nodeByTypeElement").arg(toJtype.visit(itemType, null).boxify().dotclass());
                    } else
                        name = "nodeElement";
                }

                return invokeDom(name).arg(xmlName);
            }

            @Override
            protected void generate() {
                super.generate();
                if (packer==null) {
                    for (AnnotationMirror am : p.decl().getAnnotationMirrors()) {
                        if (!am.toString().contains("hk2"))
                            addToMetadata(metadata, xmlTokenName(), am.toString());
                    }
                }
            }

            protected boolean isRequired() {
                return e.required();
            }

            protected boolean isReference() {
                return e.reference();
            }

            protected boolean isVariableExpansion() {
                return e.variableExpansion();
            }

            protected boolean isAllElementMatch() {
                return e.value().equals("*");
            }
        }
    }

    private static String getCanonicalTypeFrom(MirroredTypeException me) {
        TypeMirror tm = me.getTypeMirror();
        if (tm.getKind() == TypeKind.DECLARED) {
            DeclaredType dec = (DeclaredType) tm;
            return ((TypeElement)dec.asElement()).getQualifiedName().toString();
        }
        return "";  //ok?
    }

    private TypeMirror erasure(TypeMirror type) {
        return processingEnv.getTypeUtils().erasure(type);
    }

    /**
     * Takes {@link TypeMirror} and returns the corresponding {@link JType}.
     */
    final SimpleTypeVisitor6<JType,Void> toJtype = new SimpleTypeVisitor6<JType,Void>() {

        @Override
        public JType visitPrimitive(PrimitiveType type, Void param) {
            switch (type.getKind()) {
                case BOOLEAN:   return cm.BOOLEAN;
                case BYTE:      return cm.BYTE;
                case CHAR:      return cm.CHAR;
                case DOUBLE:    return cm.DOUBLE;
                case FLOAT:     return cm.FLOAT;
                case INT:       return cm.INT;
                case LONG:      return cm.LONG;
                case SHORT:     return cm.SHORT;
            }
            throw new AssertionError();
        }

        @Override
        public JType visitArray(ArrayType type, Void param) {
            return visit(type.getComponentType(), null).array();
        }

        @Override
        public JType visitDeclared(DeclaredType type, Void param) {
            // TODO: generics support
            return cm.ref(((TypeElement) type.asElement()).getQualifiedName().toString());
        }

        @Override
        protected JType defaultAction(TypeMirror e, Void aVoid) {
            throw new UnsupportedOperationException();
        }

        @Override
        public JType visitNoType(NoType t, Void aVoid) {
            return cm.VOID;
        }
    };

    private void printError(String error, javax.lang.model.element.Element element) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, error, element);
    }

    /**
     * {@link CodeWriter} that generates source code to {@link Filer}.
     *
     * @author Kohsuke Kawaguchi
     *
     * Moved from jaxb-xjc to break unneeded dependency.
     */
    public static final class FilerCodeWriter extends CodeWriter {

        private final Filer filer;

        public FilerCodeWriter(Filer filer) {
            this.filer = filer;
        }

        public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
            StandardLocation loc;
            if(fileName.endsWith(".java")) {
                // Annotation Processing doesn't do the proper Unicode escaping on Java source files,
                // so we can't rely on Filer.createSourceFile.
                loc = SOURCE_PATH;
            } else {
                // put non-Java files directly to the output folder
                loc = CLASS_PATH;
            }
            return filer.createResource(loc, pkg.name(), fileName).openOutputStream();
        }

        public Writer openSource(JPackage pkg, String fileName) throws IOException {
            String name;
            if(pkg.isUnnamed())
                name = fileName;
            else
                name = pkg.name()+'.'+fileName;

            name = name.substring(0,name.length()-5);   // strip ".java"

            return filer.createSourceFile(name).openWriter();
        }

        public void close() {}
    }

}


package net.cgt.weixin.utils;

import net.cgt.weixin.GlobalParams;
import net.cgt.weixin.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class AppToast extends Toast {

	private static AppToast instance = null;
	private View layout;
	private TextView text;

	private AppToast() {
		super(GlobalParams.activity);
		init();
	}

	public static AppToast getToast() {
		if (instance == null) {
			instance = new AppToast();
		}
		return instance;
	}

	private void init() {
		LayoutInflater inflate = (LayoutInflater) GlobalParams.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layout = inflate.inflate(R.layout.cgt_transient_notification, null);
		text = (TextView) layout.findViewById(R.id.message);
		this.setView(layout);
	}

	public void show(String msg) {
		text.setText(msg);
		this.setDuration(Toast.LENGTH_SHORT);
		this.show();
	}

	public void show(int msg) {
		text.setText(msg);
		this.setDuration(Toast.LENGTH_SHORT);
		this.show();
	}

}


import { TestBed } from '@angular/core/testing';

import { LazyComponentHandler } from './lazy-component.handler';
import { Priority } from '@spartacus/core';
import { DefaultComponentHandler } from '@spartacus/storefront';
import { of } from 'rxjs';
import createSpy = jasmine.createSpy;

class MockDefaultComponentHandler {
  launcher = createSpy().and.returnValue(of({}));
}

describe('LazyComponentHandler', () => {
  let service: LazyComponentHandler;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {
          provide: DefaultComponentHandler,
          useClass: MockDefaultComponentHandler,
        },
      ],
    });
    service = TestBed.inject(LazyComponentHandler);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  describe('getMatch', () => {
    it('should match function', () => {
      expect(service.hasMatch({ component: () => {} })).toBeTruthy();
    });

    it('should not match class', () => {
      class TestClass {}
      expect(service.hasMatch({ component: TestClass })).toBeFalsy();
    });
  });

  describe('getPriority', () => {
    it('should return Priority.LOW', () => {
      expect(service.getPriority()).toBe(Priority.LOW);
    });
  });

  describe('launcher', () => {
    it('should resolve component and pass it to standard launcher', async () => {
      const resolvedComponent = 'testData';
      const mapping = () => new Promise((res) => res(resolvedComponent));
      await service
        .launcher({ component: mapping }, undefined, undefined)
        .toPromise();

      const defaultHandler = TestBed.inject(DefaultComponentHandler);

      expect(defaultHandler.launcher).toHaveBeenCalledWith(
        { component: resolvedComponent },
        undefined,
        undefined
      );
    });
  });
});


/*
Copyright 2019 MNK Consulting, LLC.
http://mnkcg.com

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

#include <v1model.p4>

enum bit<16> EthTypes {
    IPv4 = 0x0800,
    ARP = 0x0806,
    RARP = 0x8035,
    EtherTalk = 0x809B,
    VLAN = 0x8100,
    IPX = 0x8137,
    IPv6 = 0x86DD
}

struct alt_t {
    bit<1> valid;
    bit<7> port;
    int<8> hashRes;
    bool   useHash;
    EthTypes type;
    bit<7> pad;
};

struct row_t {
    alt_t alt0;
    alt_t alt1;
};

header bitvec_hdr {
    row_t row;
}

struct local_metadata_t {
    row_t row0;
    row_t row1;
    bitvec_hdr bvh0;
    bitvec_hdr bvh1;
};

struct parsed_packet_t {
    bitvec_hdr bvh0;
    bitvec_hdr bvh1;
};

parser parse(packet_in pk, out parsed_packet_t h,
             inout local_metadata_t local_metadata,
             inout standard_metadata_t standard_metadata) {
    state start {
	pk.extract(h.bvh0);
	pk.extract(h.bvh1);
	transition accept;
    }
}

control ingress(inout parsed_packet_t h,
                inout local_metadata_t local_metadata,
                inout standard_metadata_t standard_metadata) {
    bitvec_hdr bh;

    action do_act() {
        h.bvh1.row.alt1.valid = 0;
        local_metadata.row0.alt0.valid = 0;
    }

    table tns {
        key = {
            h.bvh1.row.alt1.valid : exact;
            local_metadata.row0.alt0.valid : exact;
        }
	actions = {
            do_act;
        }
    }

    apply {

        tns.apply();

        // Copy another header's data to local variable.
        bh.row.alt0.useHash = h.bvh0.row.alt0.useHash;
        bh.row.alt1.type = EthTypes.IPv4;
        h.bvh0.row.alt1.type = bh.row.alt1.type;

        local_metadata.row0.alt0.useHash = true;
        clone3(CloneType.I2E, 0, local_metadata.row0);
    }
}

control egress(inout parsed_packet_t hdr,
               inout local_metadata_t local_metadata,
               inout standard_metadata_t standard_metadata) {
    apply { }
}

control deparser(packet_out b, in parsed_packet_t h) {
    apply {
        b.emit(h.bvh0);
        b.emit(h.bvh1);
    }
}

control verifyChecksum(inout parsed_packet_t hdr,
                        inout local_metadata_t local_metadata) {
    apply { }
}

control compute_checksum(inout parsed_packet_t hdr,
                         inout local_metadata_t local_metadata) {
    apply { }
}

V1Switch(parse(), verifyChecksum(), ingress(), egress(),
compute_checksum(), deparser()) main;


'<Snippet1>
Imports System
Imports System.Collections.ObjectModel

Namespace PerformanceLibrary

    Public Class Book

        Private _Pages As ReadOnlyCollection(Of String)

        Public Sub New(ByVal pages As String())
            _Pages = New ReadOnlyCollection(Of String)(pages)
        End Sub

        Public ReadOnly Property Pages() As ReadOnlyCollection(Of String)
            Get
                Return _Pages
            End Get
        End Property

    End Class

End Namespace
'</Snippet1>


////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2000 Andrei Alexandrescu
// Copyright (c) 2000 Petru Marginean
// Copyright (c) 2005 Joshua Lehrer
//
// Permission to use, copy, modify, distribute and sell this software for any
//     purpose is hereby granted without fee, provided that the above copyright
//     notice appear in all copies and that both that copyright notice and this
//     permission notice appear in supporting documentation.
// The author makes no representations about the
//     suitability of this software for any purpose. It is provided "as is"
//     without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
#ifndef LOKI_SCOPEGUARD_H_
#define LOKI_SCOPEGUARD_H_

#include "mongo/platform/compiler.h"

namespace mongo
{

    ////////////////////////////////////////////////////////////////////////////////
    ///  \class RefToValue
    ///
    ///  Transports a reference as a value
    ///  Serves to implement the Colvin/Gibbons trick for SmartPtr/ScopeGuard
    ////////////////////////////////////////////////////////////////////////////////

    template <class T>
        class RefToValue
    {
    public:

    RefToValue(T& ref) : ref_(ref)
        {}

    RefToValue(const RefToValue& rhs) : ref_(rhs.ref_)
        {}

        operator T& () const
        {
            return ref_;
        }

    private:
        // Disable - not implemented
        RefToValue();
        RefToValue& operator=(const RefToValue&);

        T& ref_;
    };

    ////////////////////////////////////////////////////////////////////////////////
    ///  RefToValue creator.
    ////////////////////////////////////////////////////////////////////////////////

    template <class T>
        inline RefToValue<T> ByRef(T& t)
    {
        return RefToValue<T>(t);
    }

    ////////////////////////////////////////////
    ///  ScopeGuard
    /*
      Trivial example for use:

      FILE* f = fopen("myfile.txt", "w+");
      if (!f)
          return error;
      ON_BLOCK_EXIT(fclose, f);

      More complicated example:

      ScopeGuard guard = MakeGuard(my_rollback_func, myparam);
      ...
      if (successful) {
         guard.Dismiss();
         return;
      }
      // guard is still active here and will fire at scope exit
      ...

    */

    class ScopeGuardImplBase
    {
        ScopeGuardImplBase& operator =(const ScopeGuardImplBase&);

    protected:

        ~ScopeGuardImplBase()
        {}

        ScopeGuardImplBase(const ScopeGuardImplBase& other) throw()
            : dismissed_(other.dismissed_)
        {
            other.Dismiss();
        }

        template <typename J>
            static void SafeExecute(J& j) throw()
        {
            if (!j.dismissed_)
                try
                {
                    j.Execute();
                }
            catch(...)
            {}
        }

        mutable bool dismissed_;

    public:
        ScopeGuardImplBase() throw() : dismissed_(false)
        {}

        void Dismiss() const throw()
        {
            dismissed_ = true;
        }
    };

    ////////////////////////////////////////////////////////////////
    ///
    /// \typedef typedef const ScopeGuardImplBase& ScopeGuard
    ///
    /// See Andrei's and Petru Marginean's CUJ article
    /// http://www.cuj.com/documents/s=8000/cujcexp1812alexandr/alexandr.htm
    ///
    /// Changes to the original code by Joshua Lehrer:
    /// http://www.lehrerfamily.com/scopeguard.html
    ////////////////////////////////////////////////////////////////

    typedef const ScopeGuardImplBase& ScopeGuard;

    template <typename F>
        class ScopeGuardImpl0 : public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl0<F> MakeGuard(F fun)
        {
            return ScopeGuardImpl0<F>(fun);
        }

        ~ScopeGuardImpl0() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_();
        }

    protected:
    ScopeGuardImpl0(F fun) : fun_(fun)
        {}

        F fun_;
    };

    template <typename F>
        inline ScopeGuardImpl0<F> MakeGuard(F fun)
    {
        return ScopeGuardImpl0<F>::MakeGuard(fun);
    }

    template <typename F, typename P1>
        class ScopeGuardImpl1 : public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl1<F, P1> MakeGuard(F fun, P1 p1)
        {
            return ScopeGuardImpl1<F, P1>(fun, p1);
        }

        ~ScopeGuardImpl1() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_(p1_);
        }

    protected:
    ScopeGuardImpl1(F fun, P1 p1) : fun_(fun), p1_(p1)
        {}

        F fun_;
        const P1 p1_;
    };

    template <typename F, typename P1>
        inline ScopeGuardImpl1<F, P1> MakeGuard(F fun, P1 p1)
    {
        return ScopeGuardImpl1<F, P1>::MakeGuard(fun, p1);
    }

    template <typename F, typename P1, typename P2>
        class ScopeGuardImpl2: public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl2<F, P1, P2> MakeGuard(F fun, P1 p1, P2 p2)
        {
            return ScopeGuardImpl2<F, P1, P2>(fun, p1, p2);
        }

        ~ScopeGuardImpl2() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_(p1_, p2_);
        }

    protected:
    ScopeGuardImpl2(F fun, P1 p1, P2 p2) : fun_(fun), p1_(p1), p2_(p2)
        {}

        F fun_;
        const P1 p1_;
        const P2 p2_;
    };

    template <typename F, typename P1, typename P2>
        inline ScopeGuardImpl2<F, P1, P2> MakeGuard(F fun, P1 p1, P2 p2)
    {
        return ScopeGuardImpl2<F, P1, P2>::MakeGuard(fun, p1, p2);
    }

    template <typename F, typename P1, typename P2, typename P3>
        class ScopeGuardImpl3 : public ScopeGuardImplBase
    {
    public:
        static ScopeGuardImpl3<F, P1, P2, P3> MakeGuard(F fun, P1 p1, P2 p2, P3 p3)
        {
            return ScopeGuardImpl3<F, P1, P2, P3>(fun, p1, p2, p3);
        }

        ~ScopeGuardImpl3() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            fun_(p1_, p2_, p3_);
        }

    protected:
    ScopeGuardImpl3(F fun, P1 p1, P2 p2, P3 p3) : fun_(fun), p1_(p1), p2_(p2), p3_(p3)
        {}

        F fun_;
        const P1 p1_;
        const P2 p2_;
        const P3 p3_;
    };

    template <typename F, typename P1, typename P2, typename P3>
        inline ScopeGuardImpl3<F, P1, P2, P3> MakeGuard(F fun, P1 p1, P2 p2, P3 p3)
    {
        return ScopeGuardImpl3<F, P1, P2, P3>::MakeGuard(fun, p1, p2, p3);
    }

    //************************************************************

    template <class Obj, typename MemFun>
        class ObjScopeGuardImpl0 : public ScopeGuardImplBase
    {
    public:
        static ObjScopeGuardImpl0<Obj, MemFun> MakeObjGuard(Obj& obj, MemFun memFun)
        {
            return ObjScopeGuardImpl0<Obj, MemFun>(obj, memFun);
        }

        ~ObjScopeGuardImpl0() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            (obj_.*memFun_)();
        }

    protected:
    ObjScopeGuardImpl0(Obj& obj, MemFun memFun) : obj_(obj), memFun_(memFun)
        {}

        Obj& obj_;
        MemFun memFun_;
    };

    template <class Obj, typename MemFun>
        inline ObjScopeGuardImpl0<Obj, MemFun> MakeObjGuard(Obj& obj, MemFun memFun)
    {
        return ObjScopeGuardImpl0<Obj, MemFun>::MakeObjGuard(obj, memFun);
    }

    template <typename Ret, class Obj1, class Obj2>
        inline ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()> MakeGuard(Ret(Obj2::*memFun)(), Obj1 &obj)
    {
        return ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()>::MakeObjGuard(obj,memFun);
    }

    template <typename Ret, class Obj1, class Obj2>
        inline ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()> MakeGuard(Ret(Obj2::*memFun)(), Obj1 *obj)
    {
        return ObjScopeGuardImpl0<Obj1,Ret(Obj2::*)()>::MakeObjGuard(*obj,memFun);
    }

    template <class Obj, typename MemFun, typename P1>
        class ObjScopeGuardImpl1 : public ScopeGuardImplBase
    {
    public:
        static ObjScopeGuardImpl1<Obj, MemFun, P1> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1)
        {
            return ObjScopeGuardImpl1<Obj, MemFun, P1>(obj, memFun, p1);
        }

        ~ObjScopeGuardImpl1() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            (obj_.*memFun_)(p1_);
        }

    protected:
    ObjScopeGuardImpl1(Obj& obj, MemFun memFun, P1 p1) : obj_(obj), memFun_(memFun), p1_(p1)
        {}

        Obj& obj_;
        MemFun memFun_;
        const P1 p1_;
    };

    template <class Obj, typename MemFun, typename P1>
        inline ObjScopeGuardImpl1<Obj, MemFun, P1> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1)
    {
        return ObjScopeGuardImpl1<Obj, MemFun, P1>::MakeObjGuard(obj, memFun, p1);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b>
        inline ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b> MakeGuard(Ret(Obj2::*memFun)(P1a), Obj1 &obj, P1b p1)
    {
        return ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b>::MakeObjGuard(obj,memFun,p1);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b>
        inline ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b> MakeGuard(Ret(Obj2::*memFun)(P1a), Obj1 *obj, P1b p1)
    {
        return ObjScopeGuardImpl1<Obj1,Ret(Obj2::*)(P1a),P1b>::MakeObjGuard(*obj,memFun,p1);
    }

    template <class Obj, typename MemFun, typename P1, typename P2>
        class ObjScopeGuardImpl2 : public ScopeGuardImplBase
    {
    public:
        static ObjScopeGuardImpl2<Obj, MemFun, P1, P2> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1, P2 p2)
        {
            return ObjScopeGuardImpl2<Obj, MemFun, P1, P2>(obj, memFun, p1, p2);
        }

        ~ObjScopeGuardImpl2() throw()
        {
            SafeExecute(*this);
        }

        void Execute()
        {
            (obj_.*memFun_)(p1_, p2_);
        }

    protected:
    ObjScopeGuardImpl2(Obj& obj, MemFun memFun, P1 p1, P2 p2) : obj_(obj), memFun_(memFun), p1_(p1), p2_(p2)
        {}

        Obj& obj_;
        MemFun memFun_;
        const P1 p1_;
        const P2 p2_;
    };

    template <class Obj, typename MemFun, typename P1, typename P2>
        inline ObjScopeGuardImpl2<Obj, MemFun, P1, P2> MakeObjGuard(Obj& obj, MemFun memFun, P1 p1, P2 p2)
    {
        return ObjScopeGuardImpl2<Obj, MemFun, P1, P2>::MakeObjGuard(obj, memFun, p1, p2);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b, typename P2a, typename P2b>
        inline ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b> MakeGuard(Ret(Obj2::*memFun)(P1a,P2a), Obj1 &obj, P1b p1, P2b p2)
    {
        return ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b>::MakeObjGuard(obj,memFun,p1,p2);
    }

    template <typename Ret, class Obj1, class Obj2, typename P1a, typename P1b, typename P2a, typename P2b>
        inline ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b> MakeGuard(Ret(Obj2::*memFun)(P1a,P2a), Obj1 *obj, P1b p1, P2b p2)
    {
        return ObjScopeGuardImpl2<Obj1,Ret(Obj2::*)(P1a,P2a),P1b,P2b>::MakeObjGuard(*obj,memFun,p1,p2);
    }

} // namespace Loki

#define LOKI_CONCATENATE_DIRECT(s1, s2)  s1##s2
#define LOKI_CONCATENATE(s1, s2)         LOKI_CONCATENATE_DIRECT(s1, s2)
#define LOKI_ANONYMOUS_VARIABLE(str)     LOKI_CONCATENATE(str, __LINE__)

#define ON_BLOCK_EXIT                                                   \
    MONGO_COMPILER_VARIABLE_UNUSED ScopeGuard LOKI_ANONYMOUS_VARIABLE(scopeGuard) = MakeGuard
#define ON_BLOCK_EXIT_OBJ \
    MONGO_COMPILER_VARIABLE_UNUSED ScopeGuard LOKI_ANONYMOUS_VARIABLE(scopeGuard) = MakeObjGuard

#endif //LOKI_SCOPEGUARD_H_


#define _GNU_SOURCE
#include <netdb.h>

struct servent *getservbyname(const char *name, const char *prots)
{
	static struct servent se;
	static char *buf[2];
	struct servent *res;
	if (getservbyname_r(name, prots, &se, (void *)buf, sizeof buf, &res))
		return 0;
	return &se;
}


//
//  ZYWBaseChartView.m
//  ZYWChart
//
//  Created by 张有为 on 2016/12/17.
//  Copyright © 2016年 zyw113. All rights reserved.
//

#import "ZYWBaseChartView.h"

@implementation ZYWBaseChartView

@synthesize maxY =  _maxY;
@synthesize minY =  _minY;
@synthesize maxX =  _maxX;
@synthesize minX = _minX;
@synthesize scaleY = _scaleY;
@synthesize scaleX = _scaleX;
@synthesize lineWidth = _lineWidth;
@synthesize lineSpace = _lineSpace;
@synthesize leftMargin = _leftMargin;
@synthesize rightMargin = _rightMargin;
@synthesize topMargin = _topMargin;
@synthesize bottomMargin = _bottomMargin;
@synthesize lineColor = _lineColor;

@end


package cn.nukkit.block;

import cn.nukkit.Player;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemCake;
import cn.nukkit.item.food.Food;
import cn.nukkit.level.Level;
import cn.nukkit.math.BlockFace;
import cn.nukkit.utils.BlockColor;

/**
 * @author Nukkit Project Team
 */
public class BlockCake extends BlockTransparentMeta {

    public BlockCake(int meta) {
        super(meta);
    }

    public BlockCake() {
        this(0);
    }

    @Override
    public String getName() {
        return "Cake Block";
    }

    @Override
    public int getId() {
        return CAKE_BLOCK;
    }

    @Override
    public boolean canBeActivated() {
        return true;
    }

    @Override
    public double getHardness() {
        return 0.5;
    }

    @Override
    public double getResistance() {
        return 2.5;
    }

    @Override
    public double getMinX() {
        return this.x + (1 + getDamage() * 2) / 16;
    }

    @Override
    public double getMinY() {
        return this.y;
    }

    @Override
    public double getMinZ() {
        return this.z + 0.0625;
    }

    @Override
    public double getMaxX() {
        return this.x - 0.0625 + 1;
    }

    @Override
    public double getMaxY() {
        return this.y + 0.5;
    }

    @Override
    public double getMaxZ() {
        return this.z - 0.0625 + 1;
    }

    @Override
    public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) {
        if (down().getId() != Block.AIR) {
            getLevel().setBlock(block, this, true, true);

            return true;
        }
        return false;
    }

    @Override
    public int onUpdate(int type) {
        if (type == Level.BLOCK_UPDATE_NORMAL) {
            if (down().getId() == Block.AIR) {
                getLevel().setBlock(this, Block.get(BlockID.AIR), true);

                return Level.BLOCK_UPDATE_NORMAL;
            }
        }

        return 0;
    }

    @Override
    public Item[] getDrops(Item item) {
        return new Item[0];
    }

    @Override
    public Item toItem() {
        return new ItemCake();
    }

    @Override
    public boolean onActivate(Item item, Player player) {
        if (player != null && player.getFoodData().getLevel() < player.getFoodData().getMaxLevel()) {
            if (getDamage() <= 0x06) setDamage(getDamage() + 1);
            if (getDamage() >= 0x06) {
                getLevel().setBlock(this, Block.get(BlockID.AIR), true);
            } else {
                Food.getByRelative(this).eatenBy(player);
                getLevel().setBlock(this, this, true);
            }
            return true;
        }
        return false;
    }

    @Override
    public BlockColor getColor() {
        return BlockColor.AIR_BLOCK_COLOR;
    }

    public int getComparatorInputOverride() {
        return (7 - this.getDamage()) * 2;
    }

    public boolean hasComparatorInputOverride() {
        return true;
    }
}


 SOA @ x 1 1 1 1 1
 NS @
 A 0.0.0.90


using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;

using com.spacepuppy;
using com.spacepuppy.Geom;
using com.spacepuppy.Utils;

namespace com.spacepuppyeditor.Base.Geom
{

    [CustomPropertyDrawer(typeof(Interval))]
    public class IntervalInspector : PropertyDrawer
    {
        private const string PROP_MIN = "_min";
        private const string PROP_MAX = "_max";

        private GUIContent[] _defaultLabels = new GUIContent[] { new GUIContent("Min"), new GUIContent("Max") };
        private GUIContent[] _reverseLabels = new GUIContent[] { new GUIContent("Max"), new GUIContent("Min") };
        private float[] _values = new float[2];

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            return base.GetPropertyHeight(property, label);
        }

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var prop_min = property.FindPropertyRelative(PROP_MIN);
            var prop_max = property.FindPropertyRelative(PROP_MAX);

            var attrib = this.fieldInfo.GetCustomAttributes(typeof(Interval.ConfigAttribute), false).Cast<Interval.ConfigAttribute>().FirstOrDefault();
            bool reverse = (attrib != null) ? attrib.Reverse : false;
            float minValue = (attrib != null) ? attrib.MinValue : float.NegativeInfinity;
            float maxValue = (attrib != null) ? attrib.MaxValue : float.PositiveInfinity;
            bool discreteValuesOnly = (attrib != null) ? attrib.DiscreteValuesOnly : false;

            GUIContent[] subLabels;
            float labelWidth;

            if (reverse)
            {
                subLabels = (attrib != null) ? new GUIContent[] { EditorHelper.TempContent(attrib.MaxLabel), EditorHelper.TempContent(attrib.MinLabel) } : _defaultLabels;
                labelWidth = (attrib != null) ? attrib.LabelWidth : 30f;
                _values[1] = prop_min.floatValue;
                _values[0] = prop_max.floatValue;
            }
            else
            {
                subLabels = (attrib != null) ? new GUIContent[] { EditorHelper.TempContent(attrib.MinLabel), EditorHelper.TempContent(attrib.MaxLabel) } : _defaultLabels;
                labelWidth = (attrib != null) ? attrib.LabelWidth : 30f;
                _values[0] = prop_min.floatValue;
                _values[1] = prop_max.floatValue;
            }

            EditorGUI.BeginProperty(position, label, property);
            EditorGUI.BeginChangeCheck();
            SPEditorGUI.DelayedMultiFloatField(position, label, subLabels, _values, labelWidth);
            if (EditorGUI.EndChangeCheck())
            {
                _values[0] = Mathf.Clamp(_values[0], minValue, maxValue);
                _values[1] = Mathf.Clamp(_values[1], minValue, maxValue);
                if (discreteValuesOnly) _values[0] = Mathf.Round(_values[0]);
                if (discreteValuesOnly) _values[1] = Mathf.Round(_values[1]);

                float min = reverse ? _values[1] : _values[0];
                float max = reverse ? _values[0] : _values[1];

                if (!MathUtil.FuzzyEqual(min, prop_min.floatValue))
                {
                    //changed min
                    if (max < min) max = min;
                }
                else
                {
                    //changed max
                    if (min > max) min = max;
                }

                prop_min.floatValue = min;
                prop_max.floatValue = max;
            }
            EditorGUI.EndProperty();
        }

    }

}


// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs_linux.go

package ipv6

const (
	sysIPV6_ADDRFORM       = 0x1
	sysIPV6_2292PKTINFO    = 0x2
	sysIPV6_2292HOPOPTS    = 0x3
	sysIPV6_2292DSTOPTS    = 0x4
	sysIPV6_2292RTHDR      = 0x5
	sysIPV6_2292PKTOPTIONS = 0x6
	sysIPV6_CHECKSUM       = 0x7
	sysIPV6_2292HOPLIMIT   = 0x8
	sysIPV6_NEXTHOP        = 0x9
	sysIPV6_FLOWINFO       = 0xb

	sysIPV6_UNICAST_HOPS        = 0x10
	sysIPV6_MULTICAST_IF        = 0x11
	sysIPV6_MULTICAST_HOPS      = 0x12
	sysIPV6_MULTICAST_LOOP      = 0x13
	sysIPV6_ADD_MEMBERSHIP      = 0x14
	sysIPV6_DROP_MEMBERSHIP     = 0x15
	sysMCAST_JOIN_GROUP         = 0x2a
	sysMCAST_LEAVE_GROUP        = 0x2d
	sysMCAST_JOIN_SOURCE_GROUP  = 0x2e
	sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
	sysMCAST_BLOCK_SOURCE       = 0x2b
	sysMCAST_UNBLOCK_SOURCE     = 0x2c
	sysMCAST_MSFILTER           = 0x30
	sysIPV6_ROUTER_ALERT        = 0x16
	sysIPV6_MTU_DISCOVER        = 0x17
	sysIPV6_MTU                 = 0x18
	sysIPV6_RECVERR             = 0x19
	sysIPV6_V6ONLY              = 0x1a
	sysIPV6_JOIN_ANYCAST        = 0x1b
	sysIPV6_LEAVE_ANYCAST       = 0x1c

	sysIPV6_FLOWLABEL_MGR = 0x20
	sysIPV6_FLOWINFO_SEND = 0x21

	sysIPV6_IPSEC_POLICY = 0x22
	sysIPV6_XFRM_POLICY  = 0x23

	sysIPV6_RECVPKTINFO  = 0x31
	sysIPV6_PKTINFO      = 0x32
	sysIPV6_RECVHOPLIMIT = 0x33
	sysIPV6_HOPLIMIT     = 0x34
	sysIPV6_RECVHOPOPTS  = 0x35
	sysIPV6_HOPOPTS      = 0x36
	sysIPV6_RTHDRDSTOPTS = 0x37
	sysIPV6_RECVRTHDR    = 0x38
	sysIPV6_RTHDR        = 0x39
	sysIPV6_RECVDSTOPTS  = 0x3a
	sysIPV6_DSTOPTS      = 0x3b
	sysIPV6_RECVPATHMTU  = 0x3c
	sysIPV6_PATHMTU      = 0x3d
	sysIPV6_DONTFRAG     = 0x3e

	sysIPV6_RECVTCLASS = 0x42
	sysIPV6_TCLASS     = 0x43

	sysIPV6_ADDR_PREFERENCES = 0x48

	sysIPV6_PREFER_SRC_TMP            = 0x1
	sysIPV6_PREFER_SRC_PUBLIC         = 0x2
	sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100
	sysIPV6_PREFER_SRC_COA            = 0x4
	sysIPV6_PREFER_SRC_HOME           = 0x400
	sysIPV6_PREFER_SRC_CGA            = 0x8
	sysIPV6_PREFER_SRC_NONCGA         = 0x800

	sysIPV6_MINHOPCOUNT = 0x49

	sysIPV6_ORIGDSTADDR     = 0x4a
	sysIPV6_RECVORIGDSTADDR = 0x4a
	sysIPV6_TRANSPARENT     = 0x4b
	sysIPV6_UNICAST_IF      = 0x4c

	sysICMPV6_FILTER = 0x1

	sysICMPV6_FILTER_BLOCK       = 0x1
	sysICMPV6_FILTER_PASS        = 0x2
	sysICMPV6_FILTER_BLOCKOTHERS = 0x3
	sysICMPV6_FILTER_PASSONLY    = 0x4

	sizeofKernelSockaddrStorage = 0x80
	sizeofSockaddrInet6         = 0x1c
	sizeofInet6Pktinfo          = 0x14
	sizeofIPv6Mtuinfo           = 0x20
	sizeofIPv6FlowlabelReq      = 0x20

	sizeofIPv6Mreq       = 0x14
	sizeofGroupReq       = 0x88
	sizeofGroupSourceReq = 0x108

	sizeofICMPv6Filter = 0x20
)

type kernelSockaddrStorage struct {
	Family  uint16
	X__data [126]int8
}

type sockaddrInet6 struct {
	Family   uint16
	Port     uint16
	Flowinfo uint32
	Addr     [16]byte /* in6_addr */
	Scope_id uint32
}

type inet6Pktinfo struct {
	Addr    [16]byte /* in6_addr */
	Ifindex int32
}

type ipv6Mtuinfo struct {
	Addr sockaddrInet6
	Mtu  uint32
}

type ipv6FlowlabelReq struct {
	Dst        [16]byte /* in6_addr */
	Label      uint32
	Action     uint8
	Share      uint8
	Flags      uint16
	Expires    uint16
	Linger     uint16
	X__flr_pad uint32
}

type ipv6Mreq struct {
	Multiaddr [16]byte /* in6_addr */
	Ifindex   int32
}

type groupReq struct {
	Interface uint32
	Pad_cgo_0 [4]byte
	Group     kernelSockaddrStorage
}

type groupSourceReq struct {
	Interface uint32
	Pad_cgo_0 [4]byte
	Group     kernelSockaddrStorage
	Source    kernelSockaddrStorage
}

type icmpv6Filter struct {
	Data [8]uint32
}


! KGEN-generated Fortran source file
!
! Filename    : mo_rrtm_params.f90
! Generated at: 2015-02-19 15:30:37
! KGEN version: 0.4.4

    MODULE mo_rrtm_params
        USE mo_kind, ONLY: wp
        IMPLICIT NONE
        PUBLIC
        !! -----------------------------------------------------------------------------------------
        !!
        !!  Shared parameters
        !!
        !< number of original g-intervals per spectral band
        INTEGER, parameter :: maxxsec= 4 !< maximum number of cross-section molecules (cfcs)
        INTEGER, parameter :: maxinpx= 38
        !< number of last band (lw and sw share band 16)
        !< number of spectral bands in sw model
        !< total number of gpts
        !< first band in sw
        !< last band in sw
        INTEGER, parameter :: nbndlw = 16 !< number of spectral bands in lw model
        INTEGER, parameter :: ngptlw = 140 !< total number of reduced g-intervals for rrtmg_lw
        !
        ! These pressures are chosen such that the ln of the first pressure
        ! has only a few non-zero digits (i.e. ln(PREF(1)) = 6.96000) and
        ! each subsequent ln(pressure) differs from the previous one by 0.2.
        !
        REAL(KIND=wp), parameter :: preflog(59) = (/        6.9600e+00_wp, 6.7600e+00_wp, 6.5600e+00_wp, 6.3600e+00_wp, &
        6.1600e+00_wp,        5.9600e+00_wp, 5.7600e+00_wp, 5.5600e+00_wp, 5.3600e+00_wp, 5.1600e+00_wp,        4.9600e+00_wp, &
        4.7600e+00_wp, 4.5600e+00_wp, 4.3600e+00_wp, 4.1600e+00_wp,        3.9600e+00_wp, 3.7600e+00_wp, 3.5600e+00_wp, &
        3.3600e+00_wp, 3.1600e+00_wp,        2.9600e+00_wp, 2.7600e+00_wp, 2.5600e+00_wp, 2.3600e+00_wp, 2.1600e+00_wp,        &
        1.9600e+00_wp, 1.7600e+00_wp, 1.5600e+00_wp, 1.3600e+00_wp, 1.1600e+00_wp,        9.6000e-01_wp, 7.6000e-01_wp, &
        5.6000e-01_wp, 3.6000e-01_wp, 1.6000e-01_wp,        -4.0000e-02_wp,-2.4000e-01_wp,-4.4000e-01_wp,-6.4000e-01_wp,&
        -8.4000e-01_wp,        -1.0400e+00_wp,-1.2400e+00_wp,-1.4400e+00_wp,-1.6400e+00_wp,-1.8400e+00_wp,        -2.0400e+00_wp,&
        -2.2400e+00_wp,-2.4400e+00_wp,-2.6400e+00_wp,-2.8400e+00_wp,        -3.0400e+00_wp,-3.2400e+00_wp,-3.4400e+00_wp,&
        -3.6400e+00_wp,-3.8400e+00_wp,        -4.0400e+00_wp,-4.2400e+00_wp,-4.4400e+00_wp,-4.6400e+00_wp /)
        !
        ! These are the temperatures associated with the respective pressures
        !
        REAL(KIND=wp), parameter :: tref(59) = (/        2.9420e+02_wp, 2.8799e+02_wp, 2.7894e+02_wp, 2.6925e+02_wp, &
        2.5983e+02_wp,        2.5017e+02_wp, 2.4077e+02_wp, 2.3179e+02_wp, 2.2306e+02_wp, 2.1578e+02_wp,        2.1570e+02_wp, &
        2.1570e+02_wp, 2.1570e+02_wp, 2.1706e+02_wp, 2.1858e+02_wp,        2.2018e+02_wp, 2.2174e+02_wp, 2.2328e+02_wp, &
        2.2479e+02_wp, 2.2655e+02_wp,        2.2834e+02_wp, 2.3113e+02_wp, 2.3401e+02_wp, 2.3703e+02_wp, 2.4022e+02_wp,        &
        2.4371e+02_wp, 2.4726e+02_wp, 2.5085e+02_wp, 2.5457e+02_wp, 2.5832e+02_wp,        2.6216e+02_wp, 2.6606e+02_wp, &
        2.6999e+02_wp, 2.7340e+02_wp, 2.7536e+02_wp,        2.7568e+02_wp, 2.7372e+02_wp, 2.7163e+02_wp, 2.6955e+02_wp, &
        2.6593e+02_wp,        2.6211e+02_wp, 2.5828e+02_wp, 2.5360e+02_wp, 2.4854e+02_wp, 2.4348e+02_wp,        2.3809e+02_wp, &
        2.3206e+02_wp, 2.2603e+02_wp, 2.2000e+02_wp, 2.1435e+02_wp,        2.0887e+02_wp, 2.0340e+02_wp, 1.9792e+02_wp, &
        1.9290e+02_wp, 1.8809e+02_wp,        1.8329e+02_wp, 1.7849e+02_wp, 1.7394e+02_wp, 1.7212e+02_wp /)

    ! read subroutines
    END MODULE mo_rrtm_params


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:background="#000"
    tools:layout_height="150dp">

    <FrameLayout
        android:id="@+id/lay_title_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_height="70dp">

        <View
            android:id="@+id/title_bg_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/shape_rect_coner_top_bg" />

        <FrameLayout
            android:id="@+id/lay_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="horizontal" />

    </FrameLayout>

    <TextView
        android:id="@+id/text_delete"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_gravity="top"
        android:background="@drawable/select_delete_bg"
        android:drawableTop="@drawable/select_delete_drop"
        android:gravity="center"
        android:paddingTop="12dp"
        android:paddingBottom="12dp"
        android:text="@string/weixin_v2_delete_out"
        android:textColor="#fff"
        android:textSize="12sp"
        tools:translationY="70dp" />

    <!--        android:layout_marginTop="70dp"-->
</FrameLayout>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace BImageViewer
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main( string[] _args )
		{

//_args = new string[] { @"..\..\..\Arkane\BImages\stainedglass2_area.bimage7" };
//_args = new string[] { @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_1127_cube_BC6H_UF16.bimage" };
//_args = new string[] { @"D:\Workspaces\Arkane\Dishonored2\Dishonored2\base\editors\arkane\preview\cubemaps\exterior.bimage" };

TestResourcesIndex();

			if ( _args.Length != 1 ) {
				MessageBox.Show( "Missing filename argument! Can't open unspecified file...", "BImage Viewer" );
				return;
			}

			System.IO.FileInfo	imageFileName = new System.IO.FileInfo( _args[0] );
			if ( !imageFileName.Exists ) {
				MessageBox.Show( "Specified image name \"" + _args[1] + "\" not found on disk!", "BImage Viewer" );
				return;
			}

			ArkaneService.BImage	Image = null;
			try {
				using ( System.IO.FileStream S = imageFileName.OpenRead() )
					using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {
						Image = new ArkaneService.BImage( R, imageFileName, true );
					}
			} catch ( Exception _e ) {
				MessageBox.Show( "An error occurred while loading bimage \"" + imageFileName.FullName + "\":\r\n\r\n" + _e.Message, "BImage Viewer" );
				return;
			}

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault( false );
			Application.Run( new ViewerForm( Image ) );
		}

		static void		TestResourcesIndex() {
			ArkaneService.ResourcesIndex	masterIndex = new ArkaneService.ResourcesIndex( new System.IO.FileInfo( @"D:\Workspaces\Arkane\Dishonored2\dishonored2_GMC2_782384_1.70.0.24\dishonored2_GMC2_782384_MULTI_2016_09_29_01_47_PC\base\master.index" ) );
		}
	}
}


#!/bin/sh
cd `dirname $0`
exec erl -pa $PWD/ebin $PWD/deps/*/ebin -boot start_sasl -s skel