text:
using UnityEngine;
using System.Collections;

public class LevelManager : MonoBehaviour {

    public GameObject currentCheckpoint;
    private static GameObject thisInstance;

    [SerializeField] private int numCheckpoints = 2;
    private UnityStandardAssets._2D.PlatformerCharacter2D player;

    // Use this for initialization
    void Start () {
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<UnityStandardAssets._2D.PlatformerCharacter2D>();
        DontDestroyOnLoad(this.gameObject);
        DontDestroyOnLoad(GameObject.Find("Checkpoints"));

        if (thisInstance == null) // Don't destroy certain objects, then make sure any new instances loaded are destroyed
        {
            thisInstance = this.gameObject;
        }
        else
        {
            DestroyObject(this.gameObject);
        }

        GameObject[] checkpoints = GameObject.FindGameObjectsWithTag("Checkpoint");
        for (int i = 0; i < checkpoints.Length; i++)
        {
            if (i >= numCheckpoints) Destroy(checkpoints[i]);
        }
    }

	// Update is called once per frame
	void Update () {

	}

    public void RespawnPlayer()
    {
        Debug.Log("Respawning...");
        player.transform.position = currentCheckpoint.transform.position; // Reset player pos
        player.fullStop();
        UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetSceneAt(0).name);
    }
}


text:
// Copyright 2016 Tim O'Brien. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build darwin
// +build darwin

package jnigi

/*
#cgo LDFLAGS:-ldl

#include <dlfcn.h>
#include <jni.h>

typedef jint (*type_JNI_GetDefaultJavaVMInitArgs)(void*);

type_JNI_GetDefaultJavaVMInitArgs var_JNI_GetDefaultJavaVMInitArgs;

jint dyn_JNI_GetDefaultJavaVMInitArgs(void *args) {
    return var_JNI_GetDefaultJavaVMInitArgs(args);
}

typedef jint (*type_JNI_CreateJavaVM)(JavaVM**, void**, void*);

type_JNI_CreateJavaVM var_JNI_CreateJavaVM;

jint dyn_JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args) {
    return var_JNI_CreateJavaVM(pvm, penv, args);
}

*/
import "C"

import (
	"errors"
	"log"
	"os"
	"path/filepath"
	"unsafe"
)

const (
	JLI_LOAD_ENV   = "LIBJLI_LOAD"
	JLI_LOAD_YES   = "yes"
	JLI_LOAD_FORCE = "force"
)

func jni_GetDefaultJavaVMInitArgs(args unsafe.Pointer) jint {
	return jint(C.dyn_JNI_GetDefaultJavaVMInitArgs((unsafe.Pointer)(args)))
}

func jni_CreateJavaVM(pvm unsafe.Pointer, penv unsafe.Pointer, args unsafe.Pointer) jint {
	return jint(C.dyn_JNI_CreateJavaVM((**C.JavaVM)(pvm), (*unsafe.Pointer)(penv), (unsafe.Pointer)(args)))
}

// LoadJVMLib loads libjvm.dyo as specified in jvmLibPath
func LoadJVMLib(jvmLibPath string) error {
	// On MacOS we need to preload libjli.dylib to workaround JDK-7131356
	// "No Java runtime present, requesting install".
	// If envar LIBJLI_LOAD; = "yes": load but just log error if load fails, =
	// "force": load and exit with error if load fails.
	if jliLoadEnv := os.Getenv(JLI_LOAD_ENV); jliLoadEnv == JLI_LOAD_YES || jliLoadEnv == JLI_LOAD_FORCE {
		libjliPath := filepath.Join(filepath.Dir(jvmLibPath), "..", "libjli.dylib")
		clibjliPath := cString(libjliPath)
		defer func() {
			if clibjliPath != nil {
				free(clibjliPath)
			}
		}()

		// Do not close JLI library handle until JVM closes
		handlelibjli := C.dlopen((*C.char)(clibjliPath), C.RTLD_NOW|C.RTLD_GLOBAL)
		if handlelibjli == nil {
			if jliLoadEnv == JLI_LOAD_YES {
				log.Printf("WARNING could not dynamically load %s", libjliPath)
			} else if jliLoadEnv == JLI_LOAD_FORCE {
				log.Fatalf("ERROR could not dynamically load %s", libjliPath)
			}
		}
	}

	cs := cString(jvmLibPath)
	defer func() {
		if cs != nil {
			free(cs)
		}
	}()

	libHandle := uintptr(C.dlopen((*C.char)(cs), C.RTLD_NOW|C.RTLD_GLOBAL))
	if libHandle == 0 {
		return errors.New("could not dynamically load libjvm.dylib")
	}

	cs2 := cString("JNI_GetDefaultJavaVMInitArgs")
	defer free(cs2)
	ptr := C.dlsym(unsafe.Pointer(libHandle), (*C.char)(cs2))
	if ptr == nil {
		return errors.New("could not find JNI_GetDefaultJavaVMInitArgs in libjvm.dylib")
	}
	C.var_JNI_GetDefaultJavaVMInitArgs = C.type_JNI_GetDefaultJavaVMInitArgs(ptr)

	cs3 := cString("JNI_CreateJavaVM")
	defer free(cs3)
	ptr = C.dlsym(unsafe.Pointer(libHandle), (*C.char)(cs3))
	if ptr == nil {
		return errors.New("could not find JNI_CreateJavaVM in libjvm.dylib")
	}
	C.var_JNI_CreateJavaVM = C.type_JNI_CreateJavaVM(ptr)
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
//  See http://www.boost.org for most recent version.

#if __IBMCPP__ <= 501
#  define BOOST_NO_STD_ALLOCATOR
#endif

#define BOOST_HAS_MACRO_USE_FACET
#define BOOST_NO_STD_MESSAGES

// Apple doesn't seem to reliably defined a *unix* macro
#if !defined(CYGWIN) && (  defined(__unix__)  \
                        || defined(__unix)    \
                        || defined(unix)      \
                        || defined(__APPLE__) \
                        || defined(__APPLE)   \
                        || defined(APPLE))
#  include <unistd.h>
#endif

//  C++0x headers not yet implemented
//
#  define BOOST_NO_CXX11_HDR_ARRAY
#  define BOOST_NO_CXX11_HDR_CHRONO
#  define BOOST_NO_CXX11_HDR_CODECVT
#  define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE
#  define BOOST_NO_CXX11_HDR_FORWARD_LIST
#  define BOOST_NO_CXX11_HDR_FUTURE
#  define BOOST_NO_CXX11_HDR_INITIALIZER_LIST
#  define BOOST_NO_CXX11_HDR_MUTEX
#  define BOOST_NO_CXX11_HDR_RANDOM
#  define BOOST_NO_CXX11_HDR_RATIO
#  define BOOST_NO_CXX11_HDR_REGEX
#  define BOOST_NO_CXX11_HDR_SYSTEM_ERROR
#  define BOOST_NO_CXX11_HDR_THREAD
#  define BOOST_NO_CXX11_HDR_TUPLE
#  define BOOST_NO_CXX11_HDR_TYPE_TRAITS
#  define BOOST_NO_CXX11_HDR_TYPEINDEX
#  define BOOST_NO_CXX11_HDR_UNORDERED_MAP
#  define BOOST_NO_CXX11_HDR_UNORDERED_SET
#  define BOOST_NO_CXX11_NUMERIC_LIMITS
#  define BOOST_NO_CXX11_ALLOCATOR
#  define BOOST_NO_CXX11_ATOMIC_SMART_PTR
#  define BOOST_NO_CXX11_SMART_PTR
#  define BOOST_NO_CXX11_HDR_FUNCTIONAL

#define BOOST_STDLIB "Visual Age default standard library"


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->
<gradient xmlns:android="http://schemas.android.com/apk/res/android"
    android:startColor="?colorPrimary"
    android:endColor="?colorControlActivated"
    android:centerColor="#f00"
    android:startX="0"
    android:startY="0"
    android:endX="100"
    android:endY="100"
    android:type="linear">
    <item android:offset="0.1" android:color="?colorPrimary"/>
    <item android:offset="0.4" android:color="#fff"/>
    <item android:offset="0.9" android:color="?colorControlActivated"/>
</gradient>


text:
package io.github.binaryfoo;

import io.github.binaryfoo.tlv.Tag;

public class QVsdcTags extends EmvTags {
  public static final TagMetaData METADATA = EmvTags.METADATA.join(TagMetaData.load("qvsdc.yaml"));

  public static final Tag TERMINAL_TX_QUALIFIERS = Tag.fromHex("9F66");
  public static final Tag CARD_TX_QUALIFIERS = Tag.fromHex("9F6C");
  public static final Tag CARD_AUTH_RELATED_DATA = Tag.fromHex("9F69");
}


text:
require 'spec_helper'

describe 'mysql2_chef_gem_test::default' do
  let(:chef_run) do
    ChefSpec::Runner.new do |node|
      node.set['mysql2_chef_gem']['resource_name'] = 'default'
    end.converge('mysql2_chef_gem_test::default')
  end

  context 'when using default parameters' do
    it 'creates mysql2_chef_gem[default]' do
      expect(chef_run).to install_mysql2_chef_gem('default')
    end
  end
end


text:
<?php

class Util {
    static private $sortfield = null;
    static private $sortorder = 1;
    static private function sort_callback(&$a, &$b) {
        if($a[self::$sortfield] == $b[self::$sortfield]) return 0;
        return ($a[self::$sortfield] < $b[self::$sortfield])? -self::$sortorder : self::$sortorder;
    }
    static function sort(&$v, $field, $asc=true) {
        self::$sortfield = $field;
        self::$sortorder = $asc? 1 : -1;
        usort($v, array('util', 'sort_callback'));
    }
}


text:
'use strict';

/**
 * @module protocol/policy
 */

var assert = require('assert');
var consensus = require('./consensus');

/**
 * Maximum transaction version (policy).
 * @const {Number}
 * @default
 */

exports.MAX_TX_VERSION = 2;

/**
 * Maximum transaction base size (policy).
 * @const {Number}
 * @default
 */

exports.MAX_TX_SIZE = consensus.MAX_BLOCK_SIZE / 10;

/**
 * Maximum transaction weight (policy).
 * @const {Number}
 * @default
 */

exports.MAX_TX_WEIGHT = consensus.MAX_BLOCK_WEIGHT / 10;

/**
 * Maximum number of transaction sigops (policy).
 * @const {Number}
 * @default
 */

exports.MAX_TX_SIGOPS = consensus.MAX_BLOCK_SIGOPS / 5;

/**
 * Maximum cost of transaction sigops (policy).
 * @const {Number}
 * @default
 */

exports.MAX_TX_SIGOPS_COST = consensus.MAX_BLOCK_SIGOPS_COST / 5;

/**
 * How much weight a sigop should
 * add to virtual size (policy).
 * @const {Number}
 * @default
 */

exports.BYTES_PER_SIGOP = 20;

/**
 * Minimum relay fee rate (policy).
 * @const {Rate}
 */

exports.MIN_RELAY = 1000;

/**
 * Whether bare multisig outputs
 * should be relayed (policy).
 * @const {Boolean}
 * @default
 */

exports.BARE_MULTISIG = true;

/**
 * Priority threshold for
 * free transactions (policy).
 * @const {Number}
 * @default
 */

exports.FREE_THRESHOLD = consensus.COIN * 144 / 250;

/**
 * Max sigops per redeem script (policy).
 * @const {Number}
 * @default
 */

exports.MAX_P2SH_SIGOPS = 15;

/**
 * Max serialized nulldata size (policy).
 * @const {Number}
 * @default
 */

exports.MAX_OP_RETURN_BYTES = 83;

/**
 * Max pushdata size in nulldata (policy).
 * @const {Number}
 * @default
 */

exports.MAX_OP_RETURN = 80;

/**
 * Max p2wsh stack size. Used for
 * witness malleation checks (policy).
 * @const {Number}
 * @default
 */

exports.MAX_P2WSH_STACK = 100;

/**
 * Max p2wsh push size. Used for
 * witness malleation checks (policy).
 * @const {Number}
 * @default
 */

exports.MAX_P2WSH_PUSH = 80;

/**
 * Max serialized p2wsh size. Used for
 * witness malleation checks (policy).
 * @const {Number}
 * @default
 */

exports.MAX_P2WSH_SIZE = 3600;

/**
 * Default ancestor limit.
 * @const {Number}
 * @default
 */

exports.MEMPOOL_MAX_ANCESTORS = 25;

/**
 * Default maximum mempool size in bytes.
 * @const {Number}
 * @default
 */

exports.MEMPOOL_MAX_SIZE = 100 * 1000000;

/**
 * Time at which transactions
 * fall out of the mempool.
 * @const {Number}
 * @default
 */

exports.MEMPOOL_EXPIRY_TIME = 72 * 60 * 60;

/**
 * Maximum number of orphan transactions.
 * @const {Number}
 * @default
 */

exports.MEMPOOL_MAX_ORPHANS = 100;

/**
 * Minimum block size to create. Block will be
 * filled with free transactions until block
 * reaches this weight.
 * @const {Number}
 * @default
 */

exports.MIN_BLOCK_WEIGHT = 0;

/**
 * Maximum block weight to be mined.
 * @const {Number}
 * @default
 */

exports.MAX_BLOCK_WEIGHT = 1000000 * consensus.WITNESS_SCALE_FACTOR;

/**
 * How much of the block should be dedicated to
 * high-priority transactions (included regardless
 * of fee rate).
 * @const {Number}
 * @default
 */

exports.BLOCK_PRIORITY_WEIGHT = 0;

/**
 * Priority threshold to be reached before
 * switching to fee rate comparison.
 * @const {Number}
 * @default
 */

exports.BLOCK_PRIORITY_THRESHOLD = exports.FREE_THRESHOLD;

/**
 * Calculate minimum fee based on rate and size.
 * @param {Number?} size
 * @param {Rate?} rate - Rate of satoshi per kB.
 * @returns {Amount} fee
 */

exports.getMinFee = function getMinFee(size, rate) {
  var fee;

  if (rate == null)
    rate = exports.MIN_RELAY;

  assert(size >= 0);
  assert(rate >= 0);

  if (size === 0)
    return 0;

  fee = Math.floor(rate * size / 1000);

  if (fee === 0 && rate > 0)
    fee = rate;

  return fee;
};

/**
 * Calculate the minimum fee in order for the transaction
 * to be relayable, but _round to the nearest kilobyte
 * when taking into account size.
 * @param {Number?} size
 * @param {Rate?} rate - Rate of satoshi per kB.
 * @returns {Amount} fee
 */

exports.getRoundFee = function getRoundFee(size, rate) {
  var fee;

  if (rate == null)
    rate = exports.MIN_RELAY;

  assert(size >= 0);
  assert(rate >= 0);

  if (size === 0)
    return 0;

  fee = rate * Math.ceil(size / 1000);

  if (fee === 0 && rate > 0)
    fee = rate;

  return fee;
};

/**
 * Calculate a fee rate based on size and fees.
 * @param {Number} size
 * @param {Amount} fee
 * @returns {Rate}
 */

exports.getRate = function getRate(size, fee) {
  assert(size >= 0);
  assert(fee >= 0);

  if (size === 0)
    return 0;

  return Math.floor(fee * 1000 / size);
};


text:
package core.framework.internal.module;

import core.framework.http.HTTPMethod;
import core.framework.internal.bean.BeanClassValidator;
import core.framework.internal.inject.BeanFactory;
import core.framework.internal.log.LogManager;
import core.framework.internal.stat.StatCollector;
import core.framework.internal.web.HTTPServer;
import core.framework.internal.web.HTTPServerConfig;
import core.framework.internal.web.HTTPServerMetrics;
import core.framework.internal.web.controller.ControllerClassValidator;
import core.framework.internal.web.controller.ControllerHolder;
import core.framework.internal.web.controller.ControllerInspector;
import core.framework.internal.web.route.PathPatternValidator;
import core.framework.internal.web.sys.APIController;
import core.framework.internal.web.sys.DiagnosticController;
import core.framework.internal.web.sys.PropertyController;
import core.framework.module.LambdaController;
import core.framework.util.ASCII;
import core.framework.util.Maps;
import core.framework.web.Controller;
import core.framework.web.SessionContext;
import core.framework.web.WebContext;
import core.framework.web.site.WebDirectory;

import javax.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * @author neo
 */
public class ModuleContext {    // after core.framework.module.App.start(), entire ModuleContext will be GCed
    public final LogManager logManager;
    public final StartupHook startupHook = new StartupHook();
    public final ShutdownHook shutdownHook;
    public final ReadinessProbe probe = new ReadinessProbe();
    public final BeanFactory beanFactory = new BeanFactory();
    public final PropertyManager propertyManager = new PropertyManager();
    public final StatCollector collector = new StatCollector();
    public final HTTPServer httpServer;
    public final HTTPServerConfig httpServerConfig = new HTTPServerConfig();
    public final APIController apiController = new APIController();
    public final BeanClassValidator beanClassValidator = new BeanClassValidator();
    protected final Map<String, Config> configs = Maps.newHashMap();
    final PropertyValidator propertyValidator = new PropertyValidator();
    private BackgroundTaskExecutor backgroundTask;

    public ModuleContext(LogManager logManager) {
        this.logManager = logManager;
        shutdownHook = new ShutdownHook(logManager);
        httpServer = createHTTPServer(logManager);

        var diagnosticController = new DiagnosticController();
        route(HTTPMethod.GET, "/_sys/vm", (LambdaController) diagnosticController::vm, true);
        route(HTTPMethod.GET, "/_sys/thread", (LambdaController) diagnosticController::thread, true);
        route(HTTPMethod.GET, "/_sys/heap", (LambdaController) diagnosticController::heap, true);
        route(HTTPMethod.GET, "/_sys/proc", (LambdaController) diagnosticController::proc, true);
        route(HTTPMethod.GET, "/_sys/property", new PropertyController(propertyManager), true);
        route(HTTPMethod.GET, "/_sys/api", apiController::service, true);
        route(HTTPMethod.GET, "/_sys/api/message", apiController::message, true);
    }

    private HTTPServer createHTTPServer(LogManager logManager) {
        var httpServer = new HTTPServer(logManager);
        beanFactory.bind(WebContext.class, null, httpServer.handler.webContext);
        beanFactory.bind(SessionContext.class, null, httpServer.siteManager.sessionManager);
        beanFactory.bind(WebDirectory.class, null, httpServer.siteManager.webDirectory);

        startupHook.start.add(() -> httpServer.start(httpServerConfig));
        shutdownHook.add(ShutdownHook.STAGE_0, timeout -> httpServer.shutdown());
        shutdownHook.add(ShutdownHook.STAGE_1, httpServer::awaitRequestCompletion);
        shutdownHook.add(ShutdownHook.STAGE_8, timeout -> httpServer.awaitTermination());

        collector.metrics.add(new HTTPServerMetrics(httpServer));
        return httpServer;
    }

    public BackgroundTaskExecutor backgroundTask() {
        if (backgroundTask == null) {
            var backgroundTask = new BackgroundTaskExecutor();
            startupHook.start.add(backgroundTask::start);
            shutdownHook.add(ShutdownHook.STAGE_2, timeout -> backgroundTask.shutdown());
            shutdownHook.add(ShutdownHook.STAGE_3, backgroundTask::awaitTermination);
            this.backgroundTask = backgroundTask;
        }
        return backgroundTask;
    }

    public final void route(HTTPMethod method, String path, Controller controller, boolean skipInterceptor) {
        new PathPatternValidator(path, true).validate();
        var inspector = new ControllerInspector(controller);
        new ControllerClassValidator(inspector.targetClass, inspector.targetMethod).validate();
        String action = "http:" + ASCII.toLowerCase(method.name()) + ":" + path;
        httpServer.handler.route.add(method, path, new ControllerHolder(controller, inspector.targetMethod, inspector.controllerInfo, action, skipInterceptor));
    }

    public <T extends Config> T config(Class<T> configClass, @Nullable String name) {
        String key = configClass.getCanonicalName() + ":" + name;   // not using computeIfAbsent, to avoid concurrent modification in nested call, e.g. httpConfig->publishAPIConfig->apiConfig
        @SuppressWarnings("unchecked")
        T config = (T) configs.get(key);
        if (config == null) {
            try {
                config = configClass(configClass).getConstructor().newInstance();
                config.initialize(this, name);
                configs.put(key, config);
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                throw new Error(e);
            }
        }
        return config;
    }

    public <T> T bind(Type type, @Nullable String name, T instance) {
        beanFactory.bind(type, name, instance);
        return instance;
    }

    public void validate() {
        Set<String> keys = propertyManager.properties.keys();
        propertyValidator.validate(keys);

        for (Config config : configs.values()) {
            config.validate();
        }
    }

    public Optional<String> property(String key) {
        propertyValidator.usedProperties.add(key);
        return propertyManager.property(key);
    }

    protected <T> Class<T> configClass(Class<T> configClass) {
        return configClass;
    }
}


text:
package com.redhat.repository.validator.filter;

import org.junit.Test;

import com.redhat.repository.validator.filter.FileBasedExceptionFilter;
import com.redhat.repository.validator.impl.signature.JarSignatureVerificationException;

import java.io.File;

public class TestFileBasedExceptionFilter extends AbstractExceptionFilterTest {

    @Test
    public void shouldIgnoreMatchingFileAndMatchingException() {
        FileBasedExceptionFilter filter = new FileBasedExceptionFilter("filename.*", null, JarSignatureVerificationException.class ,".*signature found.*");
        Exception ex = new JarSignatureVerificationException(new File("filename"), "foo signature found bar");
        assertExceptionIgnored(filter, ex, new File("filename"));
        // simple test to verify the regex: "filename.*" will also capture the string "filename2"
        ex = new JarSignatureVerificationException(new File("filename2"), "signature found");
        assertExceptionIgnored(filter, ex, new File("filename2"));
    }

    @Test
    public void shouldIgnoreMatchingPathAndMatchingException() {
        FileBasedExceptionFilter filter = new FileBasedExceptionFilter(null, ".*/some/path/.*\\.jar", JarSignatureVerificationException.class, null);
        Exception ex = new JarSignatureVerificationException(new File("/some/path/x.jar"), "some message");
        assertExceptionIgnored(filter, ex, new File("/some/path/x.jar"));
        // simple test to verify the regex: ".*/some/path/.*\.jar" will also capture the string "another/some/path/anotherlib/anotherjar.jar"
        ex = new JarSignatureVerificationException(new File("another/some/path/anotherlib/anotherjar.jar"), "Some message");
        assertExceptionIgnored(filter, ex, new File("another/some/path/x.jar"));
    }

    @Test
    public void shouldNotIgnoreOnlyMatchingFile() {
        final String matchingFilename = "filename";
        final String matchingMessage = "some message";

        //does not match exception
        FileBasedExceptionFilter filter = new FileBasedExceptionFilter(matchingFilename, null, JarSignatureVerificationException.class, matchingMessage);
        Exception ex = new RuntimeException(matchingMessage);
        assertExceptionNotIgnored(filter, ex, new File(matchingFilename));

        //does not match exception message
        ex = new JarSignatureVerificationException(new File(matchingFilename), "other message");
        assertExceptionNotIgnored(filter, ex, new File(matchingFilename));

        //match for check previous tests does not match for their defined reason
        ex = new JarSignatureVerificationException(new File(matchingFilename), matchingMessage);
        assertExceptionNotIgnored(filter, ex, new File(matchingFilename));
    }

    @Test
    public void shouldNotIgnoreOnlyMatchingPath() {
        final String matchingPath = "/some/path/filename";
        final String matchingMessage = "some message";

        //does not match exception message
        FileBasedExceptionFilter filter = new FileBasedExceptionFilter(null, matchingPath, JarSignatureVerificationException.class, matchingMessage);
        Exception ex = new RuntimeException(matchingMessage);
        assertExceptionNotIgnored(filter, ex, new File(matchingPath));

        //does not match exception message
        ex = new JarSignatureVerificationException(new File(matchingPath), "other message");
        assertExceptionNotIgnored(filter, ex, new File(matchingPath));

        //match for check previous tests does not match for their defined reason
        ex = new JarSignatureVerificationException(new File(matchingPath), matchingMessage);
        assertExceptionNotIgnored(filter, ex, new File(matchingPath));
    }

    @Test
    public void shouldNotIgnoreOnlyMatchingExceptionNotMatchingFilename() {
        FileBasedExceptionFilter filter = new FileBasedExceptionFilter("filename.*", null, JarSignatureVerificationException.class, null);
        Exception ex = new JarSignatureVerificationException(new File("foo"), "Some message");
        assertExceptionNotIgnored(filter, ex, new File("foo"));
    }

    @Test
    public void shouldNotIgnoreOnlyMatchingExceptionNotMatchingFilepath() {
        FileBasedExceptionFilter filter = new FileBasedExceptionFilter(null, ".*/some/path/.*\\.jar", JarSignatureVerificationException.class, null);
        Exception ex = new JarSignatureVerificationException(new File("/some/path/x.jar"), "Some message");
        assertExceptionNotIgnored(filter, ex, new File("/some/no/matching/path/x.jar"));
    }

}


text:
//
//  Element.h
//  Thumbprint
//
//  Created by Lee Buck on 4/18/09.
//  Copyright 2009 Blue Bright Ventures. All rights reserved.
//
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.

//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.

//	Commercial licences without many of the obligations of GPL
//	are available for a nomial fee at sales@touchtankapps.com.

//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#import <Foundation/Foundation.h>
#import "TagChunk.h"

@class CSSSelector;
@class DocumentRoot;

/**
 * An Element is the fundemental building block for ElementParser.
 */
@interface Element : TagChunk {
	NSMutableDictionary* attributes;
	BOOL attributesParsed;
	Element* nextElement;
	Element* nextSybling;
	Element* parent;
	int contentsLength;
	NSString* contentsText;
	NSString* key;
	BOOL containsMarkup; // includes entities

	NSObject* domainObject;
}

/**
 *	Returns a dictionary of attributes name/values.
 *	If an attribute had no value in the source (e.g. <table noborders>) then the value will be NSNull
 *	If the attributes have not yet been parsed, this will parser them first.
 */
@property (nonatomic, readonly) NSDictionary* attributes;

/**
 *	The character data inside the element. This text is stripped of tags, whitespace, etc
 *	by stripTags. To see the actual source within the element, use contentsSource
 */
@property (nonatomic, retain) NSString* contentsText;

/**
 *	A case-normalized version of the tagName when appropriate. Used in situations
 *	where the tag name might need to serve as a key into a dictionary
 */
@property (nonatomic, retain) NSString* key;

/**
 *	One or more chunks where encountered within this element
 *	Used for more efficient return of contentsText
 */
@property BOOL containsMarkup;

/**
 *	The length of the text from the end of the start tag to the start of the end tag
 */
@property int contentsLength;

/**
 *	The next Element encountered in the document
 */
@property (nonatomic, retain) Element* nextElement;

/**
 *	The next sybling Element (ie the Element at the same depth with the same parent)
 */
@property (nonatomic, retain) Element* nextSybling;

/**
 *	The parent Element to this Element
 */
@property (nonatomic, assign) Element* parent;

/**
 *	Available for developer's use to hang an object onto this Element
 */
@property (nonatomic, retain) NSObject* domainObject;

/**
 *	Parses the supplied source and return an Element tree with Document element serving as the root
 *	or all top level elements. As HTML, Elements shall be considered case insensative and tag
 *	specific heuristics will be used to close tags intelligently. See ElementParser for details.
 */
+(DocumentRoot*)parseHTML:(NSString*)source;

/**
 *	Parses the supplied source and return an Element tree with Document element serving as the root
 *	or all top level elements. XML, Elements shall be considered case sensative. See ElementParser for details.
 */
+(DocumentRoot*)parseXML:(NSString*)source;

/**
 *	Initializer used by ElementParser. See TagChunk for other intializers
 */
-(instancetype)initWithTag:(TagChunk*)tag caseSensative:(BOOL)aCaseSensative;

/**
 *	Returns true if the element contains the specified attribute.
 *	If the attributes have not yet been parsed, this will parser them first.
 */
-(BOOL)hasAttribute:(NSString*)attr;

/**
 *	Returns the value of a particular attribute (or nil if it doesn't exist)
 *	Note: ElementParser does not support default attributes
 *	If the attributes have not yet been parsed, this will parser them first.
 */
-(NSString*)attribute:(NSString*)attr;

/**
 *	Convenience method to compare an element's tag name.
 *	Comparision will be cases sensative for XML elements and insensative for HTML elements.
 */
-(BOOL)isEqualToString:(NSString*)string;

/**
 * Convenience methods for getting NSObjects from elements and their children
 */
- (NSString*)contentsTextOfChildElement:(NSString*)selector;

@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSNumber *contentsNumber;

- (NSNumber*)contentsNumberOfChildElement:(NSString*)selector;

/**
 *	An array of child Elements in document order
 */
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSArray *childElements;

/**
 *	An array of child Elements in document order
 */
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSArray *syblingElements;

/**
 *	The first child Element for this element (or nil if none).
 */
@property (NS_NONATOMIC_IOSONLY, readonly, strong) Element *firstChild;

/**
 *	A dictionary containing the tagnames of children as keys
 *	and the contentsText of the children as values.
 *	If duplicate children tag names are encountered, only the last will
 *	appear in the dictionary.
 */
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSDictionary *contentsOfChildren;

/**
 *	Returns true if the supplied Element is a parent of receiver or one of its parents
 */
-(BOOL)hasAncestor:(Element*)ancestor;

/**
 *	Returns the nextElement but only if it has the scope Element as an ancestor
 */
-(Element*)nextElementWithinScope:(Element*)scope;

/**
 *	Returns true if the class attribute contains the class name (perhaps as one of multiple classes).
 */
-(BOOL)hasClassName:(NSString*)aClassName;

/**
 *	Returns true receiver can be a chlid of aParent. Used by ElementParser to prevent inappropriate
 *	nesting in HTML (e.g. <p><p>)
 */
-(BOOL)acceptsParent:(Element*)aParent;

/**
 *	Debugging method
 */
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *dumpTree;

/**
 *	The source between the end of the open tag and the beginning of the close tag
 */
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *contentsSource;

/**
 *	Convenience method for using a selector to find elements within the receiver that match.
 *	See CSSSelector for details.
 */
-(Element*)elementWithCSSSelector:(CSSSelector*)selector;

/**
 *	Convenience method for using a selector to find elements within the receiver that match
 *	See CSSSelector for details.
 */
-(Element*)selectElement:(NSString*)cssSelectorString;

/**
 *	Convenience method for using a selector to find elements within the receiver that match
 *	See CSSSelector for details.
 */
-(NSArray*)elementsWithCSSSelector:(CSSSelector*)selector;

/**
 *	Convenience method for using a selector to find elements within the receiver that match
 *	See CSSSelector for details.
 */
-(NSArray*)selectElements:(NSString*)cssSelectorString;

@end


text:
package com.springer.gocd.cloudfoundry;

import com.thoughtworks.go.plugin.api.config.Property;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration;
import com.thoughtworks.go.plugin.api.material.packagerepository.PackageMaterialConfiguration;
import com.thoughtworks.go.plugin.api.material.packagerepository.PackageMaterialProperty;
import com.thoughtworks.go.plugin.api.material.packagerepository.RepositoryConfiguration;

import com.thoughtworks.go.plugin.api.response.validation.ValidationResult;

import static com.thoughtworks.go.plugin.api.config.Property.*;

public class CloudFoundryConfig implements PackageMaterialConfiguration {
    public static final String USERNAME_FIELD_NAME = "USERNAME";

    public static final String REPO_URL_FIELD_NAME = "REPO_URL";

    public static final String PASSWORD_FIELD_NAME = "PASSWORD";

    public static final String SPACE_FIELD_NAME = "SPACE";

    public static final String APP_NAME_FIELD_NAME = "APP_NAME";

    public static final String ORG_NAME_FIELD_NAME = "ORG_NAME";

    private static final Logger LOGGER = Logger.getLoggerFor(CloudFoundryConfig.class);

    public static final Property apiUrl = new PackageMaterialProperty(REPO_URL_FIELD_NAME)
            .with(DISPLAY_NAME, "CloudFoundry API URL")
            .with(Property.REQUIRED, Boolean.TRUE)
            .with(DISPLAY_ORDER, 0);

    public static final Property username = new PackageMaterialProperty(USERNAME_FIELD_NAME)
            .with(DISPLAY_NAME, "Username")
            .with(Property.REQUIRED, Boolean.TRUE)
            .with(DISPLAY_ORDER, 1);

    public static final Property password = new PackageMaterialProperty(PASSWORD_FIELD_NAME)
            .with(DISPLAY_NAME, "Password")
            .with(DISPLAY_ORDER, 2)
            .with(SECURE, Boolean.TRUE);

    public static final Property space = new PackageMaterialProperty(SPACE_FIELD_NAME)
            .with(DISPLAY_NAME, "Space");

    public static final Property appName = new PackageMaterialProperty(APP_NAME_FIELD_NAME)
        .with(DISPLAY_NAME, "App Name");

    public static final Property orgName = new PackageMaterialProperty(ORG_NAME_FIELD_NAME)
        .with(DISPLAY_NAME, "Organisation Name");

    @Override
    public RepositoryConfiguration getRepositoryConfiguration() {
        LOGGER.debug("getRepositoryConfiguration called.");

        RepositoryConfiguration repoConfig = new RepositoryConfiguration();
        repoConfig.add(apiUrl);
        repoConfig.add(username);
        repoConfig.add(password);

        return repoConfig;
    }

    @Override
    public PackageConfiguration getPackageConfiguration() {
        LOGGER.debug("getPackageConfiguration called.");
        PackageConfiguration packageConfig = new PackageConfiguration();

        packageConfig.add(space);
        packageConfig.add(appName);
        packageConfig.add(orgName);
        return packageConfig;
    }

    @Override
    public ValidationResult isRepositoryConfigurationValid(RepositoryConfiguration repositoryConfiguration) {
        LOGGER.debug("isRepositoryConfigurationValid called.");

        // Not certain what to validate here.
        ValidationResult result = new ValidationResult();

        return result;
    }

    @Override
    public ValidationResult isPackageConfigurationValid(PackageConfiguration packageConfiguration, RepositoryConfiguration repositoryConfiguration) {
        LOGGER.debug("isPackageConfigurationValid called.");
        // Not certain what to validate here.
        return new ValidationResult();
    }
}


text:
using System.Text;
using System.Collections.Generic;
using Confluent.Kafka.Serialization;

namespace Confluent.Kafka.Examples.MultiProducer
{
    /// <summary>
    ///     An example showing how to wrap a single Producer to produce messages using
    ///     different serializers.
    /// </summary>
    /// <remarks>
    ///     If you only want to use a single pair of serializers in your application,
    ///     you should use the Producer<TKey, TValue> constructor instead.
    /// </remarks>
    public class Program
    {
        public static void Main(string[] args)
        {
            var config = new Dictionary<string, object> { { "bootstrap.servers", args[0] } };

            using (var producer = new Producer(config))
            {
                // sProducer1 is a lightweight wrapper around a Producer instance that adds
                // (string, string) serialization. Note that sProducer1 does not need to be
                // (and cannot be) disposed.
                var sProducer1 = producer.GetSerializingProducer<string, string>(new StringSerializer(Encoding.UTF8), new StringSerializer(Encoding.UTF8));

                // sProducer2 is another lightweight wrapper around kafkaProducer that adds
                // (null, int) serialization. When you do not wish to write any data to a key
                // or value, the Null type should be used.
                var sProducer2 = producer.GetSerializingProducer<Null, int>(new NullSerializer(), new IntSerializer());

                // write (string, string) data to topic "first-topic", statically type checked.
                sProducer1.ProduceAsync("first-topic", "my-key-value", "my-value");

                // write (null, int) data to topic "second-data". statically type checked, using
                // the same underlying producer as the producer1.
                sProducer2.ProduceAsync("second-topic", null, 42);

                // producers are NOT tied to topics. Although it's unusual that you might want to
                // do so, you can use different serializing producers to write to the same topic.
                sProducer2.ProduceAsync("first-topic", null, 107);

                // ProducerAsync tasks are not waited on - there is a good chance they are still
                // in flight.
                producer.Flush();
            }
        }
    }
}


text:
using System;
using System.Reflection;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace MixedRealityToolkit.Utilities.Attributes
{
    // Displays an int or float property as a range
    [AttributeUsage(AttributeTargets.Property)]
    public sealed class RangePropAttribute : DrawOverrideAttribute
    {

        public enum TypeEnum
        {
            Float,
            Int,
        }

        public float MinFloat { get; private set; }
        public float MaxFloat { get; private set; }
        public int MinInt { get; private set; }
        public int MaxInt { get; private set; }
        public TypeEnum Type { get; private set; }

        public RangePropAttribute(float min, float max)
        {
            MinFloat = min;
            MaxFloat = max;
            Type = TypeEnum.Float;
        }

        public RangePropAttribute(int min, int max)
        {
            MinInt = min;
            MaxInt = max;
            Type = TypeEnum.Int;
        }

#if UNITY_EDITOR
        public override void DrawEditor(UnityEngine.Object target, FieldInfo field, SerializedProperty property)
        {
            // (safe since this is property-only attribute)
            throw new NotImplementedException();
        }

        public override void DrawEditor(UnityEngine.Object target, PropertyInfo prop)
        {
            if (prop.PropertyType == typeof(int))
            {
                int propIntValue = (int)prop.GetValue(target, null);
                propIntValue = EditorGUILayout.IntSlider(SplitCamelCase(prop.Name), propIntValue, MinInt, MaxInt);
                prop.SetValue(target, propIntValue, null);
            }
            else if (prop.PropertyType == typeof(float))
            {
                float propFloatValue = (float)prop.GetValue(target, null);
                propFloatValue = EditorGUILayout.Slider(SplitCamelCase(prop.Name), propFloatValue, MinFloat, MaxFloat);
                prop.SetValue(target, propFloatValue, null);
            }
        }
#endif

    }
}


text: Common classes and utils for Tensorflow


text:
using System.Collections.Generic;

namespace EasyNetQ
{
    /// <inheritdoc />
    public class ConsumerConfiguration : IConsumerConfiguration
    {
        /// <summary>
        ///     Create ConsumerConfiguration
        /// </summary>
        /// <param name="defaultPrefetchCount"></param>
        public ConsumerConfiguration(ushort defaultPrefetchCount)
        {
            PrefetchCount = defaultPrefetchCount;
        }

        /// <summary>
        ///     Indicates whether a consumer is in exclusive mode or not
        /// </summary>
        public bool IsExclusive { get; private set; }

        /// <summary>
        ///     Prefetch count
        /// </summary>
        public ushort PrefetchCount { get; private set; }

        /// <summary>
        ///     Arguments
        /// </summary>
        public IDictionary<string, object> Arguments { get; private set; }

        /// <inheritdoc />
        public IConsumerConfiguration WithArgument(string name, object value)
        {
            (Arguments ??= new Dictionary<string, object>())[name] = value;
            return this;
        }

        /// <inheritdoc />
        public IConsumerConfiguration WithExclusive(bool isExclusive = true)
        {
            IsExclusive = isExclusive;
            return this;
        }

        /// <inheritdoc />
        public IConsumerConfiguration WithPrefetchCount(ushort prefetchCount)
        {
            PrefetchCount = prefetchCount;
            return this;
        }
    }

    /// <summary>
    /// Allows consumer configuration to be fluently extended without adding overloads to IBus
    ///
    /// e.g.
    /// x => x.WithPrefetchCount(42)
    /// </summary>
    public interface IConsumerConfiguration
    {
        /// <summary>
        ///     Switch a consumer to exclusive mode
        /// </summary>
        /// <returns>IConsumerConfiguration</returns>
        IConsumerConfiguration WithExclusive(bool isExclusive = true);

        /// <summary>
        /// Sets prefetch count
        /// </summary>
        /// <param name="prefetchCount">The prefetchCount to set</param>
        /// <returns>IConsumerConfiguration</returns>
        IConsumerConfiguration WithPrefetchCount(ushort prefetchCount);

        /// <summary>
        /// Sets a raw argument for consumer declaration
        /// </summary>
        /// <param name="name">The argument name to set</param>
        /// <param name="value">The argument value to set</param>
        /// <returns>IConsumerConfiguration</returns>
        IConsumerConfiguration WithArgument(string name, object value);
    }
}


text:
/**
 * See (http://jquery.com/).
 * @name jQuery
 * @class
 * See the jQuery Library  (http://jquery.com/) for full details.  This just
 * documents the function and classes that are added to jQuery by this plug-in.
 */

/**
 * See (http://jquery.com/)
 * @name fn
 * @class
 * See the jQuery Library  (http://jquery.com/) for full details.  This just
 * documents the function and classes that are added to jQuery by this plug-in.
 * @memberOf jQuery
 */

var gettext = jQuery.isFunction(gettext) && gettext || function(i) { return i; }

;(function($){

    var getJsOptions = function(el){
        var data = el.data(), opts = {}, opt,
        excluded = ['adaptor', 'type', 'fieldid', 'plugin'];

        $.each(data, function(k, v){
            if ($.inArray(k.toLowerCase(), excluded) < 0) {
                opts[k] = v;
            }
        })
        return opts;
    };

    $.inherit = function(p, c) {
        for (var x in c) p[x] = c[x];
    };

    $.editlive = (function($) {
        $self = this;

        return {

            /**
             * jQuery.editlive.load
             * @function
             */
            load: function(el) {
                (el && $(el).find('editlive') || $('editlive')).each(function(k, v) {
                    $.editlive.loadWidget(v);
                });
            },

            loadWidget: function(el){
                var el = $(el);
                var initialized = el.data('initialized') || false;
                if (initialized) return true;
                else {
                    var widgetname = el.data('widget') || el.data('type');
                    if ($.isFunction($.editliveWidgets[widgetname])) {
                        var opts, options, input;
                        var opts  = getJsOptions(el);

                        if ($.editliveWidgets[widgetname].prototype._standalone) {
                            // Special case for ajaxforms and listactions
                            input = el;
                        }
                        else {
                            // We start by checking for a close match. Theorically there
                            // shouldn't be two fields with the same id, but in reality it
                            // does happens and it does fuck up editlive.
                            input_id = '#'+ el.data('field-id');
                            input = el.prev(input_id);
                            if (!input.get(0)) input = el.closest(input_id);
                            if (!input.get(0)) input = el.parent().find(input_id);
                            if (!input.get(0)) input = $(input_id);
                        }

                        input.data('widget.editlive', el);
                        input[widgetname]([input, opts]);
                        el.data('initialized', true);
                    }

                }
            }
        }

    })($);

    $.fn.editlive = function(method, arg) {
        var editlive = $(this).data('editlive');
        if (editlive) {
            switch(method) {
                case 'link':
                    $(arg).text(editlive._get_value());
                    $(this).bind('editlivesuccess', function(){
                        $(arg).text(editlive._get_value());
                    });
                break;
                case 'val':
                    if (arg) {
                        editlive._set_value(arg);
                        editlive.change();
                        return arg;
                    }
                    else {
                        return editlive._get_value();
                    }
                break;
            }
        }
    };

    $(function(){
        $.editlive.load();
        $('[rel="tooltip"]').tooltip();
    });
})(jQuery);


text:
<?php

//Get post id
$post_id = isset($_GET['id']) ? $_GET['id'] : -1;

// Retrieve data from database
$q = mysqli_query($db, "
  SELECT
    *,
    DATE_FORMAT(post_created, '%d.%m.%Y %H:%i') post_created
  FROM posts
    NATURAL JOIN authors
  WHERE post_id=$post_id");

$post = mysqli_fetch_assoc($q);


text:
package org.springframework.cloud.sleuth.stream;

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

import org.springframework.cloud.sleuth.Span;

import com.fasterxml.jackson.annotation.JsonInclude;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * Data transfer object for a collection of spans from a given host.
 *
 * @author Dave Syer
 *
 */
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@Data
@AllArgsConstructor
public class Spans {

	private Host host;
	private List<Span> spans = Collections.emptyList();

}


text:
package org.apache.commons.math;

/**
 * Exeption thrown when a sample contains several entries at the same abscissa.
 *
 * @since 1.2
 * @version $Revision: 620312 $ $Date: 2008-02-10 12:28:59 -0700 (Sun, 10 Feb 2008) $
 */
public class DuplicateSampleAbscissaException extends MathException  {

    /** Serializable version identifier */
    private static final long serialVersionUID = -2271007547170169872L;

    /**
     * Construct an exception indicating the duplicate abscissa.
     * @param abscissa duplicate abscissa
     * @param i1 index of one entry having the duplicate abscissa
     * @param i2 index of another entry having the duplicate abscissa
     */
    public DuplicateSampleAbscissaException(double abscissa, int i1, int i2) {
        super("Abscissa {0} is duplicated at both indices {1} and {2}",
              new Object[] { new Double(abscissa), new Integer(i1), new Integer(i2) });
    }

    /**
     * Get the duplicate abscissa.
     * @return duplicate abscissa
     */
    public double getDuplicateAbscissa() {
        return ((Double) getArguments()[0]).doubleValue();
    }

}


text:
use Win32::OLE::Const;
my $excelAppl = Win32::OLE->GetActiveObject('Excel.Application')
  || Win32::OLE->new('Excel.Application', 'Quit');

#ophalen van argumenten
@ARGV or die "Geef een argument nl. de filenaam van het excel-bestand\n";

my $fso = Win32::OLE->new("Scripting.FileSystemObject");
my $naam=$ARGV[0];

my $book;

if ($fso->FileExists($naam)) {
  my $padnaam = $fso->GetAbsolutePathName($naam);
  $book=$excelAppl->{Workbooks}->Open($padnaam); #volledige padnaam
}
else
{
    my $map = $fso->GetAbsolutePathName("."); #de huidige directory
    my $padnaam = $map."\\".$naam;            #bouw de absolute naam
    $book = $excelAppl->{Workbooks}->Add();   #voeg een werkboek toe
    $book->SaveAs($padnaam);                  #bewaar onder de juiste naam
}
print "\naantal werksheets: $book->{Worksheets}->{Count}\n";


text:
/*
  Author: Matt Wright
  Version 2.2: Calls htonl in the right places 20000620
  Version 2.3: Gets typed messages right.
 */

/* Here are the possible values of the state field: */

#define EMPTY 0	       /* Nothing written to packet yet */
#define ONE_MSG_ARGS 1 /* Packet has a single message; gathering arguments */
#define NEED_COUNT 2   /* Just opened a bundle; must write message name or
			  open another bundle */
#define GET_ARGS 3     /* Getting arguments to a message.  If we see a message
			  name or a bundle open/close then the current message
			  will end. */
#define DONE 4         /* All open bundles have been closed, so can't write
		          anything else */

#include "OSC-client.h"

// CR ADDED
#include <stdio.h>

char *OSC_errorMessage;

static int strlen(char *s);
static int OSC_padString(char *dest, char *str);
static int OSC_padStringWithAnExtraStupidComma(char *dest, char *str);
static int OSC_WritePadding(char *dest, int i);
static int CheckTypeTag(OSCbuf *buf, char expectedType);

void OSC_initBuffer(OSCbuf *buf, int size, char *byteArray) {
    buf->buffer = byteArray;
    buf->size = size;
    OSC_resetBuffer(buf);
}

void OSC_resetBuffer(OSCbuf *buf) {
    buf->bufptr = buf->buffer;
    buf->state = EMPTY;
    buf->bundleDepth = 0;
    buf->prevCounts[0] = 0;
    buf->gettingFirstUntypedArg = 0;
    buf->typeStringPtr = 0;
}

int OSC_isBufferEmpty(OSCbuf *buf) {
    return buf->bufptr == buf->buffer;
}

int OSC_freeSpaceInBuffer(OSCbuf *buf) {
    return buf->size - (buf->bufptr - buf->buffer);
}

int OSC_isBufferDone(OSCbuf *buf) {
    return (buf->state == DONE || buf->state == ONE_MSG_ARGS);
}

char *OSC_getPacket(OSCbuf *buf) {
#ifdef ERROR_CHECK_GETPACKET
    if (buf->state == DONE || buf->state == ONE_MSG_ARGS) {
	return buf->buffer;
    } else {
	OSC_errorMessage = "Packet has unterminated bundles";
	return 0;
    }
#else
    return buf->buffer;
#endif
}

int OSC_packetSize(OSCbuf *buf) {
#ifdef ERROR_CHECK_PACKETSIZE
    if (buf->state == DONE || buf->state == ONE_MSG_ARGS) {
	return (buf->bufptr - buf->buffer);
    } else {
        OSC_errorMessage = "Packet has unterminated bundles";
        return 0;
    }
#else
    return (buf->bufptr - buf->buffer);
#endif
}

#define CheckOverflow(buf, bytesNeeded) { \
    if ((bytesNeeded) > OSC_freeSpaceInBuffer(buf)) { \
	OSC_errorMessage = "buffer overflow"; \
	return 1; \
    } \
}

static void PatchMessageSize(OSCbuf *buf) {
    int4byte size;
    size = buf->bufptr - ((char *) buf->thisMsgSize) - 4;
    *(buf->thisMsgSize) = htonl(size);
}

int OSC_openBundle(OSCbuf *buf, OSCTimeTag tt) {
    if (buf->state == ONE_MSG_ARGS) {
	OSC_errorMessage = "Can't open a bundle in a one-message packet";
	return 3;
    }

    if (buf->state == DONE) {
	OSC_errorMessage = "This packet is finished; can't open a new bundle";
	return 4;
    }

    if (++(buf->bundleDepth) >= MAX_BUNDLE_NESTING) {
	OSC_errorMessage = "Bundles nested too deeply; change MAX_BUNDLE_NESTING in OpenSoundControl.h";
	return 2;
    }

    if (CheckTypeTag(buf, '\0')) return 9;

    if (buf->state == GET_ARGS) {
	PatchMessageSize(buf);
    }

    if (buf->state == EMPTY) {
	/* Need 16 bytes for "#bundle" and time tag */
	CheckOverflow(buf, 16);
    } else {
	/* This bundle is inside another bundle, so we need to leave
	   a blank size count for the size of this current bundle. */
	CheckOverflow(buf, 20);
	*((int4byte *)buf->bufptr) = 0xaaaaaaaa;
        buf->prevCounts[buf->bundleDepth] = (int4byte *)buf->bufptr;

	buf->bufptr += 4;
    }

    buf->bufptr += OSC_padString(buf->bufptr, "#bundle");

    *((OSCTimeTag *) buf->bufptr) = tt;

    if (htonl(1) != 1) {
	/* Byte swap the 8-byte integer time tag */
	int4byte *intp = (int4byte *)buf->bufptr;
	intp[0] = htonl(intp[0]);
	intp[1] = htonl(intp[1]);

#ifdef HAS8BYTEINT
	{ /* tt is a 64-bit int so we have to swap the two 32-bit words.
	    (Otherwise tt is a struct of two 32-bit words, and even though
	     each word was wrong-endian, they were in the right order
	     in the struct.) */
	    int4byte temp = intp[0];
	    intp[0] = intp[1];
	    intp[1] = temp;
	}
#endif
    }

    buf->bufptr += sizeof(OSCTimeTag);

    buf->state = NEED_COUNT;

    buf->gettingFirstUntypedArg = 0;
    buf->typeStringPtr = 0;
    return 0;
}

int OSC_closeBundle(OSCbuf *buf) {
    if (buf->bundleDepth == 0) {
	/* This handles EMPTY, ONE_MSG, ARGS, and DONE */
	OSC_errorMessage = "Can't close bundle; no bundle is open!";
	return 5;
    }

    if (CheckTypeTag(buf, '\0')) return 9;

    if (buf->state == GET_ARGS) {
        PatchMessageSize(buf);
    }

    if (buf->bundleDepth == 1) {
	/* Closing the last bundle: No bundle size to patch */
	buf->state = DONE;
    } else {
	/* Closing a sub-bundle: patch bundle size */
	int size = buf->bufptr - ((char *) buf->prevCounts[buf->bundleDepth]) - 4;
	*(buf->prevCounts[buf->bundleDepth]) = htonl(size);
	buf->state = NEED_COUNT;
    }

    --buf->bundleDepth;
    buf->gettingFirstUntypedArg = 0;
    buf->typeStringPtr = 0;
    return 0;
}

int OSC_closeAllBundles(OSCbuf *buf) {
    if (buf->bundleDepth == 0) {
        /* This handles EMPTY, ONE_MSG, ARGS, and DONE */
        OSC_errorMessage = "Can't close all bundles; no bundle is open!";
        return 6;
    }

    if (CheckTypeTag(buf, '\0')) return 9;

    while (buf->bundleDepth > 0) {
	OSC_closeBundle(buf);
    }
    buf->typeStringPtr = 0;
    return 0;
}

int OSC_writeAddress(OSCbuf *buf, char *name) {
    int4byte paddedLength;

    if (buf->state == ONE_MSG_ARGS) {
	OSC_errorMessage = "This packet is not a bundle, so you can't write another address";
	return 7;
    }

    if (buf->state == DONE) {
        OSC_errorMessage = "This packet is finished; can't write another address";
        return 8;
    }

    if (CheckTypeTag(buf, '\0')) return 9;

    paddedLength = OSC_effectiveStringLength(name);

    if (buf->state == EMPTY) {
	/* This will be a one-message packet, so no sizes to worry about */
	CheckOverflow(buf, paddedLength);
	buf->state = ONE_MSG_ARGS;
    } else {
	/* GET_ARGS or NEED_COUNT */
	CheckOverflow(buf, 4+paddedLength);
	if (buf->state == GET_ARGS) {
	    /* Close the old message */
	    PatchMessageSize(buf);
	}
	buf->thisMsgSize = (int4byte *)buf->bufptr;
	*(buf->thisMsgSize) = 0xbbbbbbbb;
	buf->bufptr += 4;
	buf->state = GET_ARGS;
    }

    /* Now write the name */
    buf->bufptr += OSC_padString(buf->bufptr, name);
    buf->typeStringPtr = 0;
    buf->gettingFirstUntypedArg = 1;

    return 0;
}

int OSC_writeAddressAndTypes(OSCbuf *buf, char *name, char *types) {
    int result;
    int4byte paddedLength;

    if (CheckTypeTag(buf, '\0')) return 9;

    result = OSC_writeAddress(buf, name);

    if (result) return result;

    paddedLength = OSC_effectiveStringLength(types);

    CheckOverflow(buf, paddedLength);

    buf->typeStringPtr = buf->bufptr + 1; /* skip comma */
    buf->bufptr += OSC_padString(buf->bufptr, types);

    buf->gettingFirstUntypedArg = 0;
    return 0;
}

static int CheckTypeTag(OSCbuf *buf, char expectedType) {
    if (buf->typeStringPtr) {
	if (*(buf->typeStringPtr) != expectedType) {
	    if (expectedType == '\0') {
		OSC_errorMessage =
		    "According to the type tag I expected more arguments.";
	    } else if (*(buf->typeStringPtr) == '\0') {
		OSC_errorMessage =
		    "According to the type tag I didn't expect any more arguments.";
	    } else {
		OSC_errorMessage =
		    "According to the type tag I expected an argument of a different type.";
		printf("* Expected %c, string now %s\n", expectedType, buf->typeStringPtr);
	    }
	    return 9;
	}
	++(buf->typeStringPtr);
    }
    return 0;
}

int OSC_writeFloatArg(OSCbuf *buf, float arg) {
    int4byte *intp;
//    int result;

    CheckOverflow(buf, 4);

    if (CheckTypeTag(buf, 'f')) return 9;

    /* Pretend arg is a long int so we can use htonl() */
    intp = ((int4byte *) &arg);
    *((int4byte *) buf->bufptr) = htonl(*intp);

    buf->bufptr += 4;

    buf->gettingFirstUntypedArg = 0;
    return 0;
}

int OSC_writeFloatArgs(OSCbuf *buf, int numFloats, float *args) {
    int i;
    int4byte *intp;

    CheckOverflow(buf, 4 * numFloats);

    /* Pretend args are long ints so we can use htonl() */
    intp = ((int4byte *) args);

    for (i = 0; i < numFloats; i++) {
	if (CheckTypeTag(buf, 'f')) return 9;
	*((int4byte *) buf->bufptr) = htonl(intp[i]);
	buf->bufptr += 4;
    }

    buf->gettingFirstUntypedArg = 0;
    return 0;
}

int OSC_writeIntArg(OSCbuf *buf, int4byte arg) {
    CheckOverflow(buf, 4);
    if (CheckTypeTag(buf, 'i')) return 9;

    *((int4byte *) buf->bufptr) = htonl(arg);
    buf->bufptr += 4;

    buf->gettingFirstUntypedArg = 0;
    return 0;
}

int OSC_writeStringArg(OSCbuf *buf, char *arg) {
    int len;

    if (CheckTypeTag(buf, 's')) return 9;

    len = OSC_effectiveStringLength(arg);

    if (buf->gettingFirstUntypedArg && arg[0] == ',') {
	/* This un-type-tagged message starts with a string
	   that starts with a comma, so we have to escape it
	   (with a double comma) so it won't look like a type
	   tag string. */

	CheckOverflow(buf, len+4); /* Too conservative */
	buf->bufptr +=
	    OSC_padStringWithAnExtraStupidComma(buf->bufptr, arg);

    } else {
	CheckOverflow(buf, len);
	buf->bufptr += OSC_padString(buf->bufptr, arg);
    }

    buf->gettingFirstUntypedArg = 0;
    return 0;

}

// CR ADDED
int OSC_writeSCStringArg(OSCbuf *buf, char *arg) {
    int len;

//    if (CheckTypeTag(buf, 's')) return 9;
//  SC uses an S for strings (s means symbol)
    if (CheckTypeTag(buf, 's')) return 9;

    len = OSC_effectiveStringLength(arg);

    if (buf->gettingFirstUntypedArg && arg[0] == ',') {
	/* This un-type-tagged message starts with a string
	   that starts with a comma, so we have to escape it
	   (with a double comma) so it won't look like a type
	   tag string. */

	CheckOverflow(buf, len+4); /* Too conservative */
	buf->bufptr +=
	    OSC_padStringWithAnExtraStupidComma(buf->bufptr, arg);

    } else {
	CheckOverflow(buf, len);
	buf->bufptr += OSC_padString(buf->bufptr, arg);
    }

    buf->gettingFirstUntypedArg = 0;
    return 0;

}

/* String utilities */

static int strlen(char *s) {
    int i;
    for (i=0; s[i] != '\0'; i++) /* Do nothing */ ;
    return i;
}

#define STRING_ALIGN_PAD 4
int OSC_effectiveStringLength(char *string) {
    int len = strlen(string) + 1;  /* We need space for the null char. */

    /* Round up len to next multiple of STRING_ALIGN_PAD to account for alignment padding */
    if ((len % STRING_ALIGN_PAD) != 0) {
        len += STRING_ALIGN_PAD - (len % STRING_ALIGN_PAD);
    }
    return len;
}

static int OSC_padString(char *dest, char *str) {
    int i;

    for (i = 0; str[i] != '\0'; i++) {
        dest[i] = str[i];
    }

    return OSC_WritePadding(dest, i);
}

static int OSC_padStringWithAnExtraStupidComma(char *dest, char *str) {
    int i;

    dest[0] = ',';
    for (i = 0; str[i] != '\0'; i++) {
        dest[i+1] = str[i];
    }

    return OSC_WritePadding(dest, i+1);
}

static int OSC_WritePadding(char *dest, int i) {
    dest[i] = '\0';
    i++;

    for (; (i % STRING_ALIGN_PAD) != 0; i++) {
	dest[i] = '\0';
    }

    return i;
}


text:
import django
import pytest
from admin_honeypot.models import LoginAttempt
from django.conf import settings
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase

try:
    # Python 2.7
    from urllib import quote_plus
except ImportError:
    # Python 3+
    from urllib.parse import quote_plus

class AdminHoneypotTest(TestCase):
    maxDiff = None

    @property
    def admin_login_url(self):
        return reverse('admin:login')

    @property
    def admin_url(self):
        return reverse('admin:index')

    @property
    def honeypot_login_url(self):
        return reverse('admin_honeypot:login')

    @property
    def honeypot_url(self):
        return reverse('admin_honeypot:index')

    def test_same_content(self):
        """
        The honeypot should be an exact replica of the admin login page,
        with the exception of where the form submits to and the CSS to
        hide the user tools.
        """

        admin_html = self.client.get(self.admin_url, follow=True).content.decode('utf-8')
        honeypot_html = (self.client.get(self.honeypot_url, follow=True).content.decode('utf-8')
            # /admin/login/ -> /secret/login/
            .replace(self.honeypot_login_url, self.admin_login_url)

            # "/admin/" -> "/secret/"
            .replace('"{0}"'.format(self.honeypot_url), '"{0}"'.format(self.admin_url))

            # %2fadmin%2f -> %2fsecret%2f
            .replace(quote_plus(self.honeypot_url), quote_plus(self.admin_url))
        )

        self.assertEqual(honeypot_html, admin_html)

    def test_create_login_attempt(self):
        """
        A new LoginAttempt object is created
        """
        data = {
            'username': 'admin',
            'password': 'letmein'
        }
        self.client.post(self.honeypot_login_url, data)
        attempt = LoginAttempt.objects.latest('pk')
        self.assertEqual(data['username'], attempt.username)
        self.assertEqual(data['username'], str(attempt))

    def test_email_admins(self):
        """
        An email is sent to settings.ADMINS
        """
        self.client.post(self.honeypot_login_url, {
            'username': 'admin',
            'password': 'letmein'
        })
        # CONSIDER: Is there a better way to do this?
        self.assertTrue(len(mail.outbox) > 0)  # We sent at least one email...
        self.assertIn(settings.ADMINS[0][1], mail.outbox[0].to)  # ...to an admin

    def test_trailing_slash(self):
        """
        /admin redirects to /admin/ permanent redirect.
        """
        url = self.honeypot_url + 'foo/'
        redirect_url = self.honeypot_login_url + '?next=' + url

        response = self.client.get(url.rstrip('/'), follow=True)
        self.assertRedirects(response, redirect_url, status_code=301)

    def test_real_url_leak(self):
        """
        A test to make sure the real admin URL isn't leaked in the honeypot
        login form page.
        """

        honeypot_html = self.client.get(self.honeypot_url, follow=True).content.decode('utf-8')
        self.assertNotIn('{0}'.format(self.admin_url), honeypot_html)
        self.assertNotIn('{0}'.format(self.admin_login_url), honeypot_html)