text:
from argparse import ArgumentParser
from numpy import mean
from scipy.stats import sem
from collections import defaultdict
from ChannelAnalysis.RotamerAnalysis.Preprocessor import *

# This function is useful for counting the ratio of rotameric states
# for each of the input trajectory files with respect to the last state.
# So you might get a traj_id 10 that has a state ratio of 8:1 which means
# that there was 8 times as much in state 1.
def rotamer_counter_per_res(data_lines, data_states, traj_col=11, prefix=None):

    # This is an epic datatype that I will use to quickly build a
    # dict of dicts where the 1st key is a trajectory number
    # and the second key is the ion count and the value is a
    # count of how many times that ion count was observed.
    count_totals = defaultdict(lambda: defaultdict(int))

    # This is the return list in the format:
    # traj_id d/u_ratio uncertainty
    for line, states in zip(data_lines, data_states):
        traj_id = line[traj_col]
        for state in states:
            count_totals[traj_id][state] += 1

    # D/U ratios for all trajectories
    rotamer_ratios = []
    for traj_id, count_dict in count_totals.iteritems():
        # We want the highest dunking state (1 in most cases) and to extract
        # the count for that state as the temp_max variable
        temp_max = float(sorted(count_dict.iteritems())[-1][-1])

        temp_row = [traj_id]
        for state, state_count in sorted(count_dict.iteritems()):
            temp_row.append(state_count/temp_max)
        rotamer_ratios.append(temp_row)

    # Hack to tranpose list of lists and iterate over rotamer states
    flipped_rows = zip(*rotamer_ratios)
    temp_mean = ["MEAN"]
    temp_sem = ["STDERR"]
    # The first flipped_row entry is a list of traj_id's so we skip it
    for rotamer_state in flipped_rows[1:]:
        temp_mean.append(mean(rotamer_state))
        temp_sem.append(sem(rotamer_state))
    rotamer_ratios.append(temp_mean)
    rotamer_ratios.append(temp_sem)

    return rotamer_ratios

# This function counts the number of dunking states at each step for each
# of the dihedral columns classified using the label_states function
# and separates them on a basis of trajectory id. This allows for a
# statistical measure of the distribution of dunking states much like
# the channel and selectivity filter occupancy functions.
def rotamer_counter(data_lines, data_states, traj_col=11, prefix=None):

    # This is an epic datatype that I will use to quickly build a
    # dict of dicts where the 1st key is a trajectory number
    # and the second key is the ion count and the value is a
    # count of how many times that ion count was observed.
    count_totals = defaultdict(lambda: defaultdict(int))

    for line, states in zip(data_lines, data_states):
        traj_id = line[traj_col]
        state_total = sum(states)
        count_totals[traj_id][state_total] += 1

    print count_totals
    return count_totals_to_percents(count_totals)

# This is a helper function that takes the datatype generated in
# *_counter functions (trajnum dict -> occupancy_id -> integer counts)
# and converts this to populations in a list. Num ions map is
# useful the occupancy_id's represent distinct numbers of ions
# in the selectivity filter.
def count_totals_to_percents(count_totals):

    # Here's the return datatype that stores the percentage of occupancy
    # in a given channel/sf state which can be paired with the indices
    ion_count_percents = defaultdict(list)
    ion_count_indices = defaultdict(list)
    for traj_id, count_dict in count_totals.iteritems():
        traj_total_lines = float(sum(count_dict.values()))
        for ion_state, ion_count in count_dict.iteritems():
            ion_count_percents[traj_id].append(ion_count/traj_total_lines)
            ion_count_indices[traj_id].append(ion_state)

    # Append a little statistics, sorry if this is confusing...
    all_weighted_avgs=[]
    weighted_avgs_by_occid=defaultdict(list)
    for traj_id, percents in ion_count_percents.iteritems():
        temp_weighted_avg = 0
        for occ_id, percent in enumerate(percents):
            x = ion_count_indices[traj_id][occ_id]*percent
            temp_weighted_avg += x
            weighted_avgs_by_occid[occ_id].append(x)
        all_weighted_avgs.append(temp_weighted_avg)

    for occ_id, weight_avg in weighted_avgs_by_occid.iteritems():
        ion_count_percents['MEAN'].append(mean(weight_avg))
        ion_count_indices['MEAN'].append(occ_id)
        ion_count_percents['STDERR'].append(sem(weight_avg))
        ion_count_indices['STDERR'].append(occ_id)

    ion_count_percents['MEAN'].append(mean(all_weighted_avgs))
    ion_count_indices['MEAN'].append('ALL')
    ion_count_percents['STDERR'].append(sem(all_weighted_avgs))
    ion_count_indices['STDERR'].append('ALL')

    return (dict(ion_count_percents), dict(ion_count_indices))

# This writes the total of all rotamer states as a function of time
# for use of time series plotting purposes.
def compute_rotamer_vs_time(data_lines, data_states, traj_col, prefix=None):

    # This a dictionary of file streams that will be used for output
    # when prefix is assigned.
    count_files = {}

    # These are dictionaries of dictionaries where the key is a trajectory
    # number and the list is the computed occupancy count, or frame number
    rotstate_per_traj = defaultdict(list)
    time_per_traj = defaultdict(list)

    # This is an epic datatype that I will use to quickly build a
    # dict of dicts where the 1st key is a trajectory number
    # and the second key is the ion count and the value is a
    # count of how many times that ion count was observed.
    count_totals=defaultdict(lambda: defaultdict(int))

    for line, states in zip(data_lines, data_states):
        traj_id = line[traj_col]
        state_total = sum(states)
        count_totals[traj_id][state_total] += 1

        if prefix != None:
            if traj_id not in count_files:
                count_files[traj_id] = \
                             open(prefix+"_total_n"+str(traj_id),"w")
            count_files[traj_id].write(str(line[0])+" "+
                                           str(traj_id)+" "+
                                           str(state_total)+
                                           "\n")

        rotstate_per_traj[traj_id].append(state_total)
        time_per_traj[traj_id].append(float(line[0]))

    # Close filestreams.
    if prefix != None:
        for key in count_files.keys():
            count_files[key].close()

    return (dict(rotstate_per_traj), dict(time_per_traj))

# Returns the population percentages across the entire dataset from the
# label_states array.
def label_statistics(data_states):
    cols_per_line = len(data_states[0])
    counts_per_state = defaultdict(float)
    for line in data_states:
        for state in line:
            counts_per_state[state] += 1.0

    for state in counts_per_state.keys():
        counts_per_state[state] /= len(data_states)*cols_per_line

    return dict(counts_per_state)

if __name__ == '__main__':
    parser = ArgumentParser(
    description='Produces rotamer state timeseries datafiles')

    parser.add_argument(
    '-f', dest='filenames', type=str, nargs="+", required=True,
    help='a filename of coordination data from MDAnalysis trajectory data')
    parser.add_argument(
    '-x1', dest='chi1_cols', type=int, nargs="+", required=True,
    help='column numbers in the input that denote chi1 values')
    parser.add_argument(
    '-x2', dest='chi2_cols', type=int, nargs="+", required=True,
    help='column numbers in the input that denote chi2 values')
    parser.add_argument(
    '-remove', dest='remove_frames', type=int, default=0,
    help='this is a number of frames to remove from the start of the data')
    parser.add_argument(
    '-div', dest='dividers', type=float, nargs="+", default=[180],
    help='slices in angle space that label dunking states (<180 = 0, >180 = 1')
    parser.add_argument(
    '-t', dest='traj_col', type=int, default=11,
    help='a zero inclusive column number that contains the run number')
    parser.add_argument(
    '-o', dest='outfile', type=str, default=None,
    help='the file to output the sorted padding output of all input files')
    args = parser.parse_args()

    data_f_dunk = process_rotamers(filenames=args.filenames,
                                  chi1_cols=args.chi1_cols,
                                  chi2_cols=args.chi2_cols,
                                  remove_frames=args.remove_frames,
                                  traj_col=args.traj_col)

    # Same thing but now we pass the SF column list.
    print "Dunking states using the dividers", args.dividers
    data_f_states = label_states(data_f_dunk, args.chi2_cols, args.dividers)

    print "Computing dunking populations"
    print rotamer_counter(data_f_dunk, data_f_states, traj_col=args.traj_col)

    print compute_rotamer_vs_time(data_f_dunk, data_f_states, traj_col=args.traj_col,
                          prefix="rotamer")

    print "Computing dunking counts per residue"
    print rotamer_counter_per_res(data_f_dunk, data_f_states,
                                  traj_col=args.traj_col)


text:
#ifndef UKOCT_CPU_OPERATORS_INTERSECTION_HPP_
#define UKOCT_CPU_OPERATORS_INTERSECTION_HPP_

#include "ukoct/cpu/operators/abstract.hpp"

#define ukoct_OPERCODE ukoct::OPER_INTERSECTION

namespace ukoct {
namespace impl {
namespace cpu {
namespace octdiff {

template <typename T> class IntersectionCpuOperator;

template <typename T> struct OperationImpl<T, ukoct_OPERCODE> {
	static constexpr bool valid = true;
	typedef IntersectionCpuOperator<T> Impl;
	typedef T Type;
	static constexpr ukoct::EOperation operation = ukoct_OPERCODE;
	static constexpr ukoct::OperationDetails details() { return O_EXEC_LOOP | O_DIMS_EXACT | O_IMPL_MUTATOR; }
};

template <typename T> class IntersectionCpuOperator : public AbstractCpuOperator<T> {
public:
	ukoct::EOperation operation() const { return OperationImpl<T, ukoct_OPERCODE>::operation; }
	ukoct::OperationDetails details() const { return OperationImpl<T, ukoct_OPERCODE>::details(); }

	void run(const OperatorArgs<T>& args, CpuResult<T>& ret) const {
		CpuTiming timing;
		AbstractCpuOperator<T>::start(timing);

		ukoct_ASSERT(args.other() != NULL, "Secondary matrix must be provided for this operator.");
		ukoct_ASSERT(args.state().implementation() != args.other()->implementation(), "Both matrices need to be from the same implementation.");
		ukoct::CpuState<T>& state = reinterpret_cast<CpuState<T>&>(args.state());
		ukoct::CpuState<T>& other = *reinterpret_cast<CpuState<T>*>(args.other());
		plas::DenseMatrix<T>& mat = state.input();
		plas::DenseMatrix<T>& oth = other.input();
		ret.boolResult = true;

		if (&state != &other) {
			if (state.diffSize() != other.diffSize())
				//ret.boolResult = false;
				throw Error("Problem sizes cannot be different.");

			for (plas::var_t i = 1; i <= state.diffSize() && ret.boolResult; ++i)
				for (plas::var_t j = 1; j <= state.diffSize() && ret.boolResult; ++j)
					mat(i, j) = std::min(mat(i, j), oth(i, j));
		}

		AbstractCpuOperator<T>::end(timing);
	}
};

}
}
}
}

#undef ukoct_OPERCODE

#endif /* UKOCT_OPENCL_COMMON_OPERATORS_INTERSECTION_HPP_ */

redpajama_set_name: RedPajamaGithub


text:
module Mpango
  module Gateways
    class Test < Base
      def transactions(options = {})
        options
      end

      def charge(*args)
        args
      end

      def cancel(*args)
        args
      end
    end
  end
end


text:
\documentclass[12pt,a4paper]{article}
\usepackage{graphicx}
\usepackage[margin=0.5in]{geometry}
\begin{document}
\thispagestyle{empty}
\begin{table}[]
\centering
\Huge
\begin{tabular}{cccc}
 Toothbrush& Jellyfish& Bus& Chair\\  & & & \\
 Butterfly& Pumpkin& Book& Iphone\\  & & & \\
 Lighter& Watch& Cupcake& Wheelchair\\  & & & \\
 Motorcycle& Calculator& Spider& Pineapple\\  & & & \\
 Cow& Toilet& Lamp& Hourglass\\  & & & \\
\end{tabular}
\end{table}
\end{document}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPatterns.CreationalPatterns.FactoryMethod
{
    /// <summary>
    /// allow for the creation of objects without specifying the type of object
    /// that is to be created in code. A factory class contains a method that allows determination
    /// of the created type at run-time.
    /// </summary>
    public interface IVehicleFactory
    {
        Vehicle CreateVehicle();
    }

    public class FordExplorerFactory : IVehicleFactory
    {
        public Vehicle CreateVehicle()
        {
            return new FordExplorer();
        }
    }

    public class LincolnAviatorFactory : IVehicleFactory
    {
        public Vehicle CreateVehicle()
        {
            return new LincolnAviator("Lincoln Aviator");
        }
    }

    public abstract class Vehicle
    {
        public string Model { get; set; }

        public abstract void ShowInfo();
    }

    public class FordExplorer : Vehicle
    {
        public FordExplorer()
        {
            base.Model = "Ford Explorer";
        }

        public override void ShowInfo()
        {
            Console.WriteLine("Model:{0}", this.Model);
        }
    }

    public class LincolnAviator : Vehicle
    {
        public LincolnAviator(string model)
        {
            base.Model = model;
        }

        public override void ShowInfo()
        {
            Console.WriteLine("Model:{0}", this.Model);
        }
    }
}


text:
@interface EXViewController ()

@property (nonatomic, strong) UTStateViewManager * stateViewManager;

@end

@implementation EXViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    UTBlockStateViewConfigurator * stateViewActualizer = [UTBlockStateViewConfigurator new];
    _stateViewManager = [[UTStateViewManager alloc] initWithContainerView:self.view
                                                              viewFactory:[EXStateViewFactory new]
                                                             viewSwitcher:[UTFadeInOutNonConcurrentViewSwitcher new]
                                                    stateViewConfigurator:stateViewActualizer];

    __weak EXViewController * weakSelf = self;
    [stateViewActualizer addSetupActionForViewOfProtocol:@protocol(EXReloadableStateView)
                                          withSetupBlock:^(id<EXReloadableStateView> view) {
                                              [view setReloadBlock:^{
                                                  [weakSelf reload];
                                              }];
                                          }];

    UIBarButtonItem * baseBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Base"
                                                                           style:UIBarButtonItemStylePlain
                                                                          target:self
                                                                          action:@selector(switchToBaseState)];
    UIBarButtonItem * loadingBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Loading"
                                                                           style:UIBarButtonItemStylePlain
                                                                          target:self
                                                                          action:@selector(switchToLoadingState)];

    UIBarButtonItem * errorBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Error"
                                                                              style:UIBarButtonItemStylePlain
                                                                             target:self
                                                                             action:@selector(switchToErrorState)];

    UIBarButtonItem * noDataBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"NoData"
                                                                            style:UIBarButtonItemStylePlain
                                                                           target:self
                                                                           action:@selector(switchToNoDataState)];

    self.navigationItem.leftBarButtonItems = @[ baseBarButtonItem, loadingBarButtonItem];
    self.navigationItem.rightBarButtonItems = @[errorBarButtonItem, noDataBarButtonItem];

}

- (void)reload {
    [_stateViewManager switchToState:UTStateViewStateLoading animated:YES];
}

- (void)switchToNoDataState {
    [_stateViewManager switchToState:UTStateViewStateNoData animated:YES];
}

- (void)switchToErrorState {
    [_stateViewManager switchToState:UTStateViewStateError withError:
     [NSError errorWithDomain:@"com.example" code:-1 userInfo:@{
      NSLocalizedDescriptionKey : @"Error example"
     }] animated:YES];
}

- (void)switchToLoadingState {
    [_stateViewManager switchToState:UTStateViewStateLoading animated:YES];
}

- (void)switchToBaseState {
    [_stateViewManager switchToState:UTStateViewStateBase animated:YES];
}

@end


text:
@interface AFHTTPRequestOperationManager (multipart)

- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
                       parameters:(NSDictionary *)parameters
        constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                          failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
                     parameters:(NSDictionary *)parameters
      constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

@end


text:
using Newtonsoft.Json.Linq;
using System.Linq;

namespace EDDiscovery.EliteDangerous.JournalEvents
{
    //When Written: when fetching a previously stored module
    //Parameters:
    //•	Slot
    //•	Ship
    //•	ShipID
    //•	RetrievedItem
    //•	EngineerModifications: name of modification blueprint, if any
    //•	SwapOutItem (if slot was not empty)
    //•	Cost
    public class JournalModuleRetrieve : JournalEntry
    {
        public JournalModuleRetrieve(JObject evt) : base(evt, JournalTypeEnum.ModuleRetrieve)
        {
            Slot = JSONHelper.GetStringDef(evt["Slot"]);
            Ship = JSONHelper.GetStringDef(evt["Ship"]);
            ShipId = JSONHelper.GetInt(evt["ShipID"]);
            RetrievedItem = JSONHelper.GetStringDef(evt["RetrievedItem"]);
            RetrievedItemLocalised = JSONHelper.GetStringDef(evt["RetrievedItem_Localised"]);
            EngineerModifications = JSONHelper.GetStringDef(evt["EngineerModifications"]);
            SwapOutItem = JSONHelper.GetStringDef(evt["SwapOutItem"]);
            Cost = JSONHelper.GetLong(evt["Cost"]);
        }
        public string Slot { get; set; }
        public string Ship { get; set; }
        public int ShipId { get; set; }
        public string RetrievedItem { get; set; }
        public string RetrievedItemLocalised { get; set; }
        public string EngineerModifications { get; set; }
        public string SwapOutItem { get; set; }
        public long Cost { get; set; }

        public override string DefaultRemoveItems()
        {
            return base.DefaultRemoveItems() + ";ShipID";
        }
        public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.moduleretrieve; } }

        public void Ledger(EDDiscovery2.DB.MaterialCommoditiesLedger mcl, DB.SQLiteConnectionUser conn)
        {
            string s = (RetrievedItemLocalised.Length > 0) ? RetrievedItemLocalised : RetrievedItem;

            mcl.AddEvent(Id, EventTimeUTC, EventTypeID, s + " on " + Ship, -Cost);
        }

    }
}


text:
/*
 * snmptrap.c - send snmp traps to a network entity.
 *
 */
/******************************************************************
	Copyright 1989, 1991, 1992 by Carnegie Mellon University

                      All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of CMU not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
******************************************************************/
#include <net-snmp/net-snmp-config.h>

#if HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#include <sys/types.h>
#if HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#if TIME_WITH_SYS_TIME
# ifdef WIN32
#  include <sys/timeb.h>
# else
#  include <sys/time.h>
# endif
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <stdio.h>
#if HAVE_WINSOCK_H
#include <winsock.h>
#endif
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#if HAVE_NETDB_H
#include <netdb.h>
#endif
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif

#include <net-snmp/net-snmp-includes.h>

oid             objid_enterprise[] = { 1, 3, 6, 1, 4, 1, 3, 1, 1 };
oid             objid_sysdescr[] = { 1, 3, 6, 1, 2, 1, 1, 1, 0 };
oid             objid_sysuptime[] = { 1, 3, 6, 1, 2, 1, 1, 3, 0 };
oid             objid_snmptrap[] = { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 };
int             inform = 0;

void
usage(void)
{
    fprintf(stderr, "USAGE: %s ", inform ? "snmpinform" : "snmptrap");
    snmp_parse_args_usage(stderr);
    fprintf(stderr, " TRAP-PARAMETERS\n\n");
    snmp_parse_args_descriptions(stderr);
    fprintf(stderr,
            "  -C APPOPTS\t\tSet various application specific behaviour:\n");
    fprintf(stderr, "\t\t\t  i:  send an INFORM instead of a TRAP\n");
    fprintf(stderr,
            "\n  -v 1 TRAP-PARAMETERS:\n\t enterprise-oid agent trap-type specific-type uptime [OID TYPE VALUE]...\n");
    fprintf(stderr, "  or\n");
    fprintf(stderr,
            "  -v 2 TRAP-PARAMETERS:\n\t uptime trapoid [OID TYPE VALUE] ...\n");
}

int
snmp_input(int operation,
           netsnmp_session * session,
           int reqid, netsnmp_pdu *pdu, void *magic)
{
    return 1;
}

in_addr_t
parse_address(char *address)
{
    in_addr_t       addr;
    struct sockaddr_in saddr;
    struct hostent *hp;

    if ((addr = inet_addr(address)) != -1)
        return addr;
    hp = gethostbyname(address);
    if (hp == NULL) {
        fprintf(stderr, "unknown host: %s\n", address);
        exit(1);
    } else {
        memcpy(&saddr.sin_addr, hp->h_addr, hp->h_length);
        return saddr.sin_addr.s_addr;
    }

}

static void
optProc(int argc, char *const *argv, int opt)
{
    switch (opt) {
    case 'C':
        while (*optarg) {
            switch (*optarg++) {
            case 'i':
                inform = 1;
                break;
            default:
                fprintf(stderr,
                        "Unknown flag passed to -C: %c\n", optarg[-1]);
                exit(1);
            }
        }
        break;
    }
}

int
main(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    netsnmp_pdu    *pdu, *response;
    oid             name[MAX_OID_LEN];
    size_t          name_length;
    int             arg;
    int             status;
    char           *trap = NULL;
    char           *prognam;
    int             exitval = 0;
#ifndef NETSNMP_DISABLE_SNMPV1
    char           *specific = NULL, *description = NULL, *agent = NULL;
    in_addr_t      *pdu_in_addr_t;
#endif

    prognam = strrchr(argv[0], '/');
    if (prognam)
        prognam++;
    else
        prognam = argv[0];

    putenv(strdup("POSIXLY_CORRECT=1"));

    if (strcmp(prognam, "snmpinform") == 0)
        inform = 1;
    switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) {
    case -2:
        exit(0);
    case -1:
        usage();
        exit(1);
    default:
        break;
    }

    SOCK_STARTUP;

    session.callback = snmp_input;
    session.callback_magic = NULL;

    /*
     * setup the local engineID which may be for either or both of the
     * contextEngineID and/or the securityEngineID.
     */
    setup_engineID(NULL, NULL);

    /* if we don't have a contextEngineID set via command line
       arguments, use our internal engineID as the context. */
    if (session.contextEngineIDLen == 0 ||
        session.contextEngineID == NULL) {
        session.contextEngineID =
            snmpv3_generate_engineID(&session.contextEngineIDLen);
    }

    if (session.version == SNMP_VERSION_3 && !inform) {
        /*
         * for traps, we use ourselves as the authoritative engine
         * which is really stupid since command line apps don't have a
         * notion of a persistent engine.  Hence, our boots and time
         * values are probably always really wacked with respect to what
         * a manager would like to see.
         *
         * The following should be enough to:
         *
         * 1) prevent the library from doing discovery for engineid & time.
         * 2) use our engineid instead of the remote engineid for
         * authoritative & privacy related operations.
         * 3) The remote engine must be configured with users for our engineID.
         *
         * -- Wes
         */

        /*
         * pick our own engineID
         */
        if (session.securityEngineIDLen == 0 ||
            session.securityEngineID == NULL) {
            session.securityEngineID =
                snmpv3_generate_engineID(&session.securityEngineIDLen);
        }

        /*
         * set boots and time, which will cause problems if this
         * machine ever reboots and a remote trap receiver has cached our
         * boots and time...  I'll cause a not-in-time-window report to
         * be sent back to this machine.
         */
        if (session.engineBoots == 0)
            session.engineBoots = 1;
        if (session.engineTime == 0)    /* not really correct, */
            session.engineTime = get_uptime();  /* but it'll work. Sort of. */
    }

    ss = snmp_add(&session,
                  netsnmp_transport_open_client("snmptrap", session.peername),
                  NULL, NULL);
    if (ss == NULL) {
        /*
         * diagnose netsnmp_transport_open_client and snmp_add errors with
         * the input netsnmp_session pointer
         */
        snmp_sess_perror("snmptrap", &session);
        SOCK_CLEANUP;
        exit(1);
    }

#ifndef NETSNMP_DISABLE_SNMPV1
    if (session.version == SNMP_VERSION_1) {
        if (inform) {
            fprintf(stderr, "Cannot send INFORM as SNMPv1 PDU\n");
            SOCK_CLEANUP;
            exit(1);
        }
        pdu = snmp_pdu_create(SNMP_MSG_TRAP);
        if ( !pdu ) {
            fprintf(stderr, "Failed to create trap PDU\n");
            SOCK_CLEANUP;
            exit(1);
        }
        pdu_in_addr_t = (in_addr_t *) pdu->agent_addr;
        if (arg == argc) {
            fprintf(stderr, "No enterprise oid\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        if (argv[arg][0] == 0) {
            pdu->enterprise = (oid *) malloc(sizeof(objid_enterprise));
            memcpy(pdu->enterprise, objid_enterprise,
                   sizeof(objid_enterprise));
            pdu->enterprise_length =
                sizeof(objid_enterprise) / sizeof(oid);
        } else {
            name_length = MAX_OID_LEN;
            if (!snmp_parse_oid(argv[arg], name, &name_length)) {
                snmp_perror(argv[arg]);
                usage();
                SOCK_CLEANUP;
                exit(1);
            }
            pdu->enterprise = (oid *) malloc(name_length * sizeof(oid));
            memcpy(pdu->enterprise, name, name_length * sizeof(oid));
            pdu->enterprise_length = name_length;
        }
        if (++arg >= argc) {
            fprintf(stderr, "Missing agent parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        agent = argv[arg];
        if (agent != NULL && strlen(agent) != 0) {
            *pdu_in_addr_t = parse_address(agent);
        } else {
            *pdu_in_addr_t = get_myaddr();
        }
        if (++arg == argc) {
            fprintf(stderr, "Missing generic-trap parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        trap = argv[arg];
        pdu->trap_type = atoi(trap);
        if (++arg == argc) {
            fprintf(stderr, "Missing specific-trap parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        specific = argv[arg];
        pdu->specific_type = atoi(specific);
        if (++arg == argc) {
            fprintf(stderr, "Missing uptime parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        description = argv[arg];
        if (description == NULL || *description == 0)
            pdu->time = get_uptime();
        else
            pdu->time = atol(description);
    } else
#endif
    {
        long            sysuptime;
        char            csysuptime[20];

        pdu = snmp_pdu_create(inform ? SNMP_MSG_INFORM : SNMP_MSG_TRAP2);
        if ( !pdu ) {
            fprintf(stderr, "Failed to create notification PDU\n");
            SOCK_CLEANUP;
            exit(1);
        }
        if (arg == argc) {
            fprintf(stderr, "Missing up-time parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        trap = argv[arg];
        if (*trap == 0) {
            sysuptime = get_uptime();
            sprintf(csysuptime, "%ld", sysuptime);
            trap = csysuptime;
        }
        snmp_add_var(pdu, objid_sysuptime,
                     sizeof(objid_sysuptime) / sizeof(oid), 't', trap);
        if (++arg == argc) {
            fprintf(stderr, "Missing trap-oid parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        if (snmp_add_var
            (pdu, objid_snmptrap, sizeof(objid_snmptrap) / sizeof(oid),
             'o', argv[arg]) != 0) {
            snmp_perror(argv[arg]);
            SOCK_CLEANUP;
            exit(1);
        }
    }
    arg++;

    while (arg < argc) {
        arg += 3;
        if (arg > argc) {
            fprintf(stderr, "%s: Missing type/value for variable\n",
                    argv[arg - 3]);
            SOCK_CLEANUP;
            exit(1);
        }
        name_length = MAX_OID_LEN;
        if (!snmp_parse_oid(argv[arg - 3], name, &name_length)) {
            snmp_perror(argv[arg - 3]);
            SOCK_CLEANUP;
            exit(1);
        }
        if (snmp_add_var
            (pdu, name, name_length, argv[arg - 2][0],
             argv[arg - 1]) != 0) {
            snmp_perror(argv[arg - 3]);
            SOCK_CLEANUP;
            exit(1);
        }
    }

    if (inform)
        status = snmp_synch_response(ss, pdu, &response);
    else
        status = snmp_send(ss, pdu) == 0;
    if (status) {
        snmp_sess_perror(inform ? "snmpinform" : "snmptrap", ss);
        if (!inform)
            snmp_free_pdu(pdu);
        exitval = 1;
    } else if (inform)
        snmp_free_pdu(response);

    snmp_close(ss);
    snmp_shutdown("snmpapp");
    SOCK_CLEANUP;
    return exitval;
}


text: Also copy/move dependencies when promoting.


text:
/**
 * @file
 *   This file implements the OpenThread platform abstraction for SPI communication.
 *
 */

#ifdef SL_COMPONENT_CATALOG_PRESENT
#include "sl_component_catalog.h"
#endif // SL_COMPONENT_CATALOG_PRESENT

#include <stdbool.h>
#include <stddef.h>
#include <string.h>

#include "em_cmu.h"
#include "em_core.h"
#include "em_gpio.h"
#include "em_ldma.h"

#include "gpiointerrupt.h"
#include "spidrv.h"

#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
#include "sl_power_manager.h"
#endif

#include "sl_ncp_spidrv_usart_config.h"

#include "openthread-system.h"
#include "platform-efr32.h"
#include "spi-slave.h"
#include <openthread/error.h>
#include "utils/code_utils.h"

// DEFINES
#define MAX_DMA_DESCRIPTOR_TRANSFER_COUNT ((_LDMA_CH_CTRL_XFERCNT_MASK >> _LDMA_CH_CTRL_XFERCNT_SHIFT) + 1U)

#define SL_OT_SPIDRV_SPI_CONCAT_PASTER(first, second, third) first##second##third

#define SL_OT_SPIDRV_SPI_LDMA_RX_PERIPH_TRIGGER(periph_nbr) \
    SL_OT_SPIDRV_SPI_CONCAT_PASTER(ldmaPeripheralSignal_USART, periph_nbr, _RXDATAV)
#define SL_OT_SPIDRV_SPI_LDMA_TX_PERIPH_TRIGGER(periph_nbr) \
    SL_OT_SPIDRV_SPI_CONCAT_PASTER(ldmaPeripheralSignal_USART, periph_nbr, _TXBL)

//  MEMBER VARIABLES
static volatile bool should_process_transaction = false;

static volatile bool transaction_active;

// DMA
static LDMA_TransferCfg_t rx_dma_transfer_config;
static LDMA_TransferCfg_t tx_dma_transfer_config;

static uint8_t                    default_tx_value;
static volatile LDMA_Descriptor_t tx_descriptor[2];

static volatile LDMA_Descriptor_t rx_descriptor;

// TRANSACTION EVENT'S CALLBACK
static volatile otPlatSpiSlaveTransactionCompleteCallback complete_callback;
static volatile otPlatSpiSlaveTransactionProcessCallback  process_callback;
static volatile void *                                    context;

// SPI Peripheral
static volatile SPIDRV_HandleData_t sl_spidrv_handle_data;

static void rcp_spidrv_set_host_request(void)
{
#if defined(SL_NCP_SPIDRV_USART_HOST_INT_PORT) && defined(SL_NCP_SPIDRV_USART_HOST_INT_PIN)
    GPIO_PinOutClear(SL_NCP_SPIDRV_USART_HOST_INT_PORT, SL_NCP_SPIDRV_USART_HOST_INT_PIN);
#else
    int empty = 0;
    (void)empty;
#endif
}

static void rcp_spidrv_deassert_host_request(void)
{
#if defined(SL_NCP_SPIDRV_USART_HOST_INT_PORT) && defined(SL_NCP_SPIDRV_USART_HOST_INT_PIN)
    GPIO_PinOutSet(SL_NCP_SPIDRV_USART_HOST_INT_PORT, SL_NCP_SPIDRV_USART_HOST_INT_PIN);
#else
    int empty = 0;
    (void)empty;
#endif
}

static void rcp_spidrv_spi_transaction_end_interrupt(uint8_t intNo)
{
    if (intNo == SL_NCP_SPIDRV_USART_CS_FALLING_EDGE_INT_NO)
    {
        transaction_active = true;
        return;
    }
    else if (intNo == SL_NCP_SPIDRV_USART_CS_RISING_EDGE_INT_NO)
    {
        // Must be done before calling the "complete_callback" since
        // this callback will use otPlatSpiSlavePrepareTransaction who
        // would not setup the buffers if a transaction is ongoing.
        transaction_active = false;
        rcp_spidrv_deassert_host_request();
    }

    uint32_t tx_transaction_size = 0U;

    LDMA_StopTransfer(sl_spidrv_handle_data.txDMACh);

    uint32_t tx_dma_channel_nb = sl_spidrv_handle_data.txDMACh;

    // Use the current loader DMA transfer struct to asses the number of transfered bytes.
    uint32_t tx_dma_channel_remaining_xfercnt =
        (LDMA->CH[tx_dma_channel_nb].CTRL & _LDMA_CH_CTRL_XFERCNT_MASK) >> _LDMA_CH_CTRL_XFERCNT_SHIFT;
    tx_dma_channel_remaining_xfercnt += 1U;
    tx_dma_channel_remaining_xfercnt +=
        (sl_spidrv_handle_data.peripheral.usartPort->STATUS & _USART_STATUS_TXBUFCNT_MASK)
        >> _USART_STATUS_TXBUFCNT_SHIFT;

    uint32_t current_tx_descritor_link =
        (LDMA->CH[tx_dma_channel_nb].LINK & _LDMA_CH_LINK_LINK_MASK) >> _LDMA_CH_LINK_LINK_SHIFT;

    uint8_t *old_tx_buffer      = (uint8_t *)tx_descriptor[0].xfer.srcAddr;
    uint16_t old_tx_buffer_size = tx_descriptor[0].xfer.xferCnt + 1U;

    uint8_t *old_rx_buffer      = (uint8_t *)rx_descriptor.xfer.dstAddr;
    uint16_t old_rx_buffer_size = rx_descriptor.xfer.xferCnt + 1U;

    if (current_tx_descritor_link == 0U)
    {
        // Since the link bit is not set in the tx dma channel descriptor the second tx descriptor was loaded.
        tx_transaction_size = tx_descriptor[0].xfer.xferCnt + 1U;
        tx_transaction_size += (tx_descriptor[1].xfer.xferCnt + 1U) - tx_dma_channel_remaining_xfercnt;
    }
    else
    {
        tx_transaction_size = (tx_descriptor[0].xfer.xferCnt - tx_dma_channel_remaining_xfercnt) + 1U;
    }

    // call's otPlatSpiSlavePrepareTransaction in the background, the DMA buffer's will be ready after this call.
    if (complete_callback((void *)context, (uint8_t *)old_tx_buffer, old_tx_buffer_size, (uint8_t *)old_rx_buffer,
                          old_rx_buffer_size, tx_transaction_size))
    {
        otSysEventSignalPending();
        should_process_transaction = true;
    }
}

otError otPlatSpiSlaveEnable(otPlatSpiSlaveTransactionCompleteCallback aCompleteCallback,
                             otPlatSpiSlaveTransactionProcessCallback  aProcessCallback,
                             void *                                    aContext)
{
    CORE_DECLARE_IRQ_STATE;
    otError error = OT_ERROR_NONE;

    // If driver was already configured, an error is returned.
    otEXPECT_ACTION(complete_callback == NULL, error = OT_ERROR_ALREADY);
    otEXPECT_ACTION(process_callback == NULL, error = OT_ERROR_ALREADY);
    otEXPECT_ACTION(context == NULL, error = OT_ERROR_ALREADY);

    CMU_ClockEnable(cmuClock_GPIO, true);

    SPIDRV_Init_t init_data = (SPIDRV_Init_t)
    {
        SL_NCP_SPIDRV_USART_PERIPHERAL, ///< The USART used for SPI.
#if defined(_USART_ROUTELOC0_MASK)
            SL_NCP_SPIDRV_USART_TX_LOC,  ///< A location number for the SPI Tx pin.
            SL_NCP_SPIDRV_USART_RX_LOC,  ///< A location number for the SPI Rx pin.
            SL_NCP_SPIDRV_USART_CLK_LOC, ///< A location number for the SPI Clk pin.
            SL_NCP_SPIDRV_USART_CS_LOC,  ///< A location number for the SPI Cs pin.
#elif defined(_GPIO_USART_ROUTEEN_MASK)
            SL_NCP_SPIDRV_USART_TX_PORT,  ///< Tx port.
            SL_NCP_SPIDRV_USART_RX_PORT,  ///< Rx port.
            SL_NCP_SPIDRV_USART_CLK_PORT, ///< Clock port.
            SL_NCP_SPIDRV_USART_CS_PORT,  ///< Chip select port.
            SL_NCP_SPIDRV_USART_TX_PIN,   ///< Tx pin.
            SL_NCP_SPIDRV_USART_RX_PIN,   ///< Rx pin.
            SL_NCP_SPIDRV_USART_CLK_PIN,  ///< Clock pin.
            SL_NCP_SPIDRV_USART_CS_PIN,   ///< Chip select pin.
#endif
            0U,                             ///< An SPI bitrate.
            8,                              ///< An SPI framelength, valid numbers are 4..16
            0,                              ///< The value to transmit when using SPI receive API functions.
            spidrvSlave,                    ///< An SPI type, slave.
            SL_NCP_SPIDRV_USART_BIT_ORDER,  ///< A bit order on the SPI bus, MSB or LSB first.
            SL_NCP_SPIDRV_USART_CLOCK_MODE, ///< SPI mode, CLKPOL/CLKPHASE setting.
            spidrvCsControlAuto,            ///< A select master mode chip select (CS) control scheme.
            spidrvSlaveStartImmediate,      ///< A slave mode transfer start scheme.
    };

    otEXPECT_ACTION(SPIDRV_Init((SPIDRV_HandleData_t *)&sl_spidrv_handle_data, &init_data) == ECODE_EMDRV_SPIDRV_OK,
                    error = OT_ERROR_FAILED);

    // Client callback functions.
    complete_callback = aCompleteCallback;
    process_callback  = aProcessCallback;
    context           = aContext;

    // Client complete callback request foreground processing.
    should_process_transaction = false;

    // SPI transaction status.
    transaction_active = false;

    // TX default value.
    default_tx_value = 0xFFU;

    // DMA transfer structures.
    rx_dma_transfer_config = (LDMA_TransferCfg_t)LDMA_TRANSFER_CFG_PERIPHERAL(
        SL_OT_SPIDRV_SPI_LDMA_RX_PERIPH_TRIGGER(SL_NCP_SPIDRV_USART_PERIPHERAL_NO));
    tx_dma_transfer_config = (LDMA_TransferCfg_t)LDMA_TRANSFER_CFG_PERIPHERAL(
        SL_OT_SPIDRV_SPI_LDMA_TX_PERIPH_TRIGGER(SL_NCP_SPIDRV_USART_PERIPHERAL_NO));

    rx_descriptor = (LDMA_Descriptor_t)LDMA_DESCRIPTOR_SINGLE_P2M_BYTE(
        &(sl_spidrv_handle_data.peripheral.usartPort->RXDATA), NULL, 1U);
    rx_descriptor.xfer.doneIfs = 0U;

    tx_descriptor[0] = (LDMA_Descriptor_t)LDMA_DESCRIPTOR_LINKREL_M2P_BYTE(
        &default_tx_value, &(sl_spidrv_handle_data.peripheral.usartPort->TXDATA), 1, 1);
    tx_descriptor[0].xfer.doneIfs = 0U;

    tx_descriptor[1] = (LDMA_Descriptor_t)LDMA_DESCRIPTOR_SINGLE_M2P_BYTE(
        &default_tx_value, &(sl_spidrv_handle_data.peripheral.usartPort->TXDATA), MAX_DMA_DESCRIPTOR_TRANSFER_COUNT);
    tx_descriptor[1].xfer.srcInc  = ldmaCtrlSrcIncNone;
    tx_descriptor[1].xfer.doneIfs = 0U;

    // Configuring Host INT line. Active low
#if defined(SL_NCP_SPIDRV_USART_HOST_INT_PORT) && defined(SL_NCP_SPIDRV_USART_HOST_INT_PIN)
    GPIO_PinModeSet(SL_NCP_SPIDRV_USART_HOST_INT_PORT, SL_NCP_SPIDRV_USART_HOST_INT_PIN, gpioModePushPull, 1U);
#endif

    GPIOINT_Init();

    GPIO_PinModeSet(SL_NCP_SPIDRV_USART_CS_PORT, SL_NCP_SPIDRV_USART_CS_PIN, gpioModeInputPullFilter, 1);

    CORE_ENTER_ATOMIC();

    // Initialization during transaction is not supported.
    otEXPECT_ACTION(GPIO_PinInGet(SL_NCP_SPIDRV_USART_CS_PORT, SL_NCP_SPIDRV_USART_CS_PIN) != 0U,
                    error = OT_ERROR_FAILED);

    GPIO_ExtIntConfig(SL_NCP_SPIDRV_USART_CS_PORT, SL_NCP_SPIDRV_USART_CS_PIN,
                      SL_NCP_SPIDRV_USART_CS_RISING_EDGE_INT_NO, true, false, true);
    GPIO_ExtIntConfig(SL_NCP_SPIDRV_USART_CS_PORT, SL_NCP_SPIDRV_USART_CS_PIN,
                      SL_NCP_SPIDRV_USART_CS_FALLING_EDGE_INT_NO, false, true, true);

    GPIOINT_CallbackRegister(SL_NCP_SPIDRV_USART_CS_FALLING_EDGE_INT_NO, rcp_spidrv_spi_transaction_end_interrupt);
    GPIOINT_CallbackRegister(SL_NCP_SPIDRV_USART_CS_RISING_EDGE_INT_NO, rcp_spidrv_spi_transaction_end_interrupt);

    // Clear the usart RX/TX FIFO before configuring the dma transfers.
    sl_spidrv_handle_data.peripheral.usartPort->CMD = USART_CMD_CLEARTX | USART_CMD_CLEARRX;

    // Load the default value descriptor.
    LDMA_StartTransfer(sl_spidrv_handle_data.txDMACh, (LDMA_TransferCfg_t *)&tx_dma_transfer_config,
                       (LDMA_Descriptor_t *)&tx_descriptor[1]);

#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
    sl_power_manager_add_em_requirement(SL_POWER_MANAGER_EM1);
#endif

    CORE_EXIT_ATOMIC();

exit:
    return error;
}

void otPlatSpiSlaveDisable(void)
{
    CORE_DECLARE_IRQ_STATE;
    CORE_ENTER_ATOMIC();

    // Disable CS GPIO IRQ.
    GPIO_ExtIntConfig(SL_NCP_SPIDRV_USART_CS_PORT, SL_NCP_SPIDRV_USART_CS_PIN,
                      SL_NCP_SPIDRV_USART_CS_RISING_EDGE_INT_NO, true, false, false);
    GPIO_ExtIntConfig(SL_NCP_SPIDRV_USART_CS_PORT, SL_NCP_SPIDRV_USART_CS_PIN,
                      SL_NCP_SPIDRV_USART_CS_FALLING_EDGE_INT_NO, false, true, false);

    GPIOINT_CallbackUnRegister(SL_NCP_SPIDRV_USART_CS_RISING_EDGE_INT_NO);
    GPIOINT_CallbackUnRegister(SL_NCP_SPIDRV_USART_CS_FALLING_EDGE_INT_NO);

    CORE_EXIT_ATOMIC();

    // Stop any reception DMA transfers.
    LDMA_StopTransfer(sl_spidrv_handle_data.txDMACh);
    LDMA_StopTransfer(sl_spidrv_handle_data.rxDMACh);

    // Host INT line.
    rcp_spidrv_deassert_host_request();
#if defined(SL_NCP_SPIDRV_USART_HOST_INT_PORT) && defined(SL_NCP_SPIDRV_USART_HOST_INT_PIN)
    GPIO_PinModeSet(SL_NCP_SPIDRV_USART_HOST_INT_PORT, SL_NCP_SPIDRV_USART_HOST_INT_PIN, gpioModeInput, 0U);
#endif

#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
    sl_power_manager_remove_em_requirement(SL_POWER_MANAGER_EM1);
#endif

    should_process_transaction = false;
    transaction_active         = false;

    complete_callback = NULL;
    process_callback  = NULL;
    context           = NULL;
}

otError otPlatSpiSlavePrepareTransaction(uint8_t *aOutputBuf,
                                         uint16_t aOutputBufLen,
                                         uint8_t *aInputBuf,
                                         uint16_t aInputBufLen,
                                         bool     aRequestTransactionFlag)
{
    CORE_DECLARE_IRQ_STATE;
    CORE_ENTER_ATOMIC();

    otError error = OT_ERROR_NONE;

    otEXPECT_ACTION(!transaction_active, error = OT_ERROR_BUSY);
    otEXPECT_ACTION(aOutputBufLen <= MAX_DMA_DESCRIPTOR_TRANSFER_COUNT, error = OT_ERROR_FAILED);
    otEXPECT_ACTION(aInputBufLen <= MAX_DMA_DESCRIPTOR_TRANSFER_COUNT, error = OT_ERROR_FAILED);

    uint32_t tx_dma_channel_number = sl_spidrv_handle_data.txDMACh;
    uint32_t rx_dma_channel_number = sl_spidrv_handle_data.rxDMACh;

    if (aInputBuf != NULL)
    {
        LDMA_StopTransfer(rx_dma_channel_number);
        sl_spidrv_handle_data.peripheral.usartPort->CMD = USART_CMD_CLEARRX;

        rx_descriptor.xfer.xferCnt = aInputBufLen - 1U;
        rx_descriptor.xfer.dstAddr = (uint32_t)aInputBuf;

        LDMA_StartTransfer(rx_dma_channel_number, (LDMA_TransferCfg_t *)&rx_dma_transfer_config,
                           (LDMA_Descriptor_t *)&rx_descriptor);
    }

    if (aOutputBuf != NULL)
    {
        LDMA_StopTransfer(tx_dma_channel_number);
        sl_spidrv_handle_data.peripheral.usartPort->CMD = USART_CMD_CLEARTX;

        tx_descriptor[0].xfer.xferCnt = aOutputBufLen - 1U;
        tx_descriptor[0].xfer.srcAddr = (uint32_t)aOutputBuf;

        LDMA_StartTransfer(tx_dma_channel_number, (LDMA_TransferCfg_t *)&tx_dma_transfer_config,
                           (LDMA_Descriptor_t *)&(tx_descriptor[0]));
    }

    if (aRequestTransactionFlag)
    {
        rcp_spidrv_set_host_request();
    }
    else
    {
        rcp_spidrv_deassert_host_request();
    }

exit:

    CORE_EXIT_ATOMIC();
    return error;
}

void efr32SpiProcess(void)
{
    if (should_process_transaction)
    {
        if (context)
        {
            process_callback((void *)context);
        }

        should_process_transaction = false;
    }
}


text:
import os
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
workspace_sid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

client = Client(account_sid, auth_token)

worker = client.taskrouter.workspaces(workspace_sid).workers.create(
    friendly_name='Support Worker 1', attributes='{"type":"support"}'
)

print(worker.friendly_name)


text:
__title__ = "requests"
__description__ = "Python HTTP for Humans."
__url__ = "http://python-requests.org"
__version__ = "1.2.3"


text:
using Google.Cloud.Translation.V2;
using System;

public partial class TranslateSample
{
    public string TranslateText()
    {
        TranslationClient client = TranslationClient.Create();
        var response = client.TranslateText(
            text: "Hello World.",
            targetLanguage: "ru",  // Russian
            sourceLanguage: "en");  // English
        Console.WriteLine(response.TranslatedText);
        return response.TranslatedText;
    }
}
// [END translate_translate_text]


text:
local MenuScene = require("scenes.templates.MenuScene")
local scene = MenuScene.new()
local composer = require("composer")
local logger = require("logger")
local TAG = "MENU"

function scene:getTitleText()
   return "Paused"
end

function scene:insertButtons()
   local restartButton = self:newRestartButton()
   local giveupButton = self:newGiveupButton()
   local resumeButton = self:newResumeButton()

   self:insertButton(resumeButton)
   self:insertButton(restartButton)
   self:insertButton(giveupButton)
end

return scene


text:
package org.greencheek.web.filter.memcached.cachekey.extraction;

import org.greencheek.web.filter.memcached.cachekey.CacheKeyElement;
import org.greencheek.web.filter.memcached.client.config.CacheConfigGlobals;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by dominictootell on 13/04/2014.
 */
public class PathAttributeExtractor implements KeyAttributeExtractor {
    public static final PathAttributeExtractor INSTANCE = new PathAttributeExtractor();

    @Override
    public CacheKeyElement getAttribute(HttpServletRequest request) {
        return new CacheKeyElement(CacheConfigGlobals.getBytes(request.getRequestURI()),true);
    }
}


text:
"""
Twisted Names: DNS server and client implementations.
"""

from incremental import Version
from twisted.python.deprecate import deprecatedModuleAttribute

from twisted._version import __version__ as version
__version__ = version.short()

deprecatedModuleAttribute(
    Version("Twisted", 16, 0, 0),
    "Use twisted.__version__ instead.",
    "twisted.names", "__version__")


text:
module.exports = function(node) {
    return !!(node && node.nodeType);
};


text:
require "chef/win32/api/system"
require "chef/win32/error"
require "ffi"

class Chef
  module ReservedNames::Win32
    class System
      include Chef::ReservedNames::Win32::API::System
      extend Chef::ReservedNames::Win32::API::System

      def self.get_system_wow64_directory
        ptr = FFI::MemoryPointer.new(:char, 255, true)
        succeeded = GetSystemWow64DirectoryA(ptr, 255)

        if succeeded == 0
          raise Win32APIError, "Failed to get Wow64 system directory"
        end

        ptr.read_string.strip
      end

      def self.wow64_disable_wow64_fs_redirection
        original_redirection_state = FFI::MemoryPointer.new(:pointer)

        succeeded = Wow64DisableWow64FsRedirection(original_redirection_state)

        if succeeded == 0
          raise Win32APIError, "Failed to disable Wow64 file redirection"
        end

        original_redirection_state
      end

      def self.wow64_revert_wow64_fs_redirection(original_redirection_state)
        succeeded = Wow64RevertWow64FsRedirection(original_redirection_state)

        if succeeded == 0
          raise Win32APIError, "Failed to revert Wow64 file redirection"
        end
      end

    end
  end
end


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-25.js
 * @description Array.prototype.indexOf - value of 'length' is a negative non-integer, ensure truncation occurs in the proper direction
 */

function testcase() {

        var obj = { 1: true, 2: false, length: -4294967294.5 }; //length will be 2 finally

        return Array.prototype.indexOf.call(obj, true) === 1 &&
        Array.prototype.indexOf.call(obj, false) === -1;
    }
runTestCase(testcase);


text:
package etcd

import (
	"errors"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/url"
	"path"
	"strings"
	"sync"
	"time"
)

// Errors introduced by handling requests
var (
	ErrRequestCancelled = errors.New("sending request is cancelled")
)

type RawRequest struct {
	Method       string
	RelativePath string
	Values       url.Values
	Cancel       <-chan bool
}

// NewRawRequest returns a new RawRequest
func NewRawRequest(method, relativePath string, values url.Values, cancel <-chan bool) *RawRequest {
	return &RawRequest{
		Method:       method,
		RelativePath: relativePath,
		Values:       values,
		Cancel:       cancel,
	}
}

// getCancelable issues a cancelable GET request
func (c *Client) getCancelable(key string, options Options,
	cancel <-chan bool) (*RawResponse, error) {
	logger.Debugf("get %s [%s]", key, c.cluster.Leader)
	p := keyToPath(key)

	// If consistency level is set to STRONG, append
	// the `consistent` query string.
	if c.config.Consistency == STRONG_CONSISTENCY {
		options["consistent"] = true
	}

	str, err := options.toParameters(VALID_GET_OPTIONS)
	if err != nil {
		return nil, err
	}
	p += str

	req := NewRawRequest("GET", p, nil, cancel)
	resp, err := c.SendRequest(req)

	if err != nil {
		return nil, err
	}

	return resp, nil
}

// get issues a GET request
func (c *Client) get(key string, options Options) (*RawResponse, error) {
	return c.getCancelable(key, options, nil)
}

// put issues a PUT request
func (c *Client) put(key string, value string, ttl uint64,
	options Options) (*RawResponse, error) {

	logger.Debugf("put %s, %s, ttl: %d, [%s]", key, value, ttl, c.cluster.Leader)
	p := keyToPath(key)

	str, err := options.toParameters(VALID_PUT_OPTIONS)
	if err != nil {
		return nil, err
	}
	p += str

	req := NewRawRequest("PUT", p, buildValues(value, ttl), nil)
	resp, err := c.SendRequest(req)

	if err != nil {
		return nil, err
	}

	return resp, nil
}

// post issues a POST request
func (c *Client) post(key string, value string, ttl uint64) (*RawResponse, error) {
	logger.Debugf("post %s, %s, ttl: %d, [%s]", key, value, ttl, c.cluster.Leader)
	p := keyToPath(key)

	req := NewRawRequest("POST", p, buildValues(value, ttl), nil)
	resp, err := c.SendRequest(req)

	if err != nil {
		return nil, err
	}

	return resp, nil
}

// delete issues a DELETE request
func (c *Client) delete(key string, options Options) (*RawResponse, error) {
	logger.Debugf("delete %s [%s]", key, c.cluster.Leader)
	p := keyToPath(key)

	str, err := options.toParameters(VALID_DELETE_OPTIONS)
	if err != nil {
		return nil, err
	}
	p += str

	req := NewRawRequest("DELETE", p, nil, nil)
	resp, err := c.SendRequest(req)

	if err != nil {
		return nil, err
	}

	return resp, nil
}

// SendRequest sends a HTTP request and returns a Response as defined by etcd
func (c *Client) SendRequest(rr *RawRequest) (*RawResponse, error) {

	var req *http.Request
	var resp *http.Response
	var httpPath string
	var err error
	var respBody []byte

	reqs := make([]http.Request, 0)
	resps := make([]http.Response, 0)

	checkRetry := c.CheckRetry
	if checkRetry == nil {
		checkRetry = DefaultCheckRetry
	}

	cancelled := make(chan bool, 1)
	reqLock := new(sync.Mutex)

	if rr.Cancel != nil {
		cancelRoutine := make(chan bool)
		defer close(cancelRoutine)

		go func() {
			select {
			case <-rr.Cancel:
				cancelled <-true
				logger.Debug("send.request is cancelled")
			case <-cancelRoutine:
				return
			}

			// Repeat canceling request until this thread is stopped
			// because we have no idea about whether it succeeds.
			for {
				reqLock.Lock()
				c.httpClient.Transport.(*http.Transport).CancelRequest(req)
				reqLock.Unlock()

				select {
				case <-time.After(100 * time.Millisecond):
				case <-cancelRoutine:
					return
				}
			}
		}()
	}

	// if we connect to a follower, we will retry until we find a leader
	for attempt := 0; ; attempt++ {
		select {
		case <-cancelled:
			return nil, ErrRequestCancelled
		default:
		}

		logger.Debug("begin attempt", attempt, "for", rr.RelativePath)

		if rr.Method == "GET" && c.config.Consistency == WEAK_CONSISTENCY {
			// If it's a GET and consistency level is set to WEAK,
			// then use a random machine.
			httpPath = c.getHttpPath(true, rr.RelativePath)
		} else {
			// Else use the leader.
			httpPath = c.getHttpPath(false, rr.RelativePath)
		}

		// Return a cURL command if curlChan is set
		if c.cURLch != nil {
			command := fmt.Sprintf("curl -X %s %s", rr.Method, httpPath)
			for key, value := range rr.Values {
				command += fmt.Sprintf(" -d %s=%s", key, value[0])
			}
			c.sendCURL(command)
		}

		logger.Debug("send.request.to ", httpPath, " | method ", rr.Method)

		reqLock.Lock()
		if rr.Values == nil {
			req, _ = http.NewRequest(rr.Method, httpPath, nil)
		} else {
			req, _ = http.NewRequest(rr.Method, httpPath,
				strings.NewReader(rr.Values.Encode()))

			req.Header.Set("Content-Type",
				"application/x-www-form-urlencoded; param=value")
		}
		reqLock.Unlock()

		resp, err = c.httpClient.Do(req)
		// If the request was cancelled, return ErrRequestCancelled directly
		select {
		case <-cancelled:
			return nil, ErrRequestCancelled
		default:
		}

		reqs = append(reqs, *req)

		// network error, change a machine!
		if err != nil {
			logger.Debug("network error:", err.Error())
			resps = append(resps, http.Response{})
			if checkErr := checkRetry(c.cluster, reqs, resps, err); checkErr != nil {
				return nil, checkErr
			}

			c.cluster.switchLeader(attempt % len(c.cluster.Machines))
			continue
		}

		// if there is no error, it should receive response
		resps = append(resps, *resp)
		defer resp.Body.Close()
		logger.Debug("recv.response.from", httpPath)

		if validHttpStatusCode[resp.StatusCode] {
			// try to read byte code and break the loop
			respBody, err = ioutil.ReadAll(resp.Body)
			if err == nil {
				logger.Debug("recv.success.", httpPath)
				break
			}
		}

		// if resp is TemporaryRedirect, set the new leader and retry
		if resp.StatusCode == http.StatusTemporaryRedirect {
			u, err := resp.Location()

			if err != nil {
				logger.Warning(err)
			} else {
				// Update cluster leader based on redirect location
				// because it should point to the leader address
				c.cluster.updateLeaderFromURL(u)
				logger.Debug("recv.response.relocate", u.String())
			}
			continue
		}

		if checkErr := checkRetry(c.cluster, reqs, resps,
			errors.New("Unexpected HTTP status code")); checkErr != nil {
			return nil, checkErr
		}
	}

	r := &RawResponse{
		StatusCode: resp.StatusCode,
		Body:       respBody,
		Header:     resp.Header,
	}

	return r, nil
}

// DefaultCheckRetry checks retry cases
// If it has retried 2 * machine number, stop to retry it anymore
// If resp is nil, sleep for 200ms
// If status code is InternalServerError, sleep for 200ms.
func DefaultCheckRetry(cluster *Cluster, reqs []http.Request,
	resps []http.Response, err error) error {

	if len(reqs) >= 2*len(cluster.Machines) {
		return newError(ErrCodeEtcdNotReachable,
			"Tried to connect to each peer twice and failed", 0)
	}

	resp := &resps[len(resps)-1]

	if resp == nil {
		time.Sleep(time.Millisecond * 200)
		return nil
	}

	code := resp.StatusCode
	if code == http.StatusInternalServerError {
		time.Sleep(time.Millisecond * 200)

	}

	logger.Warning("bad response status code", code)
	return nil
}

func (c *Client) getHttpPath(random bool, s ...string) string {
	var machine string
	if random {
		machine = c.cluster.Machines[rand.Intn(len(c.cluster.Machines))]
	} else {
		machine = c.cluster.Leader
	}

	fullPath := machine + "/" + version
	for _, seg := range s {
		fullPath = fullPath + "/" + seg
	}

	return fullPath
}

// buildValues builds a url.Values map according to the given value and ttl
func buildValues(value string, ttl uint64) url.Values {
	v := url.Values{}

	if value != "" {
		v.Set("value", value)
	}

	if ttl > 0 {
		v.Set("ttl", fmt.Sprintf("%v", ttl))
	}

	return v
}

// convert key string to http path exclude version
// for example: key[foo] -> path[keys/foo]
// key[/] -> path[keys/]
func keyToPath(key string) string {
	p := path.Join("keys", key)

	// corner case: if key is "/" or "//" ect
	// path join will clear the tailing "/"
	// we need to add it back
	if p == "keys" {
		p = "keys/"
	}

	return p
}


text:
cd /home/wwwroot/IHelper/
/usr/local/php/bin/php index.php job getpls >> ./application/logs/Job/pls.log


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta name="generator" content="ApiGen 2.8.0">

	<title>Interface ArrayAccess</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360">

		Overview

Namespaces

PHP

SitecRESA

Datatype

Exception

WS

Interfaces

ArrayAccess

Countable

Iterator

Traversable

Exceptions

Exception

LogicException

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text">
		<input type="submit" value="Search">
	</form>

				Overview

				Namespace

Class

				Tree

Interface ArrayAccess

Direct known implementers

			SitecRESA\Datatype\AccesResolverList,
			SitecRESA\Datatype\ObjectList

		PHP Extension: Core

		Documented at php.net

Methods summary

			 public

		#
		offsetExists( mixed <var>$offset</var> )

			 public

		#
		offsetGet( mixed <var>$offset</var> )

			 public

		#
		offsetSet( mixed <var>$offset</var>, mixed <var>$value</var> )

			 public

		#
		offsetUnset( mixed <var>$offset</var> )

		 API documentation generated by ApiGen 2.8.0


text:
// Decompiled with JetBrains decompiler
// Type: TechnologySolutions.Rfid.AsciiProtocol.AsciiCommander
// Assembly: TechnologySolutions.Rfid.AsciiProtocol.FX35, Version=1.1.5423.27429, Culture=neutral, PublicKeyToken=null
// MVID: 9C1072D5-BA32-4CFB-BB8E-6AC565EFDF12
// Assembly location: F:\Visual Studio\Repositories\IlukaOreSampleTracking\lib\Ascii 2 Windows\TechnologySolutions.Rfid.AsciiProtocol.FX35.dll

//using log4net;

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Tsl.AsciiProtocol.Pcl
{
  /// <summary>
  /// TSLAsciiCommander provides methods to communicate with TSL devices that use the TSL ASCII 2.0 Protocol
  ///             Instances of this class support:
  ///             •connection and disconnection from any TSL Reader connected via a comm port
  ///             •execution of an IAsciiCommand either synchronously or asynchronously
  ///             •management of the responder chain for data received from the TSL device
  ///
  /// </summary>
  public class AsciiCommander : AsciiCommandExecutorBase, IDisposable
  {
    /// <summary>
    /// Provides logging for this class
    ///
    /// </summary>
    //private static ILog log = LogManager.GetLogger(typeof (AsciiCommander));
    /// <summary>
    /// Provides synchronization to receive processing
    ///
    /// </summary>
    private object receiveSyncLock = new object();
    /// <summary>
    /// True when an instance is disposed
    ///
    /// </summary>
    private bool disposed;
    /// <summary>
    /// Used to communicate with the reader
    ///
    /// </summary>
    private IAsciiSerialPort reader;

    /// <summary>
    /// Gets a value indicating whether a reader is connected
    ///
    /// </summary>
    public bool IsConnected
    {
      get
      {
        return this.reader != null;
      }
    }

    /// <summary>
    /// Connect the AsciiCommander to the given reader
    ///
    /// </summary>
    /// <param name="reader">The UHF Reader that supports the TSL ASCII 2.0 protocol</param>
    /// <returns>
    /// True if successfully connected
    /// </returns>
    public bool Connect(IAsciiSerialPort reader)
    {
      //AsciiCommander.log.Info((object) "Connect+");
      if (reader == null)
        throw new ArgumentNullException("reader");
      if (this.reader != null)
        this.Disconnect();
      this.reader = reader;
      this.reader.Received += new EventHandler(this.Reader_Received);
      this.LastActivityTime = DateTime.Now;
      //AsciiCommander.log.InfoFormat("Connect- {0}", this.IsConnected);
      return this.IsConnected;
    }

    /// <summary>
    /// Disconnects from the current device
    ///
    /// </summary>
    public void Disconnect()
    {
      //AsciiCommander.log.Info((object) "Disconnect+");
      if (this.reader != null)
      {
        this.reader.Received -= new EventHandler(this.Reader_Received);
        try
        {
          this.reader.Dispose();
        }
        catch (Exception ex)
        {
          //AsciiCommander.log.Error((object) "failed to dispose reader", ex);
        }
        finally
        {
          this.reader = (IAsciiSerialPort) null;
        }
      }
      this.LastActivityTime = DateTime.Now;
      //AsciiCommander.log.Info((object) "Disconnect-");
    }

    /// <summary>
    /// Sends the signal to the accessory to permanently disconnect
    ///
    /// </summary>
    ///
    /// <remarks>
    /// Once issued this will require reconnecting to the reader to use the accessory again. This may require switching to the iOS Settings App
    ///             This is a convenience method and is equivalent to sending a TSLSleepCommand to the reader
    ///
    /// </remarks>
    public void PermanentlyDisconnect()
    {
      if (!this.IsConnected)
        return;
      this.Send(".sl");

      Task.Delay(200);
      this.Disconnect();
    }

    /// <summary>
    /// Send the given string as a CrLf terminated string, to the reader.
    ///             This method waits until the command has been successfuly sent
    ///
    /// </summary>
    /// <param name="line">line The ASCII string to send to the device</param><exception cref="T:System.InvalidOperationException">if no device is connected  </exception>
    public override void Send(string line)
    {
      base.Send(line);
      if (!this.IsConnected)
        throw new InvalidOperationException("Reader not connected");
      this.reader.WriteLine(line);
    }

    /// <summary>
    /// Disposes an instance of the AsciiCommander class
    ///
    /// </summary>
    /// <param name="disposing">True to dispose managed as well as unmanaged resources</param>
    protected override void Dispose(bool disposing)
    {
      if (!this.disposed)
      {
        if (disposing)
          this.Disconnect();
        this.disposed = true;
      }
      base.Dispose(disposing);
    }

    /// <summary>
    /// Data was received from the reader. Report all the complete lines to the ASCII commander by calling
    ///             <see cref="M:TechnologySolutions.Rfid.AsciiProtocol.AsciiCommandExecutorBase.ProcessReceivedLines(System.Collections.Generic.ICollection{System.String})"/>
    /// </summary>
    /// <param name="sender">The event source</param><param name="e">Data provided for the event</param>
    private void Reader_Received(object sender, EventArgs e)
    {
      lock (this.receiveSyncLock)
      {
        List<string> local_0 = new List<string>();
        try
        {
          IAsciiSerialPort local_2;
          while ((local_2 = this.reader) != null)
          {
            if (local_2.IsDataAvailable)
            {
              string local_1 = local_2.ReadLine();
              local_0.Add(local_1);
            }
            else
              break;
          }
        }
        catch (TimeoutException exception_0)
        {
          //AsciiCommander.log.Error((object) "SessionDataReceived", (Exception) exception_0);
        }
        this.ProcessReceivedLines((ICollection<string>) local_0);
      }
      this.LastActivityTime = DateTime.Now;
    }
  }
}


text:
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace ErrorProne.NET.AsyncAnalyzers
{
    /// <summary>
    /// A fixer for <see cref="ConfigureAwaitRequiredAnalyzer"/>.
    /// </summary>
    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ConfigureAwaitRequiredAnalyzer)), Shared]
    public class AddConfigureAwaitCodeFixProvider : CodeFixProvider
    {
        public const string RemoveConfigureAwaitTitle = "Add ConfigureAwait(false).";

        /// <inheritdoc />
        public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(ConfigureAwaitRequiredAnalyzer.DiagnosticId);

        /// <inheritdoc />
        public override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            foreach (var diagnostic in context.Diagnostics)
            {
                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: RemoveConfigureAwaitTitle,
                        createChangedDocument: c => AddConfigureAwaitAsync(context.Document, diagnostic.Location, context.CancellationToken),
                        equivalenceKey: RemoveConfigureAwaitTitle),
                    diagnostic);
            }

            return Task.CompletedTask;
        }

        /// <inheritdoc />
        public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;

        private static async Task<Document> AddConfigureAwaitAsync(Document document, Location location, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var parent = root?.FindToken(location.SourceSpan.Start).Parent;
            if (parent == null)
            {
                return document;
            }

            var awaitExpression = parent.AncestorsAndSelf()
                .OfType<AwaitExpressionSyntax>().First();

            var newExpr = SyntaxFactory.InvocationExpression(
                SyntaxFactory.MemberAccessExpression(
                    SyntaxKind.SimpleMemberAccessExpression,
                    awaitExpression.Expression,
                    SyntaxFactory.IdentifierName("ConfigureAwait")),
                SyntaxFactory.ArgumentList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))
            );

            var newAwaitExpression = awaitExpression.WithExpression(newExpr);
            var newRoot = root.ReplaceNode(awaitExpression, newAwaitExpression);

            if (newRoot == null)
            {
                return document;
            }

            return document.WithSyntaxRoot(newRoot);
        }
    }
}


text:
define(['common/eventRegistry'], function(EvReg) {

  describe('Common.EventRegistry', function(){
    var expectedMethods;

    beforeEach(function() {
      expectedMethods = ['expect', 'ensure'];
    });

    it('should be defined', function() {
      EvReg.should.not.equal(undefined);
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2017 The Android Open Source Project
  ~
  ~ 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.
-->
<resources>

  <!-- Themes V21 and above specify an android:alertDialogTheme so that text
       buttons are used instead of filled buttons. The android:alertDialogTheme
       used by default by the framework pre-21 is not public and therefore we
       cannot inherit from it, so we leave pre-21 Framework Alert Dialogs as the
       platform default. -->

  <style name="Base.V21.Theme.MaterialComponents" parent="Base.V14.Theme.MaterialComponents">
    <item name="android:alertDialogTheme">@style/ThemeOverlay.MaterialComponents.Dialog.Alert.Framework</item>
  </style>

  <style name="Base.V21.Theme.MaterialComponents.Light" parent="Base.V14.Theme.MaterialComponents.Light">
    <item name="android:alertDialogTheme">@style/ThemeOverlay.MaterialComponents.Light.Dialog.Alert.Framework</item>
  </style>

  <style name="Base.Theme.MaterialComponents" parent="Base.V21.Theme.MaterialComponents"/>

  <style name="Base.Theme.MaterialComponents.Light" parent="Base.V21.Theme.MaterialComponents.Light"/>

</resources>


text:
namespace JustGestures.OptionItems
{
    partial class UC_gestureOptions
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.gB_gestureTypes = new System.Windows.Forms.GroupBox();
            this.lbl_wheelBtn = new System.Windows.Forms.Label();
            this.lbl_doubleBtn = new System.Windows.Forms.Label();
            this.lbl_classicCurve = new System.Windows.Forms.Label();
            this.cB_wheelBtn = new System.Windows.Forms.ComboBox();
            this.cB_doubleBtn = new System.Windows.Forms.ComboBox();
            this.cB_classicCurve = new System.Windows.Forms.ComboBox();
            this.gB_activation = new System.Windows.Forms.GroupBox();
            this.lbl_typeOfWnd = new System.Windows.Forms.Label();
            this.cB_wndHandle = new System.Windows.Forms.ComboBox();
            this.nUD_deactivateTimeout = new System.Windows.Forms.NumericUpDown();
            this.cB_sensitiveZone = new System.Windows.Forms.ComboBox();
            this.cB_toggleBtn = new System.Windows.Forms.ComboBox();
            this.lbl_deactivationTimeout = new System.Windows.Forms.Label();
            this.lbl_sensitiveZone = new System.Windows.Forms.Label();
            this.lbl_toggleButton = new System.Windows.Forms.Label();
            this.btn_wizard = new System.Windows.Forms.Button();
            this.gB_gestureTypes.SuspendLayout();
            this.gB_activation.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nUD_deactivateTimeout)).BeginInit();
            this.SuspendLayout();
            //
            // gB_gestureTypes
            //
            this.gB_gestureTypes.Controls.Add(this.lbl_wheelBtn);
            this.gB_gestureTypes.Controls.Add(this.lbl_doubleBtn);
            this.gB_gestureTypes.Controls.Add(this.lbl_classicCurve);
            this.gB_gestureTypes.Controls.Add(this.cB_wheelBtn);
            this.gB_gestureTypes.Controls.Add(this.cB_doubleBtn);
            this.gB_gestureTypes.Controls.Add(this.cB_classicCurve);
            this.gB_gestureTypes.Location = new System.Drawing.Point(0, 0);
            this.gB_gestureTypes.Name = "gB_gestureTypes";
            this.gB_gestureTypes.Size = new System.Drawing.Size(400, 109);
            this.gB_gestureTypes.TabIndex = 3;
            this.gB_gestureTypes.TabStop = false;
            this.gB_gestureTypes.Text = "Gesture Types";
            //
            // lbl_wheelBtn
            //
            this.lbl_wheelBtn.AutoSize = true;
            this.lbl_wheelBtn.Location = new System.Drawing.Point(6, 76);
            this.lbl_wheelBtn.Name = "lbl_wheelBtn";
            this.lbl_wheelBtn.Size = new System.Drawing.Size(112, 13);
            this.lbl_wheelBtn.TabIndex = 5;
            this.lbl_wheelBtn.Text = "Wheel Button Gesture";
            //
            // lbl_doubleBtn
            //
            this.lbl_doubleBtn.AutoSize = true;
            this.lbl_doubleBtn.Location = new System.Drawing.Point(6, 49);
            this.lbl_doubleBtn.Name = "lbl_doubleBtn";
            this.lbl_doubleBtn.Size = new System.Drawing.Size(115, 13);
            this.lbl_doubleBtn.TabIndex = 4;
            this.lbl_doubleBtn.Text = "Double Button Gesture";
            //
            // lbl_classicCurve
            //
            this.lbl_classicCurve.AutoSize = true;
            this.lbl_classicCurve.Location = new System.Drawing.Point(6, 22);
            this.lbl_classicCurve.Name = "lbl_classicCurve";
            this.lbl_classicCurve.Size = new System.Drawing.Size(111, 13);
            this.lbl_classicCurve.TabIndex = 3;
            this.lbl_classicCurve.Text = "Classic Curve Gesture";
            //
            // cB_wheelBtn
            //
            this.cB_wheelBtn.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cB_wheelBtn.FormattingEnabled = true;
            this.cB_wheelBtn.Location = new System.Drawing.Point(234, 73);
            this.cB_wheelBtn.Name = "cB_wheelBtn";
            this.cB_wheelBtn.Size = new System.Drawing.Size(160, 21);
            this.cB_wheelBtn.TabIndex = 2;
            this.cB_wheelBtn.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
            //
            // cB_doubleBtn
            //
            this.cB_doubleBtn.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cB_doubleBtn.FormattingEnabled = true;
            this.cB_doubleBtn.Location = new System.Drawing.Point(234, 46);
            this.cB_doubleBtn.Name = "cB_doubleBtn";
            this.cB_doubleBtn.Size = new System.Drawing.Size(160, 21);
            this.cB_doubleBtn.TabIndex = 1;
            this.cB_doubleBtn.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
            //
            // cB_classicCurve
            //
            this.cB_classicCurve.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cB_classicCurve.FormattingEnabled = true;
            this.cB_classicCurve.Location = new System.Drawing.Point(234, 19);
            this.cB_classicCurve.Name = "cB_classicCurve";
            this.cB_classicCurve.Size = new System.Drawing.Size(160, 21);
            this.cB_classicCurve.TabIndex = 0;
            this.cB_classicCurve.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
            //
            // gB_activation
            //
            this.gB_activation.Controls.Add(this.lbl_typeOfWnd);
            this.gB_activation.Controls.Add(this.cB_wndHandle);
            this.gB_activation.Controls.Add(this.nUD_deactivateTimeout);
            this.gB_activation.Controls.Add(this.cB_sensitiveZone);
            this.gB_activation.Controls.Add(this.cB_toggleBtn);
            this.gB_activation.Controls.Add(this.lbl_deactivationTimeout);
            this.gB_activation.Controls.Add(this.lbl_sensitiveZone);
            this.gB_activation.Controls.Add(this.lbl_toggleButton);
            this.gB_activation.Location = new System.Drawing.Point(0, 135);
            this.gB_activation.Name = "gB_activation";
            this.gB_activation.Size = new System.Drawing.Size(400, 138);
            this.gB_activation.TabIndex = 4;
            this.gB_activation.TabStop = false;
            this.gB_activation.Text = "Activation";
            //
            // lbl_typeOfWnd
            //
            this.lbl_typeOfWnd.AutoSize = true;
            this.lbl_typeOfWnd.Location = new System.Drawing.Point(6, 22);
            this.lbl_typeOfWnd.Name = "lbl_typeOfWnd";
            this.lbl_typeOfWnd.Size = new System.Drawing.Size(167, 13);
            this.lbl_typeOfWnd.TabIndex = 10;
            this.lbl_typeOfWnd.Text = "Control Program/Window which is";
            //
            // cB_wndHandle
            //
            this.cB_wndHandle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cB_wndHandle.FormattingEnabled = true;
            this.cB_wndHandle.Location = new System.Drawing.Point(234, 19);
            this.cB_wndHandle.Name = "cB_wndHandle";
            this.cB_wndHandle.Size = new System.Drawing.Size(160, 21);
            this.cB_wndHandle.TabIndex = 11;
            this.cB_wndHandle.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
            //
            // nUD_deactivateTimeout
            //
            this.nUD_deactivateTimeout.Increment = new decimal(new int[] {
            50,
            0,
            0,
            0});
            this.nUD_deactivateTimeout.Location = new System.Drawing.Point(234, 101);
            this.nUD_deactivateTimeout.Maximum = new decimal(new int[] {
            1000,
            0,
            0,
            0});
            this.nUD_deactivateTimeout.Minimum = new decimal(new int[] {
            100,
            0,
            0,
            0});
            this.nUD_deactivateTimeout.Name = "nUD_deactivateTimeout";
            this.nUD_deactivateTimeout.Size = new System.Drawing.Size(160, 20);
            this.nUD_deactivateTimeout.TabIndex = 5;
            this.nUD_deactivateTimeout.Value = new decimal(new int[] {
            350,
            0,
            0,
            0});
            this.nUD_deactivateTimeout.ValueChanged += new System.EventHandler(this.nUD_deactivateTimeout_ValueChanged);
            //
            // cB_sensitiveZone
            //
            this.cB_sensitiveZone.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cB_sensitiveZone.FormattingEnabled = true;
            this.cB_sensitiveZone.Location = new System.Drawing.Point(234, 73);
            this.cB_sensitiveZone.Name = "cB_sensitiveZone";
            this.cB_sensitiveZone.Size = new System.Drawing.Size(160, 21);
            this.cB_sensitiveZone.TabIndex = 4;
            this.cB_sensitiveZone.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
            //
            // cB_toggleBtn
            //
            this.cB_toggleBtn.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cB_toggleBtn.FormattingEnabled = true;
            this.cB_toggleBtn.Location = new System.Drawing.Point(234, 46);
            this.cB_toggleBtn.Name = "cB_toggleBtn";
            this.cB_toggleBtn.Size = new System.Drawing.Size(160, 21);
            this.cB_toggleBtn.TabIndex = 3;
            this.cB_toggleBtn.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
            //
            // lbl_deactivationTimeout
            //
            this.lbl_deactivationTimeout.AutoSize = true;
            this.lbl_deactivationTimeout.Location = new System.Drawing.Point(6, 103);
            this.lbl_deactivationTimeout.Name = "lbl_deactivationTimeout";
            this.lbl_deactivationTimeout.Size = new System.Drawing.Size(135, 13);
            this.lbl_deactivationTimeout.TabIndex = 2;
            this.lbl_deactivationTimeout.Text = "Deactivation Timeout in ms";
            //
            // lbl_sensitiveZone
            //
            this.lbl_sensitiveZone.AutoSize = true;
            this.lbl_sensitiveZone.Location = new System.Drawing.Point(6, 76);
            this.lbl_sensitiveZone.Name = "lbl_sensitiveZone";
            this.lbl_sensitiveZone.Size = new System.Drawing.Size(118, 13);
            this.lbl_sensitiveZone.TabIndex = 1;
            this.lbl_sensitiveZone.Text = "Sensitive Zone in pixels";
            //
            // lbl_toggleButton
            //
            this.lbl_toggleButton.AutoSize = true;
            this.lbl_toggleButton.Location = new System.Drawing.Point(6, 49);
            this.lbl_toggleButton.Name = "lbl_toggleButton";
            this.lbl_toggleButton.Size = new System.Drawing.Size(74, 13);
            this.lbl_toggleButton.TabIndex = 0;
            this.lbl_toggleButton.Text = "Toggle Button";
            //
            // btn_wizard
            //
            this.btn_wizard.AutoSize = true;
            this.btn_wizard.Location = new System.Drawing.Point(0, 295);
            this.btn_wizard.Name = "btn_wizard";
            this.btn_wizard.Size = new System.Drawing.Size(106, 23);
            this.btn_wizard.TabIndex = 5;
            this.btn_wizard.Text = "Run Wizard";
            this.btn_wizard.UseVisualStyleBackColor = true;
            this.btn_wizard.Click += new System.EventHandler(this.btn_wizard_Click);
            //
            // UC_gestureOptions
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.btn_wizard);
            this.Controls.Add(this.gB_activation);
            this.Controls.Add(this.gB_gestureTypes);
            this.Name = "UC_gestureOptions";
            this.Size = new System.Drawing.Size(532, 432);
            this.gB_gestureTypes.ResumeLayout(false);
            this.gB_gestureTypes.PerformLayout();
            this.gB_activation.ResumeLayout(false);
            this.gB_activation.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nUD_deactivateTimeout)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.GroupBox gB_gestureTypes;
        private System.Windows.Forms.ComboBox cB_doubleBtn;
        private System.Windows.Forms.ComboBox cB_classicCurve;
        private System.Windows.Forms.ComboBox cB_wheelBtn;
        private System.Windows.Forms.Label lbl_wheelBtn;
        private System.Windows.Forms.Label lbl_doubleBtn;
        private System.Windows.Forms.Label lbl_classicCurve;
        private System.Windows.Forms.GroupBox gB_activation;
        private System.Windows.Forms.Label lbl_deactivationTimeout;
        private System.Windows.Forms.Label lbl_sensitiveZone;
        private System.Windows.Forms.Label lbl_toggleButton;
        private System.Windows.Forms.ComboBox cB_toggleBtn;
        private System.Windows.Forms.ComboBox cB_sensitiveZone;
        private System.Windows.Forms.NumericUpDown nUD_deactivateTimeout;
        private System.Windows.Forms.Label lbl_typeOfWnd;
        private System.Windows.Forms.ComboBox cB_wndHandle;
        private System.Windows.Forms.Button btn_wizard;
    }
}


text:
package com.t3coode.togg.activities.validators;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public abstract class BasicValidator implements Validator {

    protected static interface ValidationType {
        String value();
    }

    private ValidationType[] validations;
    private List<String> errors;
    private String name;
    private String keyName;

    public BasicValidator(String keyName, String name,
            ValidationType[] validations) {
        super();
        this.validations = validations;
        this.name = name;
        this.keyName = keyName;
        this.errors = new ArrayList<String>();
    }

    @Override
    public boolean valid() {
        errors.clear();
        boolean valid = true;

        for (ValidationType validationName : validations) {
            try {
                Method m = this.getClass().getDeclaredMethod(
                        validationName.value());
                m.setAccessible(true);
                boolean tempValid = (Boolean) m.invoke(this);
                if (!tempValid) {
                    errors.add(keyName
                            + StringUtils.capitalize(validationName.value())
                            + "ValidationError");
                    valid = tempValid;
                }
            } catch (Exception e) {
            }
        }
        return valid;
    }

    @Override
    public List<String> getErrors() {
        return errors;
    }

    @Override
    public String getName() {
        return this.name;
    }
}


text:
package com.sun.tools.doclets.formats.html.markup;

import java.io.*;
import java.util.*;

import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.ConfigurationImpl;
import com.sun.tools.doclets.formats.html.SectionName;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.DocFile;
import com.sun.tools.doclets.internal.toolkit.util.DocLink;
import com.sun.tools.doclets.internal.toolkit.util.DocPath;

/**
 * Class for the Html Format Code Generation specific to JavaDoc.
 * This Class contains methods related to the Html Code Generation which
 * are used by the Sub-Classes in the package com.sun.tools.doclets.standard
 * and com.sun.tools.doclets.oneone.
 *
 *
This is NOT part of any supported API.
 *  If you write code that depends on this, you do so at your own risk.
 *  This code and its internal interfaces are subject to change or
 *  deletion without notice.
 *
 * @since 1.2
 * @author Atul M Dambalkar
 * @author Robert Field
 */
public abstract class HtmlDocWriter extends HtmlWriter {

    public static final String CONTENT_TYPE = "text/html";

    /**
     * Constructor. Initializes the destination file name through the super
     * class HtmlWriter.
     *
     * @param filename String file name.
     */
    public HtmlDocWriter(Configuration configuration, DocPath filename)
            throws IOException {
        super(configuration, filename);
        configuration.message.notice("doclet.Generating_0",
            DocFile.createFileForOutput(configuration, filename).getPath());
    }

    /**
     * Accessor for configuration.
     */
    public abstract Configuration configuration();

    public Content getHyperLink(DocPath link, String label) {
        return getHyperLink(link, new StringContent(label), false, "", "", "");
    }

    /**
     * Get Html Hyper Link Content.
     *
     * @param where      Position of the link in the file. Character '#' is not
     *                   needed.
     * @param label      Tag for the link.
     * @return a content tree for the hyper link
     */
    public Content getHyperLink(String where,
                               Content label) {
        return getHyperLink(getDocLink(where), label, "", "");
    }

    /**
     * Get Html Hyper Link Content.
     *
     * @param sectionName      The section name to which the link will be created.
     * @param label            Tag for the link.
     * @return a content tree for the hyper link
     */
    public Content getHyperLink(SectionName sectionName,
                               Content label) {
        return getHyperLink(getDocLink(sectionName), label, "", "");
    }

    /**
     * Get Html Hyper Link Content.
     *
     * @param sectionName      The section name combined with where to which the link
     *                         will be created.
     * @param where            The fragment combined with sectionName to which the link
     *                         will be created.
     * @param label            Tag for the link.
     * @return a content tree for the hyper link
     */
    public Content getHyperLink(SectionName sectionName, String where,
                               Content label) {
        return getHyperLink(getDocLink(sectionName, where), label, "", "");
    }

    /**
     * Get the link.
     *
     * @param where      Position of the link in the file.
     * @return a DocLink object for the hyper link
     */
    public DocLink getDocLink(String where) {
        return DocLink.fragment(getName(where));
    }

    /**
     * Get the link.
     *
     * @param sectionName      The section name to which the link will be created.
     * @return a DocLink object for the hyper link
     */
    public DocLink getDocLink(SectionName sectionName) {
        return DocLink.fragment(sectionName.getName());
    }

    /**
     * Get the link.
     *
     * @param sectionName      The section name combined with where to which the link
     *                         will be created.
     * @param where            The fragment combined with sectionName to which the link
     *                         will be created.
     * @return a DocLink object for the hyper link
     */
    public DocLink getDocLink(SectionName sectionName, String where) {
        return DocLink.fragment(sectionName.getName() + getName(where));
    }

    /**
     * Convert the name to a valid HTML name.
     *
     * @param name the name that needs to be converted to valid HTML name.
     * @return a valid HTML name string.
     */
    public String getName(String name) {
        StringBuilder sb = new StringBuilder();
        char ch;
        /* The HTML 4 spec at http://www.w3.org/TR/html4/types.html#h-6.2 mentions
         * that the name/id should begin with a letter followed by other valid characters.
         * The HTML 5 spec (draft) is more permissive on names/ids where the only restriction
         * is that it should be at least one character long and should not contain spaces.
         * The spec draft is @ http://www.w3.org/html/wg/drafts/html/master/dom.html#the-id-attribute.
         *
         * For HTML 4, we need to check for non-characters at the beginning of the name and
         * substitute it accordingly, "_" and "$" can appear at the beginning of a member name.
         * The method substitutes "$" with "Z:Z:D" and will prefix "_" with "Z:Z".
         */
        for (int i = 0; i < name.length(); i++) {
            ch = name.charAt(i);
            switch (ch) {
                case '(':
                case ')':
                case '<':
                case '>':
                case ',':
                    sb.append('-');
                    break;
                case ' ':
                case '[':
                    break;
                case ']':
                    sb.append(":A");
                    break;
                // Any appearance of $ needs to be substituted with ":D" and not with hyphen
                // since a field name "P$$ and a method P(), both valid member names, can end
                // up as "P--". A member name beginning with $ needs to be substituted with
                // "Z:Z:D".
                case '$':
                    if (i == 0)
                        sb.append("Z:Z");
                    sb.append(":D");
                    break;
                // A member name beginning with _ needs to be prefixed with "Z:Z" since valid anchor
                // names can only begin with a letter.
                case '_':
                    if (i == 0)
                        sb.append("Z:Z");
                    sb.append(ch);
                    break;
                default:
                    sb.append(ch);
            }
        }
        return sb.toString();
    }

    /**
     * Get Html hyperlink.
     *
     * @param link       path of the file.
     * @param label      Tag for the link.
     * @return a content tree for the hyper link
     */
    public Content getHyperLink(DocPath link, Content label) {
        return getHyperLink(link, label, "", "");
    }

    public Content getHyperLink(DocLink link, Content label) {
        return getHyperLink(link, label, "", "");
    }

    public Content getHyperLink(DocPath link,
                               Content label, boolean strong,
                               String stylename, String title, String target) {
        return getHyperLink(new DocLink(link), label, strong,
                stylename, title, target);
    }

    public Content getHyperLink(DocLink link,
                               Content label, boolean strong,
                               String stylename, String title, String target) {
        Content body = label;
        if (strong) {
            body = HtmlTree.SPAN(HtmlStyle.typeNameLink, body);
        }
        if (stylename != null && stylename.length() != 0) {
            HtmlTree t = new HtmlTree(HtmlTag.FONT, body);
            t.addAttr(HtmlAttr.CLASS, stylename);
            body = t;
        }
        HtmlTree l = HtmlTree.A(link.toString(), body);
        if (title != null && title.length() != 0) {
            l.addAttr(HtmlAttr.TITLE, title);
        }
        if (target != null && target.length() != 0) {
            l.addAttr(HtmlAttr.TARGET, target);
        }
        return l;
    }

    /**
     * Get Html Hyper Link.
     *
     * @param link       String name of the file.
     * @param label      Tag for the link.
     * @param title      String that describes the link's content for accessibility.
     * @param target     Target frame.
     * @return a content tree for the hyper link.
     */
    public Content getHyperLink(DocPath link,
            Content label, String title, String target) {
        return getHyperLink(new DocLink(link), label, title, target);
    }

    public Content getHyperLink(DocLink link,
            Content label, String title, String target) {
        HtmlTree anchor = HtmlTree.A(link.toString(), label);
        if (title != null && title.length() != 0) {
            anchor.addAttr(HtmlAttr.TITLE, title);
        }
        if (target != null && target.length() != 0) {
            anchor.addAttr(HtmlAttr.TARGET, target);
        }
        return anchor;
    }

    /**
     * Get the name of the package, this class is in.
     *
     * @param cd    ClassDoc.
     */
    public String getPkgName(ClassDoc cd) {
        String pkgName = cd.containingPackage().name();
        if (pkgName.length() > 0) {
            pkgName += ".";
            return pkgName;
        }
        return "";
    }

    public boolean getMemberDetailsListPrinted() {
        return memberDetailsListPrinted;
    }

    /**
     * Print the frameset version of the Html file header.
     * Called only when generating an HTML frameset file.
     *
     * @param title Title of this HTML document
     * @param noTimeStamp If true, don't print time stamp in header
     * @param frameset the frameset to be added to the HTML document
     */
    public void printFramesetDocument(String title, boolean noTimeStamp,
            Content frameset) throws IOException {
        Content htmlDocType = DocType.FRAMESET;
        Content htmlComment = new Comment(configuration.getText("doclet.New_Page"));
        Content head = new HtmlTree(HtmlTag.HEAD);
        head.addContent(getGeneratedBy(!noTimeStamp));
        if (configuration.charset.length() > 0) {
            Content meta = HtmlTree.META("Content-Type", CONTENT_TYPE,
                    configuration.charset);
            head.addContent(meta);
        }
        Content windowTitle = HtmlTree.TITLE(new StringContent(title));
        head.addContent(windowTitle);
        head.addContent(getFramesetJavaScript());
        Content htmlTree = HtmlTree.HTML(configuration.getLocale().getLanguage(),
                head, frameset);
        Content htmlDocument = new HtmlDocument(htmlDocType,
                htmlComment, htmlTree);
        write(htmlDocument);
    }

    protected Comment getGeneratedBy(boolean timestamp) {
        String text = "Generated by javadoc"; // marker string, deliberately not localized
        if (timestamp) {
            Calendar calendar = new GregorianCalendar(TimeZone.getDefault());
            Date today = calendar.getTime();
            text += " ("+ configuration.getDocletSpecificBuildDate() + ") on " + today;
        }
        return new Comment(text);
    }
}