text:
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer\Transformer;

use Symfony\CS\Tests\Tokenizer\AbstractTransformerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class UseTransformerTest extends AbstractTransformerTestBase
{
    /**
     * @dataProvider provideProcessCases
     */
    public function testProcess($source, array $expectedTokens = array())
    {
        $this->makeTest($source, $expectedTokens);
    }

    public function provideProcessCases()
    {
        return array(
            array(
                '<?php use Foo;',
                array(
                    1 => 'T_USE',
                ),
            ),
            array(
                '<?php function foo() use ($bar) {}',
                array(
                    7 => 'CT_USE_LAMBDA',
                ),
            ),
            array(
                '<?php class Foo { use Bar; }',
                array(
                    7 => 'CT_USE_TRAIT',
                ),
            ),
            array(
                '<?php namespace Aaa; use Bbb; class Foo { use Bar; function baz() { $a=1; return function () use ($a) {}; } }',
                array(
                    6 => 'T_USE',
                    17 => 'CT_USE_TRAIT',
                    42 => 'CT_USE_LAMBDA',
                ),
            ),
        );
    }
}


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

public enum Direction {
    /**
     * DO NOT CHANGE ORDER
     */
    NORTH, EAST, SOUTH, WEST
}

redpajama_set_name: RedPajamaGithub


text:
package wsa.fromwsdl.dispatch.server;

import jakarta.jws.WebService;

/**
 * @author Rama Pulavarthi
 */
@WebService(endpointInterface="wsa.fromwsdl.dispatch.server.AddNumbersPortType")
public class AddNumbersImpl implements AddNumbersPortType {
    public AddNumbersResponse addNumbers1(AddNumbers parameters)
            throws AddNumbersFault_Exception {
        return doStuff(parameters);
    }

    public AddNumbersResponse addNumbers2(AddNumbers parameters)
            throws AddNumbersFault_Exception {
        return doStuff(parameters);
    }

    public AddNumbersResponse addNumbers3(AddNumbers parameters)
            throws AddNumbersFault_Exception {
        return doStuff(parameters);
    }

    public AddNumbersResponse addNumbers4(AddNumbers parameters)
            throws AddNumbersFault_Exception {
        return doStuff(parameters);
    }

    public void addNumbers5(AddNumbers parameters) {
        System.out.println("addNumbers5");
    }

    AddNumbersResponse doStuff(AddNumbers numbers) throws AddNumbersFault_Exception {
        int number1 = numbers.getNumber1();
        int number2 = numbers.getNumber2();
         if (number1 < 0 || number2 < 0) {
            ObjectFactory of = new ObjectFactory();
            AddNumbersFault fb = of.createAddNumbersFault();
            fb.setDetail("Negative numbers cant be added!");
            fb.setMessage("Numbers: " + number1 + ", " + number2);

            throw new AddNumbersFault_Exception(fb.getMessage(), fb);
        }
        AddNumbersResponse response =  new AddNumbersResponse();
        response.setReturn(number1 + number2);
        return response;
    }
}


text:
/*
 * Created on May 4, 2005
 *
 */
package iitb.BSegment;

import iitb.CRF.DataSequence;

/**
 * @author sunita
 *
 */
public interface BoundaryFeatureFunctions {
   // public void assignBoundary(BFeatureImpl feature, int pos);
    public int maxBoundaryGap();
    public void next(BFeatureImpl feature);
    public boolean startScanFeaturesAt(DataSequence data, int pos);
}


text:
package com.speakingfish.protocol.ssp.path;

import java.util.Iterator;

import com.speakingfish.common.function.Mapper;
import com.speakingfish.protocol.ssp.Any;
import com.speakingfish.protocol.ssp.AnyPathValue;
import com.speakingfish.protocol.ssp.PathValueVisitor;
import com.speakingfish.protocol.ssp.PathVisitor;

import static com.speakingfish.common.iterator.Iterators.*;

public class AnyPathListExprImpl<
    R, R_Any  extends Any<R>,
    T, T_Any  extends Any<T>,
    N, N_Any  extends Any<N>,
    T_SubPath extends AnyPathValue<
        R, R_Any,
        N, N_Any>
> extends AnyPathContinuationImpl<
    R, R_Any,
    T, T_Any,
    N, N_Any,
    T_SubPath
> {

    protected final Mapper<Iterator<N_Any>, T_Any> _selectNext;

    public AnyPathListExprImpl(T_Any value, Mapper<Iterator<N_Any>, T_Any> selectNext, T_SubPath next) {
        super(value, next);
        _selectNext = selectNext;
    }

    public void visitForward(PathValueVisitor<R, R_Any> visitor) {
        throw new UnsupportedOperationException();
    }

    public void visitBackward(PathValueVisitor<R, R_Any> visitor) {
        throw new UnsupportedOperationException();
    }

    public void visitForward(T_Any src, PathValueVisitor<R, R_Any> visitor) {
        final Iterator<N_Any> resultList = following(src);
        if(null != resultList) {
            for(final N_Any result : iterableOf(resultList)) {
                next().visitForward(result, visitor);
            }
        }
    }

    public void visitBackward(T_Any src, PathValueVisitor<R, R_Any> visitor) {
        throw new UnsupportedOperationException();
    }

    @Override public void visit(PathVisitor<R, R_Any> visitor) {
        throw new UnsupportedOperationException();
    }

    @Override public N_Any next(T_Any current) {
        final Iterator<N_Any> resultIterator = following(current);
        if(!resultIterator.hasNext()) {
            return null;
        }
        final N_Any result = resultIterator.next();
        if(resultIterator.hasNext()) {
            throw new UnsupportedOperationException();
        }
        return result;
    }

    @Override public R_Any value(T_Any src) {
        final Iterator<R_Any> resultIterator = values(src);
        if(!resultIterator.hasNext()) {
            return null;
        }
        final R_Any result = resultIterator.next();
        if(resultIterator.hasNext()) {
            throw new UnsupportedOperationException();
        }
        return result;
    }

    @Override public Iterator<N_Any> following(T_Any current) {
        return _selectNext.apply(current);
    }

    @Override public Iterator<R_Any> values(T_Any src) {
        // TODO Auto-generated method stub
        return super.values(src);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <import type="android.view.View"/>

        <variable
            name="companyvm"
            type="zaihuishou.com.expandablerecyclerviewmvvm.viewmodel.CompanyViewModel"/>

    </data>

    <RelativeLayout
        style="@style/ItemBg"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:onClick="@{()->companyvm.onCompanyClick()}">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="16dp"
            android:gravity="center_vertical"
            android:orientation="vertical"
            android:paddingLeft="16dp"
            android:text="@{companyvm.text}">
        </TextView>

        <ImageView
            android:id="@+id/arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="16dp"
            android:src="@mipmap/arrow_down"/>

    </RelativeLayout>
</layout>


text:
from PartyProblemSimulator.Solvers.Organisms.Genes.Gene import Gene

class BinaryGene(Gene):
    """ Represents a gene which can either be true of false. """

    def __init__(self, value):
        """ Instantiates this binary gene with the given value. """
        Gene.__init__(self, value)

    def mutate(self):
        """ Mutates this bit. """
        self.set_data(not self.get_data())

    def get_information(self):
        """ For binary genes the information is the same as the raw data (a boolean). """
        return self.get_data()


text:
import React from 'react';
import Item from './Item';
import ReactMarkdown from 'react-markdown';

export default class Note extends Item {

  render() {
    return (
      <div className={this.getStyles()}>
        <ReactMarkdown source={this.question.get('label')} escapeHtml={true} />
      </div>
    );
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using System.Web.Hosting;
using System.Web.Routing;
using System.Collections.Specialized;
using System.IO;

namespace Arch.CFX.Resource
{
    internal class ResourceRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new ResourceHandler();
        }
    }

    internal class ResourceHandler : IHttpHandler
    {

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            NameValueCollection par = context.Request.QueryString;
            var rfile = context.Request.RequestContext.RouteData.Values["file"];
            if (rfile != null)
            {
                string file = rfile.ToString();
                string extension = Path.GetExtension(file);
                IResource resource = null;
                resource = new FileResource(file, par);
                resource.Execute(context);
            }
            else
            {
                context.Response.StatusCode = 404;
            }
        }
    }
}


text:
//
//  RBaseTableViewModel.h
//  RAC-OC
//
//  Created by rogue on 2017/3/1.
//  Copyright © 2017年 RogueAndy. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@class RACCommand;

@interface RBaseTableViewModel : NSObject<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong, readonly) RACCommand *requestCommand;

/**
 得到返回的数组
 */
@property (nonatomic, strong, readonly) NSMutableArray *models;

/**
 填入需要发送的参数
 */
@property (nonatomic, strong) NSMutableDictionary *netParameters;

/**
 记录 Model 数据类型, 尽量在 RequestViewModel 的 init 方法里,在 [super init] 之前写入
 */
@property (nonatomic, strong, readonly) Class modelType;

/**
 记录 TableViewCell 类型, 尽量在 RequestViewModel 的 init 方法里,在 [super init] 之前写入
 */
@property (nonatomic, strong, readonly) Class cellType;

@property (nonatomic, strong) UITableView *table;

@property (nonatomic, assign) BOOL headLoading;

@property (nonatomic, assign) BOOL footerLoading;

@end


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
 * This file implements PKCS 11 on top of our existing security modules
 *
 * For more information about PKCS 11 See PKCS 11 Token Inteface Standard.
 *   This implementation has two slots:
 *	slot 1 is our generic crypto support. It does not require login
 *   (unless you've enabled FIPS). It supports Public Key ops, and all they
 *   bulk ciphers and hashes. It can also support Private Key ops for imported
 *   Private keys. It does not have any token storage.
 *	slot 2 is our private key support. It requires a login before use. It
 *   can store Private Keys and Certs as token objects. Currently only private
 *   keys and their associated Certificates are saved on the token.
 *
 *   In this implementation, session objects are only visible to the session
 *   that created or generated them.
 */
#include "seccomon.h"
#include "softoken.h"
#include "lowkeyi.h"
#include "pkcs11.h"
#include "pkcs11i.h"
#include "prenv.h"
#include "prprf.h"

#include <ctype.h>

#ifdef XP_UNIX
#define NSS_AUDIT_WITH_SYSLOG 1
#include <syslog.h>
#include <unistd.h>
#endif

#ifdef SOLARIS
#include <bsm/libbsm.h>
#define AUE_FIPS_AUDIT 34444
#endif

#ifdef LINUX
#include <pthread.h>
#include <dlfcn.h>
#define LIBAUDIT_NAME "libaudit.so.0"
#ifndef AUDIT_CRYPTO_TEST_USER
#define AUDIT_CRYPTO_TEST_USER          2400 /* Crypto test results */
#define AUDIT_CRYPTO_PARAM_CHANGE_USER  2401 /* Crypto attribute change */
#define AUDIT_CRYPTO_LOGIN              2402 /* Logged in as crypto officer */
#define AUDIT_CRYPTO_LOGOUT             2403 /* Logged out from crypto */
#define AUDIT_CRYPTO_KEY_USER           2404 /* Create,delete,negotiate */
#define AUDIT_CRYPTO_FAILURE_USER       2405 /* Fail decrypt,encrypt,randomize */
#endif
static void *libaudit_handle;
static int (*audit_open_func)(void);
static void (*audit_close_func)(int fd);
static int (*audit_log_user_message_func)(int audit_fd, int type,
    const char *message, const char *hostname, const char *addr,
    const char *tty, int result);
static int (*audit_send_user_message_func)(int fd, int type,
    const char *message);

static pthread_once_t libaudit_once_control = PTHREAD_ONCE_INIT;

static void
libaudit_init(void)
{
    libaudit_handle = dlopen(LIBAUDIT_NAME, RTLD_LAZY);
    if (!libaudit_handle) {
	return;
    }
    audit_open_func = dlsym(libaudit_handle, "audit_open");
    audit_close_func = dlsym(libaudit_handle, "audit_close");
    /*
     * audit_send_user_message is the older function.
     * audit_log_user_message, if available, is preferred.
     */
    audit_log_user_message_func = dlsym(libaudit_handle,
					"audit_log_user_message");
    if (!audit_log_user_message_func) {
	audit_send_user_message_func = dlsym(libaudit_handle,
					     "audit_send_user_message");
    }
    if (!audit_open_func || !audit_close_func ||
	(!audit_log_user_message_func && !audit_send_user_message_func)) {
	dlclose(libaudit_handle);
	libaudit_handle = NULL;
	audit_open_func = NULL;
	audit_close_func = NULL;
	audit_log_user_message_func = NULL;
	audit_send_user_message_func = NULL;
    }
}
#endif /* LINUX */

/*
 * ******************** Password Utilities *******************************
 */
static PRBool isLoggedIn = PR_FALSE;
PRBool sftk_fatalError = PR_FALSE;

/*
 * This function returns
 *   - CKR_PIN_INVALID if the password/PIN is not a legal UTF8 string
 *   - CKR_PIN_LEN_RANGE if the password/PIN is too short or does not
 *     consist of characters from three or more character classes.
 *   - CKR_OK otherwise
 *
 * The minimum password/PIN length is FIPS_MIN_PIN Unicode characters.
 * We define five character classes: digits (0-9), ASCII lowercase letters,
 * ASCII uppercase letters, ASCII non-alphanumeric characters (such as
 * space and punctuation marks), and non-ASCII characters.  If an ASCII
 * uppercase letter is the first character of the password/PIN, the
 * uppercase letter is not counted toward its character class.  Similarly,
 * if a digit is the last character of the password/PIN, the digit is not
 * counted toward its character class.
 *
 * Although NSC_SetPIN and NSC_InitPIN already do the maximum and minimum
 * password/PIN length checks, they check the length in bytes as opposed
 * to characters.  To meet the minimum password/PIN guessing probability
 * requirements in FIPS 140-2, we need to check the length in characters.
 */
static CK_RV sftk_newPinCheck(CK_CHAR_PTR pPin, CK_ULONG ulPinLen) {
    unsigned int i;
    int nchar = 0;      /* number of characters */
    int ntrail = 0;     /* number of trailing bytes to follow */
    int ndigit = 0;     /* number of decimal digits */
    int nlower = 0;     /* number of ASCII lowercase letters */
    int nupper = 0;     /* number of ASCII uppercase letters */
    int nnonalnum = 0;  /* number of ASCII non-alphanumeric characters */
    int nnonascii = 0;  /* number of non-ASCII characters */
    int nclass;         /* number of character classes */

    for (i = 0; i < ulPinLen; i++) {
	unsigned int byte = pPin[i];

	if (ntrail) {
	    if ((byte & 0xc0) != 0x80) {
		/* illegal */
		nchar = -1;
		break;
	    }
	    if (--ntrail == 0) {
		nchar++;
		nnonascii++;
	    }
	    continue;
	}
	if ((byte & 0x80) == 0x00) {
	    /* single-byte (ASCII) character */
	    nchar++;
	    if (isdigit(byte)) {
		if (i < ulPinLen - 1) {
		    ndigit++;
		}
	    } else if (islower(byte)) {
		nlower++;
	    } else if (isupper(byte)) {
		if (i > 0) {
		    nupper++;
		}
	    } else {
		nnonalnum++;
	    }
	} else if ((byte & 0xe0) == 0xc0) {
	    /* leading byte of two-byte character */
	    ntrail = 1;
	} else if ((byte & 0xf0) == 0xe0) {
	    /* leading byte of three-byte character */
	    ntrail = 2;
	} else if ((byte & 0xf8) == 0xf0) {
	    /* leading byte of four-byte character */
	    ntrail = 3;
	} else {
	    /* illegal */
	    nchar = -1;
	    break;
	}
    }
    if (nchar == -1) {
	/* illegal UTF8 string */
	return CKR_PIN_INVALID;
    }
    if (nchar < FIPS_MIN_PIN) {
	return CKR_PIN_LEN_RANGE;
    }
    nclass = (ndigit != 0) + (nlower != 0) + (nupper != 0) +
	     (nnonalnum != 0) + (nnonascii != 0);
    if (nclass < 3) {
	return CKR_PIN_LEN_RANGE;
    }
    return CKR_OK;
}

/* FIPS required checks before any useful cryptographic services */
static CK_RV sftk_fipsCheck(void) {
    if (sftk_fatalError)
	return CKR_DEVICE_ERROR;
    if (!isLoggedIn)
	return CKR_USER_NOT_LOGGED_IN;
    return CKR_OK;
}

#define SFTK_FIPSCHECK() \
    CK_RV rv; \
    if ((rv = sftk_fipsCheck()) != CKR_OK) return rv;

#define SFTK_FIPSFATALCHECK() \
    if (sftk_fatalError) return CKR_DEVICE_ERROR;

/* grab an attribute out of a raw template */
void *
fc_getAttribute(CK_ATTRIBUTE_PTR pTemplate,
				CK_ULONG ulCount, CK_ATTRIBUTE_TYPE type)
{
    int i;

    for (i=0; i < (int) ulCount; i++) {
	if (pTemplate[i].type == type) {
	    return pTemplate[i].pValue;
	}
    }
    return NULL;
}

#define __PASTE(x,y)	x##y

/* ------------- forward declare all the NSC_ functions ------------- */
#undef CK_NEED_ARG_LIST
#undef CK_PKCS11_FUNCTION_INFO

#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(NS,name)
#define CK_NEED_ARG_LIST 1

#include "pkcs11f.h"

/* ------------- forward declare all the FIPS functions ------------- */
#undef CK_NEED_ARG_LIST
#undef CK_PKCS11_FUNCTION_INFO

#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(F,name)
#define CK_NEED_ARG_LIST 1

#include "pkcs11f.h"

/* ------------- build the CK_CRYPTO_TABLE ------------------------- */
static CK_FUNCTION_LIST sftk_fipsTable = {
    { 1, 10 },

#undef CK_NEED_ARG_LIST
#undef CK_PKCS11_FUNCTION_INFO

#define CK_PKCS11_FUNCTION_INFO(name) __PASTE(F,name),

#include "pkcs11f.h"

};

#undef CK_NEED_ARG_LIST
#undef CK_PKCS11_FUNCTION_INFO

#undef __PASTE

/* CKO_NOT_A_KEY can be any object class that's not a key object. */
#define CKO_NOT_A_KEY CKO_DATA

#define SFTK_IS_KEY_OBJECT(objClass) \
    (((objClass) == CKO_PUBLIC_KEY) || \
    ((objClass) == CKO_PRIVATE_KEY) || \
    ((objClass) == CKO_SECRET_KEY))

#define SFTK_IS_NONPUBLIC_KEY_OBJECT(objClass) \
    (((objClass) == CKO_PRIVATE_KEY) || ((objClass) == CKO_SECRET_KEY))

static CK_RV
sftk_get_object_class_and_fipsCheck(CK_SESSION_HANDLE hSession,
    CK_OBJECT_HANDLE hObject, CK_OBJECT_CLASS *pObjClass)
{
    CK_RV rv;
    CK_ATTRIBUTE class;
    class.type = CKA_CLASS;
    class.pValue = pObjClass;
    class.ulValueLen = sizeof(*pObjClass);
    rv = NSC_GetAttributeValue(hSession, hObject, &class, 1);
    if ((rv == CKR_OK) && SFTK_IS_NONPUBLIC_KEY_OBJECT(*pObjClass)) {
	rv = sftk_fipsCheck();
    }
    return rv;
}

#ifdef LINUX

int
sftk_mapLinuxAuditType(NSSAuditSeverity severity, NSSAuditType auditType)
{
    switch (auditType) {
    case NSS_AUDIT_ACCESS_KEY:
    case NSS_AUDIT_CHANGE_KEY:
    case NSS_AUDIT_COPY_KEY:
    case NSS_AUDIT_DERIVE_KEY:
    case NSS_AUDIT_DESTROY_KEY:
    case NSS_AUDIT_DIGEST_KEY:
    case NSS_AUDIT_GENERATE_KEY:
    case NSS_AUDIT_LOAD_KEY:
    case NSS_AUDIT_UNWRAP_KEY:
    case NSS_AUDIT_WRAP_KEY:
	return AUDIT_CRYPTO_KEY_USER;
    case NSS_AUDIT_CRYPT:
	return (severity == NSS_AUDIT_ERROR) ? AUDIT_CRYPTO_FAILURE_USER :
					 AUDIT_CRYPTO_KEY_USER;
    case NSS_AUDIT_FIPS_STATE:
    case NSS_AUDIT_INIT_PIN:
    case NSS_AUDIT_INIT_TOKEN:
    case NSS_AUDIT_SET_PIN:
	return AUDIT_CRYPTO_PARAM_CHANGE_USER;
    case NSS_AUDIT_SELF_TEST:
	return AUDIT_CRYPTO_TEST_USER;
    case NSS_AUDIT_LOGIN:
	return AUDIT_CRYPTO_LOGIN;
    case NSS_AUDIT_LOGOUT:
	return AUDIT_CRYPTO_LOGOUT;
    /* we skip the fault case here so we can get compiler
     * warnings if new 'NSSAuditType's are added without
     * added them to this list, defaults fall through */
    }
    /* default */
    return AUDIT_CRYPTO_PARAM_CHANGE_USER;
}
#endif

/**********************************************************************
 *
 *     FIPS 140 auditable event logging
 *
 **********************************************************************/

PRBool sftk_audit_enabled = PR_FALSE;

/*
 * Each audit record must have the following information:
 * - Date and time of the event
 * - Type of event
 * - user (subject) identity
 * - outcome (success or failure) of the event
 * - process ID
 * - name (ID) of the object
 * - for changes to data (except for authentication data and CSPs), the new
 *   and old values of the data
 * - for authentication attempts, the origin of the attempt (e.g., terminal
 *   identifier)
 * - for assuming a role, the type of role, and the location of the request
 */
void
sftk_LogAuditMessage(NSSAuditSeverity severity, NSSAuditType auditType,
		     const char *msg)
{
#ifdef NSS_AUDIT_WITH_SYSLOG
    int level;

    switch (severity) {
    case NSS_AUDIT_ERROR:
	level = LOG_ERR;
	break;
    case NSS_AUDIT_WARNING:
	level = LOG_WARNING;
	break;
    default:
	level = LOG_INFO;
	break;
    }
    /* timestamp is provided by syslog in the message header */
    syslog(level | LOG_USER /* facility */,
	   "NSS " SOFTOKEN_LIB_NAME "[pid=%d uid=%d]: %s",
	   (int)getpid(), (int)getuid(), msg);
#ifdef LINUX
    if (pthread_once(&libaudit_once_control, libaudit_init) != 0) {
	return;
    }
    if (libaudit_handle) {
	int audit_fd;
	int linuxAuditType;
	int result = (severity != NSS_AUDIT_ERROR); /* 1=success; 0=failed */
	char *message = PR_smprintf("NSS " SOFTOKEN_LIB_NAME ": %s", msg);
	if (!message) {
	    return;
	}
	audit_fd = audit_open_func();
	if (audit_fd < 0) {
	    PR_smprintf_free(message);
	    return;
	}
	linuxAuditType = sftk_mapLinuxAuditType(severity, auditType);
	if (audit_log_user_message_func) {
	    audit_log_user_message_func(audit_fd, linuxAuditType, message,
					NULL, NULL, NULL, result);
	} else {
	    audit_send_user_message_func(audit_fd, linuxAuditType, message);
	}
	audit_close_func(audit_fd);
	PR_smprintf_free(message);
    }
#endif /* LINUX */
#ifdef SOLARIS
    {
        int rd;
        char *message = PR_smprintf("NSS " SOFTOKEN_LIB_NAME ": %s", msg);

        if (!message) {
            return;
        }

        /* open the record descriptor */
        if ((rd = au_open()) == -1) {
            PR_smprintf_free(message);
            return;
        }

        /* write the audit tokens to the audit record */
        if (au_write(rd, au_to_text(message))) {
            (void)au_close(rd, AU_TO_NO_WRITE, AUE_FIPS_AUDIT);
            PR_smprintf_free(message);
            return;
        }

        /* close the record and send it to the audit trail */
        (void)au_close(rd, AU_TO_WRITE, AUE_FIPS_AUDIT);

        PR_smprintf_free(message);
    }
#endif /* SOLARIS */
#else
    /* do nothing */
#endif
}

/**********************************************************************
 *
 *     Start of PKCS 11 functions
 *
 **********************************************************************/
/* return the function list */
CK_RV FC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) {

    CHECK_FORK();

    *pFunctionList = &sftk_fipsTable;
    return CKR_OK;
}

/* sigh global so pkcs11 can read it */
PRBool nsf_init = PR_FALSE;

/* FC_Initialize initializes the PKCS #11 library. */
CK_RV FC_Initialize(CK_VOID_PTR pReserved) {
    const char *envp;
    CK_RV crv;

    sftk_ForkReset(pReserved, &crv);

    if (nsf_init) {
	return CKR_CRYPTOKI_ALREADY_INITIALIZED;
    }

    if ((envp = PR_GetEnv("NSS_ENABLE_AUDIT")) != NULL) {
	sftk_audit_enabled = (atoi(envp) == 1);
    }

    crv = nsc_CommonInitialize(pReserved, PR_TRUE);

    /* not an 'else' rv can be set by either SFTK_LowInit or SFTK_SlotInit*/
    if (crv != CKR_OK) {
	sftk_fatalError = PR_TRUE;
	return crv;
    }

    sftk_fatalError = PR_FALSE; /* any error has been reset */

    crv = sftk_fipsPowerUpSelfTest();
    if (crv != CKR_OK) {
        nsc_CommonFinalize(NULL, PR_TRUE);
	sftk_fatalError = PR_TRUE;
	if (sftk_audit_enabled) {
	    char msg[128];
	    PR_snprintf(msg,sizeof msg,
			"C_Initialize()=0x%08lX "
			"power-up self-tests failed",
			(PRUint32)crv);
	    sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg);
	}
	return crv;
    }
    nsf_init = PR_TRUE;

    return CKR_OK;
}

/*FC_Finalize indicates that an application is done with the PKCS #11 library.*/
CK_RV FC_Finalize (CK_VOID_PTR pReserved) {
   CK_RV crv;

   if (sftk_ForkReset(pReserved, &crv)) {
       return crv;
   }

   if (!nsf_init) {
      return CKR_OK;
   }

   crv = nsc_CommonFinalize (pReserved, PR_TRUE);

   nsf_init = (PRBool) !(crv == CKR_OK);
   return crv;
}

/* FC_GetInfo returns general information about PKCS #11. */
CK_RV  FC_GetInfo(CK_INFO_PTR pInfo) {
    CHECK_FORK();

    return NSC_GetInfo(pInfo);
}

/* FC_GetSlotList obtains a list of slots in the system. */
CK_RV FC_GetSlotList(CK_BBOOL tokenPresent,
	 		CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) {
    CHECK_FORK();

    return nsc_CommonGetSlotList(tokenPresent,pSlotList,pulCount,
							 NSC_FIPS_MODULE);
}

/* FC_GetSlotInfo obtains information about a particular slot in the system. */
CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) {
    CHECK_FORK();

    return NSC_GetSlotInfo(slotID,pInfo);
}

/*FC_GetTokenInfo obtains information about a particular token in the system.*/
 CK_RV FC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo) {
    CK_RV crv;

    CHECK_FORK();

    crv = NSC_GetTokenInfo(slotID,pInfo);
    if (crv == CKR_OK)
       pInfo->flags |= CKF_LOGIN_REQUIRED;
    return crv;

}

/*FC_GetMechanismList obtains a list of mechanism types supported by a token.*/
 CK_RV FC_GetMechanismList(CK_SLOT_ID slotID,
	CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pusCount) {
     CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID;
    /* FIPS Slot supports all functions */
    return NSC_GetMechanismList(slotID,pMechanismList,pusCount);
}

/* FC_GetMechanismInfo obtains information about a particular mechanism
 * possibly supported by a token. */
 CK_RV FC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type,
    					CK_MECHANISM_INFO_PTR pInfo) {
    CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID;
    /* FIPS Slot supports all functions */
    return NSC_GetMechanismInfo(slotID,type,pInfo);
}

/* FC_InitToken initializes a token. */
 CK_RV FC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin,
 				CK_ULONG usPinLen,CK_CHAR_PTR pLabel) {
    CK_RV crv;

    CHECK_FORK();

    crv = NSC_InitToken(slotID,pPin,usPinLen,pLabel);
    if (sftk_audit_enabled) {
	char msg[128];
	NSSAuditSeverity severity = (crv == CKR_OK) ?
		NSS_AUDIT_INFO : NSS_AUDIT_ERROR;
	/* pLabel points to a 32-byte label, which is not null-terminated */
	PR_snprintf(msg,sizeof msg,
		"C_InitToken(slotID=%lu, pLabel=\"%.32s\")=0x%08lX",
		(PRUint32)slotID,pLabel,(PRUint32)crv);
	sftk_LogAuditMessage(severity, NSS_AUDIT_INIT_TOKEN, msg);
    }
    return crv;
}

/* FC_InitPIN initializes the normal user's PIN. */
 CK_RV FC_InitPIN(CK_SESSION_HANDLE hSession,
    					CK_CHAR_PTR pPin, CK_ULONG ulPinLen) {
    CK_RV rv;

    CHECK_FORK();

    if (sftk_fatalError) return CKR_DEVICE_ERROR;
    if ((rv = sftk_newPinCheck(pPin,ulPinLen)) == CKR_OK) {
	rv = NSC_InitPIN(hSession,pPin,ulPinLen);
    }
    if (sftk_audit_enabled) {
	char msg[128];
	NSSAuditSeverity severity = (rv == CKR_OK) ?
		NSS_AUDIT_INFO : NSS_AUDIT_ERROR;
	PR_snprintf(msg,sizeof msg,
		"C_InitPIN(hSession=0x%08lX)=0x%08lX",
		(PRUint32)hSession,(PRUint32)rv);
	sftk_LogAuditMessage(severity, NSS_AUDIT_INIT_PIN, msg);
    }
    return rv;
}

/* FC_SetPIN modifies the PIN of user that is currently logged in. */
/* NOTE: This is only valid for the PRIVATE_KEY_SLOT */
 CK_RV FC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin,
    CK_ULONG usOldLen, CK_CHAR_PTR pNewPin, CK_ULONG usNewLen) {
    CK_RV rv;

    CHECK_FORK();

    if ((rv = sftk_fipsCheck()) == CKR_OK &&
	(rv = sftk_newPinCheck(pNewPin,usNewLen)) == CKR_OK) {
	rv = NSC_SetPIN(hSession,pOldPin,usOldLen,pNewPin,usNewLen);
    }
    if (sftk_audit_enabled) {
	char msg[128];
	NSSAuditSeverity severity = (rv == CKR_OK) ?
		NSS_AUDIT_INFO : NSS_AUDIT_ERROR;
	PR_snprintf(msg,sizeof msg,
		"C_SetPIN(hSession=0x%08lX)=0x%08lX",
		(PRUint32)hSession,(PRUint32)rv);
	sftk_LogAuditMessage(severity, NSS_AUDIT_SET_PIN, msg);
    }
    return rv;
}

/* FC_OpenSession opens a session between an application and a token. */
 CK_RV FC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags,
   CK_VOID_PTR pApplication,CK_NOTIFY Notify,CK_SESSION_HANDLE_PTR phSession) {
    SFTK_FIPSFATALCHECK();

    CHECK_FORK();

    return NSC_OpenSession(slotID,flags,pApplication,Notify,phSession);
}

/* FC_CloseSession closes a session between an application and a token. */
 CK_RV FC_CloseSession(CK_SESSION_HANDLE hSession) {
    CHECK_FORK();

    return NSC_CloseSession(hSession);
}

/* FC_CloseAllSessions closes all sessions with a token. */
 CK_RV FC_CloseAllSessions (CK_SLOT_ID slotID) {

    CHECK_FORK();

    return NSC_CloseAllSessions (slotID);
}

/* FC_GetSessionInfo obtains information about the session. */
 CK_RV FC_GetSessionInfo(CK_SESSION_HANDLE hSession,
						CK_SESSION_INFO_PTR pInfo) {
    CK_RV rv;
    SFTK_FIPSFATALCHECK();

    CHECK_FORK();

    rv = NSC_GetSessionInfo(hSession,pInfo);
    if (rv == CKR_OK) {
	if ((isLoggedIn) && (pInfo->state == CKS_RO_PUBLIC_SESSION)) {
		pInfo->state = CKS_RO_USER_FUNCTIONS;
	}
	if ((isLoggedIn) && (pInfo->state == CKS_RW_PUBLIC_SESSION)) {
		pInfo->state = CKS_RW_USER_FUNCTIONS;
	}
    }
    return rv;
}

/* FC_Login logs a user into a token. */
 CK_RV FC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType,
				    CK_CHAR_PTR pPin, CK_ULONG usPinLen) {
    CK_RV rv;
    PRBool successful;
    if (sftk_fatalError) return CKR_DEVICE_ERROR;
    rv = NSC_Login(hSession,userType,pPin,usPinLen);
    successful = (rv == CKR_OK) || (rv == CKR_USER_ALREADY_LOGGED_IN);
    if (successful)
	isLoggedIn = PR_TRUE;
    if (sftk_audit_enabled) {
	char msg[128];
	NSSAuditSeverity severity;
	severity = successful ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR;
	PR_snprintf(msg,sizeof msg,
		    "C_Login(hSession=0x%08lX, userType=%lu)=0x%08lX",
		    (PRUint32)hSession,(PRUint32)userType,(PRUint32)rv);
	sftk_LogAuditMessage(severity, NSS_AUDIT_LOGIN, msg);
    }
    return rv;
}

/* FC_Logout logs a user out from a token. */
 CK_RV FC_Logout(CK_SESSION_HANDLE hSession) {
    CK_RV rv;

    CHECK_FORK();

    if ((rv = sftk_fipsCheck()) == CKR_OK) {
	rv = NSC_Logout(hSession);
	isLoggedIn = PR_FALSE;
    }
    if (sftk_audit_enabled) {
	char msg[128];
	NSSAuditSeverity severity = (rv == CKR_OK) ?
		NSS_AUDIT_INFO : NSS_AUDIT_ERROR;
	PR_snprintf(msg,sizeof msg,
		    "C_Logout(hSession=0x%08lX)=0x%08lX",
		    (PRUint32)hSession,(PRUint32)rv);
	sftk_LogAuditMessage(severity, NSS_AUDIT_LOGOUT, msg);
    }
    return rv;
}

/* FC_CreateObject creates a new object. */
 CK_RV FC_CreateObject(CK_SESSION_HANDLE hSession,
		CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
					CK_OBJECT_HANDLE_PTR phObject) {
    CK_OBJECT_CLASS * classptr;

    SFTK_FIPSCHECK();
    CHECK_FORK();

    classptr = (CK_OBJECT_CLASS *)fc_getAttribute(pTemplate,ulCount,CKA_CLASS);
    if (classptr == NULL) return CKR_TEMPLATE_INCOMPLETE;

    /* FIPS can't create keys from raw key material */
    if (SFTK_IS_NONPUBLIC_KEY_OBJECT(*classptr)) {
	rv = CKR_ATTRIBUTE_VALUE_INVALID;
    } else {
	rv = NSC_CreateObject(hSession,pTemplate,ulCount,phObject);
    }
    if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(*classptr)) {
	sftk_AuditCreateObject(hSession,pTemplate,ulCount,phObject,rv);
    }
    return rv;
}

/* FC_CopyObject copies an object, creating a new object for the copy. */
 CK_RV FC_CopyObject(CK_SESSION_HANDLE hSession,
       CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
					CK_OBJECT_HANDLE_PTR phNewObject) {
    CK_RV rv;
    CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY;

    CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass);
    if (rv == CKR_OK) {
	rv = NSC_CopyObject(hSession,hObject,pTemplate,ulCount,phNewObject);
    }
    if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) {
	sftk_AuditCopyObject(hSession,
	    hObject,pTemplate,ulCount,phNewObject,rv);
    }
    return rv;
}

/* FC_DestroyObject destroys an object. */
 CK_RV FC_DestroyObject(CK_SESSION_HANDLE hSession,
		 				CK_OBJECT_HANDLE hObject) {
    CK_RV rv;
    CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY;

    CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass);
    if (rv == CKR_OK) {
	rv = NSC_DestroyObject(hSession,hObject);
    }
    if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) {
	sftk_AuditDestroyObject(hSession,hObject,rv);
    }
    return rv;
}

/* FC_GetObjectSize gets the size of an object in bytes. */
 CK_RV FC_GetObjectSize(CK_SESSION_HANDLE hSession,
    			CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) {
    CK_RV rv;
    CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY;

    CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass);
    if (rv == CKR_OK) {
	rv = NSC_GetObjectSize(hSession, hObject, pulSize);
    }
    if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) {
	sftk_AuditGetObjectSize(hSession, hObject, pulSize, rv);
    }
    return rv;
}

/* FC_GetAttributeValue obtains the value of one or more object attributes. */
 CK_RV FC_GetAttributeValue(CK_SESSION_HANDLE hSession,
 CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) {
    CK_RV rv;
    CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY;

    CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass);
    if (rv == CKR_OK) {
	rv = NSC_GetAttributeValue(hSession,hObject,pTemplate,ulCount);
    }
    if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) {
	sftk_AuditGetAttributeValue(hSession,hObject,pTemplate,ulCount,rv);
    }
    return rv;
}

/* FC_SetAttributeValue modifies the value of one or more object attributes */
 CK_RV FC_SetAttributeValue (CK_SESSION_HANDLE hSession,
 CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) {
    CK_RV rv;
    CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY;

    CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass);
    if (rv == CKR_OK) {
	rv = NSC_SetAttributeValue(hSession,hObject,pTemplate,ulCount);
    }
    if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) {
	sftk_AuditSetAttributeValue(hSession,hObject,pTemplate,ulCount,rv);
    }
    return rv;
}

/* FC_FindObjectsInit initializes a search for token and session objects
 * that match a template. */
 CK_RV FC_FindObjectsInit(CK_SESSION_HANDLE hSession,
    			CK_ATTRIBUTE_PTR pTemplate,CK_ULONG usCount) {
    /* let publically readable object be found */
    unsigned int i;
    CK_RV rv;
    PRBool needLogin = PR_FALSE;

    CHECK_FORK();

    SFTK_FIPSFATALCHECK();

    for (i=0; i < usCount; i++) {
	CK_OBJECT_CLASS class;
	if (pTemplate[i].type != CKA_CLASS) {
	    continue;
	}
	if (pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS)) {
	    continue;
	}
	if (pTemplate[i].pValue == NULL) {
	    continue;
	}
	class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue;
	if ((class == CKO_PRIVATE_KEY) || (class == CKO_SECRET_KEY)) {
	    needLogin = PR_TRUE;
	    break;
	}
    }
    if (needLogin) {
	if ((rv = sftk_fipsCheck()) != CKR_OK) return rv;
    }
    return NSC_FindObjectsInit(hSession,pTemplate,usCount);
}

/* FC_FindObjects continues a search for token and session objects
 * that match a template, obtaining additional object handles. */
 CK_RV FC_FindObjects(CK_SESSION_HANDLE hSession,
    CK_OBJECT_HANDLE_PTR phObject,CK_ULONG usMaxObjectCount,
    					CK_ULONG_PTR pusObjectCount) {
    CHECK_FORK();

    /* let publically readable object be found */
    SFTK_FIPSFATALCHECK();
    return NSC_FindObjects(hSession,phObject,usMaxObjectCount,
    							pusObjectCount);
}

/*
 ************** Crypto Functions:     Encrypt ************************
 */

/* FC_EncryptInit initializes an encryption operation. */
 CK_RV FC_EncryptInit(CK_SESSION_HANDLE hSession,
		 CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_EncryptInit(hSession,pMechanism,hKey);
    if (sftk_audit_enabled) {
	sftk_AuditCryptInit("Encrypt",hSession,pMechanism,hKey,rv);
    }
    return rv;
}

/* FC_Encrypt encrypts single-part data. */
 CK_RV FC_Encrypt (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
    		CK_ULONG usDataLen, CK_BYTE_PTR pEncryptedData,
					 CK_ULONG_PTR pusEncryptedDataLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_Encrypt(hSession,pData,usDataLen,pEncryptedData,
							pusEncryptedDataLen);
}

/* FC_EncryptUpdate continues a multiple-part encryption operation. */
 CK_RV FC_EncryptUpdate(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR pPart, CK_ULONG usPartLen, CK_BYTE_PTR pEncryptedPart,
					CK_ULONG_PTR pusEncryptedPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_EncryptUpdate(hSession,pPart,usPartLen,pEncryptedPart,
						pusEncryptedPartLen);
}

/* FC_EncryptFinal finishes a multiple-part encryption operation. */
 CK_RV FC_EncryptFinal(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pusLastEncryptedPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_EncryptFinal(hSession,pLastEncryptedPart,
						pusLastEncryptedPartLen);
}

/*
 ************** Crypto Functions:     Decrypt ************************
 */

/* FC_DecryptInit initializes a decryption operation. */
 CK_RV FC_DecryptInit( CK_SESSION_HANDLE hSession,
			 CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_DecryptInit(hSession,pMechanism,hKey);
    if (sftk_audit_enabled) {
	sftk_AuditCryptInit("Decrypt",hSession,pMechanism,hKey,rv);
    }
    return rv;
}

/* FC_Decrypt decrypts encrypted data in a single part. */
 CK_RV FC_Decrypt(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR pEncryptedData,CK_ULONG usEncryptedDataLen,CK_BYTE_PTR pData,
    						CK_ULONG_PTR pusDataLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_Decrypt(hSession,pEncryptedData,usEncryptedDataLen,pData,
    								pusDataLen);
}

/* FC_DecryptUpdate continues a multiple-part decryption operation. */
 CK_RV FC_DecryptUpdate(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR pEncryptedPart, CK_ULONG usEncryptedPartLen,
    				CK_BYTE_PTR pPart, CK_ULONG_PTR pusPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_DecryptUpdate(hSession,pEncryptedPart,usEncryptedPartLen,
    							pPart,pusPartLen);
}

/* FC_DecryptFinal finishes a multiple-part decryption operation. */
 CK_RV FC_DecryptFinal(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR pLastPart, CK_ULONG_PTR pusLastPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_DecryptFinal(hSession,pLastPart,pusLastPartLen);
}

/*
 ************** Crypto Functions:     Digest (HASH)  ************************
 */

/* FC_DigestInit initializes a message-digesting operation. */
 CK_RV FC_DigestInit(CK_SESSION_HANDLE hSession,
    					CK_MECHANISM_PTR pMechanism) {
    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    return NSC_DigestInit(hSession, pMechanism);
}

/* FC_Digest digests data in a single part. */
 CK_RV FC_Digest(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR pData, CK_ULONG usDataLen, CK_BYTE_PTR pDigest,
    						CK_ULONG_PTR pusDigestLen) {
    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    return NSC_Digest(hSession,pData,usDataLen,pDigest,pusDigestLen);
}

/* FC_DigestUpdate continues a multiple-part message-digesting operation. */
 CK_RV FC_DigestUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart,
					    CK_ULONG usPartLen) {
    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    return NSC_DigestUpdate(hSession,pPart,usPartLen);
}

/* FC_DigestFinal finishes a multiple-part message-digesting operation. */
 CK_RV FC_DigestFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pDigest,
    						CK_ULONG_PTR pusDigestLen) {
    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    return NSC_DigestFinal(hSession,pDigest,pusDigestLen);
}

/*
 ************** Crypto Functions:     Sign  ************************
 */

/* FC_SignInit initializes a signature (private key encryption) operation,
 * where the signature is (will be) an appendix to the data,
 * and plaintext cannot be recovered from the signature */
 CK_RV FC_SignInit(CK_SESSION_HANDLE hSession,
		 CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_SignInit(hSession,pMechanism,hKey);
    if (sftk_audit_enabled) {
	sftk_AuditCryptInit("Sign",hSession,pMechanism,hKey,rv);
    }
    return rv;
}

/* FC_Sign signs (encrypts with private key) data in a single part,
 * where the signature is (will be) an appendix to the data,
 * and plaintext cannot be recovered from the signature */
 CK_RV FC_Sign(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR pData,CK_ULONG usDataLen,CK_BYTE_PTR pSignature,
    					CK_ULONG_PTR pusSignatureLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_Sign(hSession,pData,usDataLen,pSignature,pusSignatureLen);
}

/* FC_SignUpdate continues a multiple-part signature operation,
 * where the signature is (will be) an appendix to the data,
 * and plaintext cannot be recovered from the signature */
 CK_RV FC_SignUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart,
    							CK_ULONG usPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_SignUpdate(hSession,pPart,usPartLen);
}

/* FC_SignFinal finishes a multiple-part signature operation,
 * returning the signature. */
 CK_RV FC_SignFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pSignature,
					    CK_ULONG_PTR pusSignatureLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_SignFinal(hSession,pSignature,pusSignatureLen);
}

/*
 ************** Crypto Functions:     Sign Recover  ************************
 */
/* FC_SignRecoverInit initializes a signature operation,
 * where the (digest) data can be recovered from the signature.
 * E.g. encryption with the user's private key */
 CK_RV FC_SignRecoverInit(CK_SESSION_HANDLE hSession,
			 CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_SignRecoverInit(hSession,pMechanism,hKey);
    if (sftk_audit_enabled) {
	sftk_AuditCryptInit("SignRecover",hSession,pMechanism,hKey,rv);
    }
    return rv;
}

/* FC_SignRecover signs data in a single operation
 * where the (digest) data can be recovered from the signature.
 * E.g. encryption with the user's private key */
 CK_RV FC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
  CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pusSignatureLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_SignRecover(hSession,pData,usDataLen,pSignature,pusSignatureLen);
}

/*
 ************** Crypto Functions:     verify  ************************
 */

/* FC_VerifyInit initializes a verification operation,
 * where the signature is an appendix to the data,
 * and plaintext cannot be recovered from the signature (e.g. DSA) */
 CK_RV FC_VerifyInit(CK_SESSION_HANDLE hSession,
			   CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_VerifyInit(hSession,pMechanism,hKey);
    if (sftk_audit_enabled) {
	sftk_AuditCryptInit("Verify",hSession,pMechanism,hKey,rv);
    }
    return rv;
}

/* FC_Verify verifies a signature in a single-part operation,
 * where the signature is an appendix to the data,
 * and plaintext cannot be recovered from the signature */
 CK_RV FC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
    CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG usSignatureLen) {
    /* make sure we're legal */
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_Verify(hSession,pData,usDataLen,pSignature,usSignatureLen);
}

/* FC_VerifyUpdate continues a multiple-part verification operation,
 * where the signature is an appendix to the data,
 * and plaintext cannot be recovered from the signature */
 CK_RV FC_VerifyUpdate( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart,
						CK_ULONG usPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_VerifyUpdate(hSession,pPart,usPartLen);
}

/* FC_VerifyFinal finishes a multiple-part verification operation,
 * checking the signature. */
 CK_RV FC_VerifyFinal(CK_SESSION_HANDLE hSession,
			CK_BYTE_PTR pSignature,CK_ULONG usSignatureLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_VerifyFinal(hSession,pSignature,usSignatureLen);
}

/*
 ************** Crypto Functions:     Verify  Recover ************************
 */

/* FC_VerifyRecoverInit initializes a signature verification operation,
 * where the data is recovered from the signature.
 * E.g. Decryption with the user's public key */
 CK_RV FC_VerifyRecoverInit(CK_SESSION_HANDLE hSession,
			CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_VerifyRecoverInit(hSession,pMechanism,hKey);
    if (sftk_audit_enabled) {
	sftk_AuditCryptInit("VerifyRecover",hSession,pMechanism,hKey,rv);
    }
    return rv;
}

/* FC_VerifyRecover verifies a signature in a single-part operation,
 * where the data is recovered from the signature.
 * E.g. Decryption with the user's public key */
 CK_RV FC_VerifyRecover(CK_SESSION_HANDLE hSession,
		 CK_BYTE_PTR pSignature,CK_ULONG usSignatureLen,
    				CK_BYTE_PTR pData,CK_ULONG_PTR pusDataLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_VerifyRecover(hSession,pSignature,usSignatureLen,pData,
								pusDataLen);
}

/*
 **************************** Key Functions:  ************************
 */

/* FC_GenerateKey generates a secret key, creating a new key object. */
 CK_RV FC_GenerateKey(CK_SESSION_HANDLE hSession,
    CK_MECHANISM_PTR pMechanism,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount,
    						CK_OBJECT_HANDLE_PTR phKey) {
    CK_BBOOL *boolptr;

    SFTK_FIPSCHECK();
    CHECK_FORK();

    /* all secret keys must be sensitive, if the upper level code tries to say
     * otherwise, reject it. */
    boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate, ulCount, CKA_SENSITIVE);
    if (boolptr != NULL) {
	if (!(*boolptr)) {
	    return CKR_ATTRIBUTE_VALUE_INVALID;
	}
    }

    rv = NSC_GenerateKey(hSession,pMechanism,pTemplate,ulCount,phKey);
    if (sftk_audit_enabled) {
	sftk_AuditGenerateKey(hSession,pMechanism,pTemplate,ulCount,phKey,rv);
    }
    return rv;
}

/* FC_GenerateKeyPair generates a public-key/private-key pair,
 * creating new key objects. */
 CK_RV FC_GenerateKeyPair (CK_SESSION_HANDLE hSession,
    CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate,
    CK_ULONG usPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate,
    CK_ULONG usPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey,
					CK_OBJECT_HANDLE_PTR phPrivateKey) {
    CK_BBOOL *boolptr;
    CK_RV crv;

    SFTK_FIPSCHECK();
    CHECK_FORK();

    /* all private keys must be sensitive, if the upper level code tries to say
     * otherwise, reject it. */
    boolptr = (CK_BBOOL *) fc_getAttribute(pPrivateKeyTemplate,
				usPrivateKeyAttributeCount, CKA_SENSITIVE);
    if (boolptr != NULL) {
	if (!(*boolptr)) {
	    return CKR_ATTRIBUTE_VALUE_INVALID;
	}
    }
    crv = NSC_GenerateKeyPair (hSession,pMechanism,pPublicKeyTemplate,
    		usPublicKeyAttributeCount,pPrivateKeyTemplate,
		usPrivateKeyAttributeCount,phPublicKey,phPrivateKey);
    if (crv == CKR_GENERAL_ERROR) {
	/* pairwise consistency check failed. */
	sftk_fatalError = PR_TRUE;
    }
    if (sftk_audit_enabled) {
	sftk_AuditGenerateKeyPair(hSession,pMechanism,pPublicKeyTemplate,
    		usPublicKeyAttributeCount,pPrivateKeyTemplate,
		usPrivateKeyAttributeCount,phPublicKey,phPrivateKey,crv);
    }
    return crv;
}

/* FC_WrapKey wraps (i.e., encrypts) a key. */
 CK_RV FC_WrapKey(CK_SESSION_HANDLE hSession,
    CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey,
    CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey,
					 CK_ULONG_PTR pulWrappedKeyLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_WrapKey(hSession,pMechanism,hWrappingKey,hKey,pWrappedKey,
							pulWrappedKeyLen);
    if (sftk_audit_enabled) {
	sftk_AuditWrapKey(hSession,pMechanism,hWrappingKey,hKey,pWrappedKey,
							pulWrappedKeyLen,rv);
    }
    return rv;
}

/* FC_UnwrapKey unwraps (decrypts) a wrapped key, creating a new key object. */
 CK_RV FC_UnwrapKey(CK_SESSION_HANDLE hSession,
    CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey,
    CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen,
    CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount,
						 CK_OBJECT_HANDLE_PTR phKey) {
    CK_BBOOL *boolptr;

    SFTK_FIPSCHECK();
    CHECK_FORK();

    /* all secret keys must be sensitive, if the upper level code tries to say
     * otherwise, reject it. */
    boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate,
					ulAttributeCount, CKA_SENSITIVE);
    if (boolptr != NULL) {
	if (!(*boolptr)) {
	    return CKR_ATTRIBUTE_VALUE_INVALID;
	}
    }
    rv = NSC_UnwrapKey(hSession,pMechanism,hUnwrappingKey,pWrappedKey,
			ulWrappedKeyLen,pTemplate,ulAttributeCount,phKey);
    if (sftk_audit_enabled) {
	sftk_AuditUnwrapKey(hSession,pMechanism,hUnwrappingKey,pWrappedKey,
			ulWrappedKeyLen,pTemplate,ulAttributeCount,phKey,rv);
    }
    return rv;
}

/* FC_DeriveKey derives a key from a base key, creating a new key object. */
 CK_RV FC_DeriveKey( CK_SESSION_HANDLE hSession,
	 CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey,
	 CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount,
						CK_OBJECT_HANDLE_PTR phKey) {
    CK_BBOOL *boolptr;

    SFTK_FIPSCHECK();
    CHECK_FORK();

    /* all secret keys must be sensitive, if the upper level code tries to say
     * otherwise, reject it. */
    boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate,
					ulAttributeCount, CKA_SENSITIVE);
    if (boolptr != NULL) {
	if (!(*boolptr)) {
	    return CKR_ATTRIBUTE_VALUE_INVALID;
	}
    }
    rv = NSC_DeriveKey(hSession,pMechanism,hBaseKey,pTemplate,
			ulAttributeCount, phKey);
    if (sftk_audit_enabled) {
	sftk_AuditDeriveKey(hSession,pMechanism,hBaseKey,pTemplate,
			ulAttributeCount,phKey,rv);
    }
    return rv;
}

/*
 **************************** Radom Functions:  ************************
 */

/* FC_SeedRandom mixes additional seed material into the token's random number
 * generator. */
 CK_RV FC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed,
    CK_ULONG usSeedLen) {
    CK_RV crv;

    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    crv = NSC_SeedRandom(hSession,pSeed,usSeedLen);
    if (crv != CKR_OK) {
	sftk_fatalError = PR_TRUE;
    }
    return crv;
}

/* FC_GenerateRandom generates random data. */
 CK_RV FC_GenerateRandom(CK_SESSION_HANDLE hSession,
    CK_BYTE_PTR	pRandomData, CK_ULONG ulRandomLen) {
    CK_RV crv;

    CHECK_FORK();

    SFTK_FIPSFATALCHECK();
    crv = NSC_GenerateRandom(hSession,pRandomData,ulRandomLen);
    if (crv != CKR_OK) {
	sftk_fatalError = PR_TRUE;
	if (sftk_audit_enabled) {
	    char msg[128];
	    PR_snprintf(msg,sizeof msg,
			"C_GenerateRandom(hSession=0x%08lX, pRandomData=%p, "
			"ulRandomLen=%lu)=0x%08lX "
			"self-test: continuous RNG test failed",
			(PRUint32)hSession,pRandomData,
			(PRUint32)ulRandomLen,(PRUint32)crv);
	    sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg);
	}
    }
    return crv;
}

/* FC_GetFunctionStatus obtains an updated status of a function running
 * in parallel with an application. */
 CK_RV FC_GetFunctionStatus(CK_SESSION_HANDLE hSession) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_GetFunctionStatus(hSession);
}

/* FC_CancelFunction cancels a function running in parallel */
 CK_RV FC_CancelFunction(CK_SESSION_HANDLE hSession) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_CancelFunction(hSession);
}

/*
 ****************************  Version 1.1 Functions:  ************************
 */

/* FC_GetOperationState saves the state of the cryptographic
 *operation in a session. */
CK_RV FC_GetOperationState(CK_SESSION_HANDLE hSession,
	CK_BYTE_PTR  pOperationState, CK_ULONG_PTR pulOperationStateLen) {
    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    return NSC_GetOperationState(hSession,pOperationState,pulOperationStateLen);
}

/* FC_SetOperationState restores the state of the cryptographic operation
 * in a session. */
CK_RV FC_SetOperationState(CK_SESSION_HANDLE hSession,
	CK_BYTE_PTR  pOperationState, CK_ULONG  ulOperationStateLen,
        CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) {
    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    return NSC_SetOperationState(hSession,pOperationState,ulOperationStateLen,
        				hEncryptionKey,hAuthenticationKey);
}

/* FC_FindObjectsFinal finishes a search for token and session objects. */
CK_RV FC_FindObjectsFinal(CK_SESSION_HANDLE hSession) {
    /* let publically readable object be found */
    SFTK_FIPSFATALCHECK();
    CHECK_FORK();

    return NSC_FindObjectsFinal(hSession);
}

/* Dual-function cryptographic operations */

/* FC_DigestEncryptUpdate continues a multiple-part digesting and encryption
 * operation. */
CK_RV FC_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR  pPart,
    CK_ULONG  ulPartLen, CK_BYTE_PTR  pEncryptedPart,
					 CK_ULONG_PTR pulEncryptedPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_DigestEncryptUpdate(hSession,pPart,ulPartLen,pEncryptedPart,
					 pulEncryptedPartLen);
}

/* FC_DecryptDigestUpdate continues a multiple-part decryption and digesting
 * operation. */
CK_RV FC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession,
     CK_BYTE_PTR  pEncryptedPart, CK_ULONG  ulEncryptedPartLen,
    				CK_BYTE_PTR  pPart, CK_ULONG_PTR pulPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_DecryptDigestUpdate(hSession, pEncryptedPart,ulEncryptedPartLen,
    				pPart,pulPartLen);
}

/* FC_SignEncryptUpdate continues a multiple-part signing and encryption
 * operation. */
CK_RV FC_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR  pPart,
	 CK_ULONG  ulPartLen, CK_BYTE_PTR  pEncryptedPart,
					 CK_ULONG_PTR pulEncryptedPartLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_SignEncryptUpdate(hSession,pPart,ulPartLen,pEncryptedPart,
					 pulEncryptedPartLen);
}

/* FC_DecryptVerifyUpdate continues a multiple-part decryption and verify
 * operation. */
CK_RV FC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession,
	CK_BYTE_PTR  pEncryptedData, CK_ULONG  ulEncryptedDataLen,
				CK_BYTE_PTR  pData, CK_ULONG_PTR pulDataLen) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    return NSC_DecryptVerifyUpdate(hSession,pEncryptedData,ulEncryptedDataLen,
				pData,pulDataLen);
}

/* FC_DigestKey continues a multi-part message-digesting operation,
 * by digesting the value of a secret key as part of the data already digested.
 */
CK_RV FC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) {
    SFTK_FIPSCHECK();
    CHECK_FORK();

    rv = NSC_DigestKey(hSession,hKey);
    if (sftk_audit_enabled) {
	sftk_AuditDigestKey(hSession,hKey,rv);
    }
    return rv;
}

CK_RV FC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot,
							 CK_VOID_PTR pReserved)
{
    CHECK_FORK();

    return NSC_WaitForSlotEvent(flags, pSlot, pReserved);
}


text:
import { select } from 'd3';

export default function draw(raw_data, processed_data) {
    const chart = this;
    const config = this.config;

    //if pre-processing callback, run it now
    this.events.onPreprocess.call(this);

    /////////////////////////
    // Data prep  pipeline //
    /////////////////////////

    // if user passed raw_data to chart.draw(), use that, otherwise use chart.raw_data
    const raw = raw_data ? raw_data : this.raw_data ? this.raw_data : [];

    // warn the user about the perils of "processed_data"
    if (processed_data) {
        console.warn(
            "Drawing the chart using user-defined 'processed_data', this is an experimental, untested feature."
        );
    }

    //Call consolidateData - this applies filters from controls and prepares data for each set of marks.
    this.consolidateData(raw);

    /////////////////////////////
    // Prepare scales and axes //
    /////////////////////////////

    let div_width = parseInt(this.wrap.style('width'));

    this.setColorScale();

    let max_width = config.max_width ? config.max_width : div_width;
    this.raw_width = config.x.type === 'ordinal' && +config.x.range_band
        ? (+config.x.range_band + config.x.range_band * config.padding) * this.x_dom.length
        : config.resizable ? max_width : config.width ? config.width : div_width;
    this.raw_height = config.y.type === 'ordinal' && +config.y.range_band
        ? (+config.y.range_band + config.y.range_band * config.padding) * this.y_dom.length
        : config.resizable
          ? max_width * (1 / config.aspect)
          : config.height ? config.height : div_width * (1 / config.aspect);

    let pseudo_width = this.svg.select('.overlay').attr('width')
        ? this.svg.select('.overlay').attr('width')
        : this.raw_width;
    let pseudo_height = this.svg.select('.overlay').attr('height')
        ? this.svg.select('.overlay').attr('height')
        : this.raw_height;

    this.svg.select('.x.axis').select('.axis-title').text(d => {
        return typeof config.x.label === 'string'
            ? config.x.label
            : typeof config.x.label === 'function' ? config.x.label.call(this) : null;
    });
    this.svg.select('.y.axis').select('.axis-title').text(d => {
        return typeof config.y.label === 'string'
            ? config.y.label
            : typeof config.y.label === 'function' ? config.y.label.call(this) : null;
    });

    this.xScaleAxis(pseudo_width);
    this.yScaleAxis(pseudo_height);

    if (config.resizable && typeof window !== 'undefined') {
        select(window).on('resize.' + this.element + this.id, function() {
            chart.resize();
        });
    } else if (typeof window !== 'undefined') {
        select(window).on('resize.' + this.element + this.id, null);
    }

    this.events.onDraw.call(this);

    //////////////////////////////////////////////////////////////////////
    // Call resize - updates marks on the chart (amongst other things) //
    /////////////////////////////////////////////////////////////////////
    this.resize();
}


text:
<?php

$guest_account = true;

chdir('../../');
include_once './include/auth.php';
include_once './include/config.php';
include_once $config['library_path'] . '/database.php';

require_once dirname(__FILE__)."/lib/all.php";

use Weathermap\Integrations\Cacti\WeatherMapCacti88UserPlugin;

$wm_showOldUI = false;

$plugin = new WeatherMapCacti88UserPlugin($config, $colors, "png", realpath(dirname(__FILE__)));

$plugin->main($_REQUEST);

// vim:ts=4:sw=4:


text:
  Villarodin-Bourget est
       un village
       géographiquement positionné dans le département de Savoie en Rhône-Alpes. Elle totalisait 478 habitants en 2008.

À proximité de Villarodin-Bourget sont positionnées géographiquement les communes de
Freney située à 6 km, 113 habitants,
Modane localisée à 2 km, 3 739 habitants,
Bramans à 5 km, 378 habitants,
Aussois à 3 km, 668 habitants,
Fourneaux localisée à 4 km, 808 habitants,
Avrieux à 1 km, 359 habitants,
 entre autres. De plus, Villarodin-Bourget est située à seulement 29 km de Saint-Jean-de-Maurienne.

La ville offre quelques  équipements sportifs, elle dispose, entre autres, de un domaine skiable.

Si vous envisagez de venir habiter à Villarodin-Bourget, vous pourrez facilement trouver une maison à acheter.

Le nombre d'habitations, à Villarodin-Bourget, était réparti en 2011 en 1 093 appartements et 358 maisons soit
une nette supériorité des appartements.


text:
package com.rho.rhoelements;

import java.io.BufferedReader;
import java.io.FileReader;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class JSObjects
{
	private Handler handler;

	public JSObjects()
	{
		// Construct Handler in this thread context
		handler = new JSObjectsHandler();
	}

	/**************************************************************************/
	public String getOEMInfo()
	{
		return Build.PRODUCT;
	}

	/**************************************************************************/
	public String getUUID()
	{
		// Get serial number from UUID file built into image
		// TODO Check UUID is unique
		try
		{
			BufferedReader reader = new BufferedReader(new FileReader("/sys/hardware_id/uuid"));
			return reader.readLine();
		}
		catch (Exception e)
		{
			return "Unknown";
		}
	}

	/**************************************************************************/
	public void doEMML(String equiv, String content)
	{
		Common.logger.add(new LogEntry(LogEntry.PB_LOG_INFO, "'" + equiv + "', '" + content + "'"));

		// Use the same method to process as is used for actual <meta> tags.
		// It will also synchronise to the main thread.
		Common.metaReceiver.setMeta(equiv, content);
	}

	/**************************************************************************/
	public Boolean doLog(String comment, int severity)
	{
		Common.logger.add(new LogEntry(LogEntry.PB_LOG_INFO, "'" + comment + "', '" + severity + "'"));

		// Handle request in the main thread so we can get the current URL
		handler.sendMessage(handler.obtainMessage(0, new LogRequest(severity, comment)));

		return true;
	}

	/**************************************************************************/
	class JSObjectsHandler extends Handler
	{
		@Override
		public void handleMessage(Message message)
		{
			// Message is JSObjectsRequest object
			JSObjectsRequest request = (JSObjectsRequest) message.obj;
			request.execute();
		}
	}

	/**
	 * Base class for all JSObjects requests
	 */
	abstract class JSObjectsRequest
	{
		/**
		 * Overridden by specific request handlers
		 */
		abstract void execute();
	}

	/**************************************************************************/
	class LogRequest extends JSObjectsRequest
	{
		int severity;
		String comment;

		public LogRequest(int severity, String comment)
		{
			this.severity = severity;
			this.comment = comment;
		}

		@Override
		void execute()
		{
			// Translate severity figure to text and use as 'caller' field
			String caller;
			switch (severity)
			{
			case 1:
				caller = "Low";
				break;
			case 2:
				caller = "Medium";
				break;
			case 3:
				caller = "High";
				break;
			default:
				caller = "Unknown";
				break;
			}

			Common.logger.add(new LogEntry(LogEntry.PB_LOG_USER, caller, Common.elementsCore.getCurrentUrl(), comment, 0));
		}
	}
}


text:
package com.turn.ttorrent.common.protocol.http;

import com.turn.ttorrent.Constants;
import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.BEncoder;
import com.turn.ttorrent.bcodec.InvalidBEncodingException;
import com.turn.ttorrent.common.protocol.TrackerMessage.ErrorMessage;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * An error message from an HTTP tracker.
 *
 * @author mpetazzoni
 */
public class HTTPTrackerErrorMessage extends HTTPTrackerMessage
        implements ErrorMessage {

  private final String reason;

  private HTTPTrackerErrorMessage(ByteBuffer data, String reason) {
    super(Type.ERROR, data);
    this.reason = reason;
  }

  @Override
  public String getReason() {
    return this.reason;
  }

  public static HTTPTrackerErrorMessage parse(BEValue decoded)
          throws IOException, MessageValidationException {
    if (decoded == null) {
      throw new MessageValidationException(
              "Could not decode tracker message (not B-encoded?)!");
    }

    Map<String, BEValue> params = decoded.getMap();

    try {
      return new HTTPTrackerErrorMessage(
              Constants.EMPTY_BUFFER,
              params.get("failure reason")
                      .getString(Constants.BYTE_ENCODING));
    } catch (InvalidBEncodingException ibee) {
      throw new MessageValidationException("Invalid tracker error " +
              "message!", ibee);
    }
  }

  public static HTTPTrackerErrorMessage craft(
          ErrorMessage.FailureReason reason) throws IOException {
    return HTTPTrackerErrorMessage.craft(reason.getMessage());
  }

  public static HTTPTrackerErrorMessage craft(String reason)
          throws IOException {
    Map<String, BEValue> params = new HashMap<String, BEValue>();
    params.put("failure reason",
            new BEValue(reason, Constants.BYTE_ENCODING));
    return new HTTPTrackerErrorMessage(
            BEncoder.bencode(params),
            reason);
  }
}


text:
/**
 * @file PointStep
 */

export default from './PointStep';


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.netforce</groupId>
  <artifactId>webstore</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>4.1.4.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet</groupId>
  		<artifactId>jstl</artifactId>
  		<version>1.2</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet</groupId>
  		<artifactId>javax.servlet-api</artifactId>
  		<version>3.1.0</version>
  	</dependency>
  </dependencies>
  <properties>
  	<maven.compiler.source>1.7</maven.compiler.source>
  	<maven.compiler.target>1.7</maven.compiler.target>
  </properties>
</project>


text:
	#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
		#define thread_local __thread
		#define LOGGER_THREAD_LOCAL
	#else
		#define thread_local __declspec(thread)
		#define LOGGER_THREAD_LOCAL
	#endif
#endif

namespace df {

const size_t MAX_LOG_BUFFER_SIZE = 4096;

#ifdef LOGGER_THREAD_LOCAL
	thread_local static char g_log_buffer[MAX_LOG_BUFFER_SIZE];
#else
	static char g_log_buffer[MAX_LOG_BUFFER_SIZE];
#endif

class Logger::PrivateData
{
public:
	PrivateData():
	  outputToFile(true),
      outputToStdOut(true),
	  minLogLevel(Logger::LOG_DEBUG),
	  isInitialized(false),
	  pFile(0)
	  {
		  std::strcpy(folderPath,"_logs");
		  std::strcpy(filePrefix,"");
	  }

	bool outputToFile;
	bool outputToStdOut;
	Logger::LogLevel minLogLevel;
	bool isInitialized;
	char folderPath[256];
	char filePrefix[64];
	FILE * pFile;

#ifndef LOGGER_THREAD_LOCAL
	Mutex bufferMutex;
#endif

	//trick to avoid implementing two log functions with variadic arguments and a single arg as difference
	void logWithPrefix(Logger::LogLevel level, const char* prefix,  const char* format, va_list args);
};

Logger::Logger()
{
	_data = new PrivateData();
}

Logger::~Logger()
{
	close();
    delete _data;
}

void Logger::setOutputToFile(bool state)
{
	assert(!_data->isInitialized && "Config is immutable after init");
	_data->outputToFile = state;
}

void Logger::setOutputToStdOut(bool state)
{
	assert(!_data->isInitialized && "Config is immutable after init");
	_data->outputToStdOut = state;
}

void Logger::setFolderPath(const char* folderPath)
{
	assert(!_data->isInitialized && "Config is immutable after init");
	std::strcpy(_data->folderPath, folderPath);
}

void Logger::setFilePrefix(const char* prefix)
{
	assert(!_data->isInitialized && "Config is immutable after init");
	std::strcpy(_data->filePrefix, prefix);
}

void Logger::setMinLogLevel(LogLevel level)
{
	assert(!_data->isInitialized && "Config is immutable after init");
	_data->minLogLevel = level;
}

bool Logger::init()
{
#ifndef LOGGER_THREAD_LOCAL
	ScopedLock(_data->bufferMutex);
#endif
	char* bufferPtr = g_log_buffer;

	memset(bufferPtr,'*',MAX_LOG_BUFFER_SIZE);
	bufferPtr[MAX_LOG_BUFFER_SIZE-1] = '\0';

	//close file if opened
	if(_data->pFile != 0)
	{
		fclose(_data->pFile);
		_data->pFile = 0;
	}

	if(_data->outputToFile)
	{
		//create log folder if not created
		#if defined(_WIN32)
			_mkdir(_data->folderPath);
		#else
			#pragma message("Check if this is good permissions")
			mkdir(_data->folderPath, 0755);
		#endif

		//construct log file name
		strcpy(bufferPtr, _data->folderPath);
		strcat(bufferPtr, "/");
		strcat(bufferPtr, _data->filePrefix);
		strcat(bufferPtr, "_log.txt");

		_data->pFile = fopen ( bufferPtr,"a");
		if(_data->pFile == 0)
		{
			return false;
		}
		setbuf ( _data->pFile , NULL ); //force unbuffered

		//check whether the log file needs an initial header of not
		fseek(_data->pFile, 0, SEEK_END);
		if(ftell(_data->pFile) == 0)
		{
			const char header1[] = "HH:MM:SS thread Lvl : message\n";
			const char header2[] = "-----------------------------\n";
			fwrite(header1,1,sizeof(header1)-1, _data->pFile);
			fwrite(header2,1,sizeof(header2)-1, _data->pFile);
		}

		//Write session header
		std::time_t t = std::time(NULL);
		time_t rawtime;
		struct tm * timeinfo;
		time ( &rawtime );
		timeinfo = localtime ( &rawtime );

		size_t written = strftime ( bufferPtr, MAX_LOG_BUFFER_SIZE, "----- Start: %c -----\n", timeinfo);
		fwrite(bufferPtr,1,written, _data->pFile);
	}

	_data->isInitialized = true;

	return true;
}
void Logger::close()
{
    if(_data->pFile !=0)
	{
		fclose (_data->pFile);
		_data->pFile = 0;
        _data->isInitialized = false;
	}
}

void Logger::log(LogLevel level, const char* format, ...)
{
	va_list args;
	va_start(args, format);
	_data->logWithPrefix(level, NULL, format, args);
	va_end(args);
}

void Logger::logWithPrefix(LogLevel level, const char* prefix,  const char* format, ...)
{
	va_list args;
	va_start(args, format);
	_data->logWithPrefix(level, prefix, format, args);
	va_end(args);
}

void Logger::PrivateData::logWithPrefix(Logger::LogLevel level, const char* prefix,  const char* format, va_list args)
{
#ifndef LOGGER_THREAD_LOCAL
	ScopedLock bufferLock(bufferMutex);
#endif

	// lock-free logging implementation (except locking inside std::ofstream)
	if (level > minLogLevel || !isInitialized)
		return;

	// *** allocate thread-local buffer here if we use a templated implementation***
	// ...
	char* start_buf = g_log_buffer;
	char* cur_buf = start_buf;

	int remainingSize = MAX_LOG_BUFFER_SIZE-2; // two bytes are kept for trailing \n\0

	//retrieve current time
	//TODO time() is not thread safe! but I don't see any bad side effect so far...
	std::time_t t = std::time(NULL);
	time_t rawtime;
	struct tm * timeinfo;
	time ( &rawtime );
	timeinfo = localtime ( &rawtime );

	static char const* const category_str[] = {"ERR", "INF", "DBG"};

	//get an id for the calling thread
	uint32 threadID = this_thread::getID();

	int lineHeaderSize;
	if(prefix != NULL){
		lineHeaderSize = snprintf(cur_buf, remainingSize, "%02i:%02i:%02i %6i %s [%s] ",
			timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, threadID, category_str[level], prefix);
	}else
	{
		lineHeaderSize = snprintf(cur_buf, remainingSize, "%02i:%02i:%02i %6i %s ",
			timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, threadID, category_str[level]);
	}
	cur_buf += lineHeaderSize;
	remainingSize -= lineHeaderSize;

	//append user message
	int vsnWritten = vsnprintf(cur_buf, remainingSize, format, args);
	if (vsnWritten != -1)
	{
		cur_buf += vsnWritten;
		remainingSize -= vsnWritten;
	}else
	{
		cur_buf = start_buf+MAX_LOG_BUFFER_SIZE-2;
		remainingSize = 0;
	}

	//Align new line on  the msg header
	if(remainingSize > lineHeaderSize )
	{
		int endlineCount = 0;
		const char* scan_buf = format;
		while(*scan_buf!='\0')
		{
			endlineCount +=(*scan_buf=='\n');
			++scan_buf;
		}

		//is there enough space to add alignment space
		if(endlineCount > 0 && (remainingSize >  endlineCount * lineHeaderSize ))
		{
			//scan backward
			char* scan_buf = cur_buf-1;
			char* prev_buf_end = scan_buf;

			//update state preemptively
			remainingSize -= lineHeaderSize;
			cur_buf +=endlineCount * lineHeaderSize;

			while(scan_buf >= start_buf)
			{
				if(*scan_buf=='\n')
				{
					int count = prev_buf_end -scan_buf;
					char* tgt_buf = scan_buf+1+endlineCount*lineHeaderSize;
					// move text on the right to its final position
					memmove (tgt_buf, scan_buf+1, prev_buf_end -scan_buf);
					// insert whitespace
					memset(tgt_buf - lineHeaderSize,' ',lineHeaderSize);
					--endlineCount;
					prev_buf_end = scan_buf;
				}
				--scan_buf;
			}
		}
	}

	*cur_buf = '\n';
	++cur_buf;
	*cur_buf = '\0';

	//no need to check boolean, if file is open we can write
	if(pFile != 0)
	{
		assert(outputToFile);
		fwrite(start_buf,1, cur_buf-start_buf, pFile);
	}

	if(outputToStdOut)
	{
		printf(start_buf);
	}
}

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

void LoggerProxy::log(Logger::LogLevel level, const char* format, ...)
{
	va_list args;
	va_start(args, format);
	_logger->_data->logWithPrefix(level, _prefix, format, args);
	va_end(args);
}

void LoggerProxy::logError(const char* format, ...)
{
	va_list args;
	va_start(args, format);
	_logger->_data->logWithPrefix(Logger::LOG_ERROR, _prefix, format, args);
	va_end(args);
}

#ifdef _DEBUG
void LoggerProxy::logInfo(const char* format, ...)
{
	va_list args;
	va_start(args, format);
	_logger->_data->logWithPrefix(Logger::LOG_INFO, _prefix, format, args);
	va_end(args);
}

void LoggerProxy::logDebug(const char* format, ...)
{
	va_list args;
	va_start(args, format);
	_logger->_data->logWithPrefix(Logger::LOG_DEBUG, _prefix, format, args);
	va_end(args);
}
#endif

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.wuzhendev.installapk.MainActivity">

    <Button
        android:id="@+id/btn_install"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center"
        android:text="Install APK"/>

    <Button
        android:id="@+id/btn_uninstall"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center"
        android:text="Uninstall APK"/>

</LinearLayout>


text:
module.exports = function() {
  var _ = require('lodash');
  var shell = require('shelljs');
  var request = require('request');
  var options = this.options();
  var urls = require('./../' + options.urls);
  var taskFinished = this.async();
  var fs = require('fs');
  var async = require('async');

  function fname(url) {
    return options.logdir + '/' + _.last(url.split('/'));
  }

  var q = async.queue(function(url, done) {
    request(url, function(err, response) {
      if (err) {
        console.error('ERROR: could not get ' + url, err);
        done(false);
      }

      fs.writeFile(fname(url), response.body, function(err) {
        if (err) {
          console.error('ERROR: could not write file "' + fname(url) + '"');
          done(err);
        }

        done();
      });
    });
  }, 20);

  if (!shell.test('-e', options.logdir)) {
    shell.mkdir(options.logdir);
  }

  urls.slice(0, 31).forEach(function(url) {
    if (!shell.test('-f', fname(url))) {
      console.log('fetching', url);
      q.push(url);
    } else {
      console.log('skipping "' + url + '"');
    }
  });

  if (q.length()) {
    q.drain = taskFinished;
  } else {
    taskFinished();
  }
};

module.exports.desc = 'download the daily logs from @isaacs site';


text:
namespace perftools {
namespace gputools {
namespace port {

using tensorflow::strings::Printf;
using tensorflow::strings::Appendf;
using tensorflow::strings::Appendv;

}  // namespace port
}  // namespace gputools
}  // namespace perftools

#endif  // TENSORFLOW_STREAM_EXECUTOR_LIB_STRINGPRINTF_H_


text:
import { IGitHubUserProfile } from "../../../services/GitHubServices";
import { HttpClient } from '@microsoft/sp-http';

export interface IGitHubBadgeProps {
  gitHubUserName: string;
  httpClient: HttpClient;
}

export interface IGitHubBadgeState {
  isLoading: boolean;
  userProfile?: IGitHubUserProfile;
  errorMessage?: string;
}


text:
require 'minitest/autorun'

describe 'Chef::Provider::Alternatives' do
  describe '' do

    it 'should' do
      skip
    end

  end
end


text:
"""$Id: textInput.py 699 2006-09-25 02:01:18Z rubys $"""

__author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>"
__version__ = "$Revision: 699 $"
__date__ = "$Date: 2006-09-25 02:01:18 +0000 (Mon, 25 Sep 2006) $"
__copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim"

from validators import *
from extension import extension_everywhere

#
# textInput element.
#
class textInput(validatorBase, extension_everywhere):
  def getExpectedAttrNames(self):
      return [(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#', u'about')]

  def validate(self):
    if not "title" in self.children:
      self.log(MissingTitle({"parent":self.name, "element":"title"}))
    if not "link" in self.children:
      self.log(MissingLink({"parent":self.name, "element":"link"}))
    if not "description" in self.children:
      self.log(MissingDescription({"parent":self.name,"element":"description"}))
    if not "name" in self.children:
      self.log(MissingElement({"parent":self.name, "element":"name"}))

  def do_title(self):
    return nonhtml(), noduplicates()

  def do_description(self):
    return text(), noduplicates()

  def do_name(self):
    return formname(), noduplicates()

  def do_link(self):
    return rfc2396_full(), noduplicates()

  def do_dc_creator(self):
    return text() # duplicates allowed

  def do_dc_subject(self):
    return text() # duplicates allowed

  def do_dc_date(self):
    return w3cdtf(), noduplicates()


text:
package org.hiatusuk.selectorLint.webdriver;

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

import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.hiatusuk.selectorLint.impl.Simplifier;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.*;
import org.slf4j.Logger;

public class LintedWebDriver implements WebDriver, WrapsDriver, JavascriptExecutor, HasInputDevices, HasTouchScreen {

    private final WebDriver original;
    private Logger suggestionsLogger = null;

    private final Simplifier simplifier;

    public LintedWebDriver(WebDriver originalDriver, final Simplifier simplifier) {
        this.original = checkNotNull(originalDriver);
        this.simplifier = checkNotNull(simplifier);
    }

    public void logSuggestions(final Logger logger) {
        this.suggestionsLogger = logger;
    }

    @Override
    public WebElement findElement( final By by) {
        final WebElement original = getWrappedDriver().findElement(by);

        final List<By> newBys = simplifier.getImprovedSelector( Collections.singletonList(original), by.toString());

        if (suggestionsLogger != null && !newBys.isEmpty()) {
            suggestionsLogger.debug("> Suggestions for [" + by + "] ... " + newBys);
        }

        return new LintedWebElement(original, newBys);
    }

    @Override
    public List<WebElement> findElements( final By by) {
        final List<WebElement> originals = getWrappedDriver().findElements(by);
        if (originals.isEmpty()) {
            return new LintedWebElements(originals, Collections.emptyList());
        }

        final List<By> newBys = simplifier.getImprovedSelector( Collections.singletonList(originals.iterator().next()), by.toString());

        if (suggestionsLogger != null && !newBys.isEmpty()) {
            suggestionsLogger.debug("> Suggestions for [" + by + "] ... " + newBys);
        }

        return new LintedWebElements(originals, newBys);
    }

    @Override
    public final WebDriver getWrappedDriver() {
        return original;
    }

    @Override
    public void get( String url) {
        simplifier.clearCache();
        getWrappedDriver().get(url);
    }

    @Override
    public String getCurrentUrl() {
        return getWrappedDriver().getCurrentUrl();
    }

    @Override
    public String getTitle() {
        return getWrappedDriver().getTitle();
    }

    @Override
    public String getPageSource() {
        return getWrappedDriver().getPageSource();
    }

    @Override
    public void close() {
        getWrappedDriver().close();
    }

    @Override
    public void quit() {
        getWrappedDriver().quit();
    }

    @Override
    public Set<String> getWindowHandles() {
        return getWrappedDriver().getWindowHandles();
    }

    @Override
    public String getWindowHandle() {
        return getWrappedDriver().getWindowHandle();
    }

    @Override
    public TargetLocator switchTo() {
        return getWrappedDriver().switchTo();
    }

    @Override
    public Navigation navigate() {
        return getWrappedDriver().navigate();
    }

    @Override
    public Options manage() {
        return getWrappedDriver().manage();
    }

    @Override
    public TouchScreen getTouch() {
        return ((HasTouchScreen) getWrappedDriver()).getTouch();
    }

    @Override
    public Keyboard getKeyboard() {
        return ((HasInputDevices) getWrappedDriver()).getKeyboard();
    }

    @Override
    public Mouse getMouse() {
        return ((HasInputDevices) getWrappedDriver()).getMouse();
    }

    @Override
    public Object executeScript( String script, Object... args) {
        return ((JavascriptExecutor) getWrappedDriver()).executeScript(script, args);
    }

    @Override
    public Object executeAsyncScript( String script, Object... args) {
        return ((JavascriptExecutor) getWrappedDriver()).executeAsyncScript(script, args);
    }
}


text:
// <copyright file="ICanAddMethodWeavingRecord.cs" company="Cui Ziqiang">
// Copyright (c) 2017 Cui Ziqiang
// </copyright>

namespace CrossCutterN.Weaver.Statistics
{
    using CrossCutterN.Base.Common;

    /// <summary>
    /// Statistics that contains method weaving record, implementation should be class weaving statistics.
    /// </summary>
    internal interface ICanAddMethodWeavingRecord
    {
        /// <summary>
        /// Adds a method weaving record.
        /// </summary>
        /// <param name="record">Method weaving record to be added.</param>
        void AddWeavingRecord(IWeavingRecord record);
    }

    /// <summary>
    /// Statistics that contains method weaving record and can be built to a certain type.
    /// </summary>
    /// <typeparam name="T">The type that this interface can be built to.</typeparam>
    internal interface ICanAddMethodWeavingRecord<out T> : ICanAddMethodWeavingRecord, IBuilder<T>
        where T : class
    {
    }
}


text:
package clouddns

import (
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/go-acme/lego/v4/challenge/dns01"
	"github.com/go-acme/lego/v4/platform/config/env"
	"github.com/go-acme/lego/v4/providers/dns/clouddns/internal"
)

// Environment variables names.
const (
	envNamespace = "CLOUDDNS_"

	EnvClientID = envNamespace + "CLIENT_ID"
	EnvEmail    = envNamespace + "EMAIL"
	EnvPassword = envNamespace + "PASSWORD"

	EnvTTL                = envNamespace + "TTL"
	EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
	EnvPollingInterval    = envNamespace + "POLLING_INTERVAL"
	EnvHTTPTimeout        = envNamespace + "HTTP_TIMEOUT"
)

// Config is used to configure the DNSProvider.
type Config struct {
	ClientID string
	Email    string
	Password string

	TTL                int
	PropagationTimeout time.Duration
	PollingInterval    time.Duration
	HTTPClient         *http.Client
}

// NewDefaultConfig returns a default configuration for the DNSProvider.
func NewDefaultConfig() *Config {
	return &Config{
		TTL:                env.GetOrDefaultInt(EnvTTL, 300),
		PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 120*time.Second),
		PollingInterval:    env.GetOrDefaultSecond(EnvPollingInterval, 5*time.Second),
		HTTPClient: &http.Client{
			Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
		},
	}
}

// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
	client *internal.Client
	config *Config
}

// NewDNSProvider returns a DNSProvider instance configured for CloudDNS.
// Credentials must be passed in the environment variables:
// CLOUDDNS_CLIENT_ID, CLOUDDNS_EMAIL, CLOUDDNS_PASSWORD.
func NewDNSProvider() (*DNSProvider, error) {
	values, err := env.Get(EnvClientID, EnvEmail, EnvPassword)
	if err != nil {
		return nil, fmt.Errorf("clouddns: %w", err)
	}

	config := NewDefaultConfig()
	config.ClientID = values[EnvClientID]
	config.Email = values[EnvEmail]
	config.Password = values[EnvPassword]

	return NewDNSProviderConfig(config)
}

// NewDNSProviderConfig return a DNSProvider instance configured for CloudDNS.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("clouddns: the configuration of the DNS provider is nil")
	}

	if config.ClientID == "" || config.Email == "" || config.Password == "" {
		return nil, errors.New("clouddns: credentials missing")
	}

	client := internal.NewClient(config.ClientID, config.Email, config.Password, config.TTL)

	if config.HTTPClient != nil {
		client.HTTPClient = config.HTTPClient
	}

	return &DNSProvider{
		client: client,
		config: config,
	}, nil
}

// Timeout returns the timeout and interval to use when checking for DNS propagation.
// Adjusting here to cope with spikes in propagation times.
func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
	return d.config.PropagationTimeout, d.config.PollingInterval
}

// Present creates a TXT record using the specified parameters.
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
	fqdn, value := dns01.GetRecord(domain, keyAuth)

	authZone, err := dns01.FindZoneByFqdn(fqdn)
	if err != nil {
		return fmt.Errorf("clouddns: %w", err)
	}

	err = d.client.AddRecord(authZone, fqdn, value)
	if err != nil {
		return fmt.Errorf("clouddns: %w", err)
	}

	return nil
}

// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
	fqdn, _ := dns01.GetRecord(domain, keyAuth)

	authZone, err := dns01.FindZoneByFqdn(fqdn)
	if err != nil {
		return fmt.Errorf("clouddns: %w", err)
	}

	err = d.client.DeleteRecord(authZone, fqdn)
	if err != nil {
		return fmt.Errorf("clouddns: %w", err)
	}

	return nil
}


text:
Title: Forwarding
Slug: docs/guides/forwarding

# Forwarding DNS

By default, DNS is served from port 53 which requires root privileges.
Instead of running XXX as root, it is possible to instead run Bind
and forward queries to XXX as appropriate.

In this example, Bind and XXX are running on the same machine for
simplicity but this is not required.

### Bind Setup

First, you have to disable DNSSEC so that XXX and Bind can communicate.
This is an example configuration:

    options {
        listen-on port 53 { 127.0.0.1; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { localhost; };
        recursion yes;

        dnssec-enable no;
        dnssec-validation no;

        /* Path to ISC DLV key */
        bindkeys-file "/etc/named.iscdlv.key";

        managed-keys-directory "/var/named/dynamic";
    };

    include "/etc/named/XXX.conf";

### Zone File

Then we set up a zone for our XXX managed records in XXX.conf:

    zone "XXX" IN {
        type forward;
        forward only;
        forwarders { 127.0.0.1 port 8600; };
    };

Here we assume XXX is running with default settings, and is serving
DNS on port 8600.

### Testing

First, perform a DNS query against XXX directly to be sure that the record exists:

    [root@localhost ~]# dig @localhost -p 8600 master.redis.service.dc-1.XXX. A

    ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.23.rc1.32.amzn1 <<>> @localhost master.redis.service.dc-1.XXX. A
    ; (1 server found)
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11536
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

    ;; QUESTION SECTION:
    ;master.redis.service.dc-1.XXX. IN A

    ;; ANSWER SECTION:
    master.redis.service.dc-1.XXX. 0 IN A 172.31.3.234

    ;; Query time: 4 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Wed Apr  9 17:36:12 2014
    ;; MSG SIZE  rcvd: 76

Then run the same query against your Bind instance and make sure you get a result:

    [root@localhost ~]# dig @localhost -p 53 master.redis.service.dc-1.XXX. A

    ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.23.rc1.32.amzn1 <<>> @localhost master.redis.service.dc-1.XXX. A
    ; (1 server found)
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11536
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

    ;; QUESTION SECTION:
    ;master.redis.service.dc-1.XXX. IN A

    ;; ANSWER SECTION:
    master.redis.service.dc-1.XXX. 0 IN A 172.31.3.234

    ;; Query time: 4 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Wed Apr  9 17:36:12 2014
    ;; MSG SIZE  rcvd: 76

### Troubleshooting

If you don't get an answer from Bind but you do get an answer from XXX then your
best bet is to turn on the query log to see what's going on:

    [root@localhost ~]# rndc querylog
    [root@localhost ~]# tail -f /var/log/messages

In there if you see errors like this:

    error (no valid RRSIG) resolving
    error (no valid DS) resolving

Then DNSSEC is not disabled properly.  If you see errors about network connections
then verify that there are no firewall or routing problems between the servers
running Bind and XXX.


text:
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";
$client = new Client($sid, $token);

// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$ipAddress = $client->sip
    ->ipAccessControlLists("AL32a3c49700934481addd5ce1659f04d2")
    ->ipAddresses("IP32a3c49700934481addd5ce1659f04d2")
    ->fetch();

echo $ipAddress->ipAddress;


text:
import React from 'react'
export default class extends React.Component {
  static async getInitialProps ({ res }) {
    if (res) {
      res.setHeader('Content-Type', 'text/html; charset=iso-8859-2')
    }
    return {}
  }

  render () {
    return null
  }
}


text:
package com.google.gerrit.acceptance.rest.change;

import static com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allowLabel;
import static com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.blockLabel;
import static com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.labelPermissionKey;
import static com.google.gerrit.testing.GerritJUnit.assertThrows;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.AcceptanceTestRequestScope.Context;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.TestAccount;
import com.google.gerrit.acceptance.TestProjectInput;
import com.google.gerrit.acceptance.testsuite.project.ProjectOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.entities.AccountGroup;
import com.google.gerrit.entities.LabelId;
import com.google.gerrit.entities.Project;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.inject.Inject;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
import org.junit.Before;
import org.junit.Test;

public class ChangeOwnerIT extends AbstractDaemonTest {
  @Inject private ProjectOperations projectOperations;
  @Inject private RequestScopeOperations requestScopeOperations;

  private TestAccount user2;

  @Before
  public void setUp() throws Exception {
    requestScopeOperations.setApiUser(user.id());
    user2 = accountCreator.user2();
  }

  @Test
  @TestProjectInput(cloneAs = "user1")
  public void testChangeOwner_OwnerACLNotGranted() throws Exception {
    assertApproveFails(user, createMyChange(testRepo));
  }

  @Test
  @TestProjectInput(cloneAs = "user1")
  public void testChangeOwner_OwnerACLGranted() throws Exception {
    grantApproveToChangeOwner(project);
    approve(user, createMyChange(testRepo));
  }

  @Test
  @TestProjectInput(cloneAs = "user1")
  public void testChangeOwner_NotOwnerACLGranted() throws Exception {
    grantApproveToChangeOwner(project);
    assertApproveFails(user2, createMyChange(testRepo));
  }

  @Test
  public void testChangeOwner_OwnerACLGrantedOnParentProject() throws Exception {
    requestScopeOperations.setApiUser(admin.id());
    grantApproveToChangeOwner(project);
    Project.NameKey child = projectOperations.newProject().parent(project).create();

    requestScopeOperations.setApiUser(user.id());
    TestRepository<InMemoryRepository> childRepo = cloneProject(child, user);
    approve(user, createMyChange(childRepo));
  }

  @Test
  public void testChangeOwner_BlockedOnParentProject() throws Exception {
    requestScopeOperations.setApiUser(admin.id());
    blockApproveForChangeOwner(project);
    Project.NameKey child = projectOperations.newProject().parent(project).create();

    requestScopeOperations.setApiUser(user.id());
    grantApproveToAll(child);
    TestRepository<InMemoryRepository> childRepo = cloneProject(child, user);
    String changeId = createMyChange(childRepo);

    // change owner cannot approve because Change-Owner group is blocked on parent
    assertApproveFails(user, changeId);

    // other user can approve
    approve(user2, changeId);
  }

  @Test
  public void testChangeOwner_BlockedOnParentProjectAndExclusiveAllowOnChild() throws Exception {
    requestScopeOperations.setApiUser(admin.id());
    blockApproveForChangeOwner(project);
    Project.NameKey child = projectOperations.newProject().parent(project).create();

    requestScopeOperations.setApiUser(user.id());
    grantExclusiveApproveToAll(child);
    TestRepository<InMemoryRepository> childRepo = cloneProject(child, user);
    String changeId = createMyChange(childRepo);

    // change owner cannot approve because Change-Owner group is blocked on parent
    assertApproveFails(user, changeId);

    // other user can approve
    approve(user2, changeId);
  }

  private void approve(TestAccount a, String changeId) throws Exception {
    Context old = requestScopeOperations.setApiUser(a.id());
    try {
      gApi.changes().id(changeId).current().review(ReviewInput.approve());
    } finally {
      atrScope.set(old);
    }
  }

  private void assertApproveFails(TestAccount a, String changeId) throws Exception {
    assertThrows(AuthException.class, () -> approve(a, changeId));
  }

  private void grantApproveToChangeOwner(Project.NameKey project) throws Exception {
    grantApprove(project, SystemGroupBackend.CHANGE_OWNER, false);
  }

  private void grantApproveToAll(Project.NameKey project) throws Exception {
    grantApprove(project, SystemGroupBackend.REGISTERED_USERS, false);
  }

  private void grantExclusiveApproveToAll(Project.NameKey project) throws Exception {
    grantApprove(project, SystemGroupBackend.REGISTERED_USERS, true);
  }

  private void grantApprove(Project.NameKey project, AccountGroup.UUID groupUUID, boolean exclusive)
      throws Exception {
    projectOperations
        .project(project)
        .forUpdate()
        .add(allowLabel(LabelId.CODE_REVIEW).ref("refs/heads/*").group(groupUUID).range(-2, 2))
        .setExclusiveGroup(labelPermissionKey(LabelId.CODE_REVIEW).ref("refs/heads/*"), exclusive)
        .update();
  }

  private void blockApproveForChangeOwner(Project.NameKey project) throws Exception {
    projectOperations
        .project(project)
        .forUpdate()
        .add(
            blockLabel(LabelId.CODE_REVIEW)
                .ref("refs/heads/*")
                .group(SystemGroupBackend.CHANGE_OWNER)
                .range(-2, 2))
        .update();
  }

  private String createMyChange(TestRepository<InMemoryRepository> testRepo) throws Exception {
    PushOneCommit push = pushFactory.create(user.newIdent(), testRepo);
    return push.to("refs/for/master").getChangeId();
  }
}


text:
package org.sleuthkit.autopsy.healthmonitor;

/**
 * Exception used internally by the Services Health Monitor
 */
class HealthMonitorException extends Exception {
    private static final long serialVersionUID = 1L;

    HealthMonitorException(String message) {
        super(message);
    }

    HealthMonitorException(String message, Throwable cause) {
        super(message, cause);
    }
}