text:
package com.tazine.base.classes;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;

/**
 * Class类中的所有方法
 *
 * @author frank
 * @date 2017/12/15
 */
public class ClassActions {

    public static void main(String[] args) throws IOException {

        forName();

        // 当前类class文件所在的包目录
        System.out.println(ClassActions.class.getResource(""));
        // class path
        System.out.println(ClassActions.class.getResource("/"));

        // class path
        System.out.println(ClassActions.class.getClassLoader().getResource(""));

        URL url = ClassActions.class.getResource("ClassDemo.class");
        System.out.println(url.getPath());

        Enumeration<URL> urls = ClassActions.class.getClassLoader().getResources("com.tazine.base".replace(".", "/"));
        if (null == urls || !urls.hasMoreElements()) {
            System.out.println("null");
        }
        while (urls.hasMoreElements()) {
            System.out.println(urls.nextElement().getPath());
        }

        System.out.println();
        File file = new File("/usr/local/Cellar/tomcat/8.5.14/libexec/webapps/examples/index.html");
        try {
            System.out.println("URI -- " + file.toURI());
            System.out.println("URL -- " + file.toURI().toURL());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Class.forName() 默认初始化
     */
    private static void forName() {
        try {
            // Class.forName("com.tazine.base.classes.ClassUtils");
            Class.forName("com.tazine.base.classes.ClassUtils", false, Thread.currentThread().getContextClassLoader());
            // Class.forName() 默认会为Class进行初始化,初始化Class会执行static代码块和staic变量初始化
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}


text:
function setEigenvalues( obj, gamma )
% SETEIGENVALUES  Save eigenvalues of an nlsaKoopmanOperator object
%
% Modified 2020/04/15

if ~isrow( gamma ) || ~isnumeric( gamma )
    error( 'Eigenvalues must be specified as a numeric row vector' )
end

if numel( gamma ) ~= getNEigenfunction( obj )
    error( 'Number of eigenvalues must be equal to number of eigenfunctions.' )
end

save( fullfile( getEigenfunctionPath( obj ), getEigenvalueFile( obj ) ), ...
      'gamma' )

redpajama_set_name: RedPajamaGithub


text:
package edu.indiana.lib.osid.base.repository;

 public abstract class Managers
 {
	 public static void setIdManager(org.osid.id.IdManager manager)
   throws org.osid.repository.RepositoryException
	 {
			throw new org.osid.repository.RepositoryException(org.osid.OsidException.UNIMPLEMENTED);
	 }

	 public static org.osid.id.IdManager getIdManager()
   throws org.osid.repository.RepositoryException
	 {
			throw new org.osid.repository.RepositoryException(org.osid.OsidException.UNIMPLEMENTED);
	 }
 }


text:
package tv.dotstart.pandemonium.module;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Locale;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import tv.dotstart.pandemonium.configuration.ApplicationConfiguration;
import tv.dotstart.pandemonium.fx.localization.ConfigurationAwareMessageSource;

/**
 * Provides a modular message source which resolves against multiple child sources.
 *
 * @author Johannes Donath
 */
@Component
public class ModuleMessageSource extends AbstractMessageSource implements ConfigurationAwareMessageSource {
    private final LinkedList<MessageSource> childSources = new LinkedList<>();
    private final ReadWriteLock childSourceLock = new ReentrantReadWriteLock();

    private final Locale locale;

    @Autowired
    public ModuleMessageSource(@Nonnull ApplicationConfiguration configuration, @Nonnull Collection<MessageSource> messageSources) {
        this.locale = configuration.getApplicationLocale();
        this.childSources.addAll(messageSources);
    }

    /**
     * Adds a message source to the list of children.
     */
    public void addSource(@Nonnull MessageSource source) {
        this.childSourceLock.writeLock().lock();

        try {
            this.childSources.add(source);
        } finally {
            this.childSourceLock.writeLock().unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Nonnull
    @Override
    public Locale getConfiguredLocale() {
        return this.locale;
    }

    /**
     * {@inheritDoc}
     */
    @Nonnull
    @Override
    public String getMessage(@Nonnull String code, @Nonnull Object... arguments) {
        return this.getMessage(code, arguments, this.locale);
    }

    /**
     * Removes a message source from the list of children.
     */
    public void removeSource(@Nonnull MessageSource source) {
        this.childSourceLock.writeLock().lock();

        try {
            this.childSources.remove(source);
        } finally {
            this.childSourceLock.writeLock().unlock();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Nullable
    @Override
    protected MessageFormat resolveCode(String code, Locale locale) {
        this.childSourceLock.readLock().lock();

        try {
            return this.childSources.stream()
                    .flatMap((s) -> {
                        try {
                            return Stream.of(s.getMessage(code, new Object[0], locale));
                        } catch (NoSuchMessageException ex) {
                            return Stream.empty();
                        }
                    })
                    .map((m) -> this.createMessageFormat(m, locale))
                    .findAny()
                    .orElseGet(() -> this.createMessageFormat(code, locale));
        } finally {
            this.childSourceLock.readLock().unlock();
        }
    }
}


text:
(function () {

	'use strict';

	module.exports.getNamedId = function (req, name) {
		return parseInt(req.params[name], 10);
	};

	module.exports.getNamedValue = function (req, name) {
		return req.params[name];
	};

	module.exports.getUserId = function (req) {
		return this.getNamedId(req, 'userid');
	};

	module.exports.checkReadAllowed = function (req, res, success) {
		var userid = this.getUserId(req);

		if (!req.session.user || req.session.user.id !== userid) {
			res.send('Unauthorized.', 401);
			return;
		}

		success();
	};

	module.exports.checkWriteAllowed = function (req, res, success) {
		var userid = this.getUserId(req),
			now = new Date(),
			expiry = new Date(req.session.user.expiry);

		if (!req.session.user || req.session.user.id !== userid) {
			res.send('Unauthorized.', 401);
			return;
		}

		if (now > expiry) {
			res.send('Licence expired.');
			return;
		}

		success();
	};

	module.exports.toSlug = function (str) {
		str = str.replace(/^\s+|\s+$/g, '');
		str = str.toLowerCase();

		str = str.replace(/[^a-z0-9 -]/g, '')
				 .replace(/\s+/g, '-')
				 .replace(/-+/g, '-');

		return str;
	};

	module.exports.toSlugChecked = function (str, predicate, callback) {
		var initial = this.toSlug(str);

		predicate(initial, function (ok) {
			if (ok) {
				callback(initial);
			} else {
				toSlugCheckedRecurse(initial, 1, predicate, callback);
			}
		});
	};

}());


text:
require 'swig_assert'

require 'using_composition'

include Using_composition

f = FooBar.new
if f.blah(3) != 3
  raise RuntimeError,"FooBar::blah(int)"
end

if f.blah(3.5) != 3.5
  raise RuntimeError,"FooBar::blah(double)"
end

if f.blah("hello") != "hello"
  raise RuntimeError,"FooBar::blah(char *)"
end

f = FooBar2.new
if f.blah(3) != 3
  raise RuntimeError,"FooBar2::blah(int)"
end

if f.blah(3.5) != 3.5
  raise RuntimeError,"FooBar2::blah(double)"
end

if f.blah("hello") != "hello"
  raise RuntimeError,"FooBar2::blah(char *)"
end

f = FooBar3.new
if f.blah(3) != 3
  raise RuntimeError,"FooBar3::blah(int)"
end

if f.blah(3.5) != 3.5
  raise RuntimeError,"FooBar3::blah(double)"
end

if f.blah("hello") != "hello"
  raise RuntimeError,"FooBar3::blah(char *)"
end


text:
import sys
import xml.etree.ElementTree as ET
from sonLib.tree import BinaryTree
from sonLib.tree import njI
from sonLib.tree import upgmaI
from sonLib.tree import DistancePair
from sonLib.bioio import printBinaryTree

l = {}
def fn(eventName):
    if not l.has_key(eventName):
        l[eventName] = BinaryTree(0.0, False, None, None, eventName)
    return l[eventName]
distancePairs = [ DistancePair(float(i.attrib["substitutionRate"]), fn(i.attrib["eventName1"]), 1, fn(i.attrib["eventName2"]), 1) for i in ET.parse(sys.argv[1]).getroot().findall("distancesForSamples") ]
distancePairs += [ DistancePair(i.distance, i.leaf2, 1, i.leaf1, 1) for i in distancePairs ]

print len(distancePairs), l
print "NJ", printBinaryTree(njI(distancePairs, len(l.keys())), includeDistances=True)
print "UPGMA", printBinaryTree(upgmaI(distancePairs, len(l.keys())), includeDistances=True)


text:
// ECMAScript 5 strict mode
"use strict";

assert2(cr, "cr namespace not created");
assert2(cr.behaviors, "cr.behaviors not created");

/////////////////////////////////////
// Behavior class
cr.behaviors.Rex_Step = function(runtime)
{
	this.runtime = runtime;
};

(function ()
{
	var behaviorProto = cr.behaviors.Rex_Step.prototype;

	/////////////////////////////////////
	// Behavior type class
	behaviorProto.Type = function(behavior, objtype)
	{
		this.behavior = behavior;
		this.objtype = objtype;
		this.runtime = behavior.runtime;
	};

	var behtypeProto = behaviorProto.Type.prototype;

	behtypeProto.onCreate = function()
	{
	};

	/////////////////////////////////////
	// Behavior instance class
	behaviorProto.Instance = function(type, inst)
	{
		this.type = type;
		this.behavior = type.behavior;
		this.inst = inst;
		this.runtime = type.runtime;

		this.cancelStep = 0;
	};

	var behinstProto = behaviorProto.Instance.prototype;

	behinstProto.onCreate = function()
	{
		// Load properties
        this.activated = (this.properties[0] == 1);
		this.step_mode = this.properties[1];	// 0=None, 1=Linear, 2=Horizontal then vertical, 3=Vertical then horizontal
		this.pixel_per_step = this.properties[2];
        this.noise_shiftt = this.properties[3];

		this.pre_x = this.inst.x;
		this.pre_y = this.inst.y;
	};

	behinstProto.step = function (dx, dy, trigmethod)
	{
        var move_dist = Math.sqrt(dx * dx + dy * dy);
		var steps = Math.round(move_dist / this.pixel_per_step);

		if (steps === 0)
			steps = 1;

		var i, prog;
        var inst = this.inst;
		var startx = this.pre_x;
		var starty = this.pre_y;

        // unit vector of noise
        if (this.noise_shiftt != 0)
        {
            var norm_noise_x = dy/move_dist;
            var norm_noise_y = dx/move_dist;
        }

		for (i = 1; i <= steps; i++)
		{
			prog = i / steps;
			inst.x = startx + (dx * prog);
			inst.y = starty + (dy * prog);

            if (this.noise_shiftt != 0)
            {
                var noise = (Math.random()*this.noise_shiftt*2) - this.noise_shiftt;
                inst.x += (noise*norm_noise_x);
                inst.y += (noise*norm_noise_y);
            }

			inst.set_bbox_changed();

			this.runtime.trigger(trigmethod, inst);

			if (this.cancelStep === 1)
			{
				// Go back a step and stop
				i--;
				prog = i / steps;
			    inst.x = startx + (dx * prog);
			    inst.y = starty + (dy * prog);
				inst.set_bbox_changed();
				return;
			}
			else if (this.cancelStep === 2)
			{
				// Stop and do nothing
				return;
			}
		}
	};

	behinstProto.tick = function ()
	{
        if (!this.activated)
            return;

        var cur_x = this.inst.x;
        var cur_y = this.inst.y;
        var dx = cur_x - this.pre_x;
        var dy = cur_y - this.pre_y;
		// Not moving, nothing to do
        if ((dx==0) && (dy==0))
            return;

		this.cancelStep = 0;

		if (this.step_mode === 0)	// linear
		{
			this.step(dx, dy, cr.behaviors.Rex_Step.prototype.cnds.OnCMStep);
		}
		else if (this.step_mode === 1)	// horizontal then vertical
		{
			this.step(dx, 0, cr.behaviors.Rex_Step.prototype.cnds.OnCMHorizStep);

			if (this.cancelStep === 0)
				this.step(0, dy, cr.behaviors.Rex_Step.prototype.cnds.OnCMVertStep);
		}
		else if (this.step_mode === 2)	// vertical then horizontal
		{
			this.step(0, dy, cr.behaviors.Rex_Step.prototype.cnds.OnCMVertStep);

			if (this.cancelStep === 0)
				this.step(dx, 0, cr.behaviors.Rex_Step.prototype.cnds.OnCMHorizStep);
		}

		this.pre_x = cur_x;
		this.pre_y = cur_y;
        this.inst.x = cur_x;
        this.inst.y = cur_y;
		this.inst.set_bbox_changed();
	};

	behinstProto.saveToJSON = function ()
	{
		return { "en": this.activated,
		         "s": this.pixel_per_step };
	};

	behinstProto.loadFromJSON = function (o)
	{
		this.activated = o["en"];
		this.pixel_per_step = o["s"];
	};
	//////////////////////////////////////
	// Conditions
	function Cnds() {};
	behaviorProto.cnds = new Cnds();

	Cnds.prototype.OnCMStep = function ()
	{
		return true;
	};

	Cnds.prototype.OnCMHorizStep = function ()
	{
		return true;
	};

	Cnds.prototype.OnCMVertStep = function ()
	{
		return true;
	};

	//////////////////////////////////////
	// Actions
	function Acts() {};
	behaviorProto.acts = new Acts();

	Acts.prototype.SetActivated = function (s)
	{
	    var activated = (s==1);
        if ( (!this.activated) && activated )
        {
            this.pre_x = this.inst.x;
            this.pre_y = this.inst.y;
        }
		this.activated = activated;
	};

	Acts.prototype.StopStepping = function (mode)
	{
		// set to 1 = go back a step, 2 = stay at current position
		this.cancelStep = mode + 1;
	};

	Acts.prototype.SetPixelPerStep = function (s)
	{
		this.pixel_per_step = s;
	};

	Acts.prototype.ForceStepping = function ()
	{
		this.tick();
	};

	//////////////////////////////////////
	// Expressions
	function Exps() {};
	behaviorProto.exps = new Exps();

}());


text:
package me.qyh.blog.file.store;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Optional;
import java.util.function.Function;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.madgag.gif.fmsware.GifDecoder;

import me.qyh.blog.core.exception.SystemException;
import me.qyh.blog.core.util.FileUtils;

/**
 * 基于java的图片处理
 *

 * 这个类仅供测试使用,请勿在实际项目中使用
 *

 *
 *

 * BUG
 *

 *
图像缩放时旋转90度问题(可能是由于exif信息丢失)

 *

 *

 *
 * @see GraphicsMagickImageHelper
 * @author Administrator
 *
 */
public class JavaImageHelper extends ImageHelper {

	private static final WhiteBgFilter WHITE_BG_FILTER = new WhiteBgFilter();
	private static final Logger logger = LoggerFactory.getLogger(JavaImageHelper.class);

	@Override
	protected void doResize(Resize resize, Path src, Path dest) throws IOException {
		String ext = FileUtils.getFileExtension(src);
		Path todo = src;
		Path tmp;
		if (isGIF(ext)) {
			// 获取封面
			tmp = FileUtils.appTemp(PNG);
			doGetGifCover(src, tmp);
			todo = tmp;
		}
		BufferedImage bi = doResize(todo, dest, resize);
		writeImg(bi, FileUtils.getFileExtension(dest), dest.toFile());
	}

	@Override
	protected ImageInfo doRead(Path file) throws IOException {
		try {
			return readImage(file);
		} catch (IOException e) {
			String ext = FileUtils.getFileExtension(file);
			if (isGIF(ext)) {
				return readGif(file);
			}
			throw e;
		}
	}

	private ImageInfo readGif(Path file) throws IOException {
		try (InputStream is = Files.newInputStream(file)) {
			GifDecoder gd = new GifDecoder();
			int flag = gd.read(is);
			if (flag != GifDecoder.STATUS_OK) {
				throw new IOException(file + "文件无法读取");
			}
			Dimension dim = gd.getFrameSize();
			return new ImageInfo(dim.width, dim.height, GIF);
		}
	}

	private ImageInfo readImage(Path file) throws IOException {
		try (InputStream is = Files.newInputStream(file); ImageInputStream iis = ImageIO.createImageInputStream(is)) {
			Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
			if (imageReaders.hasNext()) {
				ImageReader reader = imageReaders.next();
				reader.setInput(iis);
				int minIndex = reader.getMinIndex();
				return new ImageInfo(reader.getWidth(minIndex), reader.getHeight(minIndex), reader.getFormatName());
			}
			throw new IOException("无法确定图片:" + file + "的具体类型");
		}
	}

	private void doGetGifCover(Path gif, Path dest) throws IOException {
		Path png;
		try (InputStream is = Files.newInputStream(gif)) {
			GifDecoder gd = new GifDecoder();
			int flag = gd.read(is);
			if (flag != GifDecoder.STATUS_OK) {
				throw new IOException(gif + "文件无法读取");
			}
			BufferedImage bi = gd.getFrame(0);
			png = FileUtils.appTemp(PNG);
			writeImg(bi, PNG, png.toFile());
			String destExt = FileUtils.getFileExtension(dest);
			if (isPNG(destExt)) {
				try {
					FileUtils.deleteQuietly(dest);
					FileUtils.move(png, dest);
					return;
				} catch (IOException e) {
					throw new SystemException(e.getMessage(), e);
				}
			}
			// PNG to Other Format
			BufferedImage readed = ImageIO.read(png.toFile());
			writeImg(WHITE_BG_FILTER.apply(readed), destExt, dest.toFile());
		}
	}

	private synchronized void writeImg(BufferedImage bi, String ext, File dest) throws IOException {
		FileUtils.deleteQuietly(dest.toPath());
		ImageIO.write(bi, ext, dest);
		bi.flush();
	}

	private BufferedImage doResize(Path todo, Path dest, Resize resize) throws IOException {
		BufferedImage originalImage = ImageIO.read(todo.toFile());
		if (ImageHelper.isJPEG(FileUtils.getFileExtension(todo))) {
			Optional<BufferedImage> orient = Optional.empty();
			try {
				orient = autoOrient(originalImage, todo);
			} catch (ImageProcessingException | MetadataException e) {
				logger.debug(e.getMessage(), e);
			}
			if (orient.isPresent()) {
				originalImage = orient.get();
			}
		}
		int width = originalImage.getWidth();
		int height = originalImage.getHeight();
		int resizeWidth;
		int resizeHeight;
		if (resize.getSize() != null) {
			int size = resize.getSize();
			if (width > height) {
				resizeWidth = size > width ? width : size;
				resizeHeight = resizeWidth * height / width;
			} else if (width < height) {
				resizeHeight = size > height ? height : size;
				resizeWidth = resizeHeight * width / height;
			} else {
				resizeWidth = resizeHeight = size > width ? width : size;
			}
		} else {
			if (resize.isKeepRatio()) {
				return doResize(todo, dest, new Resize(Math.max(resize.getWidth(), resize.getHeight())));
			} else {
				resizeWidth = (resize.getWidth() > width) ? width : resize.getWidth();
				resizeHeight = (resize.getHeight() > height) ? height : resize.getHeight();
			}
		}
		String destExt = FileUtils.getFileExtension(dest);

		boolean maybeTransparentBy = maybeTransparentBg(destExt);
		int imageType = maybeTransparentBy ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
		BufferedImage scaledBI = new BufferedImage(resizeWidth, resizeHeight, imageType);
		Graphics2D g = scaledBI.createGraphics();
		if (!maybeTransparentBy) {
			g.setComposite(AlphaComposite.Src);
			g.drawImage(originalImage, 0, 0, resizeWidth, resizeHeight, Color.WHITE, null);
		} else {
			g.drawImage(originalImage, 0, 0, resizeWidth, resizeHeight, null);
		}
		g.dispose();

		return scaledBI;
	}

	private static final class WhiteBgFilter implements Function<BufferedImage, BufferedImage> {

		@Override
		public BufferedImage apply(BufferedImage img) {

			int width = img.getWidth();
			int height = img.getHeight();

			BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = finalImage.createGraphics();
			g.drawImage(img, 0, 0, Color.WHITE, null);
			g.dispose();

			return finalImage;
		}
	}

	@Override
	public final boolean supportWebp() {
		return false;
	}

	@Override
	public final boolean supportAnimatedWebp() {
		return false;
	}

	@Override
	protected void doMakeAnimatedWebp(AnimatedWebpConfig config, Path gif, Path dest) throws IOException {
		throw new SystemException("unsupport");
	}

	private Optional<BufferedImage> autoOrient(BufferedImage originalImage, Path src)
			throws ImageProcessingException, IOException, MetadataException {
		Metadata metadata = ImageMetadataReader.readMetadata(src.toFile());
		ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
		if (exifIFD0Directory == null) {
			return Optional.empty();
		}
		int orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);

		int width = originalImage.getWidth();
		int height = originalImage.getHeight();

		AffineTransform affineTransform = new AffineTransform();

		switch (orientation) {
		case 1:
			break;
		case 2: // Flip X
			affineTransform.scale(-1.0, 1.0);
			affineTransform.translate(-width, 0);
			break;
		case 3: // PI rotation
			affineTransform.translate(width, height);
			affineTransform.rotate(Math.PI);
			break;
		case 4: // Flip Y
			affineTransform.scale(1.0, -1.0);
			affineTransform.translate(0, -height);
			break;
		case 5: // - PI/2 and Flip X
			affineTransform.rotate(-Math.PI / 2);
			affineTransform.scale(-1.0, 1.0);
			break;
		case 6: // -PI/2 and -width
			affineTransform.translate(height, 0);
			affineTransform.rotate(Math.PI / 2);
			break;
		case 7: // PI/2 and Flip
			affineTransform.scale(-1.0, 1.0);
			affineTransform.translate(-height, 0);
			affineTransform.translate(0, width);
			affineTransform.rotate(3 * Math.PI / 2);
			break;
		case 8: // PI / 2
			affineTransform.translate(0, width);
			affineTransform.rotate(3 * Math.PI / 2);
			break;
		default:
			break;
		}

		AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);
		BufferedImage destinationImage = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(),
				originalImage.getType());
		destinationImage = affineTransformOp.filter(originalImage, destinationImage);
		return Optional.of(destinationImage);
	}
}


text:
require 'helper'

class LoadTest < Test::Unit::TestCase
  should "let you specify where to load config files" do
    error_raised = false
    begin
      Flask::Load.config(TestAdventure, 'some/other/path/')
    rescue Exception => e
      error_raised = true
      assert e.to_s =~ /no such file/i
    end
    assert error_raised
  end

  should "throw LoadError when no constant is supplied" do
    error_raised = false
    begin
      Flask::Load.config('I am not a constant')
    rescue Flask::LoadError
      error_raised = true
    end
    assert error_raised
  end

  should "throw LoadError when empty class name is supplied in get_or_create_class" do
    error_raised = false
    begin
      Flask::Load.get_or_create_class('')
    rescue Flask::LoadError
      error_raised = true
    end
    assert error_raised
  end

  should "load classes inside an extended Adventure class" do
    TestAdventure.new
    assert TestAdventure::Rooms::Test
  end

  should "extend already loaded classes" do
    room = Class.new(Flask::Room) do
      def self.hello
        true
      end
    end

    TestAdventure.const_set('Rooms', Module.new {})
    TestAdventure::Rooms.const_set('Test', room)
    TestAdventure.new

    assert TestAdventure::Rooms::Test.hello
    assert TestAdventure::Rooms::Test.data.length > 0
  end
end


text:
package com.zingson.jfain.jdbc;

import java.io.Serializable;
import java.util.List;

/**
 * Page is the result of Model.paginate(......) or Db.paginate(......)
 */
public class Page<T> implements Serializable {

	private List<T> list;				// list result of this page
	private int pageNumber;				// page number
	private int pageSize;				// result amount of this page
	private int totalPage;				// total page
	private int totalRow;				// total row

	/**
	 * Constructor.
	 * @param list the list of paginate result
	 * @param pageNumber the page number
	 * @param pageSize the page size
	 * @param totalRow the total row of paginate
	 */
	public Page(List<T> list, int pageNumber, int pageSize, int totalRow) {
		this.list = list;
		this.pageNumber = pageNumber;
		this.pageSize = pageSize;
		this.totalPage = totalRow%pageSize==0?totalRow/pageSize:totalRow/pageSize+1;
		this.totalRow = totalRow;
	}

	public Page() {

	}

	/**
	 * Return list of this page.
	 */
	public List<T> getList() {
		return list;
	}

	/**
	 * Return page number.
	 */
	public int getPageNumber() {
		return pageNumber;
	}

	/**
	 * Return page size.
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * Return total page.
	 */
	public int getTotalPage() {
		return totalPage;
	}

	/**
	 * Return total row.
	 */
	public int getTotalRow() {
		return totalRow;
	}

	public boolean isFirstPage() {
		return pageNumber == 1;
	}

	public boolean isLastPage() {
		return pageNumber >= totalPage;
	}

	public String toString() {
		StringBuilder msg = new StringBuilder();
		msg.append("pageNumber : ").append(pageNumber);
		msg.append("\npageSize : ").append(pageSize);
		msg.append("\ntotalPage : ").append(totalPage);
		msg.append("\ntotalRow : ").append(totalRow);
		return msg.toString();
	}
}


text:
package view.utilities;

import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import utility.FilePathUtility;
import view.enums.DefaultStrings;
import view.enums.FileExtensions;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FileUtilities {
    private FileUtilities () {

    }

    /**
     * Prompts a file chooser box for the user to choose a file with ONE
     * extension filter
     *
     * @param ExtensionFilter extension: file extension that the user can choose from, all
     *                        others are not allowed
     * @param String          prompt: prompt for the file chooser box
     * @param String          dir: default directory for the file chooser box
     * @return File: return file selected by the user Note: this method works
     * with promptAndGetFile(List<ExtensionFilter> filters, String
     * prompt), which allows the addition of multiple extension filters,
     * whereas this method is called with only one extension filter is
     * needed; pairing the methods reduces replicated code
     */

    public static File promptAndGetFile (ExtensionFilter extension, String prompt, String dir) {
        List<ExtensionFilter> filters = new ArrayList<>();
        filters.add(extension);
        return promptAndGetFile(filters, prompt, dir);
    }

    /**
     * Prompts a file chooser box for the user to choose a file with MULTIPLE
     * extension filters
     *
     * @param List<ExtensionFilter> filters: file extensions that the user can choose from, all
     *                              others are not allowed
     * @param String                prompt: prompt for the file chooser box
     * @param String                dir: default directory for the file chooser box
     * @return File file: return file selected by the user
     */
    public static File promptAndGetFile (List<ExtensionFilter> filters, String prompt, String dir) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle(prompt);
        fileChooser.getExtensionFilters().addAll(filters);
        fileChooser.setInitialDirectory(new File(dir));
        return new File(FilePathUtility.relativize(fileChooser.showOpenDialog(new Stage()).getPath()));
    }

    public static File promptAndGetFile (List<ExtensionFilter> filters, String prompt) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle(prompt);
        fileChooser.getExtensionFilters().addAll(filters);
        File dir = new File(DefaultStrings.RESOURCES.getDefault());
        fileChooser.setInitialDirectory(dir);
        return new File(FilePathUtility.relativize(fileChooser.showOpenDialog(new Stage()).getPath()));
    }

    /**
     * Gets all file names from a given directory. Is static so that it can be
     * accessed as the actual class is never instantiated, also so that function
     * can be accessed without this object being passed.
     *
     * @param directoryLocation String path to a file directory
     * @return List of Strings of all file names within given directory
     */
    public static List<String> getAllFromDirectory (String directoryLocation) {

        ArrayList<String> files = new ArrayList<>();
        File directory = new File(directoryLocation);
        File[] fileList = directory.listFiles();
        for (File file : fileList) {
            String name = file.getName();
            if (name.contains(".")) {
                files.add(name.substring(0, name.lastIndexOf('.')));
            } else {
                files.add(name);
            }
        }
        return files;
    }

    public static List<ExtensionFilter> getImageFilters () {
        return Arrays.asList(FileExtensions.PNG.getFilter(), FileExtensions.JPG.getFilter(), FileExtensions.GIF.getFilter());

    }

    public static List<ExtensionFilter> getMusicFilters () {
        return Collections.singletonList(FileExtensions.MP3.getFilter());
    }

    public static List<ExtensionFilter> getPropertiesFilters () {
        return Collections.singletonList(FileExtensions.PROPERTIES.getFilter());
    }

}


text:
/***************************************************************************//**
* \file cyip_ipc.h
*
* \brief
* IPC IP definitions
*
********************************************************************************
* \copyright
* (c) (2016-2022), Cypress Semiconductor Corporation (an Infineon company) or
* an affiliate of Cypress Semiconductor Corporation.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*******************************************************************************/

#ifndef _CYIP_IPC_H_
#define _CYIP_IPC_H_

#include "cyip_headers.h"

/*******************************************************************************
*                                     IPC
*******************************************************************************/

#define IPC_STRUCT_SECTION_SIZE                 0x00000020UL
#define IPC_INTR_STRUCT_SECTION_SIZE            0x00000020UL
#define IPC_SECTION_SIZE                        0x00010000UL

/**
  * \brief IPC structure (IPC_STRUCT)
  */
typedef struct {
   __IM uint32_t ACQUIRE;                       /*!< 0x00000000 IPC acquire */
   __OM uint32_t RELEASE;                       /*!< 0x00000004 IPC release */
   __OM uint32_t NOTIFY;                        /*!< 0x00000008 IPC notification */
  __IOM uint32_t DATA;                          /*!< 0x0000000C IPC data */
   __IM uint32_t LOCK_STATUS;                   /*!< 0x00000010 IPC lock status */
   __IM uint32_t RESERVED[3];
} IPC_STRUCT_V1_Type;                           /*!< Size = 32 (0x20) */

/**
  * \brief IPC interrupt structure (IPC_INTR_STRUCT)
  */
typedef struct {
  __IOM uint32_t INTR;                          /*!< 0x00000000 Interrupt */
  __IOM uint32_t INTR_SET;                      /*!< 0x00000004 Interrupt set */
  __IOM uint32_t INTR_MASK;                     /*!< 0x00000008 Interrupt mask */
   __IM uint32_t INTR_MASKED;                   /*!< 0x0000000C Interrupt masked */
   __IM uint32_t RESERVED[4];
} IPC_INTR_STRUCT_V1_Type;                      /*!< Size = 32 (0x20) */

/**
  * \brief IPC (IPC)
  */
typedef struct {
        IPC_STRUCT_V1_Type STRUCT[16];          /*!< 0x00000000 IPC structure */
   __IM uint32_t RESERVED[896];
        IPC_INTR_STRUCT_V1_Type INTR_STRUCT[16]; /*!< 0x00001000 IPC interrupt structure */
} IPC_V1_Type;                                  /*!< Size = 4608 (0x1200) */

/* IPC_STRUCT.ACQUIRE */
#define IPC_STRUCT_ACQUIRE_P_Pos                0UL
#define IPC_STRUCT_ACQUIRE_P_Msk                0x1UL
#define IPC_STRUCT_ACQUIRE_NS_Pos               1UL
#define IPC_STRUCT_ACQUIRE_NS_Msk               0x2UL
#define IPC_STRUCT_ACQUIRE_PC_Pos               4UL
#define IPC_STRUCT_ACQUIRE_PC_Msk               0xF0UL
#define IPC_STRUCT_ACQUIRE_MS_Pos               8UL
#define IPC_STRUCT_ACQUIRE_MS_Msk               0xF00UL
#define IPC_STRUCT_ACQUIRE_SUCCESS_Pos          31UL
#define IPC_STRUCT_ACQUIRE_SUCCESS_Msk          0x80000000UL
/* IPC_STRUCT.RELEASE */
#define IPC_STRUCT_RELEASE_INTR_RELEASE_Pos     0UL
#define IPC_STRUCT_RELEASE_INTR_RELEASE_Msk     0xFFFFUL
/* IPC_STRUCT.NOTIFY */
#define IPC_STRUCT_NOTIFY_INTR_NOTIFY_Pos       0UL
#define IPC_STRUCT_NOTIFY_INTR_NOTIFY_Msk       0xFFFFUL
/* IPC_STRUCT.DATA */
#define IPC_STRUCT_DATA_DATA_Pos                0UL
#define IPC_STRUCT_DATA_DATA_Msk                0xFFFFFFFFUL
/* IPC_STRUCT.LOCK_STATUS */
#define IPC_STRUCT_LOCK_STATUS_P_Pos            0UL
#define IPC_STRUCT_LOCK_STATUS_P_Msk            0x1UL
#define IPC_STRUCT_LOCK_STATUS_NS_Pos           1UL
#define IPC_STRUCT_LOCK_STATUS_NS_Msk           0x2UL
#define IPC_STRUCT_LOCK_STATUS_PC_Pos           4UL
#define IPC_STRUCT_LOCK_STATUS_PC_Msk           0xF0UL
#define IPC_STRUCT_LOCK_STATUS_MS_Pos           8UL
#define IPC_STRUCT_LOCK_STATUS_MS_Msk           0xF00UL
#define IPC_STRUCT_LOCK_STATUS_ACQUIRED_Pos     31UL
#define IPC_STRUCT_LOCK_STATUS_ACQUIRED_Msk     0x80000000UL

/* IPC_INTR_STRUCT.INTR */
#define IPC_INTR_STRUCT_INTR_RELEASE_Pos        0UL
#define IPC_INTR_STRUCT_INTR_RELEASE_Msk        0xFFFFUL
#define IPC_INTR_STRUCT_INTR_NOTIFY_Pos         16UL
#define IPC_INTR_STRUCT_INTR_NOTIFY_Msk         0xFFFF0000UL
/* IPC_INTR_STRUCT.INTR_SET */
#define IPC_INTR_STRUCT_INTR_SET_RELEASE_Pos    0UL
#define IPC_INTR_STRUCT_INTR_SET_RELEASE_Msk    0xFFFFUL
#define IPC_INTR_STRUCT_INTR_SET_NOTIFY_Pos     16UL
#define IPC_INTR_STRUCT_INTR_SET_NOTIFY_Msk     0xFFFF0000UL
/* IPC_INTR_STRUCT.INTR_MASK */
#define IPC_INTR_STRUCT_INTR_MASK_RELEASE_Pos   0UL
#define IPC_INTR_STRUCT_INTR_MASK_RELEASE_Msk   0xFFFFUL
#define IPC_INTR_STRUCT_INTR_MASK_NOTIFY_Pos    16UL
#define IPC_INTR_STRUCT_INTR_MASK_NOTIFY_Msk    0xFFFF0000UL
/* IPC_INTR_STRUCT.INTR_MASKED */
#define IPC_INTR_STRUCT_INTR_MASKED_RELEASE_Pos 0UL
#define IPC_INTR_STRUCT_INTR_MASKED_RELEASE_Msk 0xFFFFUL
#define IPC_INTR_STRUCT_INTR_MASKED_NOTIFY_Pos  16UL
#define IPC_INTR_STRUCT_INTR_MASKED_NOTIFY_Msk  0xFFFF0000UL

#endif /* _CYIP_IPC_H_ */

/* [] END OF FILE */


text:
package org.apache.lucene.analysis.phonetic;

import java.io.IOException;
import java.io.StringReader;

import org.apache.commons.codec.Encoder;
import org.apache.commons.codec.language.Caverphone2;
import org.apache.commons.codec.language.DoubleMetaphone;
import org.apache.commons.codec.language.Metaphone;
import org.apache.commons.codec.language.Nysiis;
import org.apache.commons.codec.language.RefinedSoundex;
import org.apache.commons.codec.language.Soundex;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.KeywordTokenizer;

/**
 * Tests {@link PhoneticFilter}
 */
public class TestPhoneticFilter extends BaseTokenStreamTestCase {

  public void testAlgorithms() throws Exception {
    assertAlgorithm(new Metaphone(), true, "aaa bbb ccc easgasg",
        new String[] { "A", "aaa", "B", "bbb", "KKK", "ccc", "ESKS", "easgasg" });
    assertAlgorithm(new Metaphone(), false, "aaa bbb ccc easgasg",
        new String[] { "A", "B", "KKK", "ESKS" });

    assertAlgorithm(new DoubleMetaphone(), true, "aaa bbb ccc easgasg",
        new String[] { "A", "aaa", "PP", "bbb", "KK", "ccc", "ASKS", "easgasg" });
    assertAlgorithm(new DoubleMetaphone(), false, "aaa bbb ccc easgasg",
        new String[] { "A", "PP", "KK", "ASKS" });

    assertAlgorithm(new Soundex(), true, "aaa bbb ccc easgasg",
        new String[] { "A000", "aaa", "B000", "bbb", "C000", "ccc", "E220", "easgasg" });
    assertAlgorithm(new Soundex(), false, "aaa bbb ccc easgasg",
        new String[] { "A000", "B000", "C000", "E220" });

    assertAlgorithm(new RefinedSoundex(), true, "aaa bbb ccc easgasg",
        new String[] { "A0", "aaa", "B1", "bbb", "C3", "ccc", "E034034", "easgasg" });
    assertAlgorithm(new RefinedSoundex(), false, "aaa bbb ccc easgasg",
        new String[] { "A0", "B1", "C3", "E034034" });

    assertAlgorithm(new Caverphone2(), true, "Darda Karleen Datha Carlene",
        new String[] { "TTA1111111", "Darda", "KLN1111111", "Karleen",
          "TTA1111111", "Datha", "KLN1111111", "Carlene" });
    assertAlgorithm(new Caverphone2(), false, "Darda Karleen Datha Carlene",
        new String[] { "TTA1111111", "KLN1111111", "TTA1111111", "KLN1111111" });

    assertAlgorithm(new Nysiis(), true, "aaa bbb ccc easgasg",
        new String[] { "A", "aaa", "B", "bbb", "C", "ccc", "EASGAS", "easgasg" });
    assertAlgorithm(new Nysiis(), false, "aaa bbb ccc easgasg",
        new String[] { "A", "B", "C", "EASGAS" });
  }

  static void assertAlgorithm(Encoder encoder, boolean inject, String input,
      String[] expected) throws Exception {
    Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
    tokenizer.setReader(new StringReader(input));
    PhoneticFilter filter = new PhoneticFilter(tokenizer, encoder, inject);
    assertTokenStreamContents(filter, expected);
  }

  /** blast some random strings through the analyzer */
  public void testRandomStrings() throws IOException {
    Encoder encoders[] = new Encoder[] {
      new Metaphone(), new DoubleMetaphone(), new Soundex(), new RefinedSoundex(), new Caverphone2()
    };

    for (final Encoder e : encoders) {
      Analyzer a = new Analyzer() {
        @Override
        protected TokenStreamComponents createComponents(String fieldName) {
          Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
          return new TokenStreamComponents(tokenizer, new PhoneticFilter(tokenizer, e, false));
        }
      };

      checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);

      Analyzer b = new Analyzer() {
        @Override
        protected TokenStreamComponents createComponents(String fieldName) {
          Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
          return new TokenStreamComponents(tokenizer, new PhoneticFilter(tokenizer, e, false));
        }
      };

      checkRandomData(random(), b, 1000*RANDOM_MULTIPLIER);
    }
  }

  public void testEmptyTerm() throws IOException {
    Encoder encoders[] = new Encoder[] {
        new Metaphone(), new DoubleMetaphone(), new Soundex(), new RefinedSoundex(), new Caverphone2()
    };
    for (final Encoder e : encoders) {
      Analyzer a = new Analyzer() {
        @Override
        protected TokenStreamComponents createComponents(String fieldName) {
          Tokenizer tokenizer = new KeywordTokenizer();
          return new TokenStreamComponents(tokenizer, new PhoneticFilter(tokenizer, e, random().nextBoolean()));
        }
      };
      checkOneTerm(a, "", "");
    }
  }
}


text:
package flash.swf.builder.types;

import flash.fonts.FontFace;
import flash.swf.builder.tags.FontBuilder;
import flash.swf.tags.ZoneRecord;
import flash.util.Trace;

/**
 * A simple class to decouple FlashType ZoneRecord construction from
 * FontBuilder.
 */
public class ZoneRecordBuilder
{
    private static final String DEFAULT_BUILDER = "flash.fonts.flashtype.FlashTypeZoneRecordBuilder";

    protected String fontAlias;
    protected FontBuilder fontBuilder;
    protected FontFace fontFace;

    protected ZoneRecordBuilder()
    {
    }

    public void setFontAlias(String alias)
    {
        fontAlias = alias;
    }

    public void setFontBuilder(FontBuilder builder)
    {
        fontBuilder = builder;
    }

    public void setFontFace(FontFace face)
    {
        fontFace = face;
    }

    /**
     * This no-op method returns an empty ZoneRecord. Subclasses should
     * override this method.
     */
    public ZoneRecord build(int character)
    {
        // Return an empty Zone Record...
        ZoneRecord zoneRecord = new ZoneRecord();
        zoneRecord.numZoneData = 2;
        zoneRecord.zoneData = new long[] {0, 0};
        zoneRecord.zoneMask = 0;
        return zoneRecord;
    }

    public static ZoneRecordBuilder createInstance()
    {
        try
        {
            Class c = Class.forName(DEFAULT_BUILDER);
            ZoneRecordBuilder builder = (ZoneRecordBuilder)c.newInstance();
            return builder;
        }
        catch (Throwable t)
        {
            if (Trace.error)
                Trace.trace("ZoneRecordBuilder implementation not found '" + DEFAULT_BUILDER + "'");
        }

        return null;
    }
}


text:
Before you start implementing your model please make sure that the model in your mind is not implemented inside *docluster/models*. Note that there might be models that have a file but not implemented. Please read the Code Style guideline, if you haven't already. Thank you :)

## Steps to follow:

1) Create a file with filename being the name of your model. The filename should be all lowercase and shouldn't have any underscores.

2) Copy and paste the following template from [model template](./model_template.py).

3) Create a test file in tests/models/<the type of the model> with naming convention of **test_yourmodelname.py**.

4) Copy and paste following template from [test template](./test_template.py).


text:
/**
 * @summary Race timing system
 * @author Guillaume Deconinck & Wojciech Grynczel
*/

'use strict';

const chai = require('chai');
const chaiHttp = require('chai-http');
const expect = chai.expect;
const io = require('socket.io-client');
const app = require('../../../src/app');
const User = app.service('users');
const Checkpoints = app.service('checkpoints');
chai.use(chaiHttp);

var token;
const URL = 'http://' + app.settings.host + ':' + app.settings.port;

const defaultCheckpoints = [{ num: 1, title: 'Boucle1' },
{ num: 2, title: 'Boucle2' }];

describe('checkpoints service', () => {

  it('registered the checkpoints service', () => {
    expect(app.service('checkpoints')).to.be.ok;
  });

  describe('testing with REST', () => {

    before(function (done) {
      User.create({
        'email': 'admin@shouldexist.com',
        'password': 'azerty9'
      }).then(res => {
        Checkpoints.remove(null).then(() => {
          done();
        });
      });
    });

    /* ############################# */
    /* ##### NOT AUTHENTICATED ##### */
    /* ############################# */

    describe('without being authenticated', () => {

      it('should not create the checkpoints (not logged in)', (done) => {
        chai.request(URL).post('/checkpoints')
          .set('Accept', 'application/json')
          .send(defaultCheckpoints)
          //when finished
          .end((err, res) => {
            expect(err.response.error).to.exist;
            expect(res.statusCode).to.be.within(400, 499);
            done();
          });
      });

      it('should find the checkpoints (authorized without being logged in)', (done) => {
        chai.request(URL).get('/checkpoints')
          .set('Accept', 'application/json')
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            expect(err).to.not.exist;
            expect(res.statusCode).to.equal(200);
            done();
          });
      });

      it('should not get the checkpoint (not logged in)', (done) => {
        chai.request(URL).get('/checkpoints/' + 1)
          .set('Accept', 'application/json')
          //when finished
          .end((err, res) => {
            expect(err.response.error).to.exist;
            expect(res.statusCode).to.be.within(400, 499);
            done();
          });
      });

      it('should not update a checkpoint (not logged in)', (done) => {
        chai.request(URL).put('/checkpoints/' + 1)
          .set('Accept', 'application/json')
          .send({ num: 1, assigned: true })
          //when finished
          .end((err, res) => {
            expect(err.response.error).to.exist;
            expect(res.statusCode).to.be.within(400, 499);
            done();
          });
      });

      it('should not patch a checkpoint (not logged in)', (done) => {
        chai.request(URL).patch('/checkpoints/' + 1)
          .set('Accept', 'application/json')
          .send({ assigned: true })
          //when finished
          .end((err, res) => {
            expect(err.response.error).to.exist;
            expect(res.statusCode).to.be.within(400, 499);
            done();
          });
      });

      it('should not delete the checkpoint (not logged in)', (done) => {
        chai.request(URL).delete('/checkpoints/' + 1)
          .set('Accept', 'application/json')
          //when finished
          .end((err, res) => {
            expect(err.response.error).to.exist;
            expect(res.statusCode).to.be.within(400, 499);
            done();
          });
      });
    });

    /* ############################# */
    /* ####### AUTHENTICATED ####### */
    /* ############################# */

    describe('while being authenticated', () => {

      var token;
      var checkpoints;

      before(function (done) {
        chai.request(URL).post('/authentication')
          //set header
          .set('Accept', 'application/json')
          //send credentials
          .send({
            'strategy': 'local',
            'email': 'admin@shouldexist.com',
            'password': 'azerty9'
          })
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            token = res.body.accessToken;
            done();
          });
      });

      it('should create the checkpoints', (done) => {
        chai.request(URL).post('/checkpoints')
          .set('Accept', 'application/json')
          .set('Authorization', 'Bearer '.concat(token))
          .send(defaultCheckpoints)
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            expect(err).to.not.exist;
            expect(res.body).to.have.lengthOf(defaultCheckpoints.length);
            expect(res.statusCode).to.equal(201);
            done();
          });
      });

      it('should find the checkpoints', (done) => {
        chai.request(URL).get('/checkpoints')
          .set('Accept', 'application/json')
          .set('Authorization', 'Bearer '.concat(token))
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            expect(err).to.not.exist;
            expect(res.body.data).to.exist;
            checkpoints = res.body.data;
            done();
          });
      });

      it('should get a checkpoint', (done) => {
        chai.request(URL).get('/checkpoints/' + checkpoints[0]._id)
          .set('Accept', 'application/json')
          .set('Authorization', 'Bearer '.concat(token))
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            expect(err).to.not.exist;
            expect(res.body.num).to.exist;
            done();
          });
      });

      it('should update a checkpoint', (done) => {
        var newCheckpoint = Object.assign({}, checkpoints[0]);
        newCheckpoint.title = 'Boucle3';
        chai.request(URL).put('/checkpoints/' + newCheckpoint._id)
          .set('Accept', 'application/json')
          .set('Authorization', 'Bearer '.concat(token))
          .send(newCheckpoint)
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            expect(err).to.not.exist;
            expect(res.body).to.exist;
            expect(res.body.title).to.equal(newCheckpoint.title);
            done();
          });
      });

      it('should patch a checkpoint', (done) => {
        chai.request(URL).patch('/checkpoints/' + checkpoints[1]._id)
          .set('Accept', 'application/json')
          .set('Authorization', 'Bearer '.concat(token))
          .send({ title: 'Boucle4' })
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            expect(err).to.not.exist;
            expect(res.body).to.exist;
            expect(res.body.title).to.equal('Boucle4');
            done();
          });
      });

      it('should delete a checkpoint', (done) => {
        chai.request(URL).delete('/checkpoints/' + checkpoints[0]._id)
          .set('Accept', 'application/json')
          .set('Authorization', 'Bearer '.concat(token))
          //when finished
          .end((err, res) => {
            if (err)
              console.log(err.response.error);
            expect(err).to.not.exist;
            done();
          });
      });

    });
    // END WITH BEING AUTHENTICATED

    after(function (done) {
      User.remove(null).then(() => {
        Checkpoints.remove(null).then(() => {
          done();
        });
      });
    });

  });
  // END WITH REST

});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Body</string>
    <string name="search_hint">Search Body</string>
    <string name="welcome_title">Google Body</string>
    <string name="welcome_text">Google Body is a detailed 3D model of the human body. You can view different anatomical layers, zoom in, and navigate to parts that interest you. Click to identify anatomy, or search for muscles, organs, bones and more.</string>
    <string name="welcome_terms">Review the mobile terms of service.</string>
    <string name="eula_accept">Accept</string>
    <string name="eula_refuse">Decline</string>
</resources>


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core\task;

/**
 * Simple task to run the calendar cron.
 */
class calendar_cron_task extends scheduled_task {

    /**
     * Get a descriptive name for this task (shown to admins).
     *
     * @return string
     */
    public function get_name() {
        return get_string('taskcalendarcron', 'admin');
    }

    /**
     * Do the job.
     * Throw exceptions on errors (the job will be retried).
     */
    public function execute() {
        global $CFG;

        // Run calendar cron.
        require_once("{$CFG->dirroot}/calendar/lib.php");
        calendar_cron();
    }

}


text:
RSpec.describe 'detect command' do
  let(:command) { ['bundle', 'exec', 'bin/licensee', 'detect'] }
  let(:arguments) { [] }
  let(:output) do
    Dir.chdir project_root do
      Open3.capture3(*[command, arguments].flatten)
    end
  end
  let(:parsed_output) { YAML.safe_load(stdout) }
  let(:stdout) { output[0] }
  let(:stderr) { output[1] }
  let(:status) { output[2] }
  let(:hash) { '46cdc03462b9af57968df67b450cc4372ac41f53' }
  let(:expected) do
    {
      'License'          => 'MIT',
      'Matched files'    => 'LICENSE.md, licensee.gemspec',
      'LICENSE.md'       => {
        'Content hash' => hash,
        'Attribution'  => 'Copyright (c) 2014-2017 Ben Balter',
        'Confidence'   => '100.00%',
        'Matcher'      => 'Licensee::Matchers::Exact',
        'License'      => 'MIT'
      },
      'licensee.gemspec' => {
        'Confidence' => '90.00%',
        'Matcher'    => 'Licensee::Matchers::Gemspec',
        'License'    => 'MIT'
      }
    }
  end

  {
    'No arguments' => [],
    'Project root' => [project_root],
    'License path' => [File.expand_path('LICENSE.md', project_root)]
  }.each do |name, args|
    context "When given #{name}" do
      let(:arguments) { args }

      it 'Returns a zero exit code' do
        expect(status.exitstatus).to eql(0)
      end

      it 'returns the exected values' do
        hash = expected.dup

        if name == 'License path'
          hash.delete('licensee.gemspec')
          hash['Matched files'] = 'LICENSE.md'
        end

        expect(parsed_output).to eql(hash)
      end
    end
  end

  context 'json' do
    let(:arguments) { ['--json'] }
    let(:expected) { JSON.parse fixture_contents('detect.json') }

    it 'Returns a zero exit code' do
      expect(status.exitstatus).to eql(0)
    end

    it 'returns valid JSON' do
      expect { JSON.parse(stdout) }.to_not raise_error
    end

    it 'returns the expected output' do
      expect(JSON.parse(stdout)).to eql(expected)
    end
  end

  context 'the default command' do
    let(:command) { ['bundle', 'exec', 'bin/licensee'] }

    it 'Returns a zero exit code' do
      expect(status.exitstatus).to eql(0)
    end

    it 'returns the exected values' do
      expect(parsed_output).to eql(expected)
    end
  end
end


text:
package eni

import (
	"context"
	"fmt"
	"time"

	"github.com/cilium/cilium/pkg/controller"
	"github.com/cilium/cilium/pkg/ipam/types"
)

const gcENIControllerName = "ipam-eni-gc"

var controllerManager = controller.NewManager()

type GarbageCollectionParams struct {
	// RunInterval is both the GC interval and also the minimum amount of time
	// an ENI has to be available before it is garbage collected
	RunInterval time.Duration
	// MaxPerInterval is the maximum number of ENIs which are deleted in a
	// single interval
	MaxPerInterval int32
	// ENITags is used to only garbage collect ENIs with this set of tags
	ENITags types.Tags
}

func StartENIGarbageCollector(ctx context.Context, api EC2API, params GarbageCollectionParams) {
	log.Info("Starting to garbage collect detached ENIs")

	var enisMarkedForDeletion []string
	controllerManager.UpdateController(gcENIControllerName, controller.ControllerParams{
		DoFunc: func(ctx context.Context) error {
			// Unfortunately, the EC2 API does not allow us to determine the age of
			// a network interface. To mitigate a race where Cilium just created a new
			// ENI to be attached to a node, we wait for one run interval before we delete
			// any ENIs. If the interface has been attached by the next run interval,
			// the deletion will fail and the interface will not be garbage collected.
			for _, eniID := range enisMarkedForDeletion {
				log.WithField("eniID", eniID).Debug("Garbage collecting ENI")
				err := api.DeleteNetworkInterface(ctx, eniID)
				if err != nil {
					log.WithError(err).Debug("Failed to garbage collect ENI")
				}
			}

			var err error
			enisMarkedForDeletion, err = api.GetDetachedNetworkInterfaces(ctx, params.ENITags, params.MaxPerInterval)
			if err != nil {
				return fmt.Errorf("failed to fetch available interfaces: %w", err)
			}

			if numENIs := len(enisMarkedForDeletion); numENIs > 0 {
				log.WithField("numInterfaces", numENIs).
					Debug("Marked unattached interfaces for garbage collection")
			}

			return nil
		},
		RunInterval: params.RunInterval,
		Context:     ctx,
	})
}


text:
package com.heatonresearch.aifh.energetic;

import com.heatonresearch.aifh.AIFHError;

/**
 * Created with IntelliJ IDEA.
 * User: Jeff
 * Date: 1/27/15
 * Time: 4:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class TrainHopfieldHebbian {
    private HopfieldNetwork network;
    private double[][] sumMatrix;
    private int patternCount;

    public TrainHopfieldHebbian(HopfieldNetwork theNetwork) {
        this.network = theNetwork;
        this.sumMatrix = new double[network.getInputCount()][network.getInputCount()];
    }

    public void addPattern(double[] pattern) {
        for(int i=0;i<this.sumMatrix.length;i++) {
            for(int j=0;j<this.sumMatrix.length;j++) {
                if(i==j) {
                    this.sumMatrix[i][j] = 0;
                } else {
                    this.sumMatrix[i][j] += pattern[i] * pattern[j];
                }
            }
        }
        this.patternCount++;
    }

    public void learn() {
        if( this.patternCount==0) {
            throw new AIFHError("Please add a pattern before learning.  Nothing to learn.");
        }

        for(int i=0;i<this.sumMatrix.length;i++) {
            for(int j=0;j<this.sumMatrix.length;j++) {
                this.network.setWeight(i,j,this.sumMatrix[i][j]/this.patternCount);
            }
        }
    }

}


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

package com.google.gerrit.extensions.client;

import java.util.EnumSet;
import java.util.Set;

/** Output options available for retrieval change details. */
public enum ListChangesOption {
  LABELS(0),
  DETAILED_LABELS(8),

  /** Return information on the current patch set of the change. */
  CURRENT_REVISION(1),
  ALL_REVISIONS(2),

  /** If revisions are included, parse the commit object. */
  CURRENT_COMMIT(3),
  ALL_COMMITS(4),

  /** If a patch set is included, include the files of the patch set. */
  CURRENT_FILES(5),
  ALL_FILES(6),

  /** If accounts are included, include detailed account info. */
  DETAILED_ACCOUNTS(7),

  /** Include messages associated with the change. */
  MESSAGES(9),

  /** Include allowed actions client could perform. */
  CURRENT_ACTIONS(10),

  /** Set the reviewed boolean for the caller. */
  REVIEWED(11),

  /** Include download commands for the caller. */
  DOWNLOAD_COMMANDS(13),

  /** Include patch set weblinks. */
  WEB_LINKS(14),

  /** Include consistency check results. */
  CHECK(15),

  /** Include allowed change actions client could perform. */
  CHANGE_ACTIONS(16),

  /** Include a copy of commit messages including review footers. */
  COMMIT_FOOTERS(17);

  private final int value;

  private ListChangesOption(int v) {
    this.value = v;
  }

  public int getValue() {
    return value;
  }

  public static EnumSet<ListChangesOption> fromBits(int v) {
    EnumSet<ListChangesOption> r = EnumSet.noneOf(ListChangesOption.class);
    for (ListChangesOption o : ListChangesOption.values()) {
      if ((v & (1 << o.value)) != 0) {
        r.add(o);
        v &= ~(1 << o.value);
      }
      if (v == 0) {
        return r;
      }
    }
    if (v != 0) {
      throw new IllegalArgumentException("unknown " + Integer.toHexString(v));
    }
    return r;
  }

  public static int toBits(Set<ListChangesOption> set) {
    int r = 0;
    for (ListChangesOption o : set) {
      r |= 1 << o.value;
    }
    return r;
  }
}


text:
set -eux

for target in "clean" "install" ; do
  for d in fuse fuse/pathfs fuse/test zipfs unionfs \
    example/hello example/loopback example/zipfs \
    example/multizip example/unionfs example/memfs \
    example/autounionfs ; \
  do
    if test "${target}" = "install" && test "${d}" = "fuse/test"; then
      continue
    fi
    go ${target} github.com/hanwen/go-fuse/${d}
  done
done

for d in fuse zipfs unionfs
do
  (cd $d && go test github.com/hanwen/go-fuse/$d && go test -race github.com/hanwen/go-fuse/$d)
done

make -C benchmark
for d in benchmark
do
  go test github.com/hanwen/go-fuse/benchmark -test.bench '.*' -test.cpu 1,2
done


text:
<?php

namespace Platformsh\Cli\Exception;

use Platformsh\Cli\Service\Config;

class RootNotFoundException extends \RuntimeException
{
    public function __construct(
        $message = 'Project root not found. This can only be run from inside a project directory.',
        $code = 2
    )
    {
        // If this is a Git repository that looks like an un-configured project,
        // then suggest the "project:set-remote" command.
        if (is_dir('.git')) {
            $config = new Config();
            if (is_dir($config->get('service.project_config_dir'))) {
                $executable = $config->get('application.executable');
                $message .= "\n\nTo set the project for this Git repository, run:\n  $executable project:set-remote [id]";
            }
        }

        parent::__construct($message, $code);
    }
}


text:
package org.splash.messaging.proton;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.splash.messaging.ConnectionSettings;
import org.splash.messaging.EventHandler;
import org.splash.messaging.NetworkException;

class ConnectionImpl extends BaseConnection implements NetworkConnection.ByteReceiver
{
    private NetworkConnection _network;

    ConnectionImpl(ConnectionSettings settings, EventHandler ... handlers)
    {
        _settings = settings;
        _handlers = handlers;
    }

    void bind(NetworkConnection network) throws NetworkException
    {
        _network = network;
    }

    @Override
    void init() throws NetworkException
    {
        super.init();
        _network.start();
        try
        {
            Thread.sleep(2000);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    void write()
    {
        while (_transport.pending() > 0)
        {
            ByteBuffer data = _transport.getOutputBuffer();
            try
            {
                _network.send(data);
            }
            catch (IOException e)
            {
                throw new RuntimeException("Exception writing to socket", e);
            }
            _transport.outputConsumed();
        }
    }

    @Override
    void closeNetworkConnection()
    {
        _network.close();
    }

    @Override
    public void received(ByteBuffer data)
    {
        while (data.hasRemaining())
        {
            ByteBuffer buf = _transport.getInputBuffer();
            int maxAllowed = Math.min(data.remaining(), buf.remaining());
            ByteBuffer temp = data.duplicate();
            temp.limit(data.position() + maxAllowed);
            buf.put(temp);
            _transport.processInput();
            data.position(data.position() + maxAllowed);
        }
        processEvents();
        write();
    }

    @Override
    public void exception(Exception e)
    {

    }
}


text:
package org.apache.catalina.tribes;

import java.io.Serializable;

import org.apache.catalina.tribes.util.Arrays;

/**
 *
Title: Represents a globally unique Id

 *
 *
Company:

 *
 * @author Filip Hanik
 * @version 1.0
 */
public final class UniqueId implements Serializable{
    private static final long serialVersionUID = 1L;

    byte[] id;

    public UniqueId() {
    }

    public UniqueId(byte[] id) {
        this.id = id;
    }

    public UniqueId(byte[] id, int offset, int length) {
        this.id = new byte[length];
        System.arraycopy(id,offset,this.id,0,length);
    }

    @Override
    public int hashCode() {
        if ( id == null ) return 0;
        return Arrays.hashCode(id);
    }

    @Override
    public boolean equals(Object other) {
        boolean result = (other instanceof UniqueId);
        if ( result ) {
            UniqueId uid = (UniqueId)other;
            if ( this.id == null && uid.id == null ) result = true;
            else if ( this.id == null && uid.id != null ) result = false;
            else if ( this.id != null && uid.id == null ) result = false;
            else result = Arrays.equals(this.id,uid.id);
        }//end if
        return result;
    }

    public byte[] getBytes() {
        return id;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder("UniqueId");
        buf.append(Arrays.toString(id));
        return buf.toString();
    }

}


text:
from flask import Flask, render_template
#from flask.ext.pymongo import PyMongo
from flask_pymongo import PyMongo

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'dbfabiomac'
#app.config['MONGO_URI'] = 'mongodb://fabiomac:mrcx741a@ds029436.mlab.com:29436/dbfabiomac'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/dbfabiomac'

mongo = PyMongo(app)

@app.route('/')
def index():
    return 'Hello Flask!'

@app.route('/add')
def add():
    users = mongo.db.users
    users.insert({'name': 'Fabio', 'language': 'Python'})
    users.insert({'name': 'Maria Eduarda', 'language': 'C'})
    users.insert({'name': 'Spock', 'language': 'Ruby'})
    users.insert({'name': 'Antony', 'language': 'C++'})
    return 'Added User!!!'

@app.route('/find')
def find():
    users = mongo.db.users
    spock = users.find_one({'name': 'Spock'})
    return 'You found ' + spock['name'] + '. His favorite language is ' + spock['language']

@app.route('/update')
def update():
    users = mongo.db.users
    spock = users.find_one({'name': 'Spock'})
    spock['language'] = 'JavaScript'
    users.save(spock)
    return 'Update Spock!!!'

@app.route('/delete')
def delete():
    users = mongo.db.users
    fabio = users.find_one({'name': 'Fabio'})
    users.remove(fabio)
    return 'Removed Spock!!!'

if __name__ == '__main__':
    app.secret_key = 'mrcx741a'
    app.run(debug=True)


text:
return {
    width = 32,
    height = 48,
    animations = {
        default = {
            'loop',{'1,1','11,1'},.5,
        },
        walking = {
            'loop',{'1,1','2,1','3,1'},.2,
        },

    },

    talk_items = {
        { ['text']='i am done with you' },
        { ['text']='Lay off that booze, pal' },
        { ['text']='Any useful info for me?' },
        { ['text']='Donde esta...', ['option']={
            { ['text']='Castle Hawkthorne?' },
            { ['text']='the town blacksmith?' },
            { ['text']='the sandpits?' },
            { ['text']='la biblioteca?' },
        }},
    },
    talk_responses = {
    ['Lay off that booze, pal']={
        "Buzz off, guy. You're not my mother.",
        "Besides, I'm only on my 6th bottle of the day.",
    },
    ['Castle Hawkthorne?']={
        "I really hope you're not thinking of going there, that's a pretty darn dangrous place.",
        "That being said, the castle is northeast of here, past Gay Island and the Black Caverns.",
    },
    ['the town blacksmith?']={
        "Sleeping on the streets somewhere, probably,",
        "He's one of the few employed guys around here, and he's the laziest out of all of us.",
    },
    ['the sandpits?']={
        "The sandpits? Haven't heard anyone talk about that place in a while.",
        "I believe it's somewhere past the chili fields, I hear the entrance is very well hidden though.",
    },
    ['la biblioteca?']={
        "The library? We don't got no library here.",
        "Is that like the only Spanish word you know?",
    },
    ['Any useful info for me?']={
        "If you're thinking about going into the sandpits, it would be a good idea to bring a weapon.",
        "I hear the ceiling is so low you can't even jump on enemies to hurt them.",
    },
    },
}


text:
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "git_commands"
require "minitest/autorun"
require "tempfile"
require "fileutils"
require "mocks"

include Mocks

$VERBOSE = nil


text:
/**
 * Created by cool.blue on 2/04/2017.
 */
import FpsMeter from '../src/d3-fps-histogram'
import {select, event, mouse} from 'd3-selection'
import 'd3-selection-multi'
import {format} from 'd3-format'
import {scaleLinear} from 'd3-scale'
import {randomNormal} from 'd3-random'

let container = select('#container'),
  metrics = container.append("div")
    .attr("id", "metrics"),
  hist = FpsMeter("#metrics", {display: "block"}, {
    height: 10, width: 100,
    values: function (d) {
      return 1 / d
    },
    domain: [0, 60]
  })
    .message(function (this_lap, aveLap) {
      return 'lap: ' + format(" >4,.1f")(1 / aveLap)
    }),
  containerWidth = 960,
  containerHeight = 470 - hist.selection.node().clientHeight,
  fps = 60, sigma = 1,
  svg = container.append('svg').attr('height', containerHeight).attr('width', containerWidth);
  hist.svg.on('mousemove', function() {
      fps = x(mouse(hist.svg.node())[0]);
    }
  )
    .on('wheel', function(){
      sigma -= event.deltaY;
      event.preventDefault();
    });
  let x = scaleLinear().domain([0, hist.svg.attr('width')])
    .range([0,60]),
    y = scaleLinear().domain([0, 1000])
      .range([0,10]).clamp(true);

hist.start(100);

export let t0 = window.performance.now(), tlap;
function tick(){
  let a = Math.random();
  let _s = y(sigma);
  let tlapAct = (-t0 + (t0 = window.performance.now())),
    tDemand,
    k = 0.1;
  sigma = y.invert(_s);
  tlap = randomNormal(1/fps * 1000, _s)();
  tDemand =  (tlap - tlapAct * k) / (1 - k);
  // console.log(`SP: ${Math.round(1000/tlap)}\tAct: ${Math.round(1000/tlapAct)}\tOP: ${Math.round(1000/tDemand)}\tSigma: ${_s}`);
  window.setTimeout(() => window.requestAnimationFrame(tick), tlap);
  // window.requestAnimationFrame(tick);
  // if(Math.random()*10 < _s)
  //   window.requestAnimationFrame(tick);
  // else
  //   window.requestAnimationFrame(() => window.requestAnimationFrame(tick));
  hist.mark(a);
}

window.requestAnimationFrame(tick);


text:
/* jshint worker: true */
'use strict';

if (typeof console == 'undefined') {
  this.console = {
    error: function(e){
      postMessage(JSON.stringify({
        type: 'error',
        message: e.message,
        stack: e.stack
      }));
    },
    log: function(message){
      postMessage(JSON.stringify({
        type: 'log',
        message: message
      }));
    }
  }
}

console.log('worker BEGIN');

// The UMD wrapper tries to store on `global` if `window` isn't available
var global = {};
importScripts("phantomjs-shims.js");

try {
  importScripts("../../build/react.js");
} catch (e) {
  console.error(e);
}

postMessage(JSON.stringify({
  type: 'done'
}));

console.log('worker END');


text:
package recovery;

import org.junit.Rule;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.GraphDatabaseAPI;
import org.neo4j.kernel.impl.MyRelTypes;
import org.neo4j.kernel.impl.transaction.log.rotation.LogRotation;
import org.neo4j.test.TargetDirectory;
import org.neo4j.test.TestGraphDatabaseFactory;
import org.neo4j.tooling.GlobalGraphOperations;

import static java.lang.Runtime.getRuntime;
import static java.lang.System.exit;
import static java.lang.System.getProperty;
import static org.junit.Assert.assertEquals;

public class TestRecoveryMultipleDataSources
{
    @Rule
    public final TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() );

    /**
     * Tests an issue where loading all relationship types and property indexes after
     * the neostore data source had been started internally. The db would be in a
     * state where it would need recovery for the neostore data source, as well as some
     * other data source. This would fail since eventually TxManager#getTransaction()
     * would be called, which would fail since it hadn't as of yet recovered fully.
     * Whereas that failure would happen in a listener and merely be logged, one effect
     * of it would be that there would seem to be no relationship types in the database.
     */
    @Test
    public void recoverNeoAndIndexHavingAllRelationshipTypesAfterRecovery() throws Exception
    {
        // Given (create transactions and kill process, leaving it needing for recovery)
        File storeDir = testDirectory.graphDbDir();
        assertEquals( 0, getRuntime().exec( new String[]{"java", "-Djava.awt.headless=true", "-cp",
                getProperty( "java.class.path" ), getClass().getName(), storeDir.getAbsolutePath()} ).waitFor() );

        // When
        GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir );

        // Then
        try ( Transaction ignored = db.beginTx() )
        {
            assertEquals( MyRelTypes.TEST.name(),
                    GlobalGraphOperations.at( db ).getAllRelationshipTypes().iterator().next().name() );
        }
        finally
        {
            db.shutdown();
        }
    }

    public static void main( String[] args ) throws IOException
    {
        if ( args.length != 1 )
        {
            exit( 1 );
        }

        File storeDir = new File( args[0] );
        GraphDatabaseAPI db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( storeDir );
        Transaction tx = db.beginTx();
        db.createNode().createRelationshipTo( db.createNode(), MyRelTypes.TEST );
        tx.success();
        tx.close();

        db.getDependencyResolver().resolveDependency( LogRotation.class ).rotateLogFile();

        tx = db.beginTx();
        db.index().forNodes( "index" ).add( db.createNode(), storeDir.getAbsolutePath(), db.createNode() );
        tx.success();
        tx.close();
        exit( 0 );
    }
}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Account\Enums;

class PaymentMethodTypeEnum
{
    const C_CASHIER_CHECK = 'CASHIER_CHECK';
    const C_CASH_IN_PERSON = 'CASH_IN_PERSON';
    const C_CASH_ON_DELIVERY = 'CASH_ON_DELIVERY';
    const C_CASH_ON_PICKUP = 'CASH_ON_PICKUP';
    const C_CREDIT_CARD = 'CREDIT_CARD';
    const C_ESCROW = 'ESCROW';
    const C_INTEGRATED_MERCHANT_CREDIT_CARD = 'INTEGRATED_MERCHANT_CREDIT_CARD';
    const C_LOAN_CHECK = 'LOAN_CHECK';
    const C_MONEY_ORDER = 'MONEY_ORDER';
    const C_OTHER = 'OTHER';
    const C_PAISA_PAY = 'PAISA_PAY';
    const C_PAISA_PAY_ESCROW = 'PAISA_PAY_ESCROW';
    const C_PAISA_PAY_ESCROW_EMI = 'PAISA_PAY_ESCROW_EMI';
    const C_PAYPAL = 'PAYPAL';
    const C_PERSONAL_CHECK = 'PERSONAL_CHECK';
}


text:
<?php

namespace Zend\EventManager;

use Zend\Stdlib\CallbackHandler;
use Zend\Stdlib\PriorityQueue;

/**
 * Interface for shared event listener collections
 */
interface SharedEventManagerInterface
{
    /**
     * Retrieve all listeners for a given identifier and event
     *
     * @param  string|int $id
     * @param  string|int $event
     * @return false|PriorityQueue
     */
    public function getListeners($id, $event);

    /**
     * Attach a listener to an event
     *
     * @param  string|array $id Identifier(s) for event emitting component(s)
     * @param  string $event
     * @param  callable $callback PHP Callback
     * @param  int $priority Priority at which listener should execute
     * @return void
     */
    public function attach($id, $event, $callback, $priority = 1);

    /**
     * Detach a listener from an event offered by a given resource
     *
     * @param  string|int $id
     * @param  CallbackHandler $listener
     * @return bool Returns true if event and listener found, and unsubscribed; returns false if either event or listener not found
     */
    public function detach($id, CallbackHandler $listener);

    /**
     * Retrieve all registered events for a given resource
     *
     * @param  string|int $id
     * @return array
     */
    public function getEvents($id);

    /**
     * Clear all listeners for a given identifier, optionally for a specific event
     *
     * @param  string|int $id
     * @param  null|string $event
     * @return bool
     */
    public function clearListeners($id, $event = null);
}


text:
package qga

import "sync"

var (
	storeMutext sync.Mutex
	store       = make(map[string]map[interface{}]interface{})
)

// StoreSet set variable k with value v to namespace ns
func StoreSet(ns string, k interface{}, v interface{}) {
	storeMutext.Lock()
	defer storeMutext.Unlock()
	m, ok := store[ns]
	if !ok {
		m = make(map[interface{}]interface{})
	}
	m[k] = v
	store[ns] = m
}

// StoreGet get variable k from namespace ns
func StoreGet(ns string, k interface{}) (interface{}, bool) {
	storeMutext.Lock()
	defer storeMutext.Unlock()
	m, ok := store[ns]
	if !ok {
		return nil, false
	}
	v, ok := m[k]
	return v, ok
}

// StoreDel del variable k from namespace ns
func StoreDel(ns string, k interface{}) {
	storeMutext.Lock()
	defer storeMutext.Unlock()
	m, ok := store[ns]
	if !ok {
		return
	}
	delete(m, k)
}


text:
layout: page
title: Trippin Advanced Usages
permalink: odata-services/service-usages/trippin-advanced-usages/
---

## Trippin Advanced Usages

### Singleton

#### Requesting singleton

```
GET https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/Me
```

### Singleton

#### Requesting property of Singleton

```
GET https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/Me/AddressInfo
```

### Derived Entity Type

#### Requesting Derived Entity Type

```
GET https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/People('kristakemp')/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee
```

#### Requesting a Derived Entity Collection

```
GET https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/People/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee
```

#### Filter on Derived Entity

```
GET https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/People('kristakemp')/Microsoft.OData.Service.Sample.TrippinInMemory.Models.Employee?$filter=Cost ne 0
```

#### Create a Derived Entity

```javascript
POST https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/People
{
    "@odata.type": "Microsoft.OData.Service.Sample.TrippinInMemory.Models.Manager",
    "UserName": "mirsking",
    "FirstName": "Mirs",
    "LastName": "King",
    "AddressInfo": [
    {
      "Address": "Microsoft",
      "City": {
        "Name": "Shanghai",
        "CountryRegion": "China"
      }
    }],
    "BossOffice":{
      "Address": "Microsoft",
      "City": {
        "Name": "Shanghai",
        "CountryRegion": "China"
      }
    },
    "Budget": 100
}
```

### Containment Navigation Property

#### Requesting a Contained Entity Set

```
GET https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/People('russellwhyte')/Trips
```

#### Filter on a Contained Entity Set

```
GET https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/People('russellwhyte')/Trips?$filter=contains(Description, 'New York')
```

### Batch

#### Request

```javascript
POST https://services.odata.org/TripPinRESTierService/(S(3mslpb2bc0k5ufk24olpghzx))/$batch
OData-Version: 4.0
Content-Type: multipart/mixed;boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b

--batch_36522ad7-fc75-4b56-8c71-56071383e77b
Content-Type: application/http
Content-Transfer-Encoding:binary

GET https://services.odata.org/TripPinRESTierService/Airlines HTTP/1.1
Accept: application/json;odata.metadata=minimal

--batch_36522ad7-fc75-4b56-8c71-56071383e77b
Content-Type: application/http
Content-Transfer-Encoding:binary
Content-ID: 1

POST https://services.odata.org/TripPinRESTierService/Airlines HTTP/1.1
OData-Version: 4.0
Content-Type: application/json;odata.metadata=minimal
Accept: application/json;odata.metadata=minimal

{
"@odata.type" : "Microsoft.OData.SampleService.Models.TripPin.Airline",
"AirlineCode" : "EK",
"Name" : "Emirates Airline"
}

--batch_36522ad7-fc75-4b56-8c71-56071383e77b
Content-Type: application/http
Content-Transfer-Encoding:binary

GET https://services.odata.org/TripPinRESTierService/Airlines HTTP/1.1
Accept: application/json;odata.metadata=minimal

--batch_36522ad7-fc75-4b56-8c71-56071383e77b--
```

#### Response

```javascript
--batchresponse_5770c9a3-39c6-4794-99d1-dca99f6fadfc
Content-Type: application/http
Content-Transfer-Encoding: binary

HTTP/1.1 200 OK
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0

{
  "@odata.context":"https://services.odata.org/TripPinRESTierService/$metadata#Airlines","value":[
    {
      "@odata.etag":"W/\"J0FtZXJpY2FuIEFpcmxpbmVzJw==\"","AirlineCode":"AA","Name":"American Airlines"
    },{
      "@odata.etag":"W/\"J1NoYW5naGFpIEFpcmxpbmUn\"","AirlineCode":"FM","Name":"Shanghai Airline"
    },{
      "@odata.etag":"W/\"J0NoaW5hIEVhc3Rlcm4gQWlybGluZXMn\"","AirlineCode":"MU","Name":"China Eastern Airlines"
    }
  ]
}
--batchresponse_5770c9a3-39c6-4794-99d1-dca99f6fadfc
Content-Type: application/http
Content-Transfer-Encoding: binary

HTTP/1.1 201 Created
Location: https://services.odata.org/TripPinRESTierService/Airlines('EK')
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0

{
  "@odata.context":"https://services.odata.org/TripPinRESTierService/$metadata#Airlines/$entity","@odata.etag":"W/\"J0VtaXJhdGVzIEFpcmxpbmUn\"","AirlineCode":"EK","Name":"Emirates Airline"
}
--batchresponse_5770c9a3-39c6-4794-99d1-dca99f6fadfc
Content-Type: application/http
Content-Transfer-Encoding: binary

HTTP/1.1 200 OK
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0

{
  "@odata.context":"https://services.odata.org/TripPinRESTierService/$metadata#Airlines","value":[
    {
      "@odata.etag":"W/\"J0FtZXJpY2FuIEFpcmxpbmVzJw==\"","AirlineCode":"AA","Name":"American Airlines"
    },{
      "@odata.etag":"W/\"J1NoYW5naGFpIEFpcmxpbmUn\"","AirlineCode":"FM","Name":"Shanghai Airline"
    },{
      "@odata.etag":"W/\"J0NoaW5hIEVhc3Rlcm4gQWlybGluZXMn\"","AirlineCode":"MU","Name":"China Eastern Airlines"
    },{
      "@odata.etag":"W/\"J0VtaXJhdGVzIEFpcmxpbmUn\"","AirlineCode":"EK","Name":"Emirates Airline"
    }
  ]
}
--batchresponse_5770c9a3-39c6-4794-99d1-dca99f6fadfc--
```


text:
using System;

namespace InternetProgramming
{
    class Program
    {
        static BaseFigure[] figures = new BaseFigure[10];
        static Random rand = new Random();

        const int COLOR_MIN_VALUE = 7;
        const int COLOR_MAX_VALUE = 15;
        const int X_MIN_VALUE = 10;
        const int X_MAX_VALUE = 70;
        const int Y_MIN_VALUE = 0;
        const int Y_MAX_VALUE = 20;

        enum FigureType
        {
            //IFigure,
            //JFigure,
            //LFigure,
            OFigure,
            //ZFigure,
            //TFigure,
            //SFigure
        }

        static BaseFigure getRandomFigure(bool top = false)
        {
            int randomColor = rand.Next(COLOR_MIN_VALUE, COLOR_MAX_VALUE + 1);
            int randomX = rand.Next(X_MIN_VALUE, X_MAX_VALUE + 1);
            int y;
            if (top == false)
            {
                y = rand.Next(Y_MIN_VALUE, Y_MAX_VALUE + 1);
            }
            else
            {
                y = 1;
            }

            Array figureTypes = Enum.GetValues( typeof(FigureType) );
            FigureType randomFigure = (FigureType) figureTypes.GetValue( rand.Next(figureTypes.Length) );

            switch (randomFigure)
            {
                case (FigureType.OFigure):
                    return new OFigure(randomColor, randomX, y);
                default:
                    return null;
            }
        }

        static void Main(string[] args)
        {
            BaseFigure o = getRandomFigure();
            o.drawFigure();

            Console.ReadKey();
        }
    }

    abstract class BaseFigure
    {
        protected int color;
        protected int x;
        public int Y { get; set; }

        public int getColor()
        {
            return color;
        }

        public void setColor(int color)
        {
            this.color = color;
        }

        public int X
        {
            get
            {
                return x;
            }

            set
            {
                if (value <= 0)
                {
                    throw new ArgumentNullException("X", "x must be greater than 0");
                }
                x = value;
            }
        }

        public BaseFigure(int color, int x, int y)
        {
            this.color = color;
            this.x = x;
            this.Y = y;
        }

        abstract public void drawFigure();
    }

    class OFigure : BaseFigure
    {
        public OFigure(int color, int x, int y) : base(color, x, y)
        {
        }

        public override void drawFigure()
        {
            Console.ForegroundColor = (ConsoleColor) getColor();
            Console.BackgroundColor = (ConsoleColor) getColor();

            Console.CursorLeft = X;
            Console.CursorTop = Y;
            Console.Write("*");

            Console.CursorLeft = X + 1;
            Console.CursorTop = Y;
            Console.Write("*");

            Console.CursorLeft = X;
            Console.CursorTop = Y + 1;
            Console.Write("*");

            Console.CursorLeft = X + 1;
            Console.CursorTop = Y + 1;
            Console.Write("*");
        }
    }
}


text:
% example scrit how to use the HoghTracker class
clear all;
clear classes;

% Example 1: measuring cytosolic fluorescent expression
f_path_trans     = 'example_data/cytosolic_expression/img_trans_%04d.tif';
f_path_expr      = 'example_data/cytosolic_expression/img_yfp_%04d.tif';

% initialize HoughTracker class
% argument for the constructor is a name-string
% output images are saved in the folder "name-string"_tracker
ht = HoughTracker('pics_tracker_expr');

for i=1:3:25
    % rad the trans image
    img_trans = uint16( imread( sprintf( f_path_trans, i ) ) );
    % if a fluorescent image has been acquired, read it
    if exist( sprintf( f_path_expr, i ) )
        img_expr  = uint16( imread( sprintf( f_path_expr, i ) ) );
    else
        img_expr = 0;
    end
    % do another time point
    ht.add_timepoint( img_trans, img_expr, 0, 0 );
end

% get the data and plot it
% the first row is the time (int time-points)
time = ht.data_int(1,:)';
% all apart from the first fow is data
expr_data = ht.data_int(2:end,:)';
figure
plot(time, expr_data);

% Eample 2: measuring nuclear localization of a transcription factor
f_path_trans     = 'example_data/nuclear_localization/img_trans_%04d.tif';
f_path_expr      = 'example_data/nuclear_localization/img_yfp_%04d.tif';
f_path_nucleus   = 'example_data/nuclear_localization/img_cfp_%04d.tif';
f_path_tf        = 'example_data/nuclear_localization/img_rfp_%04d.tif';

ht = HoughTracker('pics_tracker_loc', 'cells_radii', [6, 30]);

for i=61:70
    img_trans   = uint16( imread( sprintf( f_path_trans, i ) ) );
    img_nucleus = uint16( imread( sprintf( f_path_nucleus, i ) ) );
    img_tf      = uint16( imread( sprintf( f_path_tf, i ) ) );

    % for some time point we have also expression data
    if exist( sprintf( f_path_expr, i ) )
        img_expr = uint16( imread( sprintf( f_path_expr, i ) ) );
    else
        img_expr = 0;
    end
    % do another time point
    ht.add_timepoint( img_trans, img_expr, img_tf, img_nucleus );
end

% plot the data
figure
time_int = ht.data_int(1,:);
data_int = ht.data_int(2:end,:)';
plot(time_int, data_int)
title('expression')
figure
time_coloc = ht.data_coloc(1,:);
data_coloc = ht.data_coloc(2:end,:)';
plot(time_coloc, data_coloc)
title('co-localization')

% plot also cell-radius
figure
plot(time_coloc, ht.data_size')
title('cell-size')


text:
'use strict';

// Configuring the Articles module
angular.module('users.admin').run(['Menus',
  function (Menus) {
    Menus.addSubMenuItem('topbar', 'admin', {
      title: 'Manage Users',
      state: 'admin.users'
    });

    Menus.addSubMenuItem('topbar', 'admin', {
      title: 'Register New User',
      state: 'authentication.signup'
    });
  }
]);


text:
// Copyright 2009 The Apache Software Foundation
//
// 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.apache.tapestry5.ioc.internal.services;

import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.ioc.services.SymbolProvider;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * Makes a {@link org.apache.tapestry5.ioc.Resource} available as a {@link org.apache.tapestry5.ioc.services.SymbolProvider}
 *
 * @since 5.1.0.5
 */
public class ResourceSymbolProvider implements SymbolProvider
{
    private final Resource resource;

    private final Map<String, String> properties = CollectionFactory.newCaseInsensitiveMap();

    public ResourceSymbolProvider(final Resource resource)
    {
        this.resource = resource;

        readProperties();
    }

    private void readProperties()
    {
        Properties p = new Properties();

        InputStream is = null;

        try
        {
            is = resource.openStream();

            p.load(is);

            is.close();

            is = null;

            for (Map.Entry<Object, Object> entry : p.entrySet())
            {
                String key = entry.getKey().toString();

                properties.put(key, p.getProperty(key));
            }
        }
        catch (IOException ex)
        {
            throw new RuntimeException(ex);
        }
        finally
        {
            InternalUtils.close(is);
        }
    }

    public String valueForSymbol(String symbolName)
    {
        return properties.get(symbolName);
    }
}


text:
	#include <sys/time.h>
#elif defined _WIN32 || defined _WIN64
	#include <windows.h>
#endif
#include <stddef.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

double GetUnixTimestampMilliseconds()
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (tv.tv_sec + (tv.tv_usec / 1000000.0)) * 1000.0;
}

char *GetHost(IP_TYPE Preffered, bool SSL)
{
	char *host4 = (SSL ? Host4SSL : Host4);
	char *host6 = (SSL ? Host6SSL : Host6);

	if (host4 != NULL && host6 != NULL)
		return Preffered == IPV4 ? host4 : host6;
	if (host4 == NULL)
		return host6;
	else
		return host4;
}

MEM_OUT char *FormatTime(uint64_t TimeMs)
{
	char *timeBuff = zalloc(20 + 1);

	struct tm *timeinfo;
	time_t timeRaw = TimeMs / 1000;

	timeinfo = localtime(&timeRaw);
	strftime(timeBuff, 20, "%Y-%m-%d %H:%M:%S", timeinfo);

	return timeBuff;
}

bool MemEqual(void *A, void *B, size_t Size)
{
	return memcmp(A, B, Size) == 0;
}

char *StrReplaceToNew(char *In, char *Search, char *Replace)
{
	char *ret;
	char *search = strstr(In, Search);
	size_t lSideLen = search - In;

	if (search == NULL || Replace[0] == '\0')
		return NULL;

	size_t searchLen = strlen(Search);
	size_t origLen = strlen(In);
	size_t replaceLen = strlen(Replace);

	ret = malloc((origLen - searchLen + replaceLen) * (sizeof(char) + 1));

	// Copy left side
	if (search != In)
		memcpy(ret, In, lSideLen);

	// Copy replacement
	memcpy(ret + lSideLen, Replace, replaceLen);

	// Copy right side
	if (search + (searchLen) != (In + origLen)) {
		memcpy(ret + lSideLen + replaceLen,
			   search + searchLen,
			   In + (origLen) - search - searchLen);
	}
	ret[(origLen - searchLen + replaceLen)] = L'\0';

	if (strstr(ret, Search) != NULL)
		StrReplaceOrig(&ret, Search, Replace);

	return ret;
}

bool StrReplaceOrig(char **In, char *Search, char *Replace)
{
	char *search = strstr(*In, Search);
	if (search == NULL)
		return false;

	size_t searchOffset = search - *In;

	size_t searchLen = strlen(Search);
	size_t origLen = strlen(*In);
	size_t replaceLen = strlen(Replace);

	size_t origToReplaceEndLen = (origLen - searchLen + replaceLen);

	if (replaceLen > searchLen) {
		*In = realloc(*In, origToReplaceEndLen + 1);
		search = strstr(*In, Search); // Re-search string

		char *rightSide = search + searchLen;
		size_t rightSideLen = ((*In + origLen) - rightSide);

		memmove(search + replaceLen, rightSide, rightSideLen);
		memcpy(*In + searchOffset, Replace, replaceLen);
		(*In)[origToReplaceEndLen] = '\0';
	} else if (replaceLen == searchLen)
		memcpy(*In + searchOffset, Replace, replaceLen);
	else if (replaceLen < searchLen) {
		char *rightSide = search + searchLen;
		size_t rightSideLen = ((*In + origLen) - rightSide);

		memmove(search + replaceLen, rightSide, rightSideLen);
		*In = realloc(*In, origToReplaceEndLen * (sizeof(char) + 1));

		memcpy(*In + searchOffset, Replace, replaceLen);
		(*In)[origToReplaceEndLen] = '\0';
	}

	if (strstr(*In, Search) != NULL)
		StrReplaceOrig(In, Search, Replace);

	return true;
}

MEM_OUT bool HTTPFindHeader(char *In, char *Buff, char **Out, char **StartIndex, char **EndIndex)
{
	char *valIndex = Buff;

	size_t searchIndex = 0, inLen = strlen(In);

	do {
		valIndex = strstr(Buff + searchIndex, In);
		if (valIndex == NULL)
			return false;
		if (valIndex == Buff || *(valIndex - 1) != '\n')
			searchIndex = (size_t)valIndex + inLen;
		else
			break;
	} while (1);

	char *valEnd = strstr(valIndex + inLen, "\r\n");
	if (valEnd == NULL) {
		valEnd = strchr(valIndex + inLen, '\n');
		if (valEnd == NULL)
			return false;
	}

	char *valIndexEnd = valIndex + inLen;
	size_t valLen = valEnd - valIndexEnd;

	*Out = malloc(valLen + 1);
	memcpy(*Out, valIndexEnd, valLen);
	(*Out)[valLen] = 0x00;

	if (StartIndex != NULL)
		*StartIndex = valIndex;
	if (EndIndex != NULL)
		*EndIndex = valEnd;

	return true;
}

void BufferEventFreeOnWrite(struct bufferevent *In)
{
	if (evbuffer_get_length(bufferevent_get_output(In)))
		bufferevent_setcb(In, NULL, (bufferevent_data_cb)bufferevent_free, (bufferevent_event_cb)bufferevent_free, NULL);
	else
		bufferevent_free(In);
}